/****************************************************************************
    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 NMOS_Z	0
#define NMOS_I	1
#define NMOS_G	2

#define NMOS_DELAY_ID 0
#define NMOS_DELAY_GD 1

static void Nmos_processEvent(SGate*,EvQueue*,SEvent*);
int Mos_checkGate(SGate*g);

static SGateInfo nmos_info = {
  0,
  "nmos",0x0,
  3,{{"Z",GIO_TRI,0},
     {"I",GIO_IN,0},
     {"G",GIO_IN,0}},

  {{"I-Z",bit(1),0},{"G-Z",bit(2),0},{0}},

  Generic_copyGate,
  Nmos_processEvent,
  Mos_checkGate,
  Nop_initGate,
  0,
  0,
  0,
  Generic_propFrwdDelay,
  Generic_propBackDelay,
  Generic_delay,
};

void init_nmos()
{
  SGateInfo_register(&nmos_info,0);
}

int Mos_checkGate(SGate *g)
{
  int n;

  if (g->g_ports.num != 3) {
    errorGate(g->g_name,"Wrong number of pins on %s gate.",g->g_type->gi_name);
    return -1;
  }

  n = g->g_ports.port[NMOS_Z]->p_net->n_nbits;

  if (n != g->g_ports.port[NMOS_I]->p_net->n_nbits || 
      n != g->g_ports.port[NMOS_G]->p_net->n_nbits) {
    errorGate(g->g_name,"Bit width must be same on all pins.");
    return -1;
  }

  return 0;
}

static void Nmos_processEvent(SGate *g,EvQueue *Q,SEvent *E)
{
  SPort *Z = g->g_ports.port[NMOS_Z];
  SState *I = SGate_allocPortState(g,NMOS_I);
  SState *G = SGate_allocPortState(g,NMOS_G);
  SState *S = alloc_SState();
  int delay;

#if 0
  sendMsg("echo PROCESS(%p) Z=%s  I=%s  G=%s\n",g,
	  g->g_ports.port[NMOS_Z]->p_net->n_name,
	  g->g_ports.port[NMOS_I]->p_net->n_name,
	  g->g_ports.port[NMOS_G]->p_net->n_name);
#endif

  if (IsChangeOn(E,g,NMOS_I))
    delay = g->g_delayParms[NMOS_DELAY_ID];
  else
    delay = g->g_delayParms[NMOS_DELAY_GD];

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

  SState_nmos(S,I,G);

  EvQueue_setPort(Q,Z,S,delay);

  free_SState(S);
  free_SState(I);
  free_SState(G);
}
