/*ScianDepend.c
  Eric Pepke
  May 22, 1991
  Dependencies system for SciAn
*/

#include "Scian.h"
#include "ScianTypes.h"
#include "ScianIDs.h"
#include "ScianErrors.h"
#include "ScianDepend.h"

static void CallBack(obj, destVar, indVar, sourceVar)
ObjPtr obj;
NameTyp destVar, indVar, sourceVar;
{
    ObjPtr indObject;
    if (indVar)
    {
	MakeVar(obj, indVar);
	indObject = GetVar(obj, indVar);
    }
    else
    {
	indObject = obj;
    }
    MakeVar(indObject, sourceVar);

    if (CompareVarChangeCounts(obj, destVar, indObject, sourceVar))
    {
	/*Yes, it needs to be made*/
	FuncTyp method;

	method = GetMethod(obj, destVar);
	if (method)
	{
#ifdef DEBUG
	    ObjPtr name;
	    char out[256];
	    name = GetVar(obj, NAME);

	    sprintf(out, "Making object %lx ", obj);
	    if (name)
	    {
		sprintf(tempStr, "(%s) ", GetString(name));
		strcat(out, tempStr);
	    }
	    sprintf(tempStr, "variable %s", IDName(destVar));
	    strcat(out, tempStr);

	    puts(out);
#endif
	    (*method)(obj);
	}
	else
	{
	    /*ReportError("MakeVar", "No make method found");*/
	}
    }
}

Bool MakeVar(origObj, destVar)
ObjPtr origObj;
int destVar;
/*Makes destVar within origObj.  Returns true iff it had to make it.*/
{
    ObjPtr class, var;
    long initialCount;
    FuncTyp method;
    Bool retVal = false;

    initialCount = GetVarChangeCount(origObj, destVar);
    GetDependencies(origObj, destVar, CallBack);
    retVal = initialCount == GetVarChangeCount(origObj, destVar) ? false : true;

    if (GetVarChangeCount(origObj, destVar) <= 0)
    {
	/*Yes, it needs to be made*/
	FuncTyp method;

	method = GetMethod(origObj, destVar);
	if (method)
	{
	    (*method)(origObj);
	}
	else
	{
	    /*ReportError("MakeVar", "No make method found");*/
	}
    }

    return retVal;
}

void DeclareDependency(object, destVar, sourceVar)
ObjPtr object;
int destVar, sourceVar;
/*Declares a variable dependency within object of destVar on sourceVar*/
{
    SetDependency(object, destVar, sourceVar);
}

void DeclareIndirectDependency(object, destVar, indirectObject, sourceVar)
ObjPtr object;
int destVar, indirectObject, sourceVar;
/*Declares a variable dependency within object of destVar on sourceVar
  within object indirectObject*/
{
    SetIndirectDependency(object, destVar, indirectObject, sourceVar);
}
