/*!\file: ResolvePointers.cpp
 * \brief go look for objects in a certain dataset, tracking them by their id. 
 */ 

#ifdef HAVE_CONFIG_H
	#include "config.h"
#else
#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
#endif

#include "../../objects/objects.h"
#include "../../DataSet/DataSet.h"
#include "../../include/typedefs.h"
#include "../Exceptions/exceptions.h"


#undef __FUNCT__ 
#define __FUNCT__ "ResolvePointers"

void ResolvePointers(Object** objects,int* object_ids,int* object_offsets,int num_objects,DataSet* dataset){

	/*output: */

	/*intermediary: */
	Object* object=NULL;
	int i;
	

	for(i=0;i<num_objects;i++){


		/*Check whether existing objects are correct: */
		if(objects[i]){
			if(objects[i]->GetId()==object_ids[i]) continue; //this node is good.
			else objects[i]=NULL; //this node was incorrect, reset it.
		}

		/*May be the object offsets into objects are valid?: */
		if(object_offsets[i]!=UNDEF){
			/* Look at the object_offsets[i]'th node in the nodes dataset. If it has the correct id, 
			 * we are good: */
			object=(Object*)dataset->GetObjectByOffset(object_offsets[i]);
			if (object->GetId()==object_ids[i]){
				objects[i]=object;
				continue;
			}
			else object_offsets[i]=UNDEF; //object offset was wrong, reset it.
		}

		/*Now, for objects that did not get resolved, and for which we have no offset, chase them in the dataset, by id: */
		if(objects[i]==NULL){
			objects[i]=(Object*)dataset->GetObjectById(object_offsets+i,object_ids[i]); //remember the offset for later on.
			/*check the id is correct!: */
			if (objects[i]->GetId()!=object_ids[i])throw ErrorException(__FUNCT__,exprintf("%s%i%s%i%s"," wrong id: ",objects[i]->GetId()," vs ",object_ids[i],"  in resolved pointer!"));
		}
	}
	
}

