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

#include  <genlib.h>

#include   DUT_H
#include  "dplimits.h"
#include  "nbuse.h"


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


/* Module internal constants. */
#define        E_NBUSE_WIDTH         2
#define        E_NBUSE_SLICE         3
#define        E_NBUSE_NOVIEW        4
#define        E_NBUSE_OPENVBE       5
#define        E_NBUSE_MODELNAME     6


/* Names of tristate leaf cells. */
static char *TablLeafCellNbuse[2] = { "bnt1_fp",
									   "nt1_fp"};


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

/* Internal functions of module. */
static       void  Dgn_ErrorNbuse();
static       void  Dgn_VhdlNbuse();
static       void  Dgn_NetlistNbuse();


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

extern char *Dgn_DispatchNbuse(nbuse_modelname,
							   nbuse_width    ,
							   nbuse_slice    ,
							   nbuse_msb0     ,
							   nbuse_vhdl     ,
							   nbuse_netlist  ,
							   nbuse_icon     )
	char *nbuse_modelname;  /* Model name.                    */
	long  nbuse_width;      /* Bus wide.                      */
	long  nbuse_slice;      /* LSB starting slice.            */
	long  nbuse_msb0;       /* Zero as MSB index.             */
	long  nbuse_vhdl;       /* Generation of behavioral view. */
	long  nbuse_netlist;    /* Generation of netlist view.    */
	long  nbuse_icon;       /* Generation of icon.            */
{
	static short  DispachNbuse_FirstCall = FALSE;
	static  char  ModelName[C_SUPP_MBKSZNAME];

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

	/* Check if, at least, one view is asked. */
	if (   (nbuse_netlist == FALSE)
		 &&(nbuse_vhdl    == FALSE)
		 &&(nbuse_icon    == FALSE) )
		Dut_PrintError( E_NBUSE_ERROR, E_NBUSE_NOVIEW);

	/* Check the bus wide. */
	if ((nbuse_width < 1) || (nbuse_width > DP_WIDTH))
		Dut_PrintError( E_NBUSE_ERROR, E_NBUSE_WIDTH, nbuse_width);

	/* Check the LSB starting slice. */
	if ((nbuse_slice < 0) || ( nbuse_slice
							 +nbuse_width > DP_WIDTH))
		Dut_PrintError( E_NBUSE_ERROR, E_NBUSE_SLICE, nbuse_slice);

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

	/* Generation of behaviorial view. */
	if (nbuse_vhdl)
		Dgn_VhdlNbuse( ModelName ,
			   		  nbuse_width,
					  nbuse_slice,
			   		  nbuse_msb0 );

	/* Generation of netlist view. */
	if (nbuse_netlist)
		Dgn_NetlistNbuse( ModelName ,
						 nbuse_width,
						 nbuse_slice,
						 nbuse_msb0 );

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


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

static void  Dgn_ErrorNbuse()
{
	Dut_AddError( E_NBUSE_ERROR, E_NBUSE_WIDTH,
				  "invalid bus width : %ld.");
	Dut_AddError( E_NBUSE_ERROR, E_NBUSE_SLICE,
				  "invalid LSB starting slice : %ld.");
	Dut_AddError( E_NBUSE_ERROR, E_NBUSE_MODELNAME,
				  "Missing model name.");
	Dut_AddError( E_NBUSE_ERROR, E_NBUSE_NOVIEW,
				  "No view to generate.");
	Dut_AddError( E_NBUSE_ERROR, E_NBUSE_OPENVBE,
				  "Unable to create file : \"%s\".");
}


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

static void  Dgn_VhdlNbuse(nbuse_modelname,
					      nbuse_width    ,
					      nbuse_slice    ,
						  nbuse_msb0     )
	char *nbuse_modelname;  /* Model name.         */
	long  nbuse_width;      /* Bus width.          */
	long  nbuse_slice;      /* LSB starting slice. */
	long  nbuse_msb0;       /* Zero as MSB index.  */
{
	FILE *NbuseFile;
	long  BitIndex,     LenString,      TmpTime;
	char  BusWide[256], TmpString[256];

	/* *** Creating the file holding behavioral view. *** */
	if ((NbuseFile=mbkfopen(nbuse_modelname,
						            "vbe",
						       WRITE_TEXT)) == (FILE*)NULL)
		Dut_PrintError( E_NBUSE_ERROR, E_NBUSE_OPENVBE,
					                  nbuse_modelname);


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

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

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

	/* Give the call used to generate the model. */
	sprintf(  TmpString, "\"nbuseg %ld %ld %ld%s -vhdl -o %s\"" ,
			                      DP_WIDTH                      ,
			                   nbuse_width                      ,
			                   nbuse_slice                      ,
			                  (nbuse_msb0     ) ? " -msb0"  : "",
			                   nbuse_modelname                  );
    fprintf( NbuseFile  , "-- # Generator Call : %-45s  #\n", TmpString);

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


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


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

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

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

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

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


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

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

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

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

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

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

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

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


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

static void  Dgn_NetlistNbuse(nbuse_modelname,
						     nbuse_width    ,
							 nbuse_slice    ,
						     nbuse_msb0     )
	char *nbuse_modelname;  /* Model name.         */
	long  nbuse_width;      /* Bus wide.           */
	long  nbuse_slice;      /* LSB starting slice. */
	long  nbuse_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 = TablLeafCellNbuse[1];
	LeafCellBuffrName = TablLeafCellNbuse[0];

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

	/* Name of data bus terminals. */
	if (!nbuse_msb0)
	{
		sprintf( BusNameI0,"i0[%ld:%ld]", nbuse_width-1+nbuse_slice, nbuse_slice);
		sprintf( BusNameO , "o[%ld:%ld]", nbuse_width-1+nbuse_slice, nbuse_slice);
	}
	else
	{
		sprintf( BusNameI0,"i0[%ld:%ld]", DP_WIDTH-nbuse_slice
				                                  -nbuse_width  ,
				                          DP_WIDTH-nbuse_slice-1);
		sprintf( BusNameO , "o[%ld:%ld]", DP_WIDTH-nbuse_slice
				                                  -nbuse_width  ,
				                          DP_WIDTH-nbuse_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=nbuse_slice; 
		 LeafCellIndex<nbuse_slice+nbuse_width; LeafCellIndex++)
	{
		/* Build leaf cell name. */
		sprintf( LeafCellInstaName, "nbuse_%ld", LeafCellIndex);
		
		/* Compute terminal index. */
		if (!nbuse_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, "bnbuse_%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();
}
