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

#include  <genlib.h>

#include   DUT_H
#include  "dplimits.h"
#include  "buse.h"


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


/* Module internal constants. */
#define        E_BUSE_WIDTH         2
#define        E_BUSE_SLICE         3
#define        E_BUSE_NOVIEW        4
#define        E_BUSE_OPENVBE       5
#define        E_BUSE_MODELNAME     6


/* Names of tristate leaf cells. */
static char *TablLeafCellBuse[2] = { "bt1_fp",
									  "t1_fp"};


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

/* Internal functions of module. */
static       void  Dgn_ErrorBuse();
static       void  Dgn_VhdlBuse();
static       void  Dgn_NetlistBuse();


/*  Function  :  'Dgn_DispatchBuse'                               */
/* -------------------------------------------------------------- */
/*  Interface of non-inverter tristate generator.                 */

extern char *Dgn_DispatchBuse(buse_modelname,
							  buse_width    ,
							  buse_slice    ,
							  buse_msb0     ,
							  buse_vhdl     ,
							  buse_netlist  ,
							  buse_icon     )
	char *buse_modelname;  /* Model name.                    */
	long  buse_width;      /* Bus wide.                      */
	long  buse_slice;      /* LSB starting slice.            */
	long  buse_msb0;       /* Zero as MSB index.             */
	long  buse_vhdl;       /* Generation of behavioral view. */
	long  buse_netlist;    /* Generation of netlist view.    */
	long  buse_icon;       /* Generation of icon.            */
{
	static short  DispachBuse_FirstCall = FALSE;
	static  char  ModelName[C_SUPP_MBKSZNAME];

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

	/* Check if, at least, one view is asked. */
	if (   (buse_netlist == FALSE)
		 &&(buse_vhdl    == FALSE)
		 &&(buse_icon    == FALSE) )
		Dut_PrintError( E_BUSE_ERROR, E_BUSE_NOVIEW);

	/* Check the bus wide. */
	if ((buse_width < 1) || (buse_width > DP_WIDTH))
		Dut_PrintError( E_BUSE_ERROR, E_BUSE_WIDTH, buse_width);

	/* Check the LSB starting slice. */
	if ((buse_slice < 0) || ( buse_slice
							 +buse_width > DP_WIDTH))
		Dut_PrintError( E_BUSE_ERROR, E_BUSE_SLICE, buse_slice);

	/* Check the model name. */
	if (buse_modelname == (char*)NULL)
#ifndef  CRUNCH_FILENAME
		/* Build a more explicit model name. */
		(void*)sprintf( ModelName, "buse_%ldx%ldx%ld%c_cl",
					                DP_WIDTH              ,
					              buse_width              ,
					              buse_slice              ,
					            ((buse_msb0 ) ? 'm' : 'l'));
#else
		/* Build the crunched model name. */
		strcpy( ModelName, Dut_MakeCrunchModelName(
									    "bu"       ,
									 8L,   DP_WIDTH-1,
									 8L, buse_width-1,
									 8L, buse_slice  ,
									 8L,         1L  ,
									 0L, buse_msb0   ));
#endif
	else
		strcpy( ModelName, buse_modelname);

	/* Generation of behaviorial view. */
	if (buse_vhdl)
		Dgn_VhdlBuse( ModelName ,
			   		  buse_width,
					  buse_slice,
			   		  buse_msb0 );

	/* Generation of netlist view. */
	if (buse_netlist)
		Dgn_NetlistBuse( ModelName ,
						 buse_width,
						 buse_slice,
						 buse_msb0 );

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


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

static void  Dgn_ErrorBuse()
{
	Dut_AddError( E_BUSE_ERROR, E_BUSE_WIDTH,
				  "invalid bus width : %ld.");
	Dut_AddError( E_BUSE_ERROR, E_BUSE_SLICE,
				  "invalid LSB starting slice : %ld.");
	Dut_AddError( E_BUSE_ERROR, E_BUSE_MODELNAME,
				  "Missing model name.");
	Dut_AddError( E_BUSE_ERROR, E_BUSE_NOVIEW,
				  "No view to generate.");
	Dut_AddError( E_BUSE_ERROR, E_BUSE_OPENVBE,
				  "Unable to create file : \"%s\".");
}


/*  Function  :  'Dgn_NetListBuse'                                */
/* -------------------------------------------------------------- */
/*  Generation of tristate behavioral view.                       */

static void  Dgn_VhdlBuse(buse_modelname,
					      buse_width    ,
					      buse_slice    ,
						  buse_msb0     )
	char *buse_modelname;  /* Model name.         */
	long  buse_width;      /* Bus width.          */
	long  buse_slice;      /* LSB starting slice. */
	long  buse_msb0;       /* Zero as MSB index.  */
{
	FILE *BuseFile;
	long  BitIndex,     LenString,      TmpTime;
	char  BusWide[256], TmpString[256];

	/* *** Creating the file holding behavioral view. *** */
	if ((BuseFile=mbkfopen(buse_modelname,
						            "vbe",
						       WRITE_TEXT)) == (FILE*)NULL)
		Dut_PrintError( E_BUSE_ERROR, E_BUSE_OPENVBE,
					                  buse_modelname);


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

	/* Standart begin of header. */
	fprintf( BuseFile, 
"-- ###-------------------------------------------------------------###\n"
			);
	fprintf( BuseFile, 
"-- #                                                                 #\n"
			);
	fprintf( BuseFile,
"-- #    Alliance CAD System 2.0                                      #\n"
			);
    fprintf( BuseFile,
"-- #      FITPATH Package 0.0                                        #\n"
			);
    fprintf( BuseFile,
"-- #                                                                 #\n"
			);
    fprintf( BuseFile,
"-- # Author :     Jean-Paul CHAPUT                                   #\n" 
			);
    fprintf( BuseFile,
"-- # E-mail : cao-vlsi@masi.ibp.fr                                   #\n"
			);
	fprintf( BuseFile, 
"-- # *************************************************************** #\n"
			);
	fprintf( BuseFile,
"-- #                                                                 #\n"
			);
    fprintf( BuseFile,
"-- # Generator : \"buseg\" (non-inverter tristate)                     #\n"
			);
	fprintf( BuseFile, 
"-- # --------------------------------------------------------------- #\n"
			);

	/* Print name of the generated file. */
	sprintf(  TmpString, "\"%s.vbe\"."           , buse_modelname);
    fprintf( BuseFile  , "-- # File : %-55s  #\n",      TmpString);
	fprintf( BuseFile,
"-- #                                                                 #\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( BuseFile  , "-- #           Date : %-45s  #\n", TmpString);

	/* Give the call used to generate the model. */
	sprintf(  TmpString, "\"buseg %ld %ld %ld%s -vhdl -o %s\"" ,
			                     DP_WIDTH                      ,
			                   buse_width                      ,
			                   buse_slice                      ,
			                  (buse_msb0     ) ? " -msb0"  : "",
			                   buse_modelname                  );
    fprintf( BuseFile  , "-- # Generator Call : %-45s  #\n", TmpString);

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


	/* Select terminals (and signals) bus indexation. */
	/* (depending to the flag "buse_msb0")            */
	if (!buse_msb0)
		sprintf( BusWide, "(%ld downto %ld)", buse_width-1
				                             +buse_slice  ,
				                              buse_slice  );
	else
		sprintf( BusWide,     "(%ld to %ld)", DP_WIDTH-buse_slice
				                                      -buse_width  ,
				                              DP_WIDTH-buse_slice-1);


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

	/* Controls terminals. */
	fprintf( BuseFile, "%14s :  in BIT;\n",  "sel");

	/* Terminals of data buses. */
	fprintf( BuseFile, "%14s :  in BIT_VECTOR%s;\n"    , "i0", BusWide);
	fprintf( BuseFile, "%14s : out MUX_VECTOR%s BUS;\n",  "o", BusWide);

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

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


	/* *** Behavioral view *** */
	fprintf( BuseFile, "ARCHITECTURE behaviour_data_flow OF %s IS\n\n",
			                                            buse_modelname);
	fprintf( BuseFile, "BEGIN\n");

	/* Loop on bus wide. */
	for( BitIndex=0; BitIndex<buse_width; BitIndex++)
	{
		/* Small comment to seperate differents bits. */
		fprintf( BuseFile, "\t-- ****************>");
		fprintf( BuseFile, " Bit : %ld "           , BitIndex);
		fprintf( BuseFile, "<****************\n\n" );

		/* This VHDL block drive ouput "o" to Zero. */
		fprintf( BuseFile, "\tw1_bit%ld: BLOCK "            , BitIndex);
		fprintf( BuseFile, "((i0(%ld) and sel) = '1')\n"    , BitIndex);
		fprintf( BuseFile, "\tBEGIN\n\t\to(%ld) <= "        , BitIndex);
		fprintf( BuseFile, "GUARDED '1';\n"                 );
		fprintf( BuseFile, "\tEND BLOCK w1_bit%ld;\n\n" , BitIndex);

		/* This VHDL block drive output "o" to One. */
		fprintf( BuseFile, "\tw0_bit%ld: BLOCK ((not "    , BitIndex);
		fprintf( BuseFile, "i0(%ld) and sel) = '1')\n"    , BitIndex);
		fprintf( BuseFile, "\tBEGIN\n\t\to(%ld) <= "      , BitIndex);
		fprintf( BuseFile, "GUARDED '0';\n"               );
		fprintf( BuseFile, "\tEND BLOCK w0_bit%ld;\n\n"   , BitIndex);
	}

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

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

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

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


/*  Fonction  :  'Dgn_NetListBuse'                                */
/* -------------------------------------------------------------- */
/*  Generation of Tristate Netlist.                               */

static void  Dgn_NetlistBuse(buse_modelname,
						     buse_width    ,
							 buse_slice    ,
						     buse_msb0     )
	char *buse_modelname;  /* Model name.         */
	long  buse_width;      /* Bus wide.           */
	long  buse_slice;      /* LSB starting slice. */
	long  buse_msb0;       /* Zero as MSB index.  */
{
	long       BusIndex;
	long  LeafCellIndex;

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

	char  BusNameI0[C_SUPP_MBKSZNAME];
	char  BusNameO[ C_SUPP_MBKSZNAME];
	char  PinNameI0[C_SUPP_MBKSZNAME];
	char  PinNameO[ C_SUPP_MBKSZNAME];


	/* Model names (slices and buffer). */
	LeafCellSliceName = TablLeafCellBuse[1];
	LeafCellBuffrName = TablLeafCellBuse[0];

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

	/* Name of data bus terminals. */
	if (!buse_msb0)
	{
		sprintf( BusNameI0,"i0[%ld:%ld]", buse_width-1+buse_slice, buse_slice);
		sprintf( BusNameO , "o[%ld:%ld]", buse_width-1+buse_slice, buse_slice);
	}
	else
	{
		sprintf( BusNameI0,"i0[%ld:%ld]", DP_WIDTH-buse_slice
				                                  -buse_width  ,
				                          DP_WIDTH-buse_slice-1);
		sprintf( BusNameO , "o[%ld:%ld]", DP_WIDTH-buse_slice
				                                  -buse_width  ,
				                          DP_WIDTH-buse_slice-1);
	}
 
	/* Creation of figure terminals. */
	/* **** Control terminals **** */
	LOCON(     "sel", IN   ,      "sel");

	/* **** Data bus terminals **** */
	LOCON( BusNameI0, IN   , BusNameI0);
	LOCON( BusNameO ,   OUT, BusNameO );

	/* **** Supply terminals **** */
	LOCON(     "vdd", INOUT,      "vdd"); 
	LOCON(     "vss", INOUT,      "vss"); 
	
	
	/* Creation of leaf cells instances. */
	/* ("normals" cells of column)       */
	for( LeafCellIndex=buse_slice; 
		 LeafCellIndex<buse_slice+buse_width; LeafCellIndex++)
	{
		/* Build leaf cell name. */
		sprintf( LeafCellInstaName, "buse_%ld", LeafCellIndex);
		
		/* Compute terminal index. */
		if (!buse_msb0) BusIndex =              LeafCellIndex;
		else            BusIndex = DP_WIDTH -1 -LeafCellIndex;

		/* Build signals names. */
		sprintf( PinNameI0, "i0[%ld]", BusIndex);
		sprintf( PinNameO ,  "o[%ld]", BusIndex);

		/* Leaf cell instanciation. */
		LOINS( LeafCellSliceName,
			   LeafCellInstaName,
			          PinNameI0 ,
			                "s1",
			                "s0",
			          PinNameO  , "vdd", "vss", EOL);
	}


	/* Creation of buffer instance. */

	/* Build buffer instance name. */
	sprintf( LeafCellInstaName, "bbuse_%ld", DP_WIDTH);

	/* Buffer instanciation. */
	LOINS( LeafCellBuffrName,
		   LeafCellInstaName,
		               "sel",
		                "s1",
		                "s0", "vdd", "vss", VSS, EOL);

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