Index: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h	(revision 1284)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h	(revision 1294)
@@ -227,4 +227,6 @@
 							  ) = 0;
 
+	/** Returns a stats about the global pvs.
+	*/
 	virtual void GetPvsStatistics(PvsStatistics &stat);
 
@@ -378,4 +380,6 @@
 										vector<MergeCandidate> &candidates);
 
+	/** Collects n view cells and stores it as the active view cells.
+	*/
 	void CollectViewCells(const int n);
 
@@ -453,4 +457,5 @@
 	////////////////////////////////////////////////////////7
 	// visiblity filter options
+
 	// TODO: write own visibiltiy filter class
 	void ApplyFilter(KdTree *kdTree,
@@ -472,9 +477,9 @@
 	float GetAbsFilterWidth();
 
-	
 	/** Returns the bounding box of filter width.
 	*/
 	AxisAlignedBox3 GetFilterBBox(const Vector3 &viewPoint, const float width) const;
 
+	//////////////////////////////////////////////////////////////////
 
 	/** Returns true if the view cell is equivalent to a 
@@ -482,4 +487,5 @@
 		view cell.
 		e.g. to see if the spatial tree can be reduced on this location
+		note: not implemented
 	*/
 	virtual bool EqualToSpatialNode(ViewCell *viewCell) const;
@@ -502,8 +508,4 @@
 protected:
 
-	/** Exports bounding boxes as xml stream
-	*/
-	//bool ExportBoundingBoxes(ofstream &xmlstream, const ObjectContainer &objects) const;
-
 	/** Intersects box with the tree and returns the number of intersected boxes.
 		@returns number of view cells found
@@ -520,4 +522,6 @@
 	bool ViewCellsTreeConstructed() const;
 
+	/** Requests preprocessor to cast samplesPerPass samples of a specific type.
+	*/
 	int CastPassSamples(const int samplesPerPass, 
 						const int sampleType, 
@@ -717,11 +721,15 @@
 						ViewCellContainer &viewcells);
 	
+	/** Returns the probability that the view point lies
+		in this view cells.
+	*/
 	float GetProbability(ViewCell *viewCell);
-	
-
-	/** Get a viewcell containing the specified point 
+
+	/** Get a viewcell containing the specified point.
 	*/
 	ViewCell *GetViewCell(const Vector3 &point, const bool active = false) const;
 
+	/** Creates mesh for this view cell.
+	*/
 	void CreateMesh(ViewCell *vc);
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp	(revision 1293)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp	(revision 1294)
@@ -1497,10 +1497,5 @@
 		"0");
 
-	RegisterOption("ViewCells.storeKdPvs",
-		optBool, 
-		"view_cells_store_kd_pvs=", 
-		"false");
-	
-
+	
 	/************************************************************************************/
 	/*                         Render simulation related options                        */
@@ -2220,14 +2215,4 @@
 					"vsp_construction_max_band=",
 					"0.99");
-
-	RegisterOption("VspTree.useKdPvsForHeuristics",
-					optBool,
-					"vsp_use_kd_pvs_for_heuristics=",
-					"true");
-
-	RegisterOption("VspTree.storeKdPvs",
-					optBool,
-					"vsp_store_kd_pvs=",
-					"true");
 	
 	RegisterOption("VspTree.maxTests",
@@ -2241,4 +2226,5 @@
 /*           Object space partition tree related options               */
 /***********************************************************************/
+
 
 	RegisterOption("OspTree.Construction.randomize",
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp	(revision 1293)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp	(revision 1294)
@@ -475,4 +475,5 @@
 }
 
+
 HierarchyManager *Preprocessor::CreateHierarchyManager(const char *name)
 {
@@ -850,4 +851,5 @@
 									 )
 {
+#ifdef GTP_INTERNAL
 	VssRay *vssRay  = NULL;
 	int hits = 0;
@@ -859,12 +861,10 @@
 	
 	double normal[3];
-#ifdef GTP_INTERNAL
+
 	hittriangle = mlrtaIntersectAS(&viewPoint.x,
 								   &direction.x,
 								   normal,
 								   dist);
-#else
-	hittriangle = -1;
-#endif
+
 	if (hittriangle !=-1 ) {
 	  if (hittriangle >= mFaceParents.size())
@@ -881,13 +881,10 @@
 	}
 
+	
 	Vector3 dir = -direction;
-#ifdef GTP_INTERNAL
 	hittriangle = mlrtaIntersectAS(&viewPoint.x,
 								   &dir.x,
 								   normal,
 								   dist);
-#else
-	hittriangle = -1;
-#endif
 
 	if (hittriangle !=-1 ) {
@@ -913,4 +910,7 @@
 					  box
 					  );
+#else
+	return -1;
+#endif
 }
 
@@ -929,4 +929,5 @@
 		return 0;
 	
+#ifdef GTP_INTERNAL
 	float pforg[3];
 	float pfdir[3];
@@ -936,10 +937,6 @@
 	pfdir[0] = direction[0]; pfdir[1] = direction[1]; pfdir[2] = direction[2];
 
-	float dist = 0;
-#ifdef GTP_INTERNAL
+	float dist;
 	const int hittriangle = mlrtaIntersectAS(pforg, pfdir, pfnorm, dist);
-#else
-	const int hittriangle = -1;
-#endif
 
 	if (hittriangle == -1)
@@ -970,4 +967,11 @@
 	  }
 	}
+
+#else
+	const int hittriangle = -1;
+	return NULL;
+#endif
+
+	
 	
 }
@@ -1330,9 +1334,12 @@
 	{
 	case INTEL_RAYCASTER: {
-	  float dist;
+	 
 	  int hittriangle;
+	  
+
+#ifdef GTP_INTERNAL
+	  float dist; 
 	  double n[3];
 
-#ifdef GTP_INTERNAL
 	  hittriangle = mlrtaIntersectAS(&viewPoint.x,
 									 &direction.x,
@@ -1340,9 +1347,5 @@
 									 dist);
 
-#else
-	hittriangle = -1;
-#endif
-
-	  if (hittriangle !=-1 ) {
+	   if (hittriangle !=-1 ) {
 		if (hittriangle >= mFaceParents.size())
 		  cerr<<"Warning: traingle index out of range! "<<hittriangle<<endl;
@@ -1353,4 +1356,9 @@
 		}
 	  }
+#else
+	hittriangle = -1;
+#endif
+
+	 
 	  break;
 	}
Index: GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.h	(revision 1293)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.h	(revision 1294)
@@ -290,5 +290,5 @@
 	HierarchyStatistics mHierarchyStats;
 
-	int mMaxLeaves;
+	int mTermMaxLeaves;
 	ofstream mSubdivisionStats;
 };
Index: GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.h	(revision 1292)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.h	(revision 1294)
@@ -342,4 +342,65 @@
 	{  
 	public:
+		
+		/** Returns average ray contribution.
+		*/
+		float GetAvgRayContribution() const
+		{
+			return (float)mPvs / ((float)mRays->size() + Limits::Small);
+		}
+
+
+		VspTraversalData():
+		mNode(NULL),
+		mDepth(0),
+		mRays(NULL),
+		mPvs(0),
+		mProbability(0.0),
+		mMaxCostMisses(0), 
+		mPriority(0)
+		{}
+		
+		VspTraversalData(VspLeaf *node, 
+						 const int depth, 
+						 RayInfoContainer *rays,
+						 const int pvs,
+						 const float p,
+						 const AxisAlignedBox3 &box):
+		mNode(node), 
+		mDepth(depth), 
+		mRays(rays),
+		mPvs(pvs),
+		mProbability(p),
+		mBoundingBox(box),
+		mMaxCostMisses(0),
+		mPriority(0)
+		{}
+
+		VspTraversalData(const int depth, 
+						 RayInfoContainer *rays,
+						 const AxisAlignedBox3 &box): 
+		mNode(NULL), 
+		mDepth(depth), 
+		mRays(rays),
+		mPvs(0),
+		mProbability(0),
+		mMaxCostMisses(0),
+		mBoundingBox(box)
+		{}
+
+		/** Returns cost of the traversal data.
+		*/
+		float GetCost() const
+		{
+			return mPriority;
+		}
+
+		/// deletes contents and sets them to NULL
+		void Clear()
+		{
+			DEL_PTR(mRays);
+			DEL_PTR(mNode);
+		}
+
 		/// the current node
 		VspLeaf *mNode;
@@ -360,64 +421,4 @@
 
 		
-		/** Returns average ray contribution.
-		*/
-		float GetAvgRayContribution() const
-		{
-			return (float)mPvs / ((float)mRays->size() + Limits::Small);
-		}
-
-
-		VspTraversalData():
-		mNode(NULL),
-		mDepth(0),
-		mRays(NULL),
-		mPvs(0),
-		mProbability(0.0),
-		mMaxCostMisses(0), 
-		mPriority(0)
-		{}
-		
-		VspTraversalData(VspLeaf *node, 
-						 const int depth, 
-						 RayInfoContainer *rays,
-						 const int pvs,
-						 const float p,
-						 const AxisAlignedBox3 &box):
-		mNode(node), 
-		mDepth(depth), 
-		mRays(rays),
-		mPvs(pvs),
-		mProbability(p),
-		mBoundingBox(box),
-		mMaxCostMisses(0),
-		mPriority(0)
-		{}
-
-		VspTraversalData(const int depth, 
-						 RayInfoContainer *rays,
-						 const AxisAlignedBox3 &box): 
-		mNode(NULL), 
-		mDepth(depth), 
-		mRays(rays),
-		mPvs(0),
-		mProbability(0),
-		mMaxCostMisses(0),
-		mBoundingBox(box)
-		{}
-
-		/** Returns cost of the traversal data.
-		*/
-		float GetCost() const
-		{
-			//cout << mPriority << endl;
-			return mPriority;
-		}
-
-		/// deletes contents and sets them to NULL
-		void Clear()
-		{
-			DEL_PTR(mRays);
-		}
-
 		friend bool operator<(const VspTraversalData &a, const VspTraversalData &b)
 		{
@@ -441,4 +442,6 @@
 		VspSubdivisionCandidate(const VspTraversalData &tData): mParentData(tData)
 		{};
+
+		~VspSubdivisionCandidate() { mParentData.Clear(); }
 
 		int Type() const { return VIEW_SPACE; }
@@ -922,4 +925,9 @@
 	*/
 	void CollectDirtyCandidates(VspSubdivisionCandidate *sc, vector<SubdivisionCandidate *> &dirtyList);
+
+	void CollectDirtyCandidate(
+		const VssRay &ray, 
+		const bool isTermination,
+		vector<SubdivisionCandidate *> &dirtyList) const;
 
 	/** Rays will be clipped to the bounding box.
Index: GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.cpp	(revision 1293)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.cpp	(revision 1294)
@@ -213,5 +213,6 @@
 	Environment::GetSingleton()->GetFloatValue("BvHierarchy.Termination.minGlobalCostRatio",
 		mTermMinGlobalCostRatio);
-	Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.globalCostMissTolerance", mTermGlobalCostMissTolerance);
+	Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.globalCostMissTolerance", 
+		mTermGlobalCostMissTolerance);
 
 	//-- factors for bsp tree split plane heuristics
@@ -285,6 +286,5 @@
 	// add the new nodes to the tree
 	BvhInterior *node = new BvhInterior(tData.mBoundingBox, leaf->GetParent());
-	//cout << "bbox: " << tData.mBoundingBox << endl;
-
+	
 
 	//-- the front and back traversal data is filled with the new values
@@ -292,6 +292,6 @@
 	frontData.mDepth = backData.mDepth = tData.mDepth + 1;
 
-	frontData.mBoundingBox = ComputeBoundingBox(frontObjects, &(tData.mBoundingBox));
-	backData.mBoundingBox = ComputeBoundingBox(backObjects, &(tData.mBoundingBox));
+	frontData.mBoundingBox = ComputeBoundingBox(frontObjects, &tData.mBoundingBox);
+	backData.mBoundingBox = ComputeBoundingBox(backObjects, &tData.mBoundingBox);
 	
 	/////////////
@@ -354,9 +354,9 @@
 	if (!LocalTerminationCriteriaMet(tData) && !globalCriteriaMet)
 	{	
+		//-- continue subdivision
+
 		BvhTraversalData tFrontData;
 		BvhTraversalData tBackData;
-
-		//-- continue subdivision
-		
+			
 		// create new interior node and two leaf node
 		newNode = SubdivideNode(sc->mFrontObjects,
@@ -392,5 +392,5 @@
 
 		// delete old leaf node
-		DEL_PTR(tData.mNode);
+		//DEL_PTR(tData.mNode);
 	}
 
@@ -409,7 +409,8 @@
 			CollectRays(leaf->mObjects, leaf->mVssRays);
 		}
-	}
-	
-	tData.Clear(); // cleanup
+
+		// detach node so it won't get deleted
+		tData.mNode = NULL;
+	}
 	
 	return newNode;
@@ -447,9 +448,9 @@
 	const float renderCostDecr = oldRenderCost - newRenderCost;
 
-	//Debug << "render cost decr: " << renderCostDecr << endl;
+	Debug << "\nbvh render cost decr: " << renderCostDecr << endl;
 	splitCandidate.SetRenderCostDecrease(renderCostDecr);
 
-#if 0
-	const float priority = (float)-data.mDepth;
+#if 1
+	const float priority = (float)-splitCandidate.mParentData.mDepth;
 #else	
 	// take render cost of node into account 
@@ -469,7 +470,7 @@
 	// matt: TODO
 	return ( 0
-		|| (data.mNode->mObjects.size() < mTermMinObjects)
-		|| (data.mProbability <= mTermMinProbability)
-		|| (data.mDepth >= mTermMaxDepth)
+		//|| ((int)data.mNode->mObjects.size() < mTermMinObjects)
+		//|| (data.mProbability <= mTermMinProbability)
+		//|| (data.mDepth >= mTermMaxDepth)
 		 );
 }
@@ -536,5 +537,5 @@
 		AxisAlignedBox3 box = obj->GetBox();
 
-		const float objMid = (box.Max(axis) + box.Min(axis)) * 0.5;
+		const float objMid = (box.Max(axis) + box.Min(axis)) * 0.5f;
 
 		// object mailed => belongs to back objects
@@ -936,7 +937,7 @@
 
 	const float viewSpaceVol = mVspTree->GetBoundingBox().GetVolume();
-	Debug << "\n***** eval render cost *********\n" 
+	/*Debug << "\nbvh render cost\n" 
 		  << "back p: " << pBack / viewSpaceVol << " front p " << pFront / viewSpaceVol << endl
-		  << "new rc: " << newRenderCost / viewSpaceVol << endl;
+		  << "new rc: " << newRenderCost / viewSpaceVol << endl;*/
 		 
 
@@ -1319,9 +1320,20 @@
 }
 
+void BvHierarchy::CreateRoot(const ObjectContainer &objects)
+{
+	//-- create new root
+	AxisAlignedBox3 box = ComputeBoundingBox(objects);
+	BvhLeaf *bvhleaf = new BvhLeaf(box, NULL, (int)objects.size());
+	bvhleaf->mObjects = objects;
+
+	mRoot = bvhleaf;
+
+	// associate root with current objects
+	AssociateObjectsWithLeaf(bvhleaf);
+}
+
 
 SubdivisionCandidate *BvHierarchy::PrepareConstruction(const VssRayContainer &sampleRays,
-													   const ObjectContainer &objects
-													   //,AxisAlignedBox3 *forcedObjectSpace
-													   )
+													   const ObjectContainer &objects)
 {
 	// note matt: we assume that we have objects sorted by their id
@@ -1332,25 +1344,18 @@
 
 	// compute bounding box from objects
-	mBoundingBox = ComputeBoundingBox(objects);
+	// we assume that root was already created
+	mBoundingBox = mRoot->GetBoundingBox();
+	BvhLeaf *bvhleaf = dynamic_cast<BvhLeaf *>(mRoot);
 
 	mTermMinProbability *= mBoundingBox.GetVolume();
 	mGlobalCostMisses = 0;
 	
-	//-- create new root
-
-	BvhLeaf *bvhleaf = new BvhLeaf(mBoundingBox, NULL, (int)objects.size());
-	bvhleaf->mObjects = objects;
-	mRoot = bvhleaf;
-
 	// only rays intersecting objects in node are interesting
 	AssociateObjectsWithRays(sampleRays);
-	// associate root with current objects
-	AssociateObjectsWithLeaf(bvhleaf);
-
-	//-- add first candidate for object space partition
-	
+	
+
 	// probabilty is voume of all "seen" view cells
 #if 1
-	const float prop = EvalViewCellsVolume(bvhleaf->mObjects);
+	const float prop = EvalViewCellsVolume(objects);
 #else
 	const float prop = GetBoundingBox().GetVolume();
@@ -1360,5 +1365,5 @@
 	BvhTraversalData oData(bvhleaf, 0, mBoundingBox, prop);
 
-	//-- first split candidate
+	//-- add first candidate for object space partition	
 	BvhSubdivisionCandidate *oSubdivisionCandidate = 
 		new BvhSubdivisionCandidate(oData);
Index: GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.h	(revision 1291)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.h	(revision 1294)
@@ -134,6 +134,4 @@
 	virtual bool IsLeaf() const = 0;
 
-	//virtual int Type() const = 0;
-
 	/** Determines whether this node is a root
 		@return true if root
@@ -205,6 +203,5 @@
 	*/
 	bool IsLeaf() const;
-	//int Type() const;
-
+	
 	BvhNode *GetBack() { return mBack; }
 	BvhNode *GetFront() { return mFront; }
@@ -249,6 +246,4 @@
 	bool IsLeaf() const;
 	
-	//int Type() const;
-
 	SubdivisionCandidate *GetSubdivisionCandidate() const 
 	{ 
@@ -292,20 +287,5 @@
 	{  
 	public:
-		/// the current node
-		BvhLeaf *mNode;
-		/// current depth
-		int mDepth;
-		/// the probability that this node is seen
-		float mProbability;
-		/// the bounding box of the node
-		AxisAlignedBox3 mBoundingBox;
-		/// how often this branch has missed the max-cost ratio
-		int mMaxCostMisses;
-		/// current axis
-		int mAxis;
-		/// current priority
-		float mPriority;
-
-
+		
 		BvhTraversalData():
 		mNode(NULL),
@@ -335,5 +315,4 @@
 		float GetCost() const
 		{
-			//cout << mPriority << endl;
 			return mPriority;
 		}
@@ -342,6 +321,22 @@
 		void Clear()
 		{
-			//DEL_PTR(mRays);
+			DEL_PTR(mNode);
 		}
+
+		/// the current node
+		BvhLeaf *mNode;
+		/// current depth
+		int mDepth;
+		/// the probability that this node is seen
+		float mProbability;
+		/// the bounding box of the node
+		AxisAlignedBox3 mBoundingBox;
+		/// how often this branch has missed the max-cost ratio
+		int mMaxCostMisses;
+		/// current axis
+		int mAxis;
+		/// current priority
+		float mPriority;
+
 
 		friend bool operator<(const BvhTraversalData &a, const BvhTraversalData &b)
@@ -356,13 +351,9 @@
 	{  
 	public:
-		static BvHierarchy *sBvHierarchy;
-
-		/// parent data
-		BvhTraversalData mParentData;
-		ObjectContainer mFrontObjects;
-		ObjectContainer mBackObjects;
-
-		BvhSubdivisionCandidate(const BvhTraversalData &tData): mParentData(tData)
+
+        BvhSubdivisionCandidate(const BvhTraversalData &tData): mParentData(tData)
 		{};
+
+		~BvhSubdivisionCandidate() { mParentData.Clear(); }
 
 		int Type() const { return OBJECT_SPACE; }
@@ -377,5 +368,4 @@
 			return sBvHierarchy->GlobalTerminationCriteriaMet(mParentData);
 		}
-
 
 		BvhSubdivisionCandidate(
@@ -385,4 +375,12 @@
 		mFrontObjects(frontObjects), mBackObjects(backObjects), mParentData(tData)
 		{}
+
+		
+		static BvHierarchy *sBvHierarchy;
+
+		/// parent data
+		BvhTraversalData mParentData;
+		ObjectContainer mFrontObjects;
+		ObjectContainer mBackObjects;
 	};
 
@@ -401,5 +399,4 @@
 	};
 
-	//typedef std::priority_queue<VspTraversalData> VspOspTraversalQueue;
 
 	/** Default constructor creating an empty tree.
@@ -616,5 +613,7 @@
 	float GetMemUsage() const;
 
-
+	/** Creates new root of hierarchy.
+	*/
+	void CreateRoot(const ObjectContainer &objects);
 
 	/////////////////////////////
Index: GTP/trunk/Lib/Vis/Preprocessing/src/GzBinFileInputStream.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/GzBinFileInputStream.h	(revision 1264)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/GzBinFileInputStream.h	(revision 1294)
@@ -111,4 +111,5 @@
     //  Unimplemented constructors and operators
     // -----------------------------------------------------------------------
+
     GzBinFileInputStream(const GzBinFileInputStream&);
     GzBinFileInputStream& operator=(const GzBinFileInputStream&);   
@@ -121,4 +122,5 @@
     //      per platform.
     // -----------------------------------------------------------------------
+
     FileHandle              fSource;
     MemoryManager* const    fMemoryManager;
@@ -129,7 +131,8 @@
 //  GzBinFileInputStream: Getter methods
 // ---------------------------------------------------------------------------
+
 inline bool GzBinFileInputStream::getIsOpen() const
 {
-	return (mStream.is_open());//(fSource != 0);
+	return bool (mStream.is_open());//(fSource != 0);
 }
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp	(revision 1293)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp	(revision 1294)
@@ -527,10 +527,10 @@
 inline bool VspTree::LocalTerminationCriteriaMet(const VspTraversalData &data) const
 {
-	const bool localTerminationCriteriaMet = (
-		((int)data.mRays->size() <= mTermMinRays) ||
-		(data.mPvs <= mTermMinPvs)   ||
-		(data.mProbability <= mTermMinProbability) ||
-		(data.GetAvgRayContribution() > mTermMaxRayContribution) ||
-		(data.mDepth >= mTermMaxDepth)
+	const bool localTerminationCriteriaMet = (0
+		//|| ((int)data.mRays->size() <= mTermMinRays)
+		//|| (data.mPvs <= mTermMinPvs)
+		//|| (data.mProbability <= mTermMinProbability)
+		//|| (data.GetAvgRayContribution() > mTermMaxRayContribution)
+		//|| (data.mDepth >= mTermMaxDepth)
 		);
 
@@ -545,6 +545,5 @@
 	}
 
-	return localTerminationCriteriaMet;
-		
+	return localTerminationCriteriaMet;		
 }
 
@@ -552,8 +551,8 @@
 inline bool VspTree::GlobalTerminationCriteriaMet(const VspTraversalData &data) const
 {
-	const bool terminationCriteriaMet = (
-		// mOutOfMemory || 
-		(mVspStats.Leaves() >= mMaxViewCells) || 
-        (mGlobalCostMisses >= mTermGlobalCostMissTolerance) 
+	const bool terminationCriteriaMet = (0
+		// || mOutOfMemory
+		|| (mVspStats.Leaves() >= mMaxViewCells)
+        || (mGlobalCostMisses >= mTermGlobalCostMissTolerance) 
 		);
 
@@ -674,5 +673,5 @@
 
 		// delete old leaf node
-		DEL_PTR(tData.mNode);
+		//DEL_PTR(tData.mNode);
 	}
 
@@ -713,9 +712,9 @@
 		// finally evaluate statistics for this leaf
 		EvaluateLeafStats(tData);
-	}
-
-	//-- cleanup
-	tData.Clear();
-	
+
+		// detach node so it won't get deleted
+		tData.mNode = NULL;
+	}
+
 	return newNode;
 }
@@ -750,6 +749,6 @@
 	splitCandidate.SetRenderCostDecrease(renderCostDecr);
 
-#if 0
-	const float priority = (float)-data.mDepth;
+#if 1
+	const float priority = (float)-splitCandidate.mParentData.mDepth;
 #else	
 
@@ -1426,5 +1425,5 @@
 	const float renderCostDecrease = (oldRenderCost - newRenderCost) / viewSpaceVol;
 	
-	Debug << "\n==== eval render cost decrease ===" << endl
+	Debug << "\neval vsp render cost decrease" << endl
 		  << "back pvs: " << pvsBack << " front pvs " << pvsFront << " total pvs: " << totalPvs << endl 
 		  << "back p: " << pBack / viewSpaceVol << " front p " << pFront / viewSpaceVol << " p: " << pOverall / viewSpaceVol << endl
@@ -2630,10 +2629,9 @@
 
 	//-- prepare view space partition
-
-	// add first candidate for view space partition
+	const float prop = mBoundingBox.GetVolume();
+	
+	// we assume that leaf was already created
 	VspLeaf *leaf = new VspLeaf();
 	mRoot = leaf;
-
-	const float prop = mBoundingBox.GetVolume();
 
 	// first vsp traversal data
@@ -2649,5 +2647,4 @@
 		oit_end = leaf->GetViewCell()->GetPvs().mEntries.end();
 
-
 	for (oit = leaf->GetViewCell()->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
 	{
@@ -2658,5 +2655,4 @@
 
 	//-- compute first split candidate
-
 	VspSubdivisionCandidate *splitCandidate = new VspSubdivisionCandidate(vData);
     EvalSubdivisionCandidate(*splitCandidate);
@@ -2669,40 +2665,7 @@
 
 
-void VspTree::CollectDirtyCandidates(VspSubdivisionCandidate *sc, 
-									 vector<SubdivisionCandidate *> &dirtyList)
-{
-	VspTraversalData &tData = sc->mParentData;
-	VspLeaf *node = tData.mNode;
-	
-	KdLeaf::NewMail();
-
-	RayInfoContainer::const_iterator rit, rit_end = tData.mRays->end();
-
-	// add all kd nodes seen by the rays
-	for (rit = tData.mRays->begin(); rit != rit_end; ++ rit)
-	{
-		VssRay *ray = (*rit).mRay;
-	
-		KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(ray->mOrigin, ray->mOriginNode);
-	
-		if (!leaf->Mailed())
-		{
-			leaf->Mail();
-			dirtyList.push_back(leaf->mSubdivisionCandidate);
-		}
-		
-		leaf = mHierarchyManager->mOspTree->GetLeaf(ray->mTermination, ray->mTerminationNode);
-	
-		if (!leaf->Mailed())
-		{
-			leaf->Mail();
-			dirtyList.push_back(leaf->mSubdivisionCandidate);
-		}
-	}
-}
-
-
-int VspTree::EvalMaxEventContribution(const VssRay &ray, 
-									  const bool isTermination) const
+void VspTree::CollectDirtyCandidate(const VssRay &ray, 
+									const bool isTermination,
+									vector<SubdivisionCandidate *> &dirtyList) const
 {
 	Intersectable *obj;
@@ -2712,4 +2675,61 @@
 	ray.GetSampleData(isTermination, pt, &obj, &node);
 
+	if (!obj) return;
+
+	switch (mHierarchyManager->GetObjectSpaceSubdivisonType())
+	{
+	case HierarchyManager::KD_BASED_OBJ_SUBDIV:
+		{
+			KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
+
+			if (!leaf->Mailed())
+			{
+				leaf->Mail();
+				dirtyList.push_back(leaf->mSubdivisionCandidate);
+			}
+
+			break;
+		}
+	case HierarchyManager::BV_BASED_OBJ_SUBDIV:
+		{
+		}
+		break;
+	default:
+		break;
+	}
+}
+
+
+void VspTree::CollectDirtyCandidates(VspSubdivisionCandidate *sc, 
+									 vector<SubdivisionCandidate *> &dirtyList)
+{
+	VspTraversalData &tData = sc->mParentData;
+	VspLeaf *node = tData.mNode;
+	
+	KdLeaf::NewMail();
+	BvhLeaf::NewMail();
+
+	RayInfoContainer::const_iterator rit, rit_end = tData.mRays->end();
+
+	// add all kd nodes seen by the rays
+	for (rit = tData.mRays->begin(); rit != rit_end; ++ rit)
+	{
+		VssRay *ray = (*rit).mRay;
+	
+		CollectDirtyCandidate(*ray, true, dirtyList);
+		CollectDirtyCandidate(*ray, false, dirtyList);
+	}
+}
+
+
+int VspTree::EvalMaxEventContribution(const VssRay &ray, 
+									  const bool isTermination) const
+{
+	Intersectable *obj;
+	Vector3 pt;
+	KdNode *node;
+
+	ray.GetSampleData(isTermination, pt, &obj, &node);
+
 	if (!obj) 
 		return 0;
@@ -2717,5 +2737,5 @@
 	int pvs = 0;
 
-	switch ( mHierarchyManager->GetObjectSpaceSubdivisonType())
+	switch (mHierarchyManager->GetObjectSpaceSubdivisonType())
 	{
 	case HierarchyManager::NO_OBJ_SUBDIV:
Index: GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp	(revision 1292)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp	(revision 1294)
@@ -112,5 +112,5 @@
   string result = filename;
 
-  int pos = filename.rfind(a, filename.size()-1);
+  int pos = filename.rfind(a, (int)filename.size() - 1);
   if (pos == filename.size() - a.size()) {
 	result.replace(pos, a.size(), b);
Index: GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp	(revision 1293)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp	(revision 1294)
@@ -97,7 +97,11 @@
 
 	Environment::GetSingleton()->GetIntValue(
+		"Hierarchy.Termination.maxLeaves", mTermMaxLeaves);
+
+	Environment::GetSingleton()->GetIntValue(
 		"Hierarchy.Construction.type", mConstructionType);
 
-	//Debug << "max depth: " << mTermMaxDepth << endl;
+	Debug << "******** Hierachy Manager Parameters ***********" << endl;
+	Debug << "max leaves: " << mTermMaxLeaves << endl;
 	Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
 	Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
@@ -145,24 +149,39 @@
 										   RayInfoContainer &objectSpaceRays)
 {
-	SubdivisionCandidate *vsc = 
-		mVspTree->PrepareConstruction(sampleRays, forcedViewSpace, viewSpaceRays);
-
-	mTQueue.Push(vsc);
-
-    SubdivisionCandidate *osc;
+	mHierarchyStats.Reset();
+	mHierarchyStats.Start();
 
 	switch (mObjectSpaceSubdivisonType)
 	{
 	case KD_BASED_OBJ_SUBDIV:
-		osc = mOspTree->PrepareConstruction(sampleRays, objects, objectSpaceRays);
-		mTQueue.Push(osc);
-		break;
-	case BV_BASED_OBJ_SUBDIV:
-		osc = mBvHierarchy->PrepareConstruction(sampleRays, objects);
-		mTQueue.Push(osc);
-		break;
-	default:
-		break;
-	}
+		{
+			SubdivisionCandidate *vsc = 
+				mVspTree->PrepareConstruction(sampleRays, forcedViewSpace, viewSpaceRays);
+			mTQueue.Push(vsc);
+
+			SubdivisionCandidate *osc;
+			osc = mOspTree->PrepareConstruction(sampleRays, objects, objectSpaceRays);
+			mTQueue.Push(osc);
+		}
+		break;
+	case BV_BASED_OBJ_SUBDIV:
+		{
+			mBvHierarchy->CreateRoot(objects);
+
+			SubdivisionCandidate *vsc = 
+				mVspTree->PrepareConstruction(sampleRays, forcedViewSpace, viewSpaceRays);
+			mTQueue.Push(vsc);
+
+			SubdivisionCandidate *osc;
+			osc = mBvHierarchy->PrepareConstruction(sampleRays, objects);
+			mTQueue.Push(osc);
+		}
+		break;
+	default:
+		break;
+	}
+
+	mTotalCost = (float)objects.size();
+	Debug << " setting total cost to " << mTotalCost << endl;
 }
 
@@ -211,7 +230,7 @@
 {
 	return (0
-		|| (mHierarchyStats.Leaves() >= mMaxLeaves) 
-		|| (mGlobalCostMisses >= mTermGlobalCostMissTolerance)
-		||	candidate->GlobalTerminationCriteriaMet()
+		|| (mHierarchyStats.Leaves() >= mTermMaxLeaves) 
+		//|| (mGlobalCostMisses >= mTermGlobalCostMissTolerance)
+		//||	candidate->GlobalTerminationCriteriaMet()
 		);
 }
@@ -250,11 +269,12 @@
 						*objectSpaceRays);
 
-	mHierarchyStats.Reset();
-	mHierarchyStats.Start();
 
 	cout << "Constructing view space / object space tree ... \n";
 	const long startTime = GetTime();	
 	
-	RunConstruction(true);
+	const bool repairQueue = true;
+
+	// process object space candidates
+	RunConstruction(repairQueue);
 
 	cout << "finished in " << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl;
@@ -264,8 +284,77 @@
 
 
+void HierarchyManager::ConstructBvHierarchy(const VssRayContainer &sampleRays,
+											const ObjectContainer &objects) 
+
+{
+	Debug << "\n$$$$$$$$$ bv hierarchy construction $$$$$$$$$$\n" << endl;
+	cout << "starting bv hierarchy construction ... " << endl;
+
+	mBvHierarchy->CreateRoot(objects);
+
+	// compute first candidate
+	SubdivisionCandidate *sc =
+		mBvHierarchy->PrepareConstruction(sampleRays, objects);
+
+	mTotalCost = mBvHierarchy->mTotalCost;
+	Debug << "reseting cost, new total cost: " << mTotalCost << endl;
+	
+    mTQueue.Push(sc);
+
+	mBvHierarchy->mBvhStats.Reset();
+	mBvHierarchy->mBvhStats.Start();
+
+	const long startTime = GetTime();
+	const bool repairQueue = false;
+
+	cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
+
+	mBvHierarchy->mBvhStats.Stop();
+}
+
+
+void HierarchyManager::ConstructOspTree(const VssRayContainer &sampleRays,
+										const ObjectContainer &objects) 
+
+{
+	RayInfoContainer *objectSpaceRays = new RayInfoContainer();
+
+	Debug << "\n$$$$$$$$$ osp tree construction $$$$$$$$$$\n" << endl;
+	cout << "starting osp tree construction ... " << endl;
+
+	// start with one big kd cell - all objects can be seen from everywhere
+	// note: only true for view space = object space
+
+	// compute first candidate
+	SubdivisionCandidate *osc =
+		mOspTree->PrepareConstruction(sampleRays, objects, *objectSpaceRays);
+
+	mTotalCost = mOspTree->mTotalCost;
+	Debug << "reseting cost, new total cost: " << mTotalCost << endl;
+	
+    mTQueue.Push(osc);
+
+	mOspTree->mOspStats.Reset();
+	mOspTree->mOspStats.Start();
+
+	const long startTime = GetTime();
+		
+	cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
+
+	mOspTree->mOspStats.Stop();
+
+	//////////////////////////
+	// matt: only for debugging purpose
+
+	const float rc = mOspTree->EvalRenderCost(sampleRays);
+
+	Debug << "My render cost evalulation: " << rc << endl;
+}
+
+
+
 bool HierarchyManager::ApplySubdivisionCandidate(SubdivisionCandidate *sc)
 {
 	const bool globalTerminationCriteriaMet = GlobalTerminationCriteriaMet(sc);
-
 	const bool vspSplit = (sc->Type() == SubdivisionCandidate::VIEW_SPACE);
 
@@ -289,4 +378,5 @@
 		{
 			BvhNode *n = mBvHierarchy->Subdivide(mTQueue, sc, globalTerminationCriteriaMet);
+
 			if (n->IsLeaf()) // local or global termination criteria failed
 				return false;
@@ -305,10 +395,10 @@
 	while (!FinishedConstruction())
 	{
-		SubdivisionCandidate *splitCandidate = NextSubdivisionCandidate();
+		mCurrentCandidate = NextSubdivisionCandidate();
 	    
-		mTotalCost -= splitCandidate->GetRenderCostDecrease();
+		mTotalCost -= mCurrentCandidate->GetRenderCostDecrease();
 
 		// cost ratio of cost decrease / totalCost
-		const float costRatio = splitCandidate->GetRenderCostDecrease() / mTotalCost;
+		const float costRatio = mCurrentCandidate->GetRenderCostDecrease() / mTotalCost;
 
 		//Debug << "ratio: " << costRatio << " min ratio: " << mTermMinGlobalCostRatio << endl;
@@ -318,10 +408,10 @@
 		//-- subdivide leaf node
 
-		if (ApplySubdivisionCandidate(splitCandidate))
+		if (ApplySubdivisionCandidate(mCurrentCandidate))
 		{
 			mHierarchyStats.nodes += 2;
 
 			// subdivision successful
-			EvalSubdivisionStats(*splitCandidate);
+			EvalSubdivisionStats(*mCurrentCandidate);
 		
 			// reevaluate candidates affected by the split
@@ -330,9 +420,9 @@
 			if (repair) RepairQueue();
 
-			cout << "candidate: " << splitCandidate->Type() << ", priority: " 
-				 << splitCandidate->GetPriority() << endl;
-		}
-
-		DEL_PTR(splitCandidate);
+			cout << "candidate: " << mCurrentCandidate->Type() << ", priority: " 
+				 << mCurrentCandidate->GetPriority() << endl;
+		}
+
+		DEL_PTR(mCurrentCandidate);
 	}
 }
@@ -345,6 +435,5 @@
 
 
-void HierarchyManager::CollectObjectSpaceDirtyList(
-	SubdivisionCandidateContainer &dirtyList)
+void HierarchyManager::CollectObjectSpaceDirtyList(SubdivisionCandidateContainer &dirtyList)
 {
 	switch (mObjectSpaceSubdivisonType)
@@ -383,11 +472,14 @@
 void HierarchyManager::CollectDirtyCandidates(SubdivisionCandidateContainer &dirtyList)
 {	
+	Debug << "here65" << endl;
 	// we have either a object space or view space split
 	if (mCurrentCandidate->Type() == SubdivisionCandidate::VIEW_SPACE)
 	{
+		Debug << "collected view space candidate" << endl;
 		CollectViewSpaceDirtyList(dirtyList);
 	}
 	else // object space split
 	{	
+		Debug << "collecting object space candidate" << endl;
 		CollectObjectSpaceDirtyList(dirtyList);
 	}
@@ -423,4 +515,5 @@
 	for (sit = dirtyList.begin(); sit != sit_end; ++ sit)
 	{
+		Debug << "here4423" << endl;
 		SubdivisionCandidate* sc = *sit;
 
@@ -428,5 +521,5 @@
 
 		// reevaluate
-		sc->EvalPriority();
+		//sc->EvalPriority();
 
 		// reinsert
@@ -553,8 +646,10 @@
 	RayInfoContainer *viewSpaceRays = new RayInfoContainer();
 	
+
 	/////////////////////////////////////////////////////////////
 	// view space space partition
 	/////////////////////////////////////////////////////////////
 
+
 	// use objects for evaluating vsp tree construction
 	const int savedobjectSpaceSubdivisionType = mObjectSpaceSubdivisonType;
@@ -610,85 +705,9 @@
 		break;
 	}
-}
-
-
-void HierarchyManager::ConstructBvHierarchy(const VssRayContainer &sampleRays,
-											const ObjectContainer &objects
-											//,AxisAlignedBox3 *forcedViewSpace
-											) 
-
-{
-	Debug << "\n$$$$$$$$$ bv hierarchy construction $$$$$$$$$$\n" << endl;
-	cout << "starting bv hierarchy construction ... " << endl;
-
-	//ObjectContainer obj = objects;
-
-	// compute first candidate
-	SubdivisionCandidate *sc =
-		mBvHierarchy->PrepareConstruction(sampleRays, objects);
-
-	mTotalCost = mBvHierarchy->mTotalCost;
-	Debug << "reseting cost, new total cost: " << mTotalCost << endl;
-	
-    mTQueue.Push(sc);
-
-	mBvHierarchy->mBvhStats.Reset();
-	mBvHierarchy->mBvhStats.Start();
-
-	const long startTime = GetTime();
-	const bool repairQueue = false;
 
 	// process object space candidates
 	RunConstruction(repairQueue);
-	
-	cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
-
-	mBvHierarchy->mBvhStats.Stop();
-}
-
-
-void HierarchyManager::ConstructOspTree(const VssRayContainer &sampleRays,
-										const ObjectContainer &objects) 
-
-{
-	RayInfoContainer *objectSpaceRays = new RayInfoContainer();
-
-	Debug << "\n$$$$$$$$$ osp tree construction $$$$$$$$$$\n" << endl;
-	cout << "starting osp tree construction ... " << endl;
-
-	// start with one big kd cell - all objects can be seen from everywhere
-	// note: only true for view space = object space
-
-	// compute first candidate
-	SubdivisionCandidate *osc =
-		mOspTree->PrepareConstruction(sampleRays, objects, *objectSpaceRays);
-
-	mTotalCost = mOspTree->mTotalCost;
-	Debug << "reseting cost, new total cost: " << mTotalCost << endl;
-	
-    mTQueue.Push(osc);
-
-	mOspTree->mOspStats.Reset();
-	mOspTree->mOspStats.Start();
-
-	const long startTime = GetTime();
-	const bool repairQueue = false;
-	
-	// process object space candidates
-	RunConstruction(repairQueue);
-	
-	cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
-
-	mOspTree->mOspStats.Stop();
-
-	//////////////////////////
-	// matt: only for debugging purpose
-
-	const float rc = mOspTree->EvalRenderCost(sampleRays);
-
-	Debug << "My render cost evalulation: " << rc << endl;
-}
-
-
-
-}
+}
+
+
+}
Index: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.cpp	(revision 1287)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.cpp	(revision 1294)
@@ -1243,9 +1243,9 @@
 
 		if (attrName == "min") 
-		{cout << "here6" << endl;
+		{
 			sscanf(ptr, "%f %f %f", &minBox.x, &minBox.y, &minBox.z);
 		}
 		if (attrName == "max") 
-		{cout << "here7" << endl;
+		{
 			sscanf(ptr, "%f %f %f", &maxBox.x, &maxBox.y, &maxBox.z);
 		}
@@ -1262,8 +1262,8 @@
 	}
 	else
-	{cout << "here18" << endl;
+	{
 		mHierarchyManager->mBvHierarchy->mRoot = interior;
 	}
-cout << "here28" << endl;
+
 	mCurrentBvhNode = interior;
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/OspTree.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/OspTree.cpp	(revision 1291)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/OspTree.cpp	(revision 1294)
@@ -895,5 +895,5 @@
 	}
 
-	Debug << "here32 " << touchedViewCells.size() << endl;
+	Debug << "here32 " << (int)touchedViewCells.size() << endl;
 	return renderCost;
 }
@@ -1793,5 +1793,5 @@
 		}
 	}
-	Debug << "here65 " << touchedObjects.size() << endl;
+	Debug << "here65 " << (int)touchedObjects.size() << endl;
 	ObjectContainer::const_iterator it, it_end = touchedObjects.end();
 	for (it = touchedObjects.begin(); it != it_end; ++ it)
