/*
This example illustrates the code needed to create a user-defined
function and associated C access function which will return the
relation name of a fact given a fact pointer or fact address.
Example use of the facts-relation function is shown following:

CLIPS> (fact-relation (assert (foo a b c)))
foo
CLIPS> (fact-relation 0)
foo
CLIPS>

The C code for the fact-relation function follows:
*/

#include "clips.h"

#if ANSI_COMPILER
VOID *FactRelationFunction(void);
char *FactRelation(void *);
#else
VOID *FactRelationFunction(void);
char *FactRelation(void *);
#endif

/* 
This UserFunctions should be used in place of the 
UserFunctions defined in the MAIN.C file.
*/

VOID UserFunctions()
  {   
   DefineFunction("fact-relation",
                  'w',
                  PTIF FactRelationFunction,
                  "FactRelationFunction");
  }

/**********************************************/
/* FactRelationFunction: CLIPS access routine */
/*   for the fact-relation function.          */
/**********************************************/
VOID *FactRelationFunction()
  {
   DATA_OBJECT item;
   struct fact *theFact;
   
   /*====================================*/
   /* The function expects one argument. */
   /*====================================*/

   if (ArgCountCheck("fact-relation",EXACTLY,1) == -1) return(CLIPSFalseSymbol);
   RtnUnknown(1,&item);

   /*========================================*/
   /* Get a pointer to the fact if possible. */
   /*========================================*/
   
   if (GetType(item) == FACT_ADDRESS)
     { theFact = (struct fact *) GetValue(item); }
   else if (GetType(item) == INTEGER)
     { 
      theFact = FindIndexedFact(ValueToLong(item.value));
      if (theFact == NULL)
        {
         char tempBuffer[20];
         sprintf(tempBuffer,"f-%ld",ValueToLong(item.value));
         CantFindItemErrorMessage("fact",tempBuffer);
         return(CLIPSFalseSymbol);
        }
     }
   else
     {
      ExpectedTypeError1("fact-relation",1,"fact-address or fact-index");
      return(CLIPSFalseSymbol);
     }
     
   /*=======================================*/
   /* Return the relation name of the fact. */
   /*=======================================*/
   
   AddSymbol(FactRelation(theFact)); 
  }

/******************************************************************/
/* FactRelation: C access routine for the fact-relation function. */
/******************************************************************/
char *FactRelation(factPtr)
  VOID *factPtr;
  {
   return(GetDeftemplateName((VOID *) ((struct fact *) factPtr)->whichDeftemplate));
  }

