#include  <time.h>
#include  <stdio.h>
#include  <string.h>

#include  <genlib.h>

#include   DUT_H
#include  "dplimits.h"
#include  "pms.h"


/*      Alliance CAD System 2.0                                   */
/*        FITPATH Package 0.0                                     */
/*                                                                */
/*  Author  :      Jean-Paul CHAPUT                               */
/*  E-mail  :  cao-vlsi@masi.ibp.fr                               */
/* ************************************************************** */
/*  module  :  "pms.c"                                            */


/* Module internal constants. */
#define        E_PMS_WIDTH         2
#define        E_PMS_SLICE         3
#define        E_PMS_NOVIEW        4
#define        E_PMS_OPENVBE       5
#define        E_PMS_MODELNAME     6


/* Names of tristate leaf cells. */
static char *TablLeafCellPms[2] = {  "pmsb0_fp",
									"pdffa2_fp"};


/* Interface function of module.
   extern       char *Dgn_DispachPms();
   */

/* Internal functions of module. */
static       void  Dgn_ErrorPms();
static       void  Dgn_VhdlPms();
static       void  Dgn_NetlistPms();


/*  Function  :  'Dgn_DispatchPms'                                */
/* -------------------------------------------------------------- */
/*  Interface scannable D flip-flops generator.                   */

extern char *Dgn_DispatchPms(pms_modelname,
							 pms_width    ,
							 pms_slice    ,
							 pms_msb0     ,
							 pms_vhdl     ,
							 pms_netlist  ,
							 pms_icon     )
	char *pms_modelname;  /* Model name.                    */
	long  pms_width;      /* Bus wide.                      */
	long  pms_slice;      /* LSB starting slice.            */
	long  pms_msb0;       /* Zero as MSB index.             */
	long  pms_vhdl;       /* Generation of behavioral view. */
	long  pms_netlist;    /* Generation of netlist view.    */
	long  pms_icon;       /* Generation of icon.            */
{
	static short  DispachPms_FirstCall = FALSE;
	static  char  ModelName[C_SUPP_MBKSZNAME];

	/* The first time the generator is call : */
	/*     - Load specific errors.            */
	if (!DispachPms_FirstCall)
	{
		Dgn_ErrorPms();
		DispachPms_FirstCall = TRUE;
	}

	/* Check if, at least, one view is asked. */
	if (   (pms_netlist == FALSE)
		 &&(pms_vhdl    == FALSE)
		 &&(pms_icon    == FALSE) )
		Dut_PrintError( E_PMS_ERROR, E_PMS_NOVIEW);

	/* Check the bus wide. */
	if ((pms_width < 2) || (pms_width > DP_WIDTH))
		Dut_PrintError( E_PMS_ERROR, E_PMS_WIDTH, pms_width);

	/* Check the LSB starting slice. */
	if ((pms_slice < 0) || ( pms_slice
							 +pms_width > DP_WIDTH))
		Dut_PrintError( E_PMS_ERROR, E_PMS_SLICE, pms_slice);

	/* Check the model name. */
	if (pms_modelname == (char*)NULL)
		/* Build a more explicit model name. */
		(void*)sprintf( ModelName, "pms_%ldx%ldx%ld%c_cl"  ,
					                   DP_WIDTH              ,
					                pms_width              ,
					                pms_slice              ,
					              ((pms_msb0 ) ? 'm' : 'l'));
	else
		strcpy( ModelName, pms_modelname);

	/* Generation of behaviorial view. */
	if (pms_vhdl)
		Dgn_VhdlPms(ModelName  ,
					 pms_width,
					 pms_slice,
					 pms_msb0 );

	/* Generation of netlist view. */
	if (pms_netlist)
		Dgn_NetlistPms(ModelName  ,
						pms_width,
						pms_slice,
						pms_msb0 );

	/* Generation of icon. */
	/* if (pms_icon) */
	
	/* Return name of the generated model. */
	return((pms_modelname == (char*)NULL) ?      ModelName 
		                                   : pms_modelname);
}


/*  Function  :  'Dgn_ErrorPms'                                  */
/* -------------------------------------------------------------- */
/*  Adds generator specific errors to the main errors data base.  */

static void  Dgn_ErrorPms()
{
	Dut_AddError( E_PMS_ERROR, E_PMS_WIDTH,
				  "invalid bus width : %ld.");
	Dut_AddError( E_PMS_ERROR, E_PMS_SLICE,
				  "invalid LSB starting slice : %ld.");
	Dut_AddError( E_PMS_ERROR, E_PMS_MODELNAME,
				  "Missing model name.");
	Dut_AddError( E_PMS_ERROR, E_PMS_NOVIEW,
				  "No view to generate.");
	Dut_AddError( E_PMS_ERROR, E_PMS_OPENVBE,
				  "Unable to create file : \"%s\".");
}


/*  Function  :  'Dgn_VhdlPms'                                   */
/* -------------------------------------------------------------- */
/*  Generation scannable D flip-flops behavioral view.            */

static void  Dgn_VhdlPms(pms_modelname,
						  pms_width    ,
						  pms_slice    ,
						  pms_msb0     )
	char *pms_modelname;  /* Model name.         */
	long  pms_width;      /* Bus width.          */
	long  pms_slice;      /* LSB starting slice. */
	long  pms_msb0;       /* Zero as MSB index.  */
{
	FILE *PmsFile;
	long  ConIndex;
	long  BitIndex,     LenString,      TmpTime;
	char  BusWide[  256], TmpString[256];

	/* *** Creating the file holding behavioral view. *** */
	if ((PmsFile=mbkfopen(pms_modelname,
						              "vbe",
						         WRITE_TEXT)) == (FILE*)NULL)
		Dut_PrintError( E_PMS_ERROR, E_PMS_OPENVBE,
					                   pms_modelname);


	/* *** Write an identification header *** */

	/* Standart begin of header. */
	fprintf( PmsFile, 
"-- ###-------------------------------------------------------------###\n"
			);
	fprintf( PmsFile, 
"-- #                                                                 #\n"
			);
	fprintf( PmsFile,
"-- #    Alliance CAD System 2.0                                      #\n"
			);
    fprintf( PmsFile,
"-- #      FITPATH Package 0.0                                        #\n"
			);
    fprintf( PmsFile,
"-- #                                                                 #\n"
			);
    fprintf( PmsFile,
"-- # Author :     Jean-Paul CHAPUT                                   #\n" 
			);
    fprintf( PmsFile,
"-- # E-mail : cao-vlsi@masi.ibp.fr                                   #\n"
			);
	fprintf( PmsFile, 
"-- # *************************************************************** #\n"
			);
	fprintf( PmsFile,
"-- #                                                                 #\n"
			);
    fprintf( PmsFile,
"-- # Generator : \"pmsg\" (Sample Master Slave)                        #\n"
			);
	fprintf( PmsFile, 
"-- # --------------------------------------------------------------- #\n"
			);

	/* Print name of the generated file. */
	sprintf(  TmpString, "\"%s.vbe\"."            ,pms_modelname);
    fprintf( PmsFile  , "-- # File : %-55s  #\n",      TmpString);
	fprintf( PmsFile,
"-- #                                                                 #\n"
			);

	/* Print date of generation. */
	TmpTime                = time((time_t*)NULL);
	sprintf( TmpString, "%s", asctime(localtime(&TmpTime)) );
	LenString              = strlen( TmpString);
	TmpString[LenString-1] = (char)0;
    fprintf( PmsFile  , "-- #           Date : %-45s  #\n", TmpString);

	/* Give the call used to generate the model. */
	sprintf(  TmpString, "\"pmsg %ld %ld %ld%s -vhdl -o %s\"" ,
			                      DP_WIDTH                      ,
			                   pms_width                      ,
			                   pms_slice                      ,
			                  (pms_msb0     ) ? " -msb0"  : "",
			                   pms_modelname                  );
    fprintf( PmsFile  , "-- # Generator Call : %-45s  #\n", TmpString);

	fprintf( PmsFile, 
"-- ###-------------------------------------------------------------###\n"
			);


	/* Select terminals (and signals) bus indexation. */
	/* (depending to the flag "pms_msb0")            */
	if (!pms_msb0)
	{
		sprintf( BusWide ,  "(%ld downto %ld)", pms_width-1
				                               +pms_slice  ,
				                                pms_slice  );
	}
	else
	{
		sprintf( BusWide  ,   "(%ld to %ld)", DP_WIDTH-pms_slice
				                                      -pms_width  ,
				                              DP_WIDTH-pms_slice-1);
	}


	/* *** Interface description. *** */
	fprintf( PmsFile, "\nENTITY %s IS\n\tPORT(\n", pms_modelname);

	/* Controls terminals. */
	fprintf( PmsFile, "%14s : in    BIT;\n",    "ckm");
	fprintf( PmsFile, "%14s : in    BIT;\n",    "cks");

	/* Terminals of data pmss. */
	fprintf( PmsFile, "%14s : in    BIT_VECTOR%s;\n",  "d", BusWide  );
	fprintf( PmsFile, "%14s :   out BIT_VECTOR%s;\n",  "q", BusWide );

	/* Supplies terminals. */
	fprintf( PmsFile, "%14s :  in BIT;\n", "vdd");
	fprintf( PmsFile, "%14s :  in BIT\n" , "vss");

	/* *** End of interface description *** */
	fprintf( PmsFile, "\t);\nEND %s;\n\n\n", pms_modelname);


	/* *** Behavioral view *** */
	fprintf( PmsFile, "ARCHITECTURE behaviour_data_flow OF %s IS\n\n",
			                                            pms_modelname);
	
	/* Internal register declaration. */
	for( BitIndex=pms_slice; 
		 BitIndex<pms_slice+pms_width; BitIndex++)
	{
		fprintf( PmsFile, "\tSIGNAL inst_pms_%ld_memm_s", BitIndex);
	    fprintf( PmsFile, ": REG_BIT REGISTER;\n"       );
		fprintf( PmsFile, "\tSIGNAL inst_pms_%ld_mems_s", BitIndex);
	    fprintf( PmsFile, ": REG_BIT REGISTER;\n"       );
	}

	fprintf( PmsFile, "\nBEGIN\n\n");

	/* *** Write Master Latchs *** */
	fprintf( PmsFile, "\twd:BLOCK(ckm) BEGIN\n");
	/* Loop on bus wide. */
	for( BitIndex=pms_slice; 
		 BitIndex<pms_slice+pms_width; BitIndex++)
	{
		if (!pms_msb0) ConIndex =              BitIndex;
		else           ConIndex = DP_WIDTH -1 -BitIndex;

		fprintf( PmsFile, "\t\tinst_pms_%ld_memm_s <= GUARDED ", ConIndex);
		fprintf( PmsFile,            "d(%ld);\n"               , ConIndex);
	}
	fprintf( PmsFile, "\tEND BLOCK wd;\n\n");

	/* *** Write slave registers *** */
	fprintf( PmsFile, "\tws:BLOCK(cks) BEGIN\n");
	for( BitIndex=pms_slice; 
		 BitIndex<pms_slice+pms_width; BitIndex++)
	{
		fprintf( PmsFile, "\t\tinst_pms_%ld_mems_s <= GUARDED ", BitIndex);
		fprintf( PmsFile,     "inst_pms_%ld_memm_s;\n"         , BitIndex);
	}
	fprintf( PmsFile, "\tEND BLOCK ws;\n\n");

	/* *** Affect the outputs. *** */

	/* Loop on bus wide. */
	for( BitIndex=pms_slice; 
		 BitIndex<pms_slice+pms_width; BitIndex++)
	{
		if (!pms_msb0) ConIndex =              BitIndex;
		else           ConIndex = DP_WIDTH -1 -BitIndex;

		fprintf( PmsFile, "\tq(%ld) <= inst_pms_%ld_mems_s;\n",
				                                      ConIndex,
				                                      ConIndex);
	}


	/* Check supplies connections. */
	fprintf( PmsFile, "\n\t-- ****************>");
	fprintf( PmsFile,   " Supplies Check "      );
	fprintf( PmsFile,   "<****************\n\n" );

	fprintf( PmsFile, "\tASSERT ((vdd = '1') and (vss = '0'))\n");
	fprintf( PmsFile, "\t\tREPORT \"Power supply is missing on %s.\"\n",
			                                              pms_modelname);
	fprintf( PmsFile, "\t\tSEVERITY WARNING;\n\n");

	/* *** End of behavioral view *** */
	fprintf( PmsFile, "END behaviour_data_flow;\n");

	/* *** Close the file holding the behavioral view *** */
	fclose( PmsFile);
}


/*  Fonction  :  'Dgn_NetListPms'                                */
/* -------------------------------------------------------------- */
/*  Generation of Scannable D Flip-Flop Netlist.                  */

static void  Dgn_NetlistPms(pms_modelname,
							 pms_width    ,
							 pms_slice    ,
							 pms_msb0     )
	char *pms_modelname;  /* Model name.         */
	long  pms_width;      /* Bus wide.           */
	long  pms_slice;      /* LSB starting slice. */
	long  pms_msb0;       /* Zero as MSB index.  */
{
	long       BusIndex;
	long  LeafCellIndex;

	char *LeafCellSliceName;
	char *LeafCellBuffrName;
	char  LeafCellInstaName[C_SUPP_MBKSZNAME];

	char  BusNameD[  C_SUPP_MBKSZNAME];
	char  BusNameQ[  C_SUPP_MBKSZNAME];
	char  PinNameD[  C_SUPP_MBKSZNAME];
	char  PinNameQ[  C_SUPP_MBKSZNAME];


	/* Model names (slices and buffer). */

	/* Creation of the new logical figure. */
	DEF_LOFIG( pms_modelname);

	/* Name of data bus terminals. */
	if (!pms_msb0)
	{
		sprintf( BusNameD , "d[%ld:%ld]", pms_width-1
				                         +pms_slice  , 
				                          pms_slice  );
		sprintf( BusNameQ , "q[%ld:%ld]", pms_width-1
				                         +pms_slice  ,
				                          pms_slice  );
	}
	else
	{
		sprintf( BusNameD , "d[%ld:%ld]", DP_WIDTH-pms_slice
				                                  -pms_width  ,
				                          DP_WIDTH-pms_slice-1);
		sprintf( BusNameQ , "q[%ld:%ld]", DP_WIDTH-pms_slice
				                                  -pms_width  ,
				                          DP_WIDTH-pms_slice-1);
	}
 
	/* Creation of figure terminals. */
	/* **** Control terminals **** */
	LOCON(     "ckm", IN   ,      "ckm");
	LOCON(     "cks", IN   ,      "cks");

	/* **** Data bus terminals **** */
	LOCON( BusNameD , IN   , BusNameD );
	LOCON( BusNameQ ,   OUT, BusNameQ );

	/* **** Supply terminals **** */
	LOCON(     "vdd", INOUT,      "vdd"); 
	LOCON(     "vss", INOUT,      "vss"); 


	/* Instance of bottom column. */	
	LeafCellIndex=pms_slice;

	/* Select leaf cell model name. */
	LeafCellSliceName = TablLeafCellPms[1];

	/* Creation of leaf cells instances. */
	/* ("normals" cells of column)       */
	for( LeafCellIndex=pms_slice; 
		 LeafCellIndex<pms_slice+pms_width; LeafCellIndex++)
	{
		/* Build leaf cell name. */
		sprintf( LeafCellInstaName, "pms_%ld", LeafCellIndex);
		
		/* Compute terminal index. */
		if (!pms_msb0) BusIndex =              LeafCellIndex;
		else           BusIndex = DP_WIDTH -1 -LeafCellIndex;

		/* Build signals names. */
		sprintf( PinNameD  ,   "d[%ld]", BusIndex  );
		sprintf( PinNameQ  ,   "q[%ld]", BusIndex  );

		/* Leaf cell instanciation. */
		LOINS( LeafCellSliceName,
			   LeafCellInstaName,
			                "wm",
			                "ws",
			            PinNameD,
			            PinNameQ, "vdd", "vss", EOL);
	}


	/* Creation of buffer instance. */

	/* Select buffer model name. */
	LeafCellBuffrName = TablLeafCellPms[0];
	/* Build buffer instance name. */
	sprintf( LeafCellInstaName, "bpms_%ld", DP_WIDTH);

	/* Buffer instanciation. */
	LOINS( LeafCellBuffrName,
		   LeafCellInstaName,
		               "ckm",
		               "cks",
		                "wm",
		                "ws", "vdd", "vss", "vss", EOL);

	/* Ends and write to disk the new figure. */
	SAVE_LOFIG();
}
