/****************************************************************************
    Copyright (C) 1987-2005 by Jeffery P. Hansen

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "gsim.h"

#define AND_Z	0
#define AND_I	1

#define AND_DELAY 0

static void And_processEvent(SGate*,EvQueue*,SEvent*);

static SGateInfo and_info = {
  0,
  "and:nand",0x1,
  2,{{"Z",GIO_OUT,0},
       {"I",GIO_IN,PF_MULTI}},
  {{"I-Z",bit(1),0},{0}},

  Generic_copyGate,
  And_processEvent,
  Generic_checkGate,
  Nop_initGate,
  Generic_setProp,
  0,
  0,
  Generic_propFrwdDelay,
  Generic_propBackDelay,
  Generic_delay,
};

void init_and()
{
  SGateInfo_register(&and_info,0);
}


static void And_processEvent(SGate *g,EvQueue *Q,SEvent *E)
{
  SPort *Z = g->g_ports.port[AND_Z];
  SState *S = alloc_SState();
  SState *cS = alloc_SState();
  int i;

  SState_reinit(S,Z->p_state.nbits);

  if (g->g_ports.num == 2) {		/* Reduction gate */
    SState *I = SGate_allocPortState(g,AND_I);
    int n0 = 0;
    int n1 = 0;

    for (i = 0;i < I->nbits;i++) {
      int sy = SState_getBitSym(I,i);
      if (sy == SYM_ONE) n1++;
      if (sy == SYM_ZERO) n0++;
    }

    if (n0 > 0)
      SState_zero(S);
    else if (n1 == I->nbits)
      SState_one(S);
    else
      SState_unknown(S);

    free_SState(I);
  } else {				/* Standard gate */
    SState_one(S);

    for (i = AND_I;i < g->g_ports.num;i++) {
      SState *istate = SGate_allocPortState(g,i);

      SState_expandExtend(istate,S->nbits);
      SState_and(S,S,istate,0);
      free_SState(istate);
    }
  }

  EvQueue_setPort(Q,Z,S,g->g_delayParms[AND_DELAY]);

  free_SState(S);
  free_SState(cS);
}
