//---------------------------------------------------------------------------
#include <string.h>
//---------------------------------------------------------------------------
#include "conf.h"
#include "tboolfnct.h"
#include "tpfnct.h"
#include "simulate.h"
//---------------------------------------------------------------------------
int Simulate_fd( TBoolFnct * fn, char * iv, char * ov ) /* Simulates iv vector for function fn.
The output is put into ov. ov must be pre-allocared For fd functions only Returns 1. */
{
  int i, j;
  TPfnct * ff;
  char v;

  setmem( ov, fn->outvars, '0' );

  ff = fn->fnct;
  while ( ff != 0 )
  {
    v = '1';
    for ( i = 0; i < fn->inpvars; i++ )
      if ( ff->iv[i] != '-' )
      {
        if ( ff->iv[i] != iv[i] && iv[i] != '-' )
        {
          v = '0';
          break;
        }
        if ( iv[i] == '-' ) v = '-';
      }
    for ( i = 0; i < fn->outvars; i++ )
      if ( ff->ov[i] == '1' )
      {
        if ( v == '1' ) ov[i] = '1';
        if ( v == '-' && ov[i] == '0' ) ov[i] = '~';
      }
    ff = ff->next;
  }
  return 1;
}
//---------------------------------------------------------------------------
int Simulate_fr( TBoolFnct * fn, char * iv, char * ov ) /* Simulates iv vector for function fn.
The output is put into ov. ov must be pre-allocared For fr functions only
Returns 0 when inconsistent function encountered, 1 if OK */
{
  int i, j;
  TPfnct * ff;
  char v;

  setmem( ov, fn->outvars, '~' );

  ff = fn->fnct;
  while ( ff != 0 )
  {
    v = '1';
    for ( i = 0; i < fn->inpvars; i++ )
      if ( ff->iv[i] != '-' )
      {
        if ( ff->iv[i] != iv[i] && iv[i] != '-' )
        {
          v = '0';
          break;
        }
        if ( iv[i] == '-' ) v = '-';
      }
    if ( v != '0' )
      for ( i = 0; i < fn->outvars; i++ )
      {
        if ( v == '1' )
        {
          if ( ov[i] != '~' && ov[i] != '?' && ff->ov[i] != '~' && ff->ov[i] != ov[i] ) return 0;
          else if ( ff->ov[i] != '~' ) ov[i] = ff->ov[i];
        }
        else if ( v == '-' )
          if ( ff->ov[i] != '~' && ff->ov[i] != ov[i] ) ov[i] = '?';
      }
    ff = ff->next;
  }
  return 1;
}
//---------------------------------------------------------------------------
int Simulate( TBoolFnct * fn, char * iv, char * ov ) /* Simulates iv vector for function fn.
The output is put into ov. ov must be pre-allocared Returns 0 when inconsistent function encountered, 1 if OK */
{
  switch ( fn->type )
  {
    case 0:
      return Simulate_fd( fn, iv, ov );
    break;
    case 1:
      return Simulate_fr( fn, iv, ov );
    break;
  }
  return 0;
}
//---------------------------------------------------------------------------
