/* readscene.c */

#include "readscene.h"
#include "geom.h"
#include "error.h"

int lineno;

extern int yyparse(void);

void ReadRad(void)
{
	MATERIALLIST *oMaterialLib = MaterialLib;
	GEOMLIST *oWorld = World;
	PATCHLIST *oPatches = Patches;
	int opatchid;

	World = GeomListCreate();
	MaterialLib = MaterialListCreate();

	ErrorReset();
	opatchid = PatchGetNextID();
	PatchSetNextID(1);

	lineno = 1;
	yyparse();

	if (ErrorOccurred() || GeomListCount(World) < 1) {
/* restore the old scene if there were errors while loading the new one */
		MaterialLib = oMaterialLib;
		World = oWorld;
		Patches = oPatches;
		PatchSetNextID(opatchid);

/* syntax errors should have been reported elsewhere, the only
 * kind of error that still has to be reported is when one loads
 * a valid input file containing no scene, but eg only material
 * descriptions. */
		if (!ErrorOccurred())
			Error(NULL, "Empty world.");
			
		return;
	}

/* dispose the old data */
	PatchListDestroy(oPatches);

	GeomListIterate(oWorld, GeomDestroy);
	GeomListDestroy(oWorld);

	MaterialListIterate(oMaterialLib, MaterialDestroy);
	MaterialListDestroy(oMaterialLib);

/* build the new patch list, this is duplicating already available
 * information and as such potentially dangerous, but we need it
 * so many times, so ... */
	Patches = BuildPatchList(World, PatchListCreate());
}

