/****************************************************************************
    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 ROLL_Z	0
#define ROLL_S	1
#define ROLL_I	2

#define ROLL_DELAY_SZ	0
#define ROLL_DELAY_IZ	1

#define ROLL_WORD(A,i,wshift,bshift)			\
      { unsigned n = 0;					\
      if (i-wshift >= 0)				\
	n |= (A[i-wshift] << bshift);			\
      if (i-wshift-1 >= 0) 				\
	n |= (A[i-wshift-1] >> (SSWORDSIZE-bshift));	\
      A[i] = n; }


static void Roll_processEvent(SGate*,EvQueue*,SEvent*);
int shift_checkGate(SGate*);

static SGateInfo roll_info = {
  0,
  "roll",0x0,
  3,{{"Z",GIO_OUT,0},
       {"S",GIO_IN,0},
       {"I",GIO_IN,0}},

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

  Generic_copyGate,
  Roll_processEvent,
  shift_checkGate,
  Nop_initGate,
  0,
  0,
  0,
  Generic_propFrwdDelay,
  Generic_propBackDelay,
  Generic_delay,
};

void init_roll()
{
  SGateInfo_register(&roll_info,0);
}

static void Roll_processEvent(SGate *g,EvQueue *Q,SEvent *E)
{
  SPort *Z = g->g_ports.port[ROLL_Z];
  SState *S = SGate_allocPortState(g,ROLL_S);
  SState *I = SGate_allocPortState(g,ROLL_I);
  unsigned smask = (1<<(S->nbits & SSBITMASK))-1;
  SState *out = alloc_SState();
  int delay;

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

  if ((S->flt[0]&smask))
    SState_unknown(out);
  else {
    SState_roll(out,I,(S->one[0]&smask));
  }

  if (IsChangeOn(E,g,ROLL_I))
    delay = g->g_delayParms[ROLL_DELAY_IZ];
  else
    delay = g->g_delayParms[ROLL_DELAY_SZ];

  EvQueue_setPort(Q,Z,out,delay);
  free_SState(out);
  free_SState(I);
  free_SState(S);
}
