
/* A Bison parser, made by GNU Bison 2.4.1.  */

/* Skeleton implementation for Bison's Yacc-like parsers in C
   
      Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
   Free Software Foundation, Inc.
   
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

/* As a special exception, you may create a larger work that contains
   part or all of the Bison parser skeleton and distribute that work
   under terms of your choice, so long as that work isn't itself a
   parser generator using the skeleton or a modified version thereof
   as a parser skeleton.  Alternatively, if you modify or redistribute
   the parser skeleton itself, you may (at your option) remove this
   special exception, which will cause the skeleton and the resulting
   Bison output files to be licensed under the GNU General Public
   License without this special exception.
   
   This special exception was added by the Free Software Foundation in
   version 2.2 of Bison.  */

/* C LALR(1) parser skeleton written by Richard Stallman, by
   simplifying the original so-called "semantic" parser.  */

/* All symbols defined below should begin with yy or YY, to avoid
   infringing on user name space.  This should be done even for local
   variables, as they might otherwise be expanded by user macros.
   There are some unavoidable exceptions within include files to
   define necessary library symbols; they are noted "INFRINGES ON
   USER NAME SPACE" below.  */

/* Identify Bison output.  */
#define YYBISON 1

/* Bison version.  */
#define YYBISON_VERSION "2.4.1"

/* Skeleton name.  */
#define YYSKELETON_NAME "yacc.c"

/* Pure parsers.  */
#define YYPURE 0

/* Push parsers.  */
#define YYPUSH 0

/* Pull parsers.  */
#define YYPULL 1

/* Using locations.  */
#define YYLSP_NEEDED 0



/* Copy the first part of user declarations.  */

/* Line 189 of yacc.c  */
#line 24 "parser.y"

#include <stdio.h>
#include <stdlib.h>
#include "config.h"

#ifdef _WIN32
/* Ugly hack: redefine alloca to malloc */
#define alloca malloc
#endif

#include "stdafx.h"

#include "parser.h"
#include "Scene.h"
#include "Element.h"
#include "EventIn.h"
#include "EventOut.h"
#include "ExposedField.h"
#include "Field.h"
#include "FieldValue.h"

#include "SFMFTypes.h"

#include "Node.h"
#include "NodeScript.h"
#include "NodeNurbsSurface.h"
#include "NodeNurbsTrimmedSurface.h"
#include "NodeNurbsCurve.h"
#include "NodeNurbsPositionInterpolator.h"
#include "NodeGeoCoordinate.h"
#include "NodeGeoElevationGrid.h"
#include "NodeGeoLocation.h"
#include "NodeGeoLOD.h"
#include "NodeGeoOrigin.h"
#include "NodeGeoPositionInterpolator.h"
#include "NodeGeoViewpoint.h"

#include "NodeComment.h"
#include "NodeExport.h"
#include "NodeImport.h"
#include "Proto.h"

#include "Stack.h"

extern void stopProto(void);

#define SYMB(id) (scene->getSymbol(id))
#define IS_OUTSIDE_PROTO "IS statement used outside PROTO"

#define BISON_MID_RULE_TYPE 1
#ifdef BISON_MID_RULE_TYPE
# define RET(type) $<type>$
#else
# define RET(type) $$
#endif

Scene *scene;

#ifdef HAVE_LIBZ 
 gzFile inputFile;
#else
 FILE *inputFile;
#endif
int inputFileSize;

int isInProtoLibrary = 0;

int lineno = 1;

Node *targetNode;
int targetField;

static Stack<Node *> nodeStack;
static Stack<Proto *> protoStack;
static int     defName = -1;
static int     currentType;
static NodeList commentNodeList;

static List<MyString> commentList;


static void    route(const MyString &srcNode, const MyString &srcField,
                     const MyString &dstNode, const MyString &dstField);
static Node   *addExport(const MyString &srcNode, const MyString &dstNode);
static Node   *addImport(const MyString &srcNode, const MyString &importedNode,
                         const MyString &dstNode);
                     
static Node   *newNode(const MyString &nodeType);

static int     checkField(Node *node, const MyString &fieldName);
static Field  *createField(int type, const MyString &name);
static void    setField(Node *node, int index, FieldValue *value);
static void    isField(Node *node, const MyString &fieldName, const MyString &isName);
static FieldValue *boolsToType(BoolArray *bools, int type);
static FieldValue *intsToType(IntArray *ints, int type);
static FieldValue *floatsToType(DoubleArray *floats, int type);
static FieldValue *stringToType(const char* string, int type);
static int fieldTypeToEnum(const char* str);
static DoubleArray *intsToFloats(IntArray *ints);
static DoubleArray *intsToDoubles(IntArray *ints);
static FieldValue *emptyMF(int type);
static FieldValue *emptyMFNodeOrNULL(int type);
static FieldValue *SillyDefaultValue(int type);
static MyString uniqName(const MyString name);
static MyString checkName(const MyString name);
static void repairURL(Node* node);
static void addCommentsToNode(Node* node);
static void addCommentsToNodeList(NodeList *nodelist);
static int addDynamicElement(Element *element);
static void illegalX3DV(void);
class nameTranslation {
public:
    MyString oldName;
    MyString newName;
    nameTranslation(MyString newN, MyString oldN)
       {
       newName = newN;
       oldName = oldN;
       }
};

Array<nameTranslation*> NameTranslation;

static bool x3d = false;

void setX3d(void) 
{
    x3d = true;
    scene->setX3dv();
} 

void setVrml(void) 
{
    x3d = false;
    scene->setVrml();
} 


/* Line 189 of yacc.c  */
#line 212 "y.tab.c"

/* Enabling traces.  */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif

/* Enabling verbose error messages.  */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 0
#endif

/* Enabling the token table.  */
#ifndef YYTOKEN_TABLE
# define YYTOKEN_TABLE 0
#endif


/* Tokens.  */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
   /* Put the tokens into the symbol table, so that GDB and other debuggers
      know about them.  */
   enum yytokentype {
     BRACKET_ON = 258,
     BRACKET_OFF = 259,
     WING_BRACKET_ON = 260,
     WING_BRACKET_OFF = 261,
     SCRIPT = 262,
     COMPOSED_SHADER = 263,
     PACKAGED_SHADER = 264,
     SHADER_PROGRAM = 265,
     EXPORT = 266,
     IMPORT = 267,
     AS = 268,
     ID = 269,
     ID_X3D = 270,
     STRING = 271,
     INT_NUM = 272,
     FLOAT_NUM = 273,
     DEF = 274,
     EXTERNPROTO = 275,
     FALSE_TOK = 276,
     IS = 277,
     NULL_TOK = 278,
     PROTO = 279,
     ROUTE = 280,
     TO = 281,
     TRUE_TOK = 282,
     USE = 283,
     EVENT_IN = 284,
     EVENT_OUT = 285,
     EXPOSED_FIELD = 286,
     INPUT_OUTPUT = 287,
     FIELD = 288,
     X3D = 289,
     PROFILE = 290,
     COMPONENT = 291,
     META = 292,
     VRML1 = 293
   };
#endif
/* Tokens.  */
#define BRACKET_ON 258
#define BRACKET_OFF 259
#define WING_BRACKET_ON 260
#define WING_BRACKET_OFF 261
#define SCRIPT 262
#define COMPOSED_SHADER 263
#define PACKAGED_SHADER 264
#define SHADER_PROGRAM 265
#define EXPORT 266
#define IMPORT 267
#define AS 268
#define ID 269
#define ID_X3D 270
#define STRING 271
#define INT_NUM 272
#define FLOAT_NUM 273
#define DEF 274
#define EXTERNPROTO 275
#define FALSE_TOK 276
#define IS 277
#define NULL_TOK 278
#define PROTO 279
#define ROUTE 280
#define TO 281
#define TRUE_TOK 282
#define USE 283
#define EVENT_IN 284
#define EVENT_OUT 285
#define EXPOSED_FIELD 286
#define INPUT_OUTPUT 287
#define FIELD 288
#define X3D 289
#define PROFILE 290
#define COMPONENT 291
#define META 292
#define VRML1 293




#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
{

/* Line 214 of yacc.c  */
#line 162 "parser.y"

    int                  int32;
    int                  id;
    Node                *node;
    NodeList            *nodeList;
    Element             *element;
    FieldValue          *value;
    float                sffloat;
    StringArray         *stringArray;
    BoolArray           *boolArray;
    IntArray            *intArray;
    DoubleArray         *doubleArray;



/* Line 214 of yacc.c  */
#line 340 "y.tab.c"
} YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
#endif


/* Copy the second part of user declarations.  */


/* Line 264 of yacc.c  */
#line 352 "y.tab.c"

#ifdef short
# undef short
#endif

#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif

#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#elif (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
typedef signed char yytype_int8;
#else
typedef short int yytype_int8;
#endif

#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short int yytype_uint16;
#endif

#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short int yytype_int16;
#endif

#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
#  define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
#  define YYSIZE_T size_t
# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
#  include <stddef.h> /* INFRINGES ON USER NAME SPACE */
#  define YYSIZE_T size_t
# else
#  define YYSIZE_T unsigned int
# endif
#endif

#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)

#ifndef YY_
# if YYENABLE_NLS
#  if ENABLE_NLS
#   include <libintl.h> /* INFRINGES ON USER NAME SPACE */
#   define YY_(msgid) dgettext ("bison-runtime", msgid)
#  endif
# endif
# ifndef YY_
#  define YY_(msgid) msgid
# endif
#endif

/* Suppress unused-variable warnings by "using" E.  */
#if ! defined lint || defined __GNUC__
# define YYUSE(e) ((void) (e))
#else
# define YYUSE(e) /* empty */
#endif

/* Identity function, used to suppress warnings about constant conditions.  */
#ifndef lint
# define YYID(n) (n)
#else
#if (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
static int
YYID (int yyi)
#else
static int
YYID (yyi)
    int yyi;
#endif
{
  return yyi;
}
#endif

#if ! defined yyoverflow || YYERROR_VERBOSE

/* The parser invokes alloca or malloc; define the necessary symbols.  */

# ifdef YYSTACK_USE_ALLOCA
#  if YYSTACK_USE_ALLOCA
#   ifdef __GNUC__
#    define YYSTACK_ALLOC __builtin_alloca
#   elif defined __BUILTIN_VA_ARG_INCR
#    include <alloca.h> /* INFRINGES ON USER NAME SPACE */
#   elif defined _AIX
#    define YYSTACK_ALLOC __alloca
#   elif defined _MSC_VER
#    include <malloc.h> /* INFRINGES ON USER NAME SPACE */
#    define alloca _alloca
#   else
#    define YYSTACK_ALLOC alloca
#    if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
#     include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
#     ifndef _STDLIB_H
#      define _STDLIB_H 1
#     endif
#    endif
#   endif
#  endif
# endif

# ifdef YYSTACK_ALLOC
   /* Pacify GCC's `empty if-body' warning.  */
#  define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
#  ifndef YYSTACK_ALLOC_MAXIMUM
    /* The OS might guarantee only one guard page at the bottom of the stack,
       and a page size can be as small as 4096 bytes.  So we cannot safely
       invoke alloca (N) if N exceeds 4096.  Use a slightly smaller number
       to allow for a few compiler-allocated temporary stack slots.  */
#   define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
#  endif
# else
#  define YYSTACK_ALLOC YYMALLOC
#  define YYSTACK_FREE YYFREE
#  ifndef YYSTACK_ALLOC_MAXIMUM
#   define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
#  endif
#  if (defined __cplusplus && ! defined _STDLIB_H \
       && ! ((defined YYMALLOC || defined malloc) \
	     && (defined YYFREE || defined free)))
#   include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
#   ifndef _STDLIB_H
#    define _STDLIB_H 1
#   endif
#  endif
#  ifndef YYMALLOC
#   define YYMALLOC malloc
#   if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
#   endif
#  endif
#  ifndef YYFREE
#   define YYFREE free
#   if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
void free (void *); /* INFRINGES ON USER NAME SPACE */
#   endif
#  endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */


#if (! defined yyoverflow \
     && (! defined __cplusplus \
	 || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))

/* A type that is properly aligned for any stack member.  */
union yyalloc
{
  yytype_int16 yyss_alloc;
  YYSTYPE yyvs_alloc;
};

/* The size of the maximum gap between one aligned stack and the next.  */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)

/* The size of an array large to enough to hold all stacks, each with
   N elements.  */
# define YYSTACK_BYTES(N) \
     ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
      + YYSTACK_GAP_MAXIMUM)

/* Copy COUNT objects from FROM to TO.  The source and destination do
   not overlap.  */
# ifndef YYCOPY
#  if defined __GNUC__ && 1 < __GNUC__
#   define YYCOPY(To, From, Count) \
      __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
#  else
#   define YYCOPY(To, From, Count)		\
      do					\
	{					\
	  YYSIZE_T yyi;				\
	  for (yyi = 0; yyi < (Count); yyi++)	\
	    (To)[yyi] = (From)[yyi];		\
	}					\
      while (YYID (0))
#  endif
# endif

/* Relocate STACK from its old location to the new one.  The
   local variables YYSIZE and YYSTACKSIZE give the old and new number of
   elements in the stack, and YYPTR gives the new location of the
   stack.  Advance YYPTR to a properly aligned location for the next
   stack.  */
# define YYSTACK_RELOCATE(Stack_alloc, Stack)				\
    do									\
      {									\
	YYSIZE_T yynewbytes;						\
	YYCOPY (&yyptr->Stack_alloc, Stack, yysize);			\
	Stack = &yyptr->Stack_alloc;					\
	yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
	yyptr += yynewbytes / sizeof (*yyptr);				\
      }									\
    while (YYID (0))

#endif

/* YYFINAL -- State number of the termination state.  */
#define YYFINAL  11
/* YYLAST -- Last index in YYTABLE.  */
#define YYLAST   357

/* YYNTOKENS -- Number of terminals.  */
#define YYNTOKENS  40
/* YYNNTS -- Number of nonterminals.  */
#define YYNNTS  59
/* YYNRULES -- Number of rules.  */
#define YYNRULES  125
/* YYNRULES -- Number of states.  */
#define YYNSTATES  213

/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX.  */
#define YYUNDEFTOK  2
#define YYMAXUTOK   293

#define YYTRANSLATE(YYX)						\
  ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)

/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX.  */
static const yytype_uint8 yytranslate[] =
{
       0,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,    39,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     1,     2,     3,     4,
       5,     6,     7,     8,     9,    10,    11,    12,    13,    14,
      15,    16,    17,    18,    19,    20,    21,    22,    23,    24,
      25,    26,    27,    28,    29,    30,    31,    32,    33,    34,
      35,    36,    37,    38
};

#if YYDEBUG
/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
   YYRHS.  */
static const yytype_uint16 yyprhs[] =
{
       0,     0,     3,     5,     8,    11,    14,    17,    19,    21,
      23,    25,    27,    29,    31,    32,    37,    40,    42,    44,
      47,    49,    50,    60,    64,    66,    69,    71,    72,    77,
      78,    83,    87,    91,    94,    97,    99,   100,   106,   107,
     115,   118,   120,   124,   128,   132,   136,   140,   149,   152,
     157,   162,   169,   171,   172,   173,   179,   180,   186,   189,
     191,   193,   195,   197,   199,   201,   204,   206,   208,   210,
     216,   222,   226,   230,   233,   237,   239,   241,   243,   245,
     247,   249,   251,   253,   255,   259,   261,   263,   267,   269,
     271,   273,   277,   281,   285,   288,   291,   293,   295,   297,
     300,   302,   305,   308,   311,   313,   315,   319,   321,   324,
     326,   329,   331,   333,   335,   338,   342,   346,   351,   353,
     356,   358,   361,   364,   366,   369
};

/* YYRHS -- A `-1'-separated list of the rules' RHS.  */
static const yytype_int8 yyrhs[] =
{
      41,     0,    -1,    42,    -1,    92,    42,    -1,    38,    67,
      -1,     1,    67,    -1,    42,    43,    -1,    67,    -1,    44,
      -1,    46,    -1,    63,    -1,    65,    -1,    64,    -1,    68,
      -1,    -1,    19,    78,    45,    68,    -1,    28,    78,    -1,
      48,    -1,    59,    -1,    47,    46,    -1,    67,    -1,    -1,
      24,    79,    49,     3,    51,     4,     5,    50,     6,    -1,
      47,    44,    42,    -1,    67,    -1,    51,    57,    -1,    67,
      -1,    -1,    33,    80,    53,    91,    -1,    -1,    32,    80,
      55,    91,    -1,    29,    80,    91,    -1,    30,    80,    91,
      -1,    52,    83,    -1,    54,    83,    -1,    56,    -1,    -1,
      31,    80,    58,    91,    83,    -1,    -1,    20,    79,    60,
       3,    61,     4,    66,    -1,    61,    62,    -1,    67,    -1,
      29,    80,    91,    -1,    30,    80,    91,    -1,    33,    80,
      91,    -1,    31,    80,    91,    -1,    32,    80,    91,    -1,
      25,    78,    39,    91,    26,    78,    39,    91,    -1,    11,
      78,    -1,    11,    78,    13,    78,    -1,    12,    78,    39,
      91,    -1,    12,    78,    39,    91,    13,    78,    -1,    88,
      -1,    -1,    -1,    79,     5,    69,    71,     6,    -1,    -1,
      72,     5,    70,    74,     6,    -1,    71,    76,    -1,    67,
      -1,     7,    -1,    73,    -1,     8,    -1,    10,    -1,     9,
      -1,    74,    75,    -1,    67,    -1,    76,    -1,    56,    -1,
      29,    80,    91,    22,    91,    -1,    30,    80,    91,    22,
      91,    -1,    52,    22,    91,    -1,    54,    22,    91,    -1,
      77,    83,    -1,    91,    22,    91,    -1,    63,    -1,    46,
      -1,    91,    -1,    91,    -1,    91,    -1,    91,    -1,    91,
      -1,    14,    -1,    16,    -1,     3,    89,     4,    -1,    44,
      -1,    23,    -1,     3,    90,     4,    -1,    86,    -1,    87,
      -1,    84,    -1,     3,    86,     4,    -1,     3,    87,     4,
      -1,     3,    84,     4,    -1,     3,     4,    -1,    84,    85,
      -1,    85,    -1,    27,    -1,    21,    -1,    86,    17,    -1,
      17,    -1,    87,    18,    -1,    87,    17,    -1,    86,    18,
      -1,    18,    -1,    16,    -1,     3,    89,     4,    -1,    16,
      -1,    89,    16,    -1,    44,    -1,    90,    44,    -1,    15,
      -1,    14,    -1,    93,    -1,    93,    94,    -1,    93,    94,
      95,    -1,    93,    94,    97,    -1,    93,    94,    95,    97,
      -1,    34,    -1,    35,    81,    -1,    96,    -1,    96,    95,
      -1,    36,    82,    -1,    98,    -1,    98,    97,    -1,    37,
      16,    16,    -1
};

/* YYRLINE[YYN] -- source line where rule number YYN was defined.  */
static const yytype_uint16 yyrline[] =
{
       0,   206,   206,   211,   216,   217,   220,   225,   228,   229,
     230,   231,   232,   235,   236,   236,   239,   242,   243,   246,
     247,   250,   250,   273,   275,   278,   285,   288,   288,   292,
     292,   296,   297,   298,   301,   307,   308,   308,   313,   312,
     328,   335,   338,   339,   340,   344,   348,   354,   361,   363,
     367,   369,   373,   375,   378,   378,   392,   392,   409,   410,
     413,   414,   417,   418,   419,   423,   424,   427,   428,   429,
     436,   444,   451,   460,   461,   464,   465,   469,   474,   477,
     480,   484,   488,   492,   495,   497,   498,   499,   501,   502,
     503,   504,   505,   506,   507,   511,   515,   522,   523,   526,
     527,   530,   531,   532,   535,   538,   539,   543,   545,   548,
     553,   559,   560,   571,   572,   573,   574,   575,   578,   581,
     584,   585,   588,   590,   591,   594
};
#endif

#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
   First, the terminals, then, starting at YYNTOKENS, nonterminals.  */
static const char *const yytname[] =
{
  "$end", "error", "$undefined", "BRACKET_ON", "BRACKET_OFF",
  "WING_BRACKET_ON", "WING_BRACKET_OFF", "SCRIPT", "COMPOSED_SHADER",
  "PACKAGED_SHADER", "SHADER_PROGRAM", "EXPORT", "IMPORT", "AS", "ID",
  "ID_X3D", "STRING", "INT_NUM", "FLOAT_NUM", "DEF", "EXTERNPROTO",
  "FALSE_TOK", "IS", "NULL_TOK", "PROTO", "ROUTE", "TO", "TRUE_TOK", "USE",
  "EVENT_IN", "EVENT_OUT", "EXPOSED_FIELD", "INPUT_OUTPUT", "FIELD", "X3D",
  "PROFILE", "COMPONENT", "META", "VRML1", "'.'", "$accept", "vrmlScene",
  "statements", "statement", "nodeStatement", "$@1", "protoStatement",
  "protoStatements", "proto", "$@2", "protoBody", "interfaceDeclarations",
  "fieldDeclaration", "$@3", "exposedFieldDeclaration", "$@4",
  "restrictedInterfaceDeclaration", "interfaceDeclaration", "$@5",
  "externproto", "$@6", "externInterfaceDeclarations",
  "externInterfaceDeclaration", "routeStatement", "exportStatement",
  "importStatement", "URLList", "empty", "node", "@7", "@8", "nodeBody",
  "dynamicNode", "shaderNode", "scriptBody", "scriptBodyElement",
  "nodeBodyElement", "fieldName", "nodeName", "nodeType", "fieldType",
  "profileId", "componentId", "fieldValue", "bools", "sfboolValue", "ints",
  "floats", "mfstringValue", "strings", "nodeStatements", "id",
  "x3dHeaderStatement", "headerStatement", "profileStatement",
  "componentStatements", "componentStatement", "metaStatements",
  "metaStatement", 0
};
#endif

# ifdef YYPRINT
/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
   token YYLEX-NUM.  */
static const yytype_uint16 yytoknum[] =
{
       0,   256,   257,   258,   259,   260,   261,   262,   263,   264,
     265,   266,   267,   268,   269,   270,   271,   272,   273,   274,
     275,   276,   277,   278,   279,   280,   281,   282,   283,   284,
     285,   286,   287,   288,   289,   290,   291,   292,   293,    46
};
# endif

/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
static const yytype_uint8 yyr1[] =
{
       0,    40,    41,    41,    41,    41,    42,    42,    43,    43,
      43,    43,    43,    44,    45,    44,    44,    46,    46,    47,
      47,    49,    48,    50,    50,    51,    51,    53,    52,    55,
      54,    56,    56,    56,    56,    57,    58,    57,    60,    59,
      61,    61,    62,    62,    62,    62,    62,    63,    64,    64,
      65,    65,    66,    67,    69,    68,    70,    68,    71,    71,
      72,    72,    73,    73,    73,    74,    74,    75,    75,    75,
      75,    75,    75,    76,    76,    76,    76,    77,    78,    79,
      80,    81,    82,    83,    83,    83,    83,    83,    83,    83,
      83,    83,    83,    83,    83,    84,    84,    85,    85,    86,
      86,    87,    87,    87,    87,    88,    88,    89,    89,    90,
      90,    91,    91,    92,    92,    92,    92,    92,    93,    94,
      95,    95,    96,    97,    97,    98
};

/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN.  */
static const yytype_uint8 yyr2[] =
{
       0,     2,     1,     2,     2,     2,     2,     1,     1,     1,
       1,     1,     1,     1,     0,     4,     2,     1,     1,     2,
       1,     0,     9,     3,     1,     2,     1,     0,     4,     0,
       4,     3,     3,     2,     2,     1,     0,     5,     0,     7,
       2,     1,     3,     3,     3,     3,     3,     8,     2,     4,
       4,     6,     1,     0,     0,     5,     0,     5,     2,     1,
       1,     1,     1,     1,     1,     2,     1,     1,     1,     5,
       5,     3,     3,     2,     3,     1,     1,     1,     1,     1,
       1,     1,     1,     1,     3,     1,     1,     3,     1,     1,
       1,     3,     3,     3,     2,     2,     1,     1,     1,     2,
       1,     2,     2,     2,     1,     1,     3,     1,     2,     1,
       2,     1,     1,     1,     2,     3,     3,     4,     1,     2,
       1,     2,     2,     1,     2,     3
};

/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
   STATE-NUM when YYTABLE doesn't specify something else to do.  Zero
   means the default is an error.  */
static const yytype_uint8 yydefact[] =
{
       0,    53,   118,    53,     0,     2,     7,    53,   113,     5,
       4,     1,    60,    62,    64,    63,     0,     0,   112,   111,
       0,     0,     0,     0,     0,     6,     8,     9,    17,    18,
      10,    12,    11,    13,     0,    61,     0,    79,     3,     0,
     114,    48,    78,     0,    14,    38,    21,     0,    16,    56,
      54,   119,    81,     0,     0,   115,   120,   116,   123,     0,
       0,     0,     0,     0,     0,    53,    53,    82,   122,     0,
     117,   121,   124,    49,    50,    15,    53,    53,     0,    66,
       0,    59,     0,   125,     0,     0,    41,     0,    26,     0,
      57,     0,     0,     0,     0,    76,     0,     0,    68,    75,
      65,    67,     0,    77,    55,    58,    51,     0,     0,     0,
       0,     0,     0,    40,     0,     0,     0,     0,     0,     0,
      35,    25,     0,     0,    80,     0,    29,    27,     0,    83,
     100,   104,    98,     0,    86,    97,    85,    33,    90,    96,
      88,    89,     0,    34,    73,     0,     0,   105,    39,    52,
       0,     0,     0,     0,     0,    53,     0,     0,    36,     0,
      31,    32,     0,     0,    94,   107,   109,     0,     0,     0,
       0,     0,    71,    95,    99,   103,   102,   101,    72,    74,
       0,    42,    43,    45,    46,    44,     0,     0,    20,    31,
      32,     0,    47,     0,     0,    30,    28,    93,    91,    92,
      84,   108,    87,   110,   106,    53,    19,    22,     0,    69,
      70,    23,    37
};

/* YYDEFGOTO[NTERM-NUM].  */
static const yytype_int16 yydefgoto[] =
{
      -1,     4,     5,    25,   136,    61,    27,   186,    28,    63,
     187,    87,    96,   163,    97,   162,    98,   121,   191,    29,
      62,    85,   113,    30,    31,    32,   148,     6,    33,    66,
      65,    82,    34,    35,    80,   100,   101,   102,    41,    36,
     123,    51,    68,   137,   138,   139,   140,   141,   149,   170,
     171,    37,     7,     8,    40,    55,    56,    57,    58
};

/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
   STATE-NUM.  */
#define YYPACT_NINF -134
static const yytype_int16 yypact[] =
{
     150,  -134,  -134,  -134,    48,   307,  -134,  -134,   -21,  -134,
    -134,  -134,  -134,  -134,  -134,  -134,    69,    69,  -134,  -134,
      69,    69,    69,    69,    69,  -134,  -134,  -134,  -134,  -134,
    -134,  -134,  -134,  -134,    17,  -134,    66,  -134,   307,    69,
      50,    60,  -134,    37,  -134,  -134,  -134,    51,  -134,  -134,
    -134,  -134,  -134,    77,    84,    68,    74,  -134,    68,    69,
      69,    49,    82,   109,    69,  -134,  -134,  -134,  -134,    97,
    -134,  -134,  -134,  -134,   103,  -134,  -134,  -134,    95,  -134,
     100,  -134,   327,  -134,    69,    11,  -134,    22,  -134,    69,
    -134,    69,    69,    69,    69,  -134,   186,   208,  -134,  -134,
    -134,  -134,   230,   104,  -134,  -134,  -134,    46,    69,    69,
      69,    69,    69,  -134,   117,    69,    69,    69,   230,   230,
    -134,  -134,    88,    69,  -134,    69,  -134,  -134,   276,  -134,
    -134,  -134,  -134,    69,  -134,  -134,  -134,  -134,    -3,  -134,
      13,    71,    69,  -134,  -134,    69,   118,  -134,  -134,  -134,
      69,    69,    69,    69,    69,  -134,    69,    69,  -134,    69,
     113,   119,    69,    69,  -134,  -134,  -134,     0,    19,    43,
       4,   292,  -134,  -134,  -134,  -134,  -134,  -134,  -134,  -134,
      12,  -134,  -134,  -134,  -134,  -134,   329,   138,   140,  -134,
    -134,    69,  -134,    69,    69,  -134,  -134,  -134,  -134,  -134,
    -134,  -134,  -134,  -134,  -134,  -134,  -134,  -134,   230,  -134,
    -134,   307,  -134
};

/* YYPGOTO[NTERM-NUM].  */
static const yytype_int16 yypgoto[] =
{
    -134,  -134,    -6,  -134,    -5,  -134,   -69,  -134,  -134,  -134,
    -134,  -134,    65,  -134,    67,  -134,    76,  -134,  -134,  -134,
    -134,  -134,  -134,   -15,  -134,  -134,  -134,    16,    92,  -134,
    -134,  -134,  -134,  -134,  -134,  -134,    73,  -134,    15,    86,
     162,  -134,  -134,   -90,    28,  -133,    39,    40,  -134,     1,
    -134,   -14,  -134,  -134,  -134,   116,  -134,    14,  -134
};

/* YYTABLE[YYPACT[STATE-NUM]].  What to do in state STATE-NUM.  If
   positive, shift that token.  If negative, reduce the rule which
   number is the opposite.  If zero, do what YYDEFACT says.
   If YYTABLE_NINF, syntax error.  */
#define YYTABLE_NINF -54
static const yytype_int16 yytable[] =
{
      26,    38,    42,    42,   197,   173,    42,   143,   200,    42,
      42,    95,   144,    95,    39,   107,   204,     9,   132,    10,
     201,   132,    49,   198,   135,    52,   114,   135,   201,   143,
     174,   175,    43,    26,   173,    44,   174,   175,    47,    48,
     108,   109,   110,   111,   112,    42,    74,   199,    11,   146,
      78,   115,   116,   117,    93,    94,    12,    13,    14,    15,
     176,   177,   147,    18,    19,    99,   103,    99,   103,    70,
      42,    50,    72,    59,    73,    42,    60,   124,   124,   124,
     124,    79,    81,    18,    19,    76,    53,    54,   176,   177,
      64,    67,    86,    88,   124,   124,   124,   124,   124,   106,
      69,   124,   124,   124,   122,    54,    90,    45,    46,   160,
      53,   161,    77,    83,    18,    19,    84,   206,   212,   172,
      21,    89,   155,   166,    22,    23,   145,   159,   178,    91,
      92,   179,    93,    94,   165,   193,   181,   182,   183,   184,
     185,   194,   189,   190,   207,   192,   -24,   180,   195,   196,
     -53,     1,   118,    75,   119,   105,   167,   -53,   -53,   -53,
     -53,   -53,   -53,   120,   -53,   -53,   203,   168,   169,   -53,
     -53,   188,    71,     0,   -53,   -53,     0,   208,   -53,   209,
     210,   205,     0,     0,     2,     0,     0,     0,     3,   128,
       0,     0,     0,    12,    13,    14,    15,     0,     0,   211,
      18,    19,   129,   130,   131,    20,    26,   132,   133,   134,
       0,   128,     0,   135,    24,    12,    13,    14,    15,     0,
       0,     0,    18,    19,   129,   130,   131,    20,     0,   132,
     142,   134,     0,   128,     0,   135,    24,    12,    13,    14,
      15,     0,     0,     0,    18,    19,   129,   130,   131,    20,
       0,   132,     0,   134,   125,   126,   127,   135,    24,     0,
       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
     150,   151,   152,   153,   154,     0,     0,   156,   157,   158,
     164,     0,     0,    12,    13,    14,    15,     0,     0,     0,
      18,    19,   165,   130,   131,    20,   202,   132,     0,    12,
      13,    14,    15,   135,    24,     0,    18,    19,     0,     0,
       0,    20,     0,     0,    12,    13,    14,    15,    16,    17,
      24,    18,    19,     0,     0,     0,    20,    21,     0,     0,
       0,    22,    23,   104,     0,    24,    12,    13,    14,    15,
       0,    18,    19,    18,    19,     0,     0,    21,    20,    21,
       0,    22,    23,    22,     0,     0,     0,    24
};

static const yytype_int16 yycheck[] =
{
       5,     7,    16,    17,     4,   138,    20,    97,     4,    23,
      24,    80,   102,    82,    35,     4,     4,     1,    21,     3,
      16,    21,     5,     4,    27,    39,     4,    27,    16,   119,
      17,    18,    17,    38,   167,    20,    17,    18,    23,    24,
      29,    30,    31,    32,    33,    59,    60,     4,     0,     3,
      64,    29,    30,    31,    32,    33,     7,     8,     9,    10,
      17,    18,    16,    14,    15,    80,    80,    82,    82,    55,
      84,     5,    58,    13,    59,    89,    39,    91,    92,    93,
      94,    65,    66,    14,    15,     3,    36,    37,    17,    18,
      39,    14,    76,    77,   108,   109,   110,   111,   112,    84,
      16,   115,   116,   117,    89,    37,     6,    21,    22,   123,
      36,   125,     3,    16,    14,    15,    13,   186,   208,   133,
      20,    26,     5,   128,    24,    25,    22,    39,   142,    29,
      30,   145,    32,    33,    16,    22,   150,   151,   152,   153,
     154,    22,   156,   157,     6,   159,     6,   146,   162,   163,
       0,     1,    87,    61,    87,    82,   128,     7,     8,     9,
      10,    11,    12,    87,    14,    15,   171,   128,   128,    19,
      20,   155,    56,    -1,    24,    25,    -1,   191,    28,   193,
     194,   186,    -1,    -1,    34,    -1,    -1,    -1,    38,     3,
      -1,    -1,    -1,     7,     8,     9,    10,    -1,    -1,   205,
      14,    15,    16,    17,    18,    19,   211,    21,    22,    23,
      -1,     3,    -1,    27,    28,     7,     8,     9,    10,    -1,
      -1,    -1,    14,    15,    16,    17,    18,    19,    -1,    21,
      22,    23,    -1,     3,    -1,    27,    28,     7,     8,     9,
      10,    -1,    -1,    -1,    14,    15,    16,    17,    18,    19,
      -1,    21,    -1,    23,    92,    93,    94,    27,    28,    -1,
      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
     108,   109,   110,   111,   112,    -1,    -1,   115,   116,   117,
       4,    -1,    -1,     7,     8,     9,    10,    -1,    -1,    -1,
      14,    15,    16,    17,    18,    19,     4,    21,    -1,     7,
       8,     9,    10,    27,    28,    -1,    14,    15,    -1,    -1,
      -1,    19,    -1,    -1,     7,     8,     9,    10,    11,    12,
      28,    14,    15,    -1,    -1,    -1,    19,    20,    -1,    -1,
      -1,    24,    25,     6,    -1,    28,     7,     8,     9,    10,
      -1,    14,    15,    14,    15,    -1,    -1,    20,    19,    20,
      -1,    24,    25,    24,    -1,    -1,    -1,    28
};

/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
   symbol of state STATE-NUM.  */
static const yytype_uint8 yystos[] =
{
       0,     1,    34,    38,    41,    42,    67,    92,    93,    67,
      67,     0,     7,     8,     9,    10,    11,    12,    14,    15,
      19,    20,    24,    25,    28,    43,    44,    46,    48,    59,
      63,    64,    65,    68,    72,    73,    79,    91,    42,    35,
      94,    78,    91,    78,    78,    79,    79,    78,    78,     5,
       5,    81,    91,    36,    37,    95,    96,    97,    98,    13,
      39,    45,    60,    49,    39,    70,    69,    14,    82,    16,
      97,    95,    97,    78,    91,    68,     3,     3,    91,    67,
      74,    67,    71,    16,    13,    61,    67,    51,    67,    26,
       6,    29,    30,    32,    33,    46,    52,    54,    56,    63,
      75,    76,    77,    91,     6,    76,    78,     4,    29,    30,
      31,    32,    33,    62,     4,    29,    30,    31,    52,    54,
      56,    57,    78,    80,    91,    80,    80,    80,     3,    16,
      17,    18,    21,    22,    23,    27,    44,    83,    84,    85,
      86,    87,    22,    83,    83,    22,     3,    16,    66,    88,
      80,    80,    80,    80,    80,     5,    80,    80,    80,    39,
      91,    91,    55,    53,     4,    16,    44,    84,    86,    87,
      89,    90,    91,    85,    17,    18,    17,    18,    91,    91,
      89,    91,    91,    91,    91,    91,    47,    50,    67,    91,
      91,    58,    91,    22,    22,    91,    91,     4,     4,     4,
       4,    16,     4,    44,     4,    44,    46,     6,    91,    91,
      91,    42,    83
};

#define yyerrok		(yyerrstatus = 0)
#define yyclearin	(yychar = YYEMPTY)
#define YYEMPTY		(-2)
#define YYEOF		0

#define YYACCEPT	goto yyacceptlab
#define YYABORT		goto yyabortlab
#define YYERROR		goto yyerrorlab


/* Like YYERROR except do call yyerror.  This remains here temporarily
   to ease the transition to the new meaning of YYERROR, for GCC.
   Once GCC version 2 has supplanted version 1, this can go.  */

#define YYFAIL		goto yyerrlab

#define YYRECOVERING()  (!!yyerrstatus)

#define YYBACKUP(Token, Value)					\
do								\
  if (yychar == YYEMPTY && yylen == 1)				\
    {								\
      yychar = (Token);						\
      yylval = (Value);						\
      yytoken = YYTRANSLATE (yychar);				\
      YYPOPSTACK (1);						\
      goto yybackup;						\
    }								\
  else								\
    {								\
      yyerror (YY_("syntax error: cannot back up")); \
      YYERROR;							\
    }								\
while (YYID (0))


#define YYTERROR	1
#define YYERRCODE	256


/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
   If N is 0, then set CURRENT to the empty location which ends
   the previous symbol: RHS[0] (always defined).  */

#define YYRHSLOC(Rhs, K) ((Rhs)[K])
#ifndef YYLLOC_DEFAULT
# define YYLLOC_DEFAULT(Current, Rhs, N)				\
    do									\
      if (YYID (N))                                                    \
	{								\
	  (Current).first_line   = YYRHSLOC (Rhs, 1).first_line;	\
	  (Current).first_column = YYRHSLOC (Rhs, 1).first_column;	\
	  (Current).last_line    = YYRHSLOC (Rhs, N).last_line;		\
	  (Current).last_column  = YYRHSLOC (Rhs, N).last_column;	\
	}								\
      else								\
	{								\
	  (Current).first_line   = (Current).last_line   =		\
	    YYRHSLOC (Rhs, 0).last_line;				\
	  (Current).first_column = (Current).last_column =		\
	    YYRHSLOC (Rhs, 0).last_column;				\
	}								\
    while (YYID (0))
#endif


/* YY_LOCATION_PRINT -- Print the location on the stream.
   This macro was not mandated originally: define only if we know
   we won't break user code: when these are the locations we know.  */

#ifndef YY_LOCATION_PRINT
# if YYLTYPE_IS_TRIVIAL
#  define YY_LOCATION_PRINT(File, Loc)			\
     fprintf (File, "%d.%d-%d.%d",			\
	      (Loc).first_line, (Loc).first_column,	\
	      (Loc).last_line,  (Loc).last_column)
# else
#  define YY_LOCATION_PRINT(File, Loc) ((void) 0)
# endif
#endif


/* YYLEX -- calling `yylex' with the right arguments.  */

#ifdef YYLEX_PARAM
# define YYLEX yylex (YYLEX_PARAM)
#else
# define YYLEX yylex ()
#endif

/* Enable debugging if requested.  */
#if YYDEBUG

# ifndef YYFPRINTF
#  include <stdio.h> /* INFRINGES ON USER NAME SPACE */
#  define YYFPRINTF fprintf
# endif

# define YYDPRINTF(Args)			\
do {						\
  if (yydebug)					\
    YYFPRINTF Args;				\
} while (YYID (0))

# define YY_SYMBOL_PRINT(Title, Type, Value, Location)			  \
do {									  \
  if (yydebug)								  \
    {									  \
      YYFPRINTF (stderr, "%s ", Title);					  \
      yy_symbol_print (stderr,						  \
		  Type, Value); \
      YYFPRINTF (stderr, "\n");						  \
    }									  \
} while (YYID (0))


/*--------------------------------.
| Print this symbol on YYOUTPUT.  |
`--------------------------------*/

/*ARGSUSED*/
#if (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
#else
static void
yy_symbol_value_print (yyoutput, yytype, yyvaluep)
    FILE *yyoutput;
    int yytype;
    YYSTYPE const * const yyvaluep;
#endif
{
  if (!yyvaluep)
    return;
# ifdef YYPRINT
  if (yytype < YYNTOKENS)
    YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
# else
  YYUSE (yyoutput);
# endif
  switch (yytype)
    {
      default:
	break;
    }
}


/*--------------------------------.
| Print this symbol on YYOUTPUT.  |
`--------------------------------*/

#if (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
#else
static void
yy_symbol_print (yyoutput, yytype, yyvaluep)
    FILE *yyoutput;
    int yytype;
    YYSTYPE const * const yyvaluep;
#endif
{
  if (yytype < YYNTOKENS)
    YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
  else
    YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);

  yy_symbol_value_print (yyoutput, yytype, yyvaluep);
  YYFPRINTF (yyoutput, ")");
}

/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included).                                                   |
`------------------------------------------------------------------*/

#if (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
static void
yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
#else
static void
yy_stack_print (yybottom, yytop)
    yytype_int16 *yybottom;
    yytype_int16 *yytop;
#endif
{
  YYFPRINTF (stderr, "Stack now");
  for (; yybottom <= yytop; yybottom++)
    {
      int yybot = *yybottom;
      YYFPRINTF (stderr, " %d", yybot);
    }
  YYFPRINTF (stderr, "\n");
}

# define YY_STACK_PRINT(Bottom, Top)				\
do {								\
  if (yydebug)							\
    yy_stack_print ((Bottom), (Top));				\
} while (YYID (0))


/*------------------------------------------------.
| Report that the YYRULE is going to be reduced.  |
`------------------------------------------------*/

#if (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
static void
yy_reduce_print (YYSTYPE *yyvsp, int yyrule)
#else
static void
yy_reduce_print (yyvsp, yyrule)
    YYSTYPE *yyvsp;
    int yyrule;
#endif
{
  int yynrhs = yyr2[yyrule];
  int yyi;
  unsigned long int yylno = yyrline[yyrule];
  YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
	     yyrule - 1, yylno);
  /* The symbols being reduced.  */
  for (yyi = 0; yyi < yynrhs; yyi++)
    {
      YYFPRINTF (stderr, "   $%d = ", yyi + 1);
      yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
		       &(yyvsp[(yyi + 1) - (yynrhs)])
		       		       );
      YYFPRINTF (stderr, "\n");
    }
}

# define YY_REDUCE_PRINT(Rule)		\
do {					\
  if (yydebug)				\
    yy_reduce_print (yyvsp, Rule); \
} while (YYID (0))

/* Nonzero means print parse trace.  It is left uninitialized so that
   multiple parsers can coexist.  */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */


/* YYINITDEPTH -- initial size of the parser's stacks.  */
#ifndef	YYINITDEPTH
# define YYINITDEPTH 200
#endif

/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
   if the built-in stack extension method is used).

   Do not make this value too large; the results are undefined if
   YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
   evaluated with infinite-precision integer arithmetic.  */

#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif



#if YYERROR_VERBOSE

# ifndef yystrlen
#  if defined __GLIBC__ && defined _STRING_H
#   define yystrlen strlen
#  else
/* Return the length of YYSTR.  */
#if (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
static YYSIZE_T
yystrlen (const char *yystr)
#else
static YYSIZE_T
yystrlen (yystr)
    const char *yystr;
#endif
{
  YYSIZE_T yylen;
  for (yylen = 0; yystr[yylen]; yylen++)
    continue;
  return yylen;
}
#  endif
# endif

# ifndef yystpcpy
#  if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
#   define yystpcpy stpcpy
#  else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
   YYDEST.  */
#if (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
static char *
yystpcpy (char *yydest, const char *yysrc)
#else
static char *
yystpcpy (yydest, yysrc)
    char *yydest;
    const char *yysrc;
#endif
{
  char *yyd = yydest;
  const char *yys = yysrc;

  while ((*yyd++ = *yys++) != '\0')
    continue;

  return yyd - 1;
}
#  endif
# endif

# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
   quotes and backslashes, so that it's suitable for yyerror.  The
   heuristic is that double-quoting is unnecessary unless the string
   contains an apostrophe, a comma, or backslash (other than
   backslash-backslash).  YYSTR is taken from yytname.  If YYRES is
   null, do not copy; instead, return the length of what the result
   would have been.  */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
  if (*yystr == '"')
    {
      YYSIZE_T yyn = 0;
      char const *yyp = yystr;

      for (;;)
	switch (*++yyp)
	  {
	  case '\'':
	  case ',':
	    goto do_not_strip_quotes;

	  case '\\':
	    if (*++yyp != '\\')
	      goto do_not_strip_quotes;
	    /* Fall through.  */
	  default:
	    if (yyres)
	      yyres[yyn] = *yyp;
	    yyn++;
	    break;

	  case '"':
	    if (yyres)
	      yyres[yyn] = '\0';
	    return yyn;
	  }
    do_not_strip_quotes: ;
    }

  if (! yyres)
    return yystrlen (yystr);

  return yystpcpy (yyres, yystr) - yyres;
}
# endif

/* Copy into YYRESULT an error message about the unexpected token
   YYCHAR while in state YYSTATE.  Return the number of bytes copied,
   including the terminating null byte.  If YYRESULT is null, do not
   copy anything; just return the number of bytes that would be
   copied.  As a special case, return 0 if an ordinary "syntax error"
   message will do.  Return YYSIZE_MAXIMUM if overflow occurs during
   size calculation.  */
static YYSIZE_T
yysyntax_error (char *yyresult, int yystate, int yychar)
{
  int yyn = yypact[yystate];

  if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
    return 0;
  else
    {
      int yytype = YYTRANSLATE (yychar);
      YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
      YYSIZE_T yysize = yysize0;
      YYSIZE_T yysize1;
      int yysize_overflow = 0;
      enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
      char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
      int yyx;

# if 0
      /* This is so xgettext sees the translatable formats that are
	 constructed on the fly.  */
      YY_("syntax error, unexpected %s");
      YY_("syntax error, unexpected %s, expecting %s");
      YY_("syntax error, unexpected %s, expecting %s or %s");
      YY_("syntax error, unexpected %s, expecting %s or %s or %s");
      YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
# endif
      char *yyfmt;
      char const *yyf;
      static char const yyunexpected[] = "syntax error, unexpected %s";
      static char const yyexpecting[] = ", expecting %s";
      static char const yyor[] = " or %s";
      char yyformat[sizeof yyunexpected
		    + sizeof yyexpecting - 1
		    + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
		       * (sizeof yyor - 1))];
      char const *yyprefix = yyexpecting;

      /* Start YYX at -YYN if negative to avoid negative indexes in
	 YYCHECK.  */
      int yyxbegin = yyn < 0 ? -yyn : 0;

      /* Stay within bounds of both yycheck and yytname.  */
      int yychecklim = YYLAST - yyn + 1;
      int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
      int yycount = 1;

      yyarg[0] = yytname[yytype];
      yyfmt = yystpcpy (yyformat, yyunexpected);

      for (yyx = yyxbegin; yyx < yyxend; ++yyx)
	if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
	  {
	    if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
	      {
		yycount = 1;
		yysize = yysize0;
		yyformat[sizeof yyunexpected - 1] = '\0';
		break;
	      }
	    yyarg[yycount++] = yytname[yyx];
	    yysize1 = yysize + yytnamerr (0, yytname[yyx]);
	    yysize_overflow |= (yysize1 < yysize);
	    yysize = yysize1;
	    yyfmt = yystpcpy (yyfmt, yyprefix);
	    yyprefix = yyor;
	  }

      yyf = YY_(yyformat);
      yysize1 = yysize + yystrlen (yyf);
      yysize_overflow |= (yysize1 < yysize);
      yysize = yysize1;

      if (yysize_overflow)
	return YYSIZE_MAXIMUM;

      if (yyresult)
	{
	  /* Avoid sprintf, as that infringes on the user's name space.
	     Don't have undefined behavior even if the translation
	     produced a string with the wrong number of "%s"s.  */
	  char *yyp = yyresult;
	  int yyi = 0;
	  while ((*yyp = *yyf) != '\0')
	    {
	      if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
		{
		  yyp += yytnamerr (yyp, yyarg[yyi++]);
		  yyf += 2;
		}
	      else
		{
		  yyp++;
		  yyf++;
		}
	    }
	}
      return yysize;
    }
}
#endif /* YYERROR_VERBOSE */


/*-----------------------------------------------.
| Release the memory associated to this symbol.  |
`-----------------------------------------------*/

/*ARGSUSED*/
#if (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
#else
static void
yydestruct (yymsg, yytype, yyvaluep)
    const char *yymsg;
    int yytype;
    YYSTYPE *yyvaluep;
#endif
{
  YYUSE (yyvaluep);

  if (!yymsg)
    yymsg = "Deleting";
  YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);

  switch (yytype)
    {

      default:
	break;
    }
}

/* Prevent warnings from -Wmissing-prototypes.  */
#ifdef YYPARSE_PARAM
#if defined __STDC__ || defined __cplusplus
int yyparse (void *YYPARSE_PARAM);
#else
int yyparse ();
#endif
#else /* ! YYPARSE_PARAM */
#if defined __STDC__ || defined __cplusplus
int yyparse (void);
#else
int yyparse ();
#endif
#endif /* ! YYPARSE_PARAM */


/* The lookahead symbol.  */
int yychar;

/* The semantic value of the lookahead symbol.  */
YYSTYPE yylval;

/* Number of syntax errors so far.  */
int yynerrs;



/*-------------------------.
| yyparse or yypush_parse.  |
`-------------------------*/

#ifdef YYPARSE_PARAM
#if (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
int
yyparse (void *YYPARSE_PARAM)
#else
int
yyparse (YYPARSE_PARAM)
    void *YYPARSE_PARAM;
#endif
#else /* ! YYPARSE_PARAM */
#if (defined __STDC__ || defined __C99__FUNC__ \
     || defined __cplusplus || defined _MSC_VER)
int
yyparse (void)
#else
int
yyparse ()

#endif
#endif
{


    int yystate;
    /* Number of tokens to shift before error messages enabled.  */
    int yyerrstatus;

    /* The stacks and their tools:
       `yyss': related to states.
       `yyvs': related to semantic values.

       Refer to the stacks thru separate pointers, to allow yyoverflow
       to reallocate them elsewhere.  */

    /* The state stack.  */
    yytype_int16 yyssa[YYINITDEPTH];
    yytype_int16 *yyss;
    yytype_int16 *yyssp;

    /* The semantic value stack.  */
    YYSTYPE yyvsa[YYINITDEPTH];
    YYSTYPE *yyvs;
    YYSTYPE *yyvsp;

    YYSIZE_T yystacksize;

  int yyn;
  int yyresult;
  /* Lookahead token as an internal (translated) token number.  */
  int yytoken;
  /* The variables used to return semantic value and location from the
     action routines.  */
  YYSTYPE yyval;

#if YYERROR_VERBOSE
  /* Buffer for error messages, and its allocated size.  */
  char yymsgbuf[128];
  char *yymsg = yymsgbuf;
  YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif

#define YYPOPSTACK(N)   (yyvsp -= (N), yyssp -= (N))

  /* The number of symbols on the RHS of the reduced rule.
     Keep to zero when no symbol should be popped.  */
  int yylen = 0;

  yytoken = 0;
  yyss = yyssa;
  yyvs = yyvsa;
  yystacksize = YYINITDEPTH;

  YYDPRINTF ((stderr, "Starting parse\n"));

  yystate = 0;
  yyerrstatus = 0;
  yynerrs = 0;
  yychar = YYEMPTY; /* Cause a token to be read.  */

  /* Initialize stack pointers.
     Waste one element of value and location stack
     so that they stay on the same level as the state stack.
     The wasted elements are never initialized.  */
  yyssp = yyss;
  yyvsp = yyvs;

  goto yysetstate;

/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate.  |
`------------------------------------------------------------*/
 yynewstate:
  /* In all cases, when you get here, the value and location stacks
     have just been pushed.  So pushing a state here evens the stacks.  */
  yyssp++;

 yysetstate:
  *yyssp = yystate;

  if (yyss + yystacksize - 1 <= yyssp)
    {
      /* Get the current used size of the three stacks, in elements.  */
      YYSIZE_T yysize = yyssp - yyss + 1;

#ifdef yyoverflow
      {
	/* Give user a chance to reallocate the stack.  Use copies of
	   these so that the &'s don't force the real ones into
	   memory.  */
	YYSTYPE *yyvs1 = yyvs;
	yytype_int16 *yyss1 = yyss;

	/* Each stack pointer address is followed by the size of the
	   data in use in that stack, in bytes.  This used to be a
	   conditional around just the two extra args, but that might
	   be undefined if yyoverflow is a macro.  */
	yyoverflow (YY_("memory exhausted"),
		    &yyss1, yysize * sizeof (*yyssp),
		    &yyvs1, yysize * sizeof (*yyvsp),
		    &yystacksize);

	yyss = yyss1;
	yyvs = yyvs1;
      }
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
      goto yyexhaustedlab;
# else
      /* Extend the stack our own way.  */
      if (YYMAXDEPTH <= yystacksize)
	goto yyexhaustedlab;
      yystacksize *= 2;
      if (YYMAXDEPTH < yystacksize)
	yystacksize = YYMAXDEPTH;

      {
	yytype_int16 *yyss1 = yyss;
	union yyalloc *yyptr =
	  (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
	if (! yyptr)
	  goto yyexhaustedlab;
	YYSTACK_RELOCATE (yyss_alloc, yyss);
	YYSTACK_RELOCATE (yyvs_alloc, yyvs);
#  undef YYSTACK_RELOCATE
	if (yyss1 != yyssa)
	  YYSTACK_FREE (yyss1);
      }
# endif
#endif /* no yyoverflow */

      yyssp = yyss + yysize - 1;
      yyvsp = yyvs + yysize - 1;

      YYDPRINTF ((stderr, "Stack size increased to %lu\n",
		  (unsigned long int) yystacksize));

      if (yyss + yystacksize - 1 <= yyssp)
	YYABORT;
    }

  YYDPRINTF ((stderr, "Entering state %d\n", yystate));

  if (yystate == YYFINAL)
    YYACCEPT;

  goto yybackup;

/*-----------.
| yybackup.  |
`-----------*/
yybackup:

  /* Do appropriate processing given the current state.  Read a
     lookahead token if we need one and don't already have one.  */

  /* First try to decide what to do without reference to lookahead token.  */
  yyn = yypact[yystate];
  if (yyn == YYPACT_NINF)
    goto yydefault;

  /* Not known => get a lookahead token if don't already have one.  */

  /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol.  */
  if (yychar == YYEMPTY)
    {
      YYDPRINTF ((stderr, "Reading a token: "));
      yychar = YYLEX;
    }

  if (yychar <= YYEOF)
    {
      yychar = yytoken = YYEOF;
      YYDPRINTF ((stderr, "Now at end of input.\n"));
    }
  else
    {
      yytoken = YYTRANSLATE (yychar);
      YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
    }

  /* If the proper action on seeing token YYTOKEN is to reduce or to
     detect an error, take that action.  */
  yyn += yytoken;
  if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
    goto yydefault;
  yyn = yytable[yyn];
  if (yyn <= 0)
    {
      if (yyn == 0 || yyn == YYTABLE_NINF)
	goto yyerrlab;
      yyn = -yyn;
      goto yyreduce;
    }

  /* Count tokens shifted since error; after three, turn off error
     status.  */
  if (yyerrstatus)
    yyerrstatus--;

  /* Shift the lookahead token.  */
  YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);

  /* Discard the shifted token.  */
  yychar = YYEMPTY;

  yystate = yyn;
  *++yyvsp = yylval;

  goto yynewstate;


/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state.  |
`-----------------------------------------------------------*/
yydefault:
  yyn = yydefact[yystate];
  if (yyn == 0)
    goto yyerrlab;
  goto yyreduce;


/*-----------------------------.
| yyreduce -- Do a reduction.  |
`-----------------------------*/
yyreduce:
  /* yyn is the number of a rule to reduce with.  */
  yylen = yyr2[yyn];

  /* If YYLEN is nonzero, implement the default value of the action:
     `$$ = $1'.

     Otherwise, the following line sets YYVAL to garbage.
     This behavior is undocumented and Bison
     users should not rely upon it.  Assigning to YYVAL
     unconditionally makes the parser a bit smaller, and it avoids a
     GCC warning that YYVAL may be used uninitialized.  */
  yyval = yyvsp[1-yylen];


  YY_REDUCE_PRINT (yyn);
  switch (yyn)
    {
        case 2:

/* Line 1455 of yacc.c  */
#line 206 "parser.y"
    { 
                                  nodeComment();
                                  addCommentsToNodeList((yyvsp[(1) - (1)].nodeList));
                                  scene->addNodes(targetNode, targetField, (yyvsp[(1) - (1)].nodeList)); 
                                }
    break;

  case 3:

/* Line 1455 of yacc.c  */
#line 211 "parser.y"
    { 
                                  nodeComment();
                                  addCommentsToNodeList((yyvsp[(2) - (2)].nodeList));
                                  scene->addNodes(targetNode, targetField, (yyvsp[(2) - (2)].nodeList)); 
                                }
    break;

  case 6:

/* Line 1455 of yacc.c  */
#line 220 "parser.y"
    {
                                  if ((yyvsp[(2) - (2)].node) != NULL) 
                                      (yyvsp[(2) - (2)].node)->appendTo((yyvsp[(1) - (2)].nodeList)); 
                                  (yyval.nodeList) = (yyvsp[(1) - (2)].nodeList); 
                                }
    break;

  case 7:

/* Line 1455 of yacc.c  */
#line 225 "parser.y"
    { (yyval.nodeList) = new NodeList(); }
    break;

  case 8:

/* Line 1455 of yacc.c  */
#line 228 "parser.y"
    { (yyval.node) = (yyvsp[(1) - (1)].node); }
    break;

  case 9:

/* Line 1455 of yacc.c  */
#line 229 "parser.y"
    { (yyval.node) = NULL; }
    break;

  case 10:

/* Line 1455 of yacc.c  */
#line 230 "parser.y"
    { (yyval.node) = NULL; }
    break;

  case 11:

/* Line 1455 of yacc.c  */
#line 231 "parser.y"
    { (yyval.node) = (yyvsp[(1) - (1)].node); }
    break;

  case 12:

/* Line 1455 of yacc.c  */
#line 232 "parser.y"
    { (yyval.node) = (yyvsp[(1) - (1)].node); }
    break;

  case 13:

/* Line 1455 of yacc.c  */
#line 235 "parser.y"
    { scene->updateURLs((yyvsp[(1) - (1)].node)); (yyval.node) = (yyvsp[(1) - (1)].node); }
    break;

  case 14:

/* Line 1455 of yacc.c  */
#line 236 "parser.y"
    { defName = (yyvsp[(2) - (2)].id); }
    break;

  case 15:

/* Line 1455 of yacc.c  */
#line 236 "parser.y"
    { (yyval.node) = (yyvsp[(4) - (4)].node); 
                                                scene->updateURLs((yyvsp[(4) - (4)].node)); 
                                              }
    break;

  case 16:

/* Line 1455 of yacc.c  */
#line 239 "parser.y"
    { (yyval.node) = scene->use(checkName(SYMB((yyvsp[(2) - (2)].id)))); }
    break;

  case 21:

/* Line 1455 of yacc.c  */
#line 250 "parser.y"
    { 
                                   Proto *proto = scene->getProto(SYMB((yyvsp[(2) - (2)].id)));
                                   if ((proto == NULL) || 
                                       proto->isScriptedProto())
                                       proto = new Proto(scene, SYMB((yyvsp[(2) - (2)].id)));
                                   else
                                       proto->deleteElements(); 
                                   protoStack.push(proto);
                                   if (!scene->addProtoName(SYMB((yyvsp[(2) - (2)].id)))) {
                                      swDebugf("warning: proto already definied: %s\n",
                                               (const char*)SYMB((yyvsp[(2) - (2)].id)));
                                   }  
                                 }
    break;

  case 22:

/* Line 1455 of yacc.c  */
#line 265 "parser.y"
    { 
                                   if (!protoStack.peek()->isExternProto())
                                       scene->addProto(SYMB((yyvsp[(2) - (9)].id)),
                                                       protoStack.pop()); 
                                   stopProto();
                                 }
    break;

  case 23:

/* Line 1455 of yacc.c  */
#line 274 "parser.y"
    { protoStack.peek()->define((yyvsp[(2) - (3)].node), (yyvsp[(3) - (3)].nodeList)); }
    break;

  case 25:

/* Line 1455 of yacc.c  */
#line 279 "parser.y"
    {
            if (protoStack.empty()) 
                yyerror("syntax error");
            else 
                protoStack.peek()->addElement((yyvsp[(2) - (2)].element));
          }
    break;

  case 27:

/* Line 1455 of yacc.c  */
#line 288 "parser.y"
    { currentType = (yyvsp[(2) - (2)].int32); }
    break;

  case 28:

/* Line 1455 of yacc.c  */
#line 289 "parser.y"
    { (yyval.element) = createField((yyvsp[(2) - (4)].int32), SYMB((yyvsp[(4) - (4)].id))); }
    break;

  case 29:

/* Line 1455 of yacc.c  */
#line 292 "parser.y"
    { currentType = (yyvsp[(2) - (2)].int32); }
    break;

  case 30:

/* Line 1455 of yacc.c  */
#line 293 "parser.y"
    { (yyval.element) = createField((yyvsp[(2) - (4)].int32), SYMB((yyvsp[(4) - (4)].id))); }
    break;

  case 31:

/* Line 1455 of yacc.c  */
#line 296 "parser.y"
    { (yyval.element) = new EventIn((yyvsp[(2) - (3)].int32), SYMB((yyvsp[(3) - (3)].id))); }
    break;

  case 32:

/* Line 1455 of yacc.c  */
#line 297 "parser.y"
    { (yyval.element) = new EventOut((yyvsp[(2) - (3)].int32), SYMB((yyvsp[(3) - (3)].id))); }
    break;

  case 33:

/* Line 1455 of yacc.c  */
#line 298 "parser.y"
    { (yyval.element) = new Field((yyvsp[(1) - (2)].element)->getType(), 
                                                         (yyvsp[(1) - (2)].element)->getName(x3d), (yyvsp[(2) - (2)].value)); 
                                        }
    break;

  case 34:

/* Line 1455 of yacc.c  */
#line 302 "parser.y"
    { (yyval.element) = new ExposedField((yyvsp[(1) - (2)].element)->getType(), 
                                                     (yyvsp[(1) - (2)].element)->getName(x3d), (yyvsp[(2) - (2)].value)); 
                                        }
    break;

  case 36:

/* Line 1455 of yacc.c  */
#line 308 "parser.y"
    { currentType = (yyvsp[(2) - (2)].int32); }
    break;

  case 37:

/* Line 1455 of yacc.c  */
#line 309 "parser.y"
    { (yyval.element) = new ExposedField((yyvsp[(2) - (5)].int32), SYMB((yyvsp[(4) - (5)].id)), (yyvsp[(5) - (5)].value)); }
    break;

  case 38:

/* Line 1455 of yacc.c  */
#line 313 "parser.y"
    { 
                                  protoStack.push(new Proto(scene, SYMB((yyvsp[(2) - (2)].id))));
                                  if (!scene->addProtoName(SYMB((yyvsp[(2) - (2)].id)))) {
                                      swDebugf("warning: proto already definied: %s\n",
                                               (const char*)SYMB((yyvsp[(2) - (2)].id)));
                                  }
                                }
    break;

  case 39:

/* Line 1455 of yacc.c  */
#line 321 "parser.y"
    { 
                                  scene->addProto(SYMB((yyvsp[(2) - (7)].id)), protoStack.pop()); 
                                  scene->getProto(SYMB((yyvsp[(2) - (7)].id)))->addURLs((yyvsp[(7) - (7)].value));
                                  stopProto();
                                }
    break;

  case 40:

/* Line 1455 of yacc.c  */
#line 329 "parser.y"
    {
            if (protoStack.empty()) 
                yyerror("syntax error");
            else 
                protoStack.peek()->addElement((yyvsp[(2) - (2)].element));
          }
    break;

  case 42:

/* Line 1455 of yacc.c  */
#line 338 "parser.y"
    { (yyval.element) = new EventIn((yyvsp[(2) - (3)].int32), SYMB((yyvsp[(3) - (3)].id))); }
    break;

  case 43:

/* Line 1455 of yacc.c  */
#line 339 "parser.y"
    { (yyval.element) = new EventOut((yyvsp[(2) - (3)].int32), SYMB((yyvsp[(3) - (3)].id))); }
    break;

  case 44:

/* Line 1455 of yacc.c  */
#line 340 "parser.y"
    { 
                                          (yyval.element) = new Field((yyvsp[(2) - (3)].int32), SYMB((yyvsp[(3) - (3)].id)),
                                                         SillyDefaultValue((yyvsp[(2) - (3)].int32)));
                                        }
    break;

  case 45:

/* Line 1455 of yacc.c  */
#line 344 "parser.y"
    {
                                          (yyval.element) = new ExposedField((yyvsp[(2) - (3)].int32), SYMB((yyvsp[(3) - (3)].id)),
                                                SillyDefaultValue((yyvsp[(2) - (3)].int32)));
                                        }
    break;

  case 46:

/* Line 1455 of yacc.c  */
#line 348 "parser.y"
    {
                                          (yyval.element) = new ExposedField((yyvsp[(2) - (3)].int32), SYMB((yyvsp[(3) - (3)].id)),
                                                SillyDefaultValue((yyvsp[(2) - (3)].int32)));
                                        }
    break;

  case 47:

/* Line 1455 of yacc.c  */
#line 355 "parser.y"
    { 
               route(checkName(SYMB((yyvsp[(2) - (8)].id))), SYMB((yyvsp[(4) - (8)].id)), 
                     checkName(SYMB((yyvsp[(6) - (8)].id))), SYMB((yyvsp[(8) - (8)].id))); 
             }
    break;

  case 48:

/* Line 1455 of yacc.c  */
#line 362 "parser.y"
    { (yyval.node) = addExport(checkName(SYMB((yyvsp[(2) - (2)].id))), ""); }
    break;

  case 49:

/* Line 1455 of yacc.c  */
#line 364 "parser.y"
    { (yyval.node) = addExport(checkName(SYMB((yyvsp[(2) - (4)].id))), SYMB((yyvsp[(4) - (4)].id))); }
    break;

  case 50:

/* Line 1455 of yacc.c  */
#line 368 "parser.y"
    { (yyval.node) = addImport(checkName(SYMB((yyvsp[(2) - (4)].id))), SYMB((yyvsp[(4) - (4)].id)), ""); }
    break;

  case 51:

/* Line 1455 of yacc.c  */
#line 370 "parser.y"
    { (yyval.node) = addImport(checkName(SYMB((yyvsp[(2) - (6)].id))), SYMB((yyvsp[(4) - (6)].id)), SYMB((yyvsp[(6) - (6)].id))); }
    break;

  case 54:

/* Line 1455 of yacc.c  */
#line 378 "parser.y"
    { 
                                        (yyval.node) = newNode(SYMB((yyvsp[(1) - (2)].id)));
                                        Node *node = (yyval.node);
                                        if (node != NULL) {
                                            addCommentsToNode((yyval.node));
                                            nodeStack.push((yyval.node));
                                            if (defName != -1) { 
                                                scene->def(uniqName(SYMB(
                                                       defName)), (yyval.node));
                                                defName = -1;
                                            }
                                        }
                                      }
    break;

  case 55:

/* Line 1455 of yacc.c  */
#line 391 "parser.y"
    { (yyval.node) = nodeStack.pop(); }
    break;

  case 56:

/* Line 1455 of yacc.c  */
#line 392 "parser.y"
    { 
                                        (yyval.node) = (yyvsp[(1) - (2)].node);
                                        addCommentsToNode((yyval.node)); 
                                        nodeStack.push((yyval.node));
                                        if (defName != -1) { 
                                            scene->def(uniqName(SYMB(defName)), 
                                                       (yyval.node));
                                            defName = -1;
                                        }
                                      }
    break;

  case 57:

/* Line 1455 of yacc.c  */
#line 402 "parser.y"
    { 
                                        (yyval.node) = nodeStack.pop(); 
                                        ((NodeScript *) (yyval.node))->update(); 
                                      }
    break;

  case 60:

/* Line 1455 of yacc.c  */
#line 413 "parser.y"
    { (yyval.node) = new NodeScript(scene); }
    break;

  case 61:

/* Line 1455 of yacc.c  */
#line 414 "parser.y"
    { (yyval.node) = (yyvsp[(1) - (1)].node); }
    break;

  case 62:

/* Line 1455 of yacc.c  */
#line 417 "parser.y"
    { (yyval.node) = newNode("ComposedShader"); }
    break;

  case 63:

/* Line 1455 of yacc.c  */
#line 418 "parser.y"
    { (yyval.node) = newNode("ShaderProgram"); }
    break;

  case 64:

/* Line 1455 of yacc.c  */
#line 419 "parser.y"
    { (yyval.node) = newNode("PackagedShader"); }
    break;

  case 67:

/* Line 1455 of yacc.c  */
#line 427 "parser.y"
    { (yyval.element) = NULL; }
    break;

  case 68:

/* Line 1455 of yacc.c  */
#line 428 "parser.y"
    { addDynamicElement((yyvsp[(1) - (1)].element)); }
    break;

  case 69:

/* Line 1455 of yacc.c  */
#line 429 "parser.y"
    { if (protoStack.empty()) 
                                              yyerror(IS_OUTSIDE_PROTO); 
                                          (yyval.element) = new EventIn((yyvsp[(2) - (5)].int32), SYMB((yyvsp[(3) - (5)].id)));
                                          addDynamicElement((yyval.element));
                                          isField(nodeStack.peek(),
                                                  SYMB((yyvsp[(3) - (5)].id)), SYMB((yyvsp[(5) - (5)].id))); 
                                        }
    break;

  case 70:

/* Line 1455 of yacc.c  */
#line 436 "parser.y"
    { if (protoStack.empty()) 
                                              yyerror(IS_OUTSIDE_PROTO); 
                                          (yyval.element) = new EventOut((yyvsp[(2) - (5)].int32), SYMB((yyvsp[(3) - (5)].id))); 
                                          addDynamicElement((yyval.element));
                                          isField(nodeStack.peek(),
                                                  SYMB((yyvsp[(3) - (5)].id)), SYMB((yyvsp[(5) - (5)].id))); 
                                        }
    break;

  case 71:

/* Line 1455 of yacc.c  */
#line 444 "parser.y"
    { if (protoStack.empty())
                                              yyerror(IS_OUTSIDE_PROTO);
                                          (yyval.element) = (yyvsp[(1) - (3)].element);
                                          addDynamicElement((yyval.element));
                                          isField(nodeStack.peek(), 
                                                  (yyvsp[(1) - (3)].element)->getName(x3d), SYMB((yyvsp[(3) - (3)].id)));
                                        }
    break;

  case 72:

/* Line 1455 of yacc.c  */
#line 451 "parser.y"
    { if (protoStack.empty()) 
                                              yyerror(IS_OUTSIDE_PROTO); 
                                          (yyval.element) = (yyvsp[(1) - (3)].element);
                                          addDynamicElement((yyval.element));
                                          isField(nodeStack.peek(),
                                                  (yyvsp[(1) - (3)].element)->getName(x3d), SYMB((yyvsp[(3) - (3)].id))); 
                                        }
    break;

  case 73:

/* Line 1455 of yacc.c  */
#line 460 "parser.y"
    { setField(nodeStack.peek(), (yyvsp[(1) - (2)].int32), (yyvsp[(2) - (2)].value)); }
    break;

  case 74:

/* Line 1455 of yacc.c  */
#line 461 "parser.y"
    { isField(nodeStack.peek(),
                                                  SYMB((yyvsp[(1) - (3)].id)), SYMB((yyvsp[(3) - (3)].id))); 
                                        }
    break;

  case 77:

/* Line 1455 of yacc.c  */
#line 469 "parser.y"
    { (yyval.int32) = checkField(nodeStack.peek(),
                                                          SYMB((yyvsp[(1) - (1)].id))); 
                                        }
    break;

  case 80:

/* Line 1455 of yacc.c  */
#line 480 "parser.y"
    { (yyval.int32) = fieldTypeToEnum(SYMB((yyvsp[(1) - (1)].id))); }
    break;

  case 83:

/* Line 1455 of yacc.c  */
#line 492 "parser.y"
    { (yyval.value) = stringToType(SYMB((yyvsp[(1) - (1)].id)),
                                                            currentType); 
                                        }
    break;

  case 84:

/* Line 1455 of yacc.c  */
#line 496 "parser.y"
    { (yyval.value) = new MFString((yyvsp[(2) - (3)].stringArray)); }
    break;

  case 85:

/* Line 1455 of yacc.c  */
#line 497 "parser.y"
    { (yyval.value) = new SFNode((yyvsp[(1) - (1)].node)); }
    break;

  case 86:

/* Line 1455 of yacc.c  */
#line 498 "parser.y"
    { (yyval.value) = emptyMFNodeOrNULL(currentType); }
    break;

  case 87:

/* Line 1455 of yacc.c  */
#line 500 "parser.y"
    { (yyval.value) = new MFNode((yyvsp[(2) - (3)].nodeList)); }
    break;

  case 88:

/* Line 1455 of yacc.c  */
#line 501 "parser.y"
    { (yyval.value) = intsToType((yyvsp[(1) - (1)].intArray), currentType); }
    break;

  case 89:

/* Line 1455 of yacc.c  */
#line 502 "parser.y"
    { (yyval.value) = floatsToType((yyvsp[(1) - (1)].doubleArray), currentType); }
    break;

  case 90:

/* Line 1455 of yacc.c  */
#line 503 "parser.y"
    { (yyval.value) = boolsToType((yyvsp[(1) - (1)].boolArray), currentType); }
    break;

  case 91:

/* Line 1455 of yacc.c  */
#line 504 "parser.y"
    { (yyval.value) = intsToType((yyvsp[(2) - (3)].intArray), currentType); }
    break;

  case 92:

/* Line 1455 of yacc.c  */
#line 505 "parser.y"
    { (yyval.value) = floatsToType((yyvsp[(2) - (3)].doubleArray), currentType); }
    break;

  case 93:

/* Line 1455 of yacc.c  */
#line 506 "parser.y"
    { (yyval.value) = boolsToType((yyvsp[(2) - (3)].boolArray), currentType); }
    break;

  case 94:

/* Line 1455 of yacc.c  */
#line 507 "parser.y"
    { (yyval.value) = emptyMF(currentType); }
    break;

  case 95:

/* Line 1455 of yacc.c  */
#line 511 "parser.y"
    { 
                                (yyvsp[(1) - (2)].boolArray)->append(((SFBool *)(yyvsp[(2) - (2)].value))->getValue()); 
                                (yyval.boolArray) = (yyvsp[(1) - (2)].boolArray); 
                                }
    break;

  case 96:

/* Line 1455 of yacc.c  */
#line 515 "parser.y"
    { 
                                (yyval.boolArray) = new BoolArray(); 
                                (yyval.boolArray)->append(((SFBool *)(yyvsp[(1) - (1)].value))->getValue()); 
                                }
    break;

  case 97:

/* Line 1455 of yacc.c  */
#line 522 "parser.y"
    { (yyval.value) = new SFBool(true); }
    break;

  case 98:

/* Line 1455 of yacc.c  */
#line 523 "parser.y"
    { (yyval.value) = new SFBool(false); }
    break;

  case 99:

/* Line 1455 of yacc.c  */
#line 526 "parser.y"
    { (yyvsp[(1) - (2)].intArray)->append((yyvsp[(2) - (2)].int32)); (yyval.intArray) = (yyvsp[(1) - (2)].intArray); }
    break;

  case 100:

/* Line 1455 of yacc.c  */
#line 527 "parser.y"
    { (yyval.intArray) = new IntArray(); (yyval.intArray)->append((yyvsp[(1) - (1)].int32)); }
    break;

  case 101:

/* Line 1455 of yacc.c  */
#line 530 "parser.y"
    { (yyvsp[(1) - (2)].doubleArray)->append((yyvsp[(2) - (2)].sffloat)); (yyval.doubleArray) = (yyvsp[(1) - (2)].doubleArray); }
    break;

  case 102:

/* Line 1455 of yacc.c  */
#line 531 "parser.y"
    { (yyvsp[(1) - (2)].doubleArray)->append((float) (yyvsp[(2) - (2)].int32)); (yyval.doubleArray) = (yyvsp[(1) - (2)].doubleArray); }
    break;

  case 103:

/* Line 1455 of yacc.c  */
#line 532 "parser.y"
    { (yyval.doubleArray) = intsToFloats((yyvsp[(1) - (2)].intArray)); (yyval.doubleArray)->append((yyvsp[(2) - (2)].sffloat)); 
                                  delete (yyvsp[(1) - (2)].intArray); 
                                }
    break;

  case 104:

/* Line 1455 of yacc.c  */
#line 535 "parser.y"
    { (yyval.doubleArray) = new DoubleArray(); (yyval.doubleArray)->append((yyvsp[(1) - (1)].sffloat)); }
    break;

  case 105:

/* Line 1455 of yacc.c  */
#line 538 "parser.y"
    { (yyval.value) = new MFString(SYMB((yyvsp[(1) - (1)].id))); }
    break;

  case 106:

/* Line 1455 of yacc.c  */
#line 540 "parser.y"
    { (yyval.value) = new MFString((yyvsp[(2) - (3)].stringArray)); }
    break;

  case 107:

/* Line 1455 of yacc.c  */
#line 543 "parser.y"
    { (yyval.stringArray) = new StringArray();
                                  (yyval.stringArray)->append(SYMB((yyvsp[(1) - (1)].id))); }
    break;

  case 108:

/* Line 1455 of yacc.c  */
#line 545 "parser.y"
    { (yyvsp[(1) - (2)].stringArray)->append(SYMB((yyvsp[(2) - (2)].id))); (yyval.stringArray) = (yyvsp[(1) - (2)].stringArray); }
    break;

  case 109:

/* Line 1455 of yacc.c  */
#line 548 "parser.y"
    {
                                          (yyval.nodeList) = new NodeList();
                                          if ((yyvsp[(1) - (1)].node)) 
                                              (yyvsp[(1) - (1)].node)->appendTo((yyval.nodeList));
                                        }
    break;

  case 110:

/* Line 1455 of yacc.c  */
#line 553 "parser.y"
    { 
                                          if ((yyvsp[(2) - (2)].node)) 
                                              (yyvsp[(2) - (2)].node)->appendTo((yyvsp[(1) - (2)].nodeList)); 
                                          (yyval.nodeList) = (yyvsp[(1) - (2)].nodeList);
                                        }
    break;

  case 111:

/* Line 1455 of yacc.c  */
#line 559 "parser.y"
    { (yyval.id) = (yyvsp[(1) - (1)].id); }
    break;

  case 112:

/* Line 1455 of yacc.c  */
#line 560 "parser.y"
    {  
                                          if (x3d)
                                              fprintf(stderr,
                                                     "warning: %s %s %s",
                                                     "a character in ID",
                                                     (const char *)SYMB((yyvsp[(1) - (1)].id)),
                                                     "is illegal in X3D\n");
                                          (yyval.id) = (yyvsp[(1) - (1)].id); 
                                        }
    break;

  case 113:

/* Line 1455 of yacc.c  */
#line 571 "parser.y"
    { illegalX3DV(); }
    break;

  case 125:

/* Line 1455 of yacc.c  */
#line 594 "parser.y"
    { scene->addMeta(SYMB((yyvsp[(2) - (3)].id)), SYMB((yyvsp[(3) - (3)].id))); }
    break;



/* Line 1455 of yacc.c  */
#line 2566 "y.tab.c"
      default: break;
    }
  YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);

  YYPOPSTACK (yylen);
  yylen = 0;
  YY_STACK_PRINT (yyss, yyssp);

  *++yyvsp = yyval;

  /* Now `shift' the result of the reduction.  Determine what state
     that goes to, based on the state we popped back to and the rule
     number reduced by.  */

  yyn = yyr1[yyn];

  yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
  if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
    yystate = yytable[yystate];
  else
    yystate = yydefgoto[yyn - YYNTOKENS];

  goto yynewstate;


/*------------------------------------.
| yyerrlab -- here on detecting error |
`------------------------------------*/
yyerrlab:
  /* If not already recovering from an error, report this error.  */
  if (!yyerrstatus)
    {
      ++yynerrs;
#if ! YYERROR_VERBOSE
      yyerror (YY_("syntax error"));
#else
      {
	YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
	if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
	  {
	    YYSIZE_T yyalloc = 2 * yysize;
	    if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
	      yyalloc = YYSTACK_ALLOC_MAXIMUM;
	    if (yymsg != yymsgbuf)
	      YYSTACK_FREE (yymsg);
	    yymsg = (char *) YYSTACK_ALLOC (yyalloc);
	    if (yymsg)
	      yymsg_alloc = yyalloc;
	    else
	      {
		yymsg = yymsgbuf;
		yymsg_alloc = sizeof yymsgbuf;
	      }
	  }

	if (0 < yysize && yysize <= yymsg_alloc)
	  {
	    (void) yysyntax_error (yymsg, yystate, yychar);
	    yyerror (yymsg);
	  }
	else
	  {
	    yyerror (YY_("syntax error"));
	    if (yysize != 0)
	      goto yyexhaustedlab;
	  }
      }
#endif
    }



  if (yyerrstatus == 3)
    {
      /* If just tried and failed to reuse lookahead token after an
	 error, discard it.  */

      if (yychar <= YYEOF)
	{
	  /* Return failure if at end of input.  */
	  if (yychar == YYEOF)
	    YYABORT;
	}
      else
	{
	  yydestruct ("Error: discarding",
		      yytoken, &yylval);
	  yychar = YYEMPTY;
	}
    }

  /* Else will try to reuse lookahead token after shifting the error
     token.  */
  goto yyerrlab1;


/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR.  |
`---------------------------------------------------*/
yyerrorlab:

  /* Pacify compilers like GCC when the user code never invokes
     YYERROR and the label yyerrorlab therefore never appears in user
     code.  */
  if (/*CONSTCOND*/ 0)
     goto yyerrorlab;

  /* Do not reclaim the symbols of the rule which action triggered
     this YYERROR.  */
  YYPOPSTACK (yylen);
  yylen = 0;
  YY_STACK_PRINT (yyss, yyssp);
  yystate = *yyssp;
  goto yyerrlab1;


/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR.  |
`-------------------------------------------------------------*/
yyerrlab1:
  yyerrstatus = 3;	/* Each real token shifted decrements this.  */

  for (;;)
    {
      yyn = yypact[yystate];
      if (yyn != YYPACT_NINF)
	{
	  yyn += YYTERROR;
	  if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
	    {
	      yyn = yytable[yyn];
	      if (0 < yyn)
		break;
	    }
	}

      /* Pop the current state because it cannot handle the error token.  */
      if (yyssp == yyss)
	YYABORT;


      yydestruct ("Error: popping",
		  yystos[yystate], yyvsp);
      YYPOPSTACK (1);
      yystate = *yyssp;
      YY_STACK_PRINT (yyss, yyssp);
    }

  *++yyvsp = yylval;


  /* Shift the error token.  */
  YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);

  yystate = yyn;
  goto yynewstate;


/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here.  |
`-------------------------------------*/
yyacceptlab:
  yyresult = 0;
  goto yyreturn;

/*-----------------------------------.
| yyabortlab -- YYABORT comes here.  |
`-----------------------------------*/
yyabortlab:
  yyresult = 1;
  goto yyreturn;

#if !defined(yyoverflow) || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here.  |
`-------------------------------------------------*/
yyexhaustedlab:
  yyerror (YY_("memory exhausted"));
  yyresult = 2;
  /* Fall through.  */
#endif

yyreturn:
  if (yychar != YYEMPTY)
     yydestruct ("Cleanup: discarding lookahead",
		 yytoken, &yylval);
  /* Do not reclaim the symbols of the rule which action triggered
     this YYABORT or YYACCEPT.  */
  YYPOPSTACK (yylen);
  YY_STACK_PRINT (yyss, yyssp);
  while (yyssp != yyss)
    {
      yydestruct ("Cleanup: popping",
		  yystos[*yyssp], yyvsp);
      YYPOPSTACK (1);
    }
#ifndef yyoverflow
  if (yyss != yyssa)
    YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
  if (yymsg != yymsgbuf)
    YYSTACK_FREE (yymsg);
#endif
  /* Make sure YYID is used.  */
  return YYID (yyresult);
}



/* Line 1675 of yacc.c  */
#line 596 "parser.y"


int yywrap(void)
{
    return 1;
}

void yyerror(const char *s)
{
    scene->setErrorLineNumber(lineno);
#ifdef HAVE_LIBZ
    scene->errorf("%s in line %d\n", s, lineno);
#else
    if (strcmp(s,"parse error") == 0)
        scene->errorf("%s (or %s) in line %d\n",
                      s, "unsupported compression (no gzip in this version)",
                      lineno);
    else
        scene->errorf("%s in line %d\n", s, lineno);
#endif
}

static Node *
newNode(const MyString &nodeType)
{
   Proto *proto;

   if (TheApp->getPrefix() != NULL) {
       proto = scene->getExtensionProto(scene->getNodeWithPrefix(nodeType));
       if (proto)
           return proto->create(scene);
       }    
    proto = scene->getExtensionProto(nodeType);
    if (!proto) {
        scene->errorf("invalid node type \"%s\" in line %d\n", 
                      (const char *) nodeType, lineno);
        return NULL;
    } else {
        return proto->create(scene);
    }
}

static FieldValue *
intsToType(IntArray *ints, int type)
{
    FieldValue *r = NULL;
    const int  *data = ints->getData();
    int len = ints->size();

    switch(type) {
      case SFCOLOR:
        if (len != 3) {
            yyerror("SFColor must have 3 values");
        } else {
            r = new SFColor((float) data[0], (float) data[1], (float) data[2]);
        }
        break;
      case SFCOLORRGBA:
        if (len != 4) {
            yyerror("SFColorRGBA must have 4 values");
        } else {
            r = new SFColorRGBA((float) data[0], (float) data[1],
                                (float) data[2], (float) data[3]);
        }
        break;
      case SFDOUBLE:
        if (len != 1) {
            yyerror("SFDouble must have 1 value");
        } else {
            r = new SFDouble((double) data[0]);
        }
        break;
      case SFFLOAT:
        if (len != 1) {
            yyerror("SFFloat must have 1 float value");
        } else {
            r = new SFFloat((float) data[0]);
        }
        break;
      case SFIMAGE:
        if (len < 3) {
            yyerror("SFImage must have at least 3 values");
        } else {
            int width = data[0];
            int height = data[1];
            int depth = data[2];

            if (len - 3 != width * height) {
                char buf[1024];
                mysnprintf(buf, 1024, "SFImage data must have %d values\n", 
                        width * height);
                yyerror(buf);
            } else {
                int *pixels = new int[len - 3];
                for (int i = 0; i < (len - 3); i++)
                    pixels[i] = data[i + 3];
                r = new SFImage(width, height, depth, pixels);
            }
        }
        break;
      case SFINT32:
        if (len != 1) {
            yyerror("SFInt32 must have 1 integer value");
        } else {
            r = new SFInt32(data[0]);
        }
        break;
      case SFROTATION:
        if (len != 4) {
            yyerror("SFRotation must have 4 values");
        } else {
            r = new SFRotation((float) data[0], (float) data[1], 
                               (float) data[2], (float) data[3]);
        }
        break;
      case SFTIME:
        if (len != 1) {
            yyerror("SFTime must have 1 value");
        } else {
            r = new SFTime((double) data[0]);
        }
        break;
      case SFVEC2F:
        if (len != 2) {
            yyerror("SFVec2f must have 2 values");
        } else {
            r = new SFVec2f((float) data[0], (float) data[1]);
        }
        break;
      case SFVEC3D:
        if (len != 3) {
            yyerror("SFVec3d must have 3 values");
        } else {
            r = new SFVec3d((double) data[0], (double) data[1], 
                            (double) data[2]);
        }
        break;
      case SFVEC3F:
        if (len != 3) {
            yyerror("SFVec3f must have 3 values");
        } else {
            r = new SFVec3f((float) data[0], (float) data[1], (float) data[2]);
        }
        break;
      case SFVEC4F:
        if (len != 4) {
            yyerror("SFVec4f must have 4 values");
        } else {
            r = new SFVec4f((float) data[0], (float) data[1], (float) data[2],
                            (float) data[3]);
        }
        break;
      case SFMATRIX3F:
        if (len != 9) {
            yyerror("SFMatrix3f must have 9 values");
        } else {
            r = new SFMatrix3f((float) data[0], 
                               (float) data[1], 
                               (float) data[2], 
                               (float) data[3], 
                               (float) data[4], 
                               (float) data[5], 
                               (float) data[6], 
                               (float) data[7], 
                               (float) data[8]);
        }
        break;
      case SFMATRIX4F:
        if (len != 16) {
            yyerror("SFMatrix4f must have 16 values");
        } else {
            r = new SFMatrix4f((float) data[0], 
                               (float) data[1], 
                               (float) data[2], 
                               (float) data[3], 
                               (float) data[4], 
                               (float) data[5], 
                               (float) data[6], 
                               (float) data[7], 
                               (float) data[8],
                               (float) data[9],
                               (float) data[10],
                               (float) data[11],
                               (float) data[12],
                               (float) data[13],
                               (float) data[14],
                               (float) data[15]);
        }
        break;
      case MFINT32:
        r = new MFInt32(ints->extractData(), len);
        break;
      case MFCOLOR:
      case MFCOLORRGBA:
      case MFFLOAT:
      case MFROTATION:
      case MFTIME:
      case MFVEC2F:
      case MFVEC3F:
      case MFVEC4F:
      case MFMATRIX3F:
      case MFMATRIX4F:
        r = floatsToType(intsToFloats(ints), type);
        break;
      case MFDOUBLE:
      case MFVEC3D:
        r = floatsToType(intsToDoubles(ints), type);
        break;
      default:
        yyerror("type mismatch ");
        break;
    }
    delete ints;
    return r;
}

static FieldValue *
boolsToType(BoolArray *bools, int type)
{
    FieldValue *r = NULL;
    const bool *data = bools->getData();
    int len = bools->size();

    switch(type) {
      case SFBOOL:
        if (len != 1) {
            yyerror("SFBool must have 1 bool value");
        } else {
            r = new SFBool(data[0]);
        }
        break;
      case MFBOOL:
        r = new MFBool(bools->extractData(), len);
        break;
      default:
        yyerror("type mismatch ");
        break;
    }
    delete bools;
    return r;
}

static FieldValue *
floatsToType(DoubleArray *floats, int type)
{
    FieldValue     *r = NULL;
    const double   *data = floats->getData();
    int len = floats->size();

    switch(type) {
      case SFCOLOR:
        if (len != 3) {
            yyerror("SFColor must have 3 values");
        } else {
            r = new SFColor(data[0], data[1], data[2]);
        }
        break;
      case SFCOLORRGBA:
        if (len != 4) {
            yyerror("SFColorRGBA must have 3 values");
        } else {
            r = new SFColorRGBA(data[0], data[1], data[2], data[3]);
        }
        break;
      case SFDOUBLE:
        if (len != 1) {
            yyerror("SFDouble must have 1 float value");
        } else {
            r = new SFDouble(data[0]);
        }
        break;
      case SFFLOAT:
        if (len != 1) {
            yyerror("SFFloat must have 1 float value");
        } else {
            r = new SFFloat(data[0]);
        }
        break;
      case SFROTATION:
        if (len != 4) {
            yyerror("SFRotation must have 4 values");
        } else {
            r = new SFRotation(data[0], data[1], data[2], data[3]);
        }
        break;
      case SFTIME:
        if (len != 1) {
            yyerror("SFTime must have 1 value");
        } else {
            r = new SFTime((double) data[0]);
        }
        break;
      case SFVEC2F:
        if (len != 2) {
            yyerror("SFVec2f must have 2 values");
        } else {
            r = new SFVec2f(data[0], data[1]);
        }
        break;
      case SFVEC3D:
        if (len != 3) {
            yyerror("SFVec3d must have 3 values");
        } else {
            r = new SFVec3d(data[0], data[1], data[2]);
        }
        break;
      case SFVEC3F:
        if (len != 3) {
            yyerror("SFVec3f must have 3 values");
        } else {
            r = new SFVec3f(data[0], data[1], data[2]);
        }
        break;
      case SFVEC4F:
        if (len != 4) {
            yyerror("SFVec4f must have 4 values");
        } else {
            r = new SFVec4f((float) data[0], (float) data[1], (float) data[2],
                            (float) data[3]);
        }
        break;
      case SFMATRIX3F:
        if (len != 9) {
            yyerror("SFMatrix3f must have 9 values");
        } else {
            r = new SFMatrix3f(data[0], data[1], data[2], 
                               data[3], data[4], data[5], 
                               data[6], data[7], data[8]);
        }
        break;
      case SFMATRIX4F:
        if (len != 16) {
            yyerror("SFMatrix4f must have 16 values");
        } else {
            r = new SFMatrix4f(data[0], data[1], data[2], data[3], 
                               data[4], data[5], data[6], data[7],
                               data[8], data[9], data[10], data[11],
                               data[12], data[13], data[14], data[15]);
        }
        break;
      case MFCOLOR:
        if (len % 3 != 0) {
            yyerror("MFColor must be a multiple of 3 values");
        } else {
            r = new MFColor(floats->extractData(), len);
        }
        break;
      case MFCOLORRGBA:
        if (len % 4 != 0) {
            yyerror("MFColorRGBA must be a multiple of 4 values");
        } else {
            r = new MFColorRGBA(floats->extractData(), len);
        }
        break;
      case MFDOUBLE:
        r = new MFDouble(floats->extractData(), len);
        break;
      case MFFLOAT:
        r = new MFFloat(floats->extractData(), len);
        break;
      case MFROTATION:
        if (len % 4 != 0) {
            yyerror("MFRotation must be a multiple of 4 values");
        } else {
            r = new MFRotation(floats->extractData(), len);
        }
        break;
      case MFTIME:
        r = new MFTime(data, len);
        break;
      case MFVEC2F:
        if (len % 2 != 0) {
            yyerror("MFVec2f must be a multiple of 2 values");
        } else {
            r = new MFVec2f(floats->extractData(), len);
        }
        break;
      case MFVEC3D:
        if (len % 3 != 0) {
            yyerror("MFVec3d must be a multiple of 3 values");
        } else {
            r = new MFVec3d(floats->extractData(), len);
        }
        break;
      case MFVEC3F:
        if (len % 3 != 0) {
            yyerror("MFVec3f must be a multiple of 3 values");
        } else {
            r = new MFVec3f(floats->extractData(), len);
        }
        break;
      case MFVEC4F:
        if (len % 4 != 0) {
            yyerror("MFVec4f must be a multiple of 4 values");
        } else {
            r = new MFVec4f(floats->extractData(), len);
        }
        break;
      case MFMATRIX3F:
        if (len % 9 != 0) {
            yyerror("MFMatrix3f must be a multiple of 9 values");
        } else {
            r = new MFMatrix3f(floats->extractData(), len);
        }
        break;
      case MFMATRIX4F:
        if (len % 16 != 0) {
            yyerror("MFMatrix4f must be a multiple of 16 values");
        } else {
            r = new MFMatrix4f(floats->extractData(), len);
        }
        break;
      default:
        yyerror("type mismatch ");
        break;
    }
    delete floats;
    return r;
}

static FieldValue *
stringToType(const char *string, int type)
{
    FieldValue *r = NULL;

    switch(type) {
      case SFSTRING:
        r=new SFString(string);
        break;
      case MFSTRING:
        r=new MFString(string);
        break;
      default:
        yyerror("type mismatch ");
        break;
    }
    return r;
}

static int 
fieldTypeToEnum(const char* str)
{
    int ret = typeStringToEnum(str);
    if (ret == -1) {
        MyString errorMesg = "";
        errorMesg += "unknown type \"";
        errorMesg += str;
        errorMesg += "\"";
        yyerror(errorMesg);
        }
    return ret;
}

static FieldValue *
emptyMFNodeOrNULL(int type)
{
    if (type==SFNODE)
       return new SFNode(NULL);
    else if (type==MFNODE)
       return emptyMF(type);
    else {
       /* NULL only allowed for Node types
          see VRML97 Grammar 
          http://www.web3d.org/x3d/specifications/vrml/ISO-IEC-14772-IS-VRML97WithAmendment1/part1/grammar.html
          sfnodeValue ::= 
              nodeStatement | 
              NULL ; 
       
       */
       yyerror("NULL only allowed for Node types, assuming \"[]\"");
       return emptyMF(type);
    }
}

static FieldValue *
emptyMF(int type)
{
    return typeDefaultValue(type);
}

/*
 * Currently, EXTERNPROTO Definitions are not read
 * field need a senseful default value
 */

static FieldValue *
SillyDefaultValue(int type)
{
    if (FieldValue *value = typeDefaultValue(type))
       return value;
    else {
       yyerror("intern error: type no supported");
       return NULL;
    }
}

static int
repairField(Node *node, int index)
{
    // TODO: handle x3d variants in a better way
    if (x3d && (node->getType() == VRML_NURBS_SURFACE))
        if (index == ((NodeNurbsSurface *)node)->controlPoint_Field())
            index = ((NodeNurbsSurface *)node)->controlPointX3D_Field();
    if (x3d && (node->getType() == X3D_NURBS_TRIMMED_SURFACE))
        if (index == ((NodeNurbsTrimmedSurface *)node)->controlPoint_Field())
            index = ((NodeNurbsTrimmedSurface *)node)->controlPointX3D_Field();
    if (x3d && (node->getType() == VRML_NURBS_CURVE))
        if (index == ((NodeNurbsCurve *)node)->controlPoint_Field())
            index = ((NodeNurbsCurve *)node)->controlPointX3D_Field();
    if (x3d && (node->getType() == VRML_NURBS_POSITION_INTERPOLATOR))
        if (index == ((NodeNurbsPositionInterpolator *)node)->keyValue_Field())
            index = ((NodeNurbsPositionInterpolator *)node)->controlPoint_Field();
    if (x3d && (node->getType() == VRML_GEO_COORDINATE))
        if (index == ((NodeGeoCoordinate *)node)->point_Field())
            index = ((NodeGeoCoordinate *)node)->pointX3D_Field();
    if (x3d && (node->getType() == VRML_GEO_ELEVATION_GRID)) {
        if (index == ((NodeGeoElevationGrid *)node)->yScale_Field())
            index = ((NodeGeoElevationGrid *)node)->yScaleX3D_Field();
        if (index == ((NodeGeoElevationGrid *)node)->creaseAngle_Field())
            index = ((NodeGeoElevationGrid *)node)->creaseAngleX3D_Field();
        if (index == ((NodeGeoElevationGrid *)node)->geoGridOrigin_Field())
            index = ((NodeGeoElevationGrid *)node)->geoGridOriginX3D_Field();
        if (index == ((NodeGeoElevationGrid *)node)->height_Field())
            index = ((NodeGeoElevationGrid *)node)->heightX3D_Field();
        if (index == ((NodeGeoElevationGrid *)node)->xSpacing_Field())
            index = ((NodeGeoElevationGrid *)node)->xSpacingX3D_Field();
        if (index == ((NodeGeoElevationGrid *)node)->zSpacing_Field())
            index = ((NodeGeoElevationGrid *)node)->zSpacingX3D_Field();
    }
    if (x3d && (node->getType() == VRML_GEO_LOCATION))
        if (index == ((NodeGeoLocation *)node)->geoCoords_Field())
            index = ((NodeGeoLocation *)node)->geoCoordsX3D_Field();
    if (x3d && (node->getType() == VRML_GEO_LOD))
        if (index == ((NodeGeoLOD *)node)->center_Field())
            index = ((NodeGeoLOD *)node)->centerX3D_Field();
    if (x3d && (node->getType() == VRML_GEO_ORIGIN))
        if (index == ((NodeGeoOrigin *)node)->geoCoords_Field())
            index = ((NodeGeoOrigin *)node)->geoCoordsX3D_Field();
    if (x3d && (node->getType() == VRML_GEO_POSITION_INTERPOLATOR))
        if (index == ((NodeGeoPositionInterpolator *)node)->keyValue_Field())
            index = ((NodeGeoPositionInterpolator *)node)->keyValueX3D_Field();
    if (x3d && (node->getType() == VRML_GEO_VIEWPOINT)) {
        if (index == ((NodeGeoViewpoint *)node)->navType_Field())
            index = ((NodeGeoViewpoint *)node)->navTypeX3D_Field();
        if (index == ((NodeGeoViewpoint *)node)->position_Field())
            index = ((NodeGeoViewpoint *)node)->positionX3D_Field();
    }
    return index;
}

//
// checkField() - verify a field reference
//
// check that the node "node" has the field "fieldName"
// if not, print an error
// if so, stash its type in the lexer, and return its index

static int
checkField(Node *node, const MyString &fieldName)
{
    if (!node) return INVALID_INDEX;

    Proto *proto = node->getProto();

    if (!proto) return INVALID_INDEX;

    int index = proto->lookupField(fieldName, x3d);

    if (index == INVALID_INDEX) {
        if (TheApp->getKambiMode())
           if (node->getType() == KAMBI_KAMBI_NAVIGATION_INFO)
               if (strcmp(fieldName, "headBobbingDistance") == 0)
                   scene->errorf("KambiNavigationInfo.headBobbingDistance is deprecated/not supported any more");
        scene->invalidField(proto->getName(x3d), fieldName);
    } else {
        currentType = proto->getField(repairField(node, index))->getType();
    }

    return index;
}

static FieldValue *
convertSFToMFValue(FieldValue *value, int fieldType)
{
    if (value->getType() == SFSTRING && fieldType == MFSTRING) {
        FieldValue *newValue = new MFString(((SFString *) value)->getValue());
        value->unref();
        return newValue;
    } else if (value->getType() == SFNODE && fieldType == MFNODE) {
        NodeList *list = new NodeList();
        list->append(((SFNode *) value)->getValue());
        FieldValue *newValue = new MFNode(list);
        value->unref();
        return newValue;
    } else if (value->getType() == SFBOOL && fieldType == MFBOOL) {
        FieldValue *newValue = new MFBool(((SFBool *) value)->getValue());
        value->unref();
        return newValue;
    } else
        return value;
}

static Field *
createField(int type, const MyString &name)
{
    return new Field(type, name, typeDefaultValue(type));
}

static void
setField(Node *node, int index, FieldValue *value)
{
    if (!node || !value || index < 0) return;

    Proto *proto = node->getProto();

    if (!proto) return;

    int newIndex = repairField(node, index);
    Field *field = proto->getField(newIndex);

    if (field == NULL) {
        scene->errorf("unknown/unsupported field 8-(\n");
        delete value;
        return;
    }

    value = convertSFToMFValue(value, field->getType());

    if (value->getType() != field->getType()) {
        scene->errorf("type mismatch:  field \"%s\"\n", 
                      (const char *)field->getName(x3d));
        delete value;
        value = typeDefaultValue(field->getType());
    } 

    scene->setField(node, newIndex, value);
    if (TheApp->is4Catt())
        node->generateTreeLabel();
}

static void
isField(Node *node, const MyString &fieldName, const MyString &isName)
{
    int srcField, srcEventIn, srcEventOut, srcExposedField;
    int dstField, dstEventIn, dstEventOut, dstExposedField;

    if (!node) return;

    Proto *source = node->getProto();

    if (!source) return;

    if (protoStack.empty()) {
        scene->errorf("IS statement used outside PROTO\n");
        return;
    }

    Proto *proto = protoStack.peek(); // wrong for recursive PROTOs 8-(

    if ((srcExposedField = source->lookupExposedField(fieldName, x3d)) != -1) {
        dstEventIn = proto->lookupEventIn(isName, x3d);
        dstEventOut = proto->lookupEventOut(isName, x3d);

        if ((dstExposedField = proto->lookupExposedField(isName, x3d)) != -1) {
            ExposedField *expField = proto->getExposedField(dstExposedField);
            if (expField != NULL) {
                srcField = source->lookupField(fieldName, x3d);
                if (srcField != -1)
                    expField->addIs(node, srcField, EL_EXPOSED_FIELD,
                                    proto, dstExposedField);
            }
        } else if ((dstField = proto->lookupField(isName, x3d)) != -1) {
            Field *field = proto->getField(dstField);
            if (field != NULL) {
                srcField = source->lookupField(fieldName, x3d);
                if (srcField != -1)
                    field->addIs(node, srcField, EL_EXPOSED_FIELD,
                                 proto, dstField);
            }
        } else if ((dstEventIn = proto->lookupEventIn(isName, x3d)) != -1) {
            EventIn *eventIn = proto->getEventIn(dstEventIn);
            if (eventIn != NULL)
                eventIn->addIs(node, srcExposedField, EL_EXPOSED_FIELD,
                               proto, dstEventIn, EIF_IS);
        } else if ((dstEventOut = proto->lookupEventOut(isName, x3d)) != -1) {
            EventOut *eventOut = proto->getEventOut(dstEventOut);
            if (eventOut != NULL)
                eventOut->addIs(node, srcExposedField, EL_EXPOSED_FIELD,
                                proto, dstEventOut, EOF_IS);
        } else {
            scene->invalidField(source->getName(x3d), isName);
        }
    } else if ((srcField = source->lookupField(fieldName, x3d)) != -1) {
        dstField = proto->lookupField(isName, x3d);
        if (dstField != -1) {
            Field *field = proto->getField(dstField);
            if (field != NULL)
                field->addIs(node, srcField, EL_FIELD, proto, dstField);
        } else {
            scene->invalidField(source->getName(x3d), isName);
        }
    } else if ((srcEventIn = source->lookupEventIn(fieldName, x3d)) != -1) {
        dstEventIn = proto->lookupEventIn(isName, x3d);
        if (dstEventIn != -1) {
            EventIn *eventIn = proto->getEventIn(dstEventIn);
            if (eventIn != NULL)
                eventIn->addIs(node, srcEventIn, EL_EVENT_IN, 
                               proto, dstEventIn, EIF_IS);
        } else {
            scene->invalidField(source->getName(x3d), isName);
        }
    } else if ((srcEventOut = source->lookupEventOut(fieldName, x3d)) != -1) {
        dstEventOut = proto->lookupEventOut(isName, x3d);
        if (dstEventOut != -1) {
            EventOut *eventOut = proto->getEventOut(dstEventOut);
            if (eventOut != NULL)
                eventOut->addIs(node, srcEventOut, EL_EVENT_OUT, 
                                proto, dstEventOut, EOF_IS);
        } else {
            scene->invalidField(source->getName(x3d), isName);
        }
    }
}

static void
route(const MyString &srcNode, const MyString &srcField,
      const MyString &dstNode, const MyString &dstField)
{
    int eventIn;
    int eventOut;
    bool valid = true;

    Node *src = scene->use(srcNode);
    if (!src) {
        scene->invalidNode(srcNode);
        valid = false;
        
    } else
        eventOut = src->lookupEventOut(srcField, x3d);

    Node *dst = scene->use(dstNode);
    if (!dst) {
        scene->invalidNode(dstNode);
        valid = false;
    } else
        eventIn = dst->lookupEventIn(dstField, x3d);

    if ((eventIn == INVALID_INDEX) && (eventOut == INVALID_INDEX)) {
        valid = false;
        scene->errorf("invalid ROUTE command -both end types unknown- in line %d -ignoring\n",
                      lineno); 
    }
 
    if (valid && (eventIn == INVALID_INDEX)) {
        // create matching eventIn for IMPORT command
        if (dst->getType() == X3D_IMPORT) {
            NodeImport *node = (NodeImport *)dst;
            int type = src->getProto()->getEventOut(eventOut)->getType();
            node->addEventIn(type, dstField);
            eventIn = dst->lookupEventIn(dstField, x3d);
        } else {
            scene->errorf("node \"%s\" has no eventIn \"%s\"\n",
                          (const char *) dstNode, (const char *) dstField);
            valid = false;
        }
    }

    if (valid && (eventOut == INVALID_INDEX)) {
        // create matching eventOut for IMPORT command
        if (src->getType() == X3D_IMPORT) {
            NodeImport *node = (NodeImport *)src;
            int type = dst->getProto()->getEventIn(eventIn)->getType();
            node->addEventOut(type, srcField);
            eventOut = src->lookupEventOut(srcField, x3d);
        } else {
            scene->errorf("node \"%s\" has no eventOut \"%s\"\n",
                          (const char *) srcNode, (const char *) srcField);
            valid = false;
        }
    }


    if (valid) {
        src->update();
        dst->update();
        if (!scene->addRoute(src, eventOut, dst, eventIn))
            scene->errorf("invalid ROUTE command in line %d\n",lineno);        
    }

}

static Node *    
addExport(const MyString &srcNode, const MyString &dstNode) {
    NodeExport *node = (NodeExport *) scene->createNode("EXPORT");
    node->localDEF(new SFString(srcNode));
    if (dstNode.length() > 0)
        scene->def(dstNode, node);
    return node;
}

static Node *  
addImport(const MyString &srcNode, const MyString &importedNode,
          const MyString &dstNode) {
    NodeImport *node = (NodeImport *) scene->createNode("IMPORT");
    if (dstNode.length() > 0)
        scene->def(dstNode, node);
    node->inlineDEF(new SFString(srcNode));
    node->importedDEF(new SFString(importedNode));
    return node;
}


static DoubleArray *
intsToFloats(IntArray *ints)
{
    if (ints == NULL) return NULL;

    int len = ints->size();
    DoubleArray *r = new DoubleArray(len);
    const int *d = ints->getData();
    for (int i = 0; i < len; i++) {
        r->set(i, (float) d[i]);
    }
    return r;
}

static DoubleArray *
intsToDoubles(IntArray *ints)
{
    if (ints == NULL) return NULL;

    int len = ints->size();
    DoubleArray *r = new DoubleArray(len);
    const int *d = ints->getData();
    for (int i = 0; i < len; i++) {
        r->set(i, (double) d[i]);
    }
    return r;
}

/* avoid double DEFs while file import */

static MyString
uniqName(const MyString name)
{
    int i = 0;
    if (scene->hasAlreadyName(name)) {
        while (true) {
            int len = strlen((const char*) name) + 512;
            char* buf=(char*) malloc(len);
            mysnprintf(buf, len, "%s_%d", (const char*) name, i++);
            MyString* newName=new MyString(buf);
            free(buf);
            if (!scene->hasAlreadyName(*newName)) {
                NameTranslation.append(new nameTranslation(*newName,name));
                return *newName;
            }
        }
    }
    return name;
}

/* replace double DEFs while file import */

static MyString
checkName(const MyString name)
{
    for (int i = NameTranslation.size() - 1; i >= 0; i--)
        if (name == NameTranslation[i]->oldName) {
            return NameTranslation[i]->newName;
        }
    return name;
}

void forgetNameTranslation(void)
{
    NameTranslation.resize(0);
}

static void 
addCommentsToNode(Node* node)
{
    if (commentNodeList.size() > 0) {
        for (int i = 0;i < commentNodeList.size(); i++)
            node->appendComment(commentNodeList[i]);
        commentNodeList.resize(0);
    }
}

static void 
addCommentsToNodeList(NodeList *nodelist)
{
    if (commentNodeList.size() > 0) {
        for (int i = 0;i < commentNodeList.size(); i++)
            nodelist->append(commentNodeList[i]);
        commentNodeList.resize(0);
    }    
}

static int addDynamicElement(Node *node, Element *element)
{
    int fieldIndex = -1;
    if (nodeStack.empty()) 
        yyerror("syntax error");
    else if (element) { 
        node->getProto()->addElement(element);
        node->update();
        if (element->getElementType() == EL_FIELD) {
            Field *field = (Field *)element;
            // search for number of field to use setField 
            Proto *proto = node->getProto();
            for (int i = 0; i < proto->getNumFields(); i++)
                if (proto->getField(i)->getName(x3d) == field->getName(x3d)) {
                    FieldValue *value = field->getDefault(x3d);
                    value = convertSFToMFValue(value, field->getType());
                    setField(node, i, value);
                    fieldIndex = i;
                }
        }
    }
    return fieldIndex;
}

static int addDynamicElement(Element *element)
{
    return addDynamicElement(nodeStack.peek(), element);
} 

void
addToCurrentComment(char *string)
{
   if (strlen(string) > 0)
       commentList.append(string);
}

void
nodeComment(void)
{
    if (commentList.size() != 0) {
        StringArray *mfString = new StringArray();
        for (List<MyString>::Iterator* commentpointer = commentList.first();
            commentpointer != NULL; commentpointer = commentpointer->next()) {
            const char *string = commentpointer->item();
            bool isVRMLheader = false;
            if (strcmp(string, "#VRML V2.0 utf8") == 0) 
                isVRMLheader = true;
            if (!isVRMLheader) {
                if (string[0] == '\n')
                    string++;
                mfString->append(mystrdup(++string));
            }
        }
        if (mfString->size() > 0) {
            NodeComment *node = (NodeComment *) scene->createNode("#");
            node->comment(new MFString(mfString));
            commentNodeList.append(node);
        }
        commentList.removeAll();
    }
}

void
insideNodeComment(void)
{
}

void
MFComment(void)
{
}

void
insideMFComment(void)
{
}

void 
illegalX3DV(void)
{
    swDebugf("Warning: Illegal X3DV file (missing PROFILE statement)\n");
}

#ifdef HAVE_LIBEXPAT

// XML parsing code from doug sanden
// incomplete parser, misses PROTO, currently experimental code

// "nodes" current node's contained children when pushing

# include <expat.h>
# include <ctype.h>
static int depth = 0; //xml elements
static int level = 0; //x3d nodes
static Stack<NodeList *> nodes;

#define STATUS_NONE 0
#define STATUS_NODE 1
#define STATUS_USE 2
#define STATUS_ROUTE 3
#define STATUS_SCRIPT 4
#define STATUS_SCRIPT_ELEMENT 5
#define STATUS_PROTO 6
#define STATUS_PROTOINTERFACE -7
#define STATUS_PROTO_ELEMENT 8
#define STATUS_PROTOBODY 9
#define STATUS_PROTOINSTANCE_FIELDVALUE 10
#define STATUS_HEAD 11
#define STATUS_IMPORTEXPORT 12
#define STATUS_SHADERPART 13

static Stack<int> status;
static Stack<int> currentFieldIndex;
static bool done;
static NodeList *rootNodes;
char *currentURL = NULL;
char *parentURL = NULL;
static Array<XML_Parser> x3dParser;
static int contextIndex = -1; //contextIndex 0=scene, protobody 1, protobody 2..
static int doingcdata = 0;
static int gotcdata = 0;

#ifdef __sgi
# define XMLCALL
#endif

extern void startProto(void);

static void XMLCALL startCDATA (void *userData) 
{
    if (currentURL != NULL) {
        free(currentURL);
        currentURL = NULL;
    }
    currentURL = (char *) malloc(1);
    currentURL[0] = '\0';
    doingcdata = 1;
    gotcdata = 0;

}

static void XMLCALL endCDATA (void *userData) 
{
    doingcdata = 0;
}

static void XMLCALL handleCDATA (void *userData, const char *string, int len) 
{
    if (doingcdata) {
        if (len == 1)
            if (string[0] == '\r')
                return;
        int curlen = strlen(currentURL);
        int newlen = curlen + len + 1;

        // == awk gsub("\r", "", string)
        char *temp = (char *)malloc(len + 2);
        strncpy(temp, string, len);
        temp[len] = '\0';
        temp[len + 1] = '\0';
        char *firstToken = strtok(temp, "\r");
        currentURL = (char *)realloc(currentURL, newlen);
        currentURL[curlen] = 0;
        if (firstToken == NULL)
            currentURL = strcat(currentURL, temp);
        else {
            char *token = strtok(firstToken, "\r");
            while (token != NULL) {
                currentURL = strcat(currentURL, token);
                token = strtok(token + strlen(token) + 1, "\r");
            }                
        }
        free(temp);
        gotcdata = strlen(currentURL);
    }
}


static void XMLCALL handleComment(void *userData, const XML_Char *data)
{
    char *mydata = strdup(data);
    addToCurrentComment(mydata);
    nodeComment(); //converts from list of strings to list of comment nodes
    if (protoStack.peek())
        addCommentsToNodeList(nodes.peek());
    else if (nodeStack.peek() == NULL)
        addCommentsToNodeList(rootNodes);
    else {
        addCommentsToNodeList(nodes.peek());
    }
}

static char **mfstrsplit(char *string, int *tcount)
{
    /* special version of strsplit just for mf strings */
    int count = 0;
    char **toksArray;
    char *token;
    int toksSize = 256;
    toksArray = (char **)malloc(sizeof(char*) * toksSize);
 
    int len = strlen(string);
    if (len == 0) /* is it an empty string */
        count = 0;
    else {
        char *quote1 = strchr(string, '"');
        char *apos1 = strchr(string, '\'');
        // is it an SF String. If so, there won't be any ' or "
        bool isSF =  quote1 == NULL && apos1 == NULL;  
        // check to see if the ' is in the middle of the string like
        // string="isn't"
        isSF = isSF || (quote1 == NULL && apos1-string > 0); 
        if (isSF) {
            toksArray[0] = string;
            count = 1;
        } else {
            // parse like an MFString
            // decide what the SFs are wrapped with - assume it's the first 
            // type ' or " encountered
            bool isQuoted = quote1 != NULL;
            if (quote1 != NULL && apos1 != NULL) 
                isQuoted = apos1 > quote1;
            const char *seps;
            char *start;
            if (isQuoted) {
                seps = "\"";
                start = quote1;
        } else {
            seps = "'";
            start = apos1;
        }
        int k = 0;
        count = 0;
        token = strtok(start, seps);
        while (token != NULL) {
            /* While there are tokens in "string" */
            k++;
            if (k % 2 == 0) {
                // verify it's whitespace or , 
                // otherwise assume they forgot the whitespace delimiter
                const char *wseps = " \t\n\r,";
                bool white = true;
                for (int j = 0; j < strlen(token); j++)
                    white = white && (strchr(wseps,token[j]) != NULL);
                if (!white) 
                    k++;
            }
            if (k % 2 != 0) {
                // every second token is supposed to be whitespace 
                // ie string='"WALK" "ANY"' has a whitespace between tokens 
                count++;
                if (count + 1 > toksSize) {
                    toksSize = 2 * count;
                    toksArray = (char **)realloc(toksArray, sizeof(char*) *
                                                            toksSize);
                }
                toksArray[count-1] = token;
            }
            /* Get next token: */
            token = strtok(NULL, seps);
        }
        toksArray[count] = NULL;
    }
   }
   *tcount = count;

   return toksArray;
}

static char **strsplit(char *string, char *seps, int *tcount)
{
    int count = 0;
    char **toksArray;
    char *token;
    int toksSize = 256;
    toksArray = (char **)malloc(sizeof(char*) * toksSize);
    token = strtok(string, seps);
    while (token != NULL) {
        /* While there are tokens in "string" */
        count++;
        if (count + 1 > toksSize) {
            toksSize = 2 * count;
            toksArray = (char **)realloc(toksArray,sizeof(char*) * toksSize);
        }
        toksArray[count - 1] = token;
        /* Get next token: */
        token = strtok(NULL, seps);
    }
    toksArray[count] = NULL;
    *tcount = count;
    return toksArray;
}

#define TYPE_BOOL   0
#define TYPE_STRING 1
#define TYPE_FLOAT  2
#define TYPE_INT    3

FieldValue *parseFieldValue(int curtype, const char* value)
{
    int sftype = curtype;
    int fmtype = -1;
    if (isMFType(curtype))
        sftype = getSFType(curtype);

    switch (sftype) {
        case SFBOOL:
        fmtype = TYPE_BOOL; 
        break;
        case SFSTRING:
        fmtype = TYPE_STRING;
        break;
        case SFCOLOR:
        case SFCOLORRGBA:
        case SFDOUBLE:
        case SFFLOAT:
        case SFMATRIX3F:
        case SFMATRIX4F:
        case SFROTATION:
        case SFTIME:
        case SFVEC2F:
        case SFVEC3D:
        case SFVEC3F:
        case SFVEC4F:
        fmtype = TYPE_FLOAT;
        break;
        case SFIMAGE:
        case SFINT32:
        fmtype = TYPE_INT;
        break;
        default:
        assert("internal error: no fmtype");
    }

    FieldValue *fv;
    char seps[]  = " ,\t\n";
    char **tokens;
    int tcount;
    switch (fmtype) {
      case TYPE_BOOL:
        {
        char cbool[6];
        int len = strlen(value);
        if (len == 4 || len == 5) {
            strcpy(cbool, value);
            for (int i = 0; i < len; i++) { 
                // upper casing covers: false, False, FALSE
                cbool[i] = toupper(cbool[i]); 
            }
            if (!strcmp(cbool, "FALSE")) 
                fv = new SFBool(false);
            if (!strcmp(cbool,"TRUE")) 
                fv = new SFBool(true); 
        }
        }
        break;
      case TYPE_STRING:
        {
        StringArray *strings = new StringArray();
        // doesn't split on blank (but does on ") 
        // in case a filename has a blank in it.
        tokens = mfstrsplit((char *)value, &tcount);
        for (int i = 0; i < tcount; i++) {
            strings->append(MyString(tokens[i]));
        }
        if (curtype == MFSTRING)
            fv = new MFString(strings);  // '"WALK" "ANY"' 
        else if (curtype == SFSTRING)
            fv = new SFString(strings->get(0));
        free(tokens);
        }
        break;
      case TYPE_FLOAT:
        {                                     
        DoubleArray *floats = new DoubleArray();
        tokens = strsplit((char *)value, seps, &tcount);
        double tmp;
        for (int i = 0; i < tcount; i++) {
            sscanf(tokens[i], "%lf", &tmp);
            floats->append(tmp);
        }
        fv = floatsToType(floats, curtype);
        free(tokens);
        }
        break;
      case TYPE_INT:
        {
        IntArray *ints = new IntArray();
        tokens = strsplit((char *) value, seps,&tcount);
        for (int i = 0; i < tcount; i++) {
            int icnt;
            int itmp;
            /* check for hex */
            if ((strchr(tokens[i], 'x') == NULL) &&
                (strchr(tokens[i], 'X') == NULL))
                icnt = sscanf(tokens[i],"%d",&itmp);
            else
                icnt = sscanf(tokens[i],"%x",&itmp); 
            if (icnt > 0)
                ints->append(itmp);
        }
        fv = intsToType(ints, curtype);
        free(tokens);
        }
        break;
      default:
        assert("internal error: no fmtype");
    }
    return fv;
}

/*
Concept of operation:
<X3D>
 <Scene>
  <Transform>
   <Shape>
     ...
   </Shape>
   <Transform>
     ...
   </Transform>
  </Transform>
 </Scene>
<X3D>

To gather children [] or other defaultContainer field data nested 
within a <Type> </Type> pair, we provide an empty node list at the end of 
a xml start() and check it for contents at the beginning of the corresponding xml end().
If there's something in the node list, and the parent node takes nodes in children or other field
as indicated by a status flag we go through it item by item finding the best parent field to put it in.
Some xml elements -like X3D, Scene, ProtoInterface, ProtoBody, head- don't correspond to vrml nodes.
we skip adding non-node elements in the end() function by checking status and acting accoringly. 

depth - indent depth for xml 
level - node depth
status     - holds a status flag indicating how to handle the xml element in end()
- STATUS_NONE  - a non-node xml element, such as X3D, Scene, ROUTE, IS - skip in end()
- STATUS_NODE  - a regular node - most go here
- STATUS_PROTOINSTANCE - a proto instance, with fieldValues
- STATUS_PROTO - a proto definition
...
nodeStack  - holds the current node (or NULL at the scene rootnode level)
protoStack - holds the current proto (or NULL in the scene context)
current_node  - is the one that children  nodes and fields are added to
current_proto - is where proto body nodes are added (if null, added to scene)
nodes      - stack of node lists. Each nodelist captures the children or 
             defaultContainer child elements, or SFNode/MFNode field nodes, 
             or protobody nodes, for retrieval in xml end().
*/

static void XMLCALL start(void *data, const char *element, const char **attrib)
{
    int i;

    //we'll do some unconditional pushes here, and if wrong we'll pop and re-push below
    status.push(STATUS_NONE); //assume a non-node xml element here
    Node  * current_node  = nodeStack.peek(); //null is at the scene rootnode level
    nodeStack.push(current_node); //assume a non-node xml element here and re-push parent node as current node to bridge node gap
    Proto * current_proto = protoStack.peek(); //null is in the scene context

    if (strcmp(element, "X3D") && strcmp(element, "Scene") && 
        strcmp(element, "head") && strcmp(element, "component") && 
        strcmp(element, "IMPORT") && strcmp(element, "EXPORT") && 
        strcmp(element, "meta") && strcmp(element, "ROUTE")) {
        Node *node = NULL;
        bool isUse = false;
        /* check for a USE */
        for (i = 0; attrib[i] != NULL; i += 2) { 
            if (strcmp("USE",attrib[i]) == 0) { //"USE" 
                node = scene->use(attrib[i + 1]);
                MyString name = "";
                name += attrib[i + 1];
                checkName(name);
                if (node != NULL) {
                    isUse = true;
                    status.pop();
                    status.push(STATUS_USE);
                    nodeStack.pop();
                    nodeStack.push(node);
                    current_node = node;
                    level++;
                    node->appendTo(nodes.peek());
                }
                break; //if it's a USE we ignor all other attributes
            }
        }
        if (!isUse) {
            /* create node */
            bool protoInstance = false;
            if (!strcmp(element, "field")) {
                /* doesn't create a node, adds to it's parents fields */
                const char *name = NULL;
                const char *type = NULL;
                const char *accessType = NULL;
                const char *value = NULL;
                const char *appinfo = NULL;
                const char *documentation = NULL;
                for (i = 0; attrib[i] != NULL; i += 2) { 
                    if (!strcmp(attrib[i], "name"))
                        name = attrib[i + 1];
                    else if (!strcmp(attrib[i], "type"))
                        type = attrib[i + 1];
                    else if (!strcmp(attrib[i], "accessType"))
                        accessType = attrib[i + 1];
                    else if (!strcmp(attrib[i],"value"))
                        value = attrib[i + 1];
                    else if (!strcmp(attrib[i],"appinfo"))
                        appinfo = attrib[i + 1];
                    else if (!strcmp(attrib[i],"documentation"))
                        documentation = attrib[i + 1];
                    else
                        swDebugf("unrecognized field attribute %s line %d -ignoring\n",
                                 attrib[i], lineno);
                }
                int itype = typeStringToEnum(type); //data type ie MFString, SFVec3f ...
                FieldValue *fv = SillyDefaultValue(itype);
                if (value) {
                    /*do string delimited values here in xml start(), and do contained SFNode/MFNode values in xml end() */
                    fv = parseFieldValue(itype, value);
                }

                Element *element = NULL;
                if (!strcmp(accessType, "inputOnly")) {
                    element = new EventIn(itype, MyString(name));
                } else if (!strcmp(accessType, "outputOnly")) {
                    element = new EventOut(itype, MyString(name));
                } else if (!strcmp(accessType, "initializeOnly")) {
                    element = new Field(itype, MyString(name), fv);
                } else if (!strcmp(accessType, "inputOutput")) {
                    element = new ExposedField(itype, MyString(name), fv);
                }
                element->setAppinfo(MyString(appinfo));
                element->setDocumentation(MyString(documentation));

                int nullStatus = status.pop();
                int currStatus = status.peek();
                bool isScript = status.peek() == STATUS_SCRIPT; 
                bool isProto = status.peek() == STATUS_PROTOINTERFACE;
                status.push(nullStatus);
                if (isScript) {
                    NodeScript *current_script = (NodeScript *)current_node; 
                    if (current_script != NULL) {
                        int ifield = addDynamicElement(current_script, element);
                        currentFieldIndex.push(ifield);
                        status.pop();
                        status.push(STATUS_SCRIPT_ELEMENT); 
                    }
                }
                if (isProto) {
                    if (current_proto != NULL) {
                        int ifield = current_proto->addElement(element);
                        currentFieldIndex.push(ifield);
                        status.pop();
                        status.push(STATUS_PROTO_ELEMENT); 
                    }
                }
                // we need to look for SFNode/MFNode contained field values 
                // when we get to xml end()
            } else if (!strcmp(element, "Script") || 
                       !strcmp(element, "ComposedShader") || 
                       !strcmp(element, "ShaderProgram") || 
                       !strcmp(element, "PackagedShader")) {
                if (!strcmp(element, "Script"))
                    node = new NodeScript(scene);
                else
                    node = newNode(element);
                if (node) {
                    status.pop();
                    status.push(STATUS_SCRIPT);
                    XML_SetCdataSectionHandler(x3dParser[contextIndex], 
                                               startCDATA, endCDATA);
                    XML_SetCharacterDataHandler(x3dParser[contextIndex], 
                                                handleCDATA);
                    gotcdata = 0;
                }
            } else if (!strcmp(element, "ShaderPart")) {
                //seems like if you have a url, the url can be a CDATA child.
                //problem: ComposedShader can have a direct CDATA, 
                // and so can it's child ShaderPart have a CDATA
                // and I'm not assigning the retrieved ComposedShader CDATA to 
                // ComposedShader node
                // until I get to /ComposedShader.
                parentURL = currentURL;
                currentURL = NULL;
                node = newNode(element);
                if (node) {
                    status.pop();
                    status.push(STATUS_SHADERPART);
                } 
            } else if (!strcmp(element, "fieldValue")) {
                /* doesn't create a node, adds to it's parents fields */
                //<fieldValue name='initValuep' value='.15'/>
                const char *name = NULL;
                const char *value = NULL;
                for (i = 0; attrib[i] != NULL; i += 2) { 
                    if (!strcmp(attrib[i], "name"))
                        name = attrib[i + 1];
                    else if (!strcmp(attrib[i],"value"))
                        value = attrib[i + 1];
                    else
                        swDebugf("unrecognized fieldValue attribute %s line %d -ignoring\n",
                                 attrib[i], lineno);
                }
                int ifield = -1;
                int itype = -1;

                if (current_node != NULL) {
                    Proto *proto = current_node->getProto();
                    int nf = proto->getNumFields();
                    Field *f = NULL;
                    for (int j = 0; j < nf; j++) {
                        f = proto->getField(j);
                        if (f->getName(x3d) == MyString(name)) {
                            ifield = j;
                            itype = f->getType();
                        }
                    }
                    if (ifield > -1) {
                        if (value) {
                            FieldValue *fv = SillyDefaultValue(itype);
                            // do string delimited values here in xml start(), 
                            // and do contained SFNode/MFNode values in xml end()
                            fv = parseFieldValue(itype, value);
                            current_node->setField(ifield, fv);
                        }
                        currentFieldIndex.push(ifield);
                        status.pop();
                        status.push(STATUS_PROTOINSTANCE_FIELDVALUE); 
                    }
                }
            } else if (!strcmp(element, "ProtoDeclare")) {
                const char *name = NULL;
                const char *appinfo = NULL;
                const char *documentation = NULL;

                for (i = 0; attrib[i] != NULL; i += 2) { 
                    if (!strcmp(attrib[i], "name"))
                        name = attrib[i + 1];
                    else if (!strcmp(attrib[i], "appinfo"))
                        appinfo = attrib[i + 1];
                    else if (!strcmp(attrib[i], "documentation"))
                        documentation = attrib[i + 1];
                    else
                        swDebugf("unrecognized ProtoDeclare attribute %s line %d -ignoring\n",
                                 attrib[i], lineno);
                }
                Proto *proto = scene->getProto(MyString(name));
                if ((proto == NULL) || proto->isScriptedProto()) {
                   proto = new Proto(scene, MyString(name));
                   proto->setAppinfo(appinfo);
                   proto->setDocumentation(documentation);
                } else
                   proto->deleteElements(); 
                protoStack.push(proto); 
                current_proto = proto;
                level++;          
                status.push(STATUS_PROTO);
                if (!scene->addProtoName(MyString(name))) {
                    swDebugf("warning: proto already definied: %s\n",name);
                }
                startProto();
            } else if (!strcmp(element, "ExternProtoDeclare")) {
                const char *name = NULL;
                const char *appinfo = NULL;
                const char *documentation = NULL;
                const char *url = NULL;

                for (i = 0; attrib[i] != NULL; i += 2) { 
                    if (!strcmp(attrib[i], "name"))
                        name = attrib[i + 1];
                    else if (!strcmp(attrib[i], "appinfo"))
                        appinfo = attrib[i + 1];
                    else if (!strcmp(attrib[i], "documentation"))
                        documentation = attrib[i + 1];
                    else if (!strcmp(attrib[i], "url"))
                        url = attrib[i + 1];
                    else
                        swDebugf("unrecognized ExternProtoDeclare attribute %s line %d -ignoring\n",
                                 attrib[i], lineno);
                }
                Proto *proto = new Proto(scene, MyString(name));
                proto->setAppinfo(appinfo);
                proto->setDocumentation(documentation);
                if (url) {
                    int itype = typeStringToEnum("MFString"); 
                    FieldValue *fv = SillyDefaultValue(itype);
                    fv = parseFieldValue(itype, url);
                    proto->addURLs(fv);
                } else
                    swDebugf("warning: extern proto has no url field: %s\n",
                             name);

                protoStack.push(proto); 
                current_proto = proto;
                level++;          
                status.push(STATUS_PROTO);
                if (!scene->addProtoName(MyString(name))) {
                    swDebugf("warning: extern proto already definied: %s\n",name);
                } 
                startProto();
            } else if (!strcmp(element, "ProtoInterface")) {
                status.pop();
                status.push(STATUS_PROTOINTERFACE);
            } else if (!strcmp(element, "ProtoBody")) {
                status.pop();
                status.push(STATUS_PROTOBODY);
            } else if (!strcmp(element, "IS")) {
            } else if (!strcmp(element, "connect")) {
                const char *nodeField = NULL;
                const char *protoField = NULL;

                for (i = 0; attrib[i] != NULL; i += 2) { 
                    if (!strcmp(attrib[i], "nodeField"))
                        nodeField = attrib[i + 1];
                    else if (!strcmp(attrib[i],"protoField"))
                        protoField = attrib[i + 1];
                    else
                        swDebugf("unrecognized IS connect attribute %s line %d -ignoring\n",
                                 attrib[i], lineno);
                }
                isField(current_node, MyString(nodeField), MyString(protoField));
            } else if (!strcmp(element, "ProtoInstance")) {
                // <ProtoInstance DEF='SliderPhotoTransparency' containerField='children' name='sliderProto'>
                const char *name = NULL;
                for (i = 0; attrib[i] != NULL; i += 2) { 
                    if (!strcmp(attrib[i], "name"))
                        name = attrib[i + 1];
                }
                if (name == NULL) 
                    swDebugf("ProtoInstance has no type line %d\n",lineno);
                else {
                    Proto* proto = scene->getProto(MyString(name));
                    if (proto) {
                        protoInstance = true;
                        node = proto->create(scene);
                    }
                    else
                        swDebugf("ProtoInstance - failed to find proto of type %s line %d\n",name,lineno);
                }
                status.pop();
                status.push(STATUS_NODE);
            } else {
                node = newNode(element); // element would be a string like "Transform" 
                if (node) {
                    status.pop();
                    status.push(STATUS_NODE);
                } 
            }
            if (node != NULL) {
                nodeStack.pop();
                nodeStack.push(node);
                current_node = node;
                level++;
                node->appendTo(nodes.peek());
                for (i = 0; attrib[i] != NULL; i += 2) { 
                    if (strcmp("DEF", attrib[i]) == 0)   //"DEF" 
                        scene->def(uniqName(attrib[i + 1]), node);  // "myTrans"
                    else if (!strcmp("containerField", attrib[i])) {
                        //skip containerField which is in specs -other tools export- but dune doesn't need
                        continue; 
                    } else if (!strcmp("name", attrib[i]) && protoInstance) {
                        //ProtoInstance has a name= field processed above, but checkField doesn't handle
                        continue;
                    } else {
                        int iField = checkField(current_node, attrib[i]);
                        if (iField != INVALID_INDEX) {
                            // x3d knows the node type and field type - 
                            // get types before attempting to parse tokens
                            iField = repairField(nodeStack.peek(), iField);
                            int curtype = current_node->getProto()->
                                          getField(iField)->getType();
                            FieldValue *fv;
                            fv = parseFieldValue(curtype, attrib[i + 1]);
                            setField(current_node, iField, fv);
                        }
                    }
                }
                protoInstance = false;
            }
        }
    } else {
        if (!strcmp(element, "ROUTE")) {
            MyString srcNode, srcField, dstNode, dstField, tmp;
            for (i = 0; attrib[i] != NULL; i += 2) { 
                tmp = "";
                tmp += MyString(attrib[i + 1]);
                if ( strcmp("fromNode", attrib[i]) == 0)    
                    srcNode = tmp;  
                else if (strcmp("fromField", attrib[i]) == 0)
                    srcField = tmp;
                else if (strcmp("toNode", attrib[i]) == 0)
                    dstNode = tmp;
                else if (strcmp("toField", attrib[i]) == 0)
                    dstField = tmp;
            }
            if (srcNode && srcField && dstNode && dstField) {
                status.pop();
                status.push(STATUS_ROUTE);
                level++;
                route(srcNode,srcField, dstNode, dstField);
            } else
                swDebugf("ouch - bad route fn=%s ff=%s tn=%s tf=%s lineno=%d\n",
                         srcNode.getData(), srcField.getData(),
                         dstNode.getData(), dstField.getData(), lineno);
        }
        if (!strcmp(element, "head")) {
            status.pop();
            status.push(STATUS_HEAD);
        }
        if (!strcmp(element, "meta")) {
            if (status.peek() == STATUS_HEAD) {
                const char *name = NULL;
                const char *content = NULL;
		for (i = 0; attrib[i] != NULL; i += 2) { 
                    if (strcmp("name", attrib[i]) == 0)    
                        name = attrib[i + 1];  
                    if (strcmp("content", attrib[i]) == 0)    
                        content = attrib[i + 1];  
                }
                if (name != NULL && content != NULL)
                    scene->addMeta(strdup(name), strdup(content));
            }
        }
        if (!strcmp(element, "IMPORT") || !strcmp(element, "EXPORT")) {
            Node *node = NULL;
            if (!strcmp(element,"IMPORT")) {
                const char *InlineDEF = NULL;
                const char *importedDEF = NULL;
		const char *as = NULL;
                for (i = 0; attrib[i] != NULL; i += 2) { 
                    if (strcmp("InlineDEF", attrib[i]) == 0)    
                        InlineDEF = attrib[i + 1];  
                    if (strcmp("importedDEF", attrib[i]) == 0)    
                        importedDEF = attrib[i + 1];  
                    if (strcmp("AS", attrib[i]) == 0)    
                        as = attrib[i + 1];  
                }
                if (InlineDEF != NULL && importedDEF != NULL)
                    node = addImport(checkName(InlineDEF),importedDEF, as);
                else
                    swDebugf("IMPORT missing InlineDEF=[%s] or importedDEF=[%s]\n",
                             InlineDEF,importedDEF);

            } else if (!strcmp(element,"EXPORT")){
                const char *localDEF = NULL;
                const char *as = NULL;
                for (i = 0; attrib[i] != NULL; i += 2) { 
                    if (strcmp("localDEF", attrib[i]) == 0)    
                        localDEF = attrib[i + 1];  
                    if (strcmp("AS", attrib[i]) == 0)    
                        as = attrib[i + 1];  
                 }
                 if (localDEF != NULL)
                     node = addExport(checkName(localDEF), as);
                 else
                     swDebugf("EXPORT missing localDEF\n");

            }
            if (node) {
                status.pop();
                status.push(STATUS_IMPORTEXPORT);
                nodeStack.pop();
                nodeStack.push(node);
                current_node = node;
                level++;
                node->appendTo(nodes.peek());
            } 
        }
    }
    depth++;
    nodes.push(new NodeList());
}

static void XMLCALL end(void *data, const char *el) 
{
    NodeList *childList;  
    bool usedChildren = false;
    depth--;
    childList = nodes.pop();
    Node *current_node = nodeStack.pop();
    Proto *current_proto = protoStack.peek(); 
    int istatus = status.pop();

    if (istatus > 0) {
        if (istatus == STATUS_SCRIPT_ELEMENT || istatus == STATUS_PROTO_ELEMENT) {
            /* it was a script field */
            int nc = childList->size();
            int ifield =  currentFieldIndex.pop();
            if (nc > 0) {
                // we have field > SFNode or MFNode value > contained nodes
                if (istatus == STATUS_SCRIPT_ELEMENT) {
                    NodeScript *parentScript = (NodeScript *)current_node; //nodeStack.peek(); //or current_node
                    FieldValue *fv = parentScript->getField(ifield);

                    if (fv->getType() == SFNODE) {
                        Node * cc = childList->get(0);
                        FieldValue *newValue = new SFNode(cc) ; 
                        parentScript->setField(ifield,newValue);
                    } else if (fv->getType() == MFNODE){
                        NodeList *list = new NodeList();
                        for (int i = 0; i < nc; i++)
                            list->append(childList->get(i));
                        FieldValue *newValue = new MFNode(list);
                        parentScript->setField(ifield, newValue);
                    }
                } else if (istatus == STATUS_PROTO_ELEMENT) {
                    Proto *currentProto = current_proto; //protoStack.peek();
                    Field *ff = current_proto->getField(ifield);
                    FieldValue *fv = ff->getDefault(x3d); 
                    if (fv->getType() == SFNODE) {
                        Node * cc = childList->get(0);
                        fv->addNode(cc);
                    } else if (fv->getType() == MFNODE){
                        for (int i = 0; i < nc; i++)
                            fv->addNode(childList->get(i));
                    }
                }
            }
        } else if (istatus == STATUS_PROTOINSTANCE_FIELDVALUE) {
            /* it was a protoinstance fieldvalue */
            int nc = childList->size();
            int ifield =  currentFieldIndex.pop();
            if (nc > 0) {
                Node *node = current_node;
                FieldValue *fv = node->getField(ifield);
                if (fv->getType() == SFNODE) {
                    Node * cc = childList->get(0);
                    FieldValue *newValue = new SFNode(cc) ; 
                    node->setField(ifield,newValue);
                } else if (fv->getType() == MFNODE){
                    NodeList *list = new NodeList();
                    for (int i = 0; i < nc; i++)
                        list->append(childList->get(i));
                    FieldValue *newValue = new MFNode(list);
                    node->setField(ifield, newValue);
                }
            }
        } else if (istatus == STATUS_PROTOBODY) {
            int nc = childList->size();
            if (nc > 0) {
                //Q. where do we put the proto body nodes?
                if (current_proto) {
                    Node* first = childList->get(0);
                    childList->remove(0);
                    current_proto->define(first, childList); // define(primary,list)
                }
            }
        } else if (istatus == STATUS_PROTO) {
            Proto *currentProto = protoStack.peek();
            Proto *newProto = protoStack.pop();
            if (currentProto != NULL)
                scene->addProto(currentProto->getName(x3d), newProto); 
            stopProto();
            level--;
        } else if (istatus == STATUS_SHADERPART) {
            level--;
            if (gotcdata) {
                MFString *mfs = new MFString(currentURL);
                currentURL = NULL; //ownership transferred to MFString
                int ic = checkField(current_node, "url");
                current_node->setField(ic, mfs);
            }
            currentURL = parentURL;
            if (currentURL)
               gotcdata = strlen(currentURL);
            else
               gotcdata = 0;
        } else if (istatus == STATUS_NODE || 
                   istatus == STATUS_SCRIPT || 
                   istatus == STATUS_USE || 
                   istatus == STATUS_ROUTE || 
                   istatus == STATUS_IMPORTEXPORT) {
            level--;
            if (istatus == STATUS_SCRIPT) {
                /* any script url CDATA section ? */
                XML_SetCdataSectionHandler(x3dParser[contextIndex], NULL, NULL);
                XML_SetDefaultHandler(x3dParser[contextIndex], NULL);
                if (gotcdata) {
                    MFString * mfs = new MFString(MyString(currentURL));
                    currentURL = NULL; //ownership transferred to MFString
                    int ic = checkField(current_node, "url");
                    current_node->setField(ic, mfs);
                }
            }
            int nc = childList->size();
            if (nc > 0) {
                if (istatus == STATUS_NODE || istatus == STATUS_SCRIPT) {
                    /* children or defaultContainerfield possible */
                    int ic = current_node->getChildrenField();
                    if (ic > -1) {
                        // it has children so we'll put the node in the children field
                        current_node->addFieldNodeList(ic,childList);
                    } else {
                        /* no chidren field, so we'll hunt down a good field to put the node in */
                        int nc = childList->size();
                        for (int i = 0; i < nc; i++) {
                            Node* child = childList->get(i);
                            int childType = child->getType();
                            int ic = current_node->findFirstValidFieldType(childType);
                            if (ic < 0) {
                                int childClass = child->getNodeClass();
                                ic = current_node->findFirstValidFieldType(childClass);
                            }
                            if (ic > -1) {
                                Field *field = current_node->getProto()->getField(ic);
                                int fieldType = field->getType();
                                if (fieldType == SFNODE)
                                    current_node->setField(ic, new SFNode(child));
                                else if (fieldType == MFNODE) {
                                    /* works with 2.x3d and 19.x3d */
                                    NodeList *nl = new NodeList(childList->get(i));
                                    current_node->addFieldNodeList(ic,nl);
                                }
                                usedChildren = true;
                            } else {
                                swDebugf("internal parse error: no field index %d\n",
                                         ic);
                            }
                        }
                    }
                } else if (istatus == STATUS_USE) {
                    swDebugf("USE should not have children - ignoring, lineno=%d\n",
                             lineno);
                } else if (istatus == STATUS_ROUTE) {
                    swDebugf("ROUTE should not have children - ignoring, lineno=%d\n",
                             lineno);
                } else if (istatus == STATUS_IMPORTEXPORT) {
                    swDebugf("Inline, IMPORT and EXPORT should not have children - ignoring, lineno=%d\n",
                             lineno);
                }
            } 
            if (level == 0) {
                //level tracks real nodes not nodeless xml elements such as <X3D> and <Scene> (use depth for all elements)
                //so when we get to level 0, it means there's no more real nodes above us in the nodeListX3d -or scenegraph-
                // and we should take this real node and shove it .. into rootNodes.
                rootNodes->append(current_node);
            }
        } 
    } 
}

const char *parseX3d()
{
    setX3d();
    rootNodes = new NodeList();
    done = false;     
    contextIndex++;
    x3dParser[contextIndex] = XML_ParserCreate(NULL);

    XML_SetElementHandler(x3dParser[contextIndex], start, end);
    //XML_SetCdataSectionHandler(x3dParser[contextIndex], startCDATA, endCDATA);
    //XML_SetDefaultHandler(x3dParser[contextIndex], handleCDATA);
    //XML_SetUserData(x3dParser[contextIndex], &iparent); // iparent
    XML_SetCommentHandler(x3dParser[contextIndex], handleComment);

    int max_size = 1024; 
    char *buf = (char *) malloc(max_size);
    int count = 0;
    const char *retval;
    bool xmlError = false;
    depth = 0;
    level = 0;
    while (!nodes.empty())
        nodes.pop();
    while (!nodeStack.empty())
        nodeStack.pop();
    while (!protoStack.empty())
        protoStack.pop();
    do {
#ifdef HAVE_LIBZ
        count = gzread(inputFile, buf, max_size);
#else
        char *more = fgets(buf, max_size, inputFile);
        count = (more == NULL) ? 0 : strlen(buf);
#endif
        if (count > 0) {
            XML_Parser parser = x3dParser[contextIndex];
            if (XML_Parse(parser, buf, count, FALSE) == XML_STATUS_ERROR) {
               swDebugf("Xml error: %s at line %u\n",
                        XML_ErrorString(XML_GetErrorCode(parser)),
                        XML_GetCurrentLineNumber(parser));
                retval = "ouch - couldn't finish x3d parsing";
                xmlError = true;
                break;
            }
            lineno++;
        }
    } while (count > 0);
    bool saveXmlError = xmlError;
    XML_ParserFree(x3dParser[contextIndex]);
    contextIndex--;
    free(buf);
    if (currentURL != NULL) {
        free(currentURL);
        currentURL = NULL;
    }
    if (!saveXmlError) {
        retval = NULL;
        // recursive: addNodes indirectly calls 
        // Scene.cpp L.497 scanForExternProtos() and scanForInlines(nodes)
        // which call parseX3D
        scene->addNodes(targetNode, targetField, rootNodes);
    }
    return retval;
}
#endif

