/****************************************************************************
    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 LSHIFT_Z	0
#define LSHIFT_S	1
#define LSHIFT_I	2

#define LSHIFT_DELAY_SZ	0
#define LSHIFT_DELAY_IZ	1


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

static SGateInfo lshift_info = {
  0,
  "lshift",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,
  Lshift_processEvent,
  shift_checkGate,
  Nop_initGate,
  0,
  0,
  0,
  Generic_propFrwdDelay,
  Generic_propBackDelay,
  Generic_delay,
};

void init_lshift()
{
  SGateInfo_register(&lshift_info,0);
}

int shift_checkGate(SGate *g)
{
  SPort *Z = g->g_ports.port[LSHIFT_Z];
  SPort *S = g->g_ports.port[LSHIFT_S];
  SPort *I = g->g_ports.port[LSHIFT_I];
  int sn = S->p_net->n_nbits;
  int in = I->p_net->n_nbits;
  int zn = Z->p_net->n_nbits;

  if ( (1<<sn) < in) {
    errorGate(g->g_name,"Too few bits on shift line.");
    return -1;
  }
  if ( (1<<(sn-1)) >= in) {
    errorGate(g->g_name,"Too many bits on shift line.");
    return -1;
  }
  if (in != zn) {
    errorGate(g->g_name,"Input and output must have same bit width.");
    return -1;
  }

  return 0;
}

static void Lshift_processEvent(SGate *g,EvQueue *Q,SEvent *E)
{
  SPort *Z = g->g_ports.port[LSHIFT_Z];
  SState *S = SGate_allocPortState(g,LSHIFT_S);
  SState *I = SGate_allocPortState(g,LSHIFT_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_shift(out,I,(S->one[0]&smask),0,1,0);
  }

  if (IsChangeOn(E,g,LSHIFT_I))
    delay = g->g_delayParms[LSHIFT_DELAY_IZ];
  else
    delay = g->g_delayParms[LSHIFT_DELAY_SZ];

  EvQueue_setPort(Q,Z,out,delay);

  free_SState(out);
  free_SState(S);
  free_SState(I);
}
