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

#include  <genlib.h>

#include   DUT_H
#include  "dplimits.h"
#include  "inv.h"

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


/* Module internal constants. */
#define        E_INV_WIDTH         2
#define        E_INV_SLICE         3
#define        E_INV_DRIVE         4
#define        E_INV_NOVIEW        5
#define        E_INV_OPENVBE       6
#define        E_INV_MODELNAME     7


/* Names of inverter/buffer leaf cells. */
static char *TablLeafCellInv[4] = {    "n1_fp",
								      "np1_fp",
									 "ndrv_fp",
									"ndrvp_fp" };


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

/* Internal functions of module. */
static       void  Dgn_ErrorInv();
static       void  Dgn_VhdlInv();
static       void  Dgn_NetlistInv();


/*  Function  :  'Dgn_DispatchInv'                                */
/* -------------------------------------------------------------- */
/*  Interface of inverter/buffer generator.                       */

extern char *Dgn_DispatchInv(inv_modelname,
							 inv_width    ,
							 inv_slice    ,
							 inv_drive    ,
							 inv_msb0     ,
							 inv_vhdl     ,
							 inv_netlist  ,
							 inv_icon     )
	char *inv_modelname;  /* Model name.                    */
	long  inv_width;      /* Bus wide.                      */
	long  inv_slice;      /* give the LSB starting slice.   */
	long  inv_drive;      /* Output drive capacity.         */
	long  inv_msb0;       /* Zero as MSB index.             */
	long  inv_vhdl;       /* Generation of behavioral view. */
	long  inv_netlist;    /* Generation of netlist view.    */
	long  inv_icon;       /* Generation of icon.            */
{
	static short  DispachInv_FirstCall = FALSE;
	static  char  ModelName[C_SUPP_MBKSZNAME];

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

	/* Check if, at least, one view is asked. */
	if (   (inv_netlist == FALSE)
		 &&(inv_vhdl    == FALSE)
		 &&(inv_icon    == FALSE) )
		Dut_PrintError( E_INV_ERROR, E_INV_NOVIEW);

	/* Check the bus wide. */
	if ((inv_width < 1) || (inv_width > C_DPLIMITS_MAXSLICE))
		Dut_PrintError( E_INV_ERROR, E_INV_WIDTH, inv_width);

	/* Check the LSB starting slice. */
	if ((inv_slice < 0) || ( inv_slice
							+inv_width > DP_WIDTH))
		Dut_PrintError( E_INV_ERROR, E_INV_SLICE, inv_slice);

	/* Check the output drive capacity. */
	if ((inv_drive < 1) || (inv_drive > C_INV_NBDRIVE))
		Dut_PrintError( E_INV_ERROR, E_INV_DRIVE, inv_drive);

	/* Check the model name. */
	if (inv_modelname == (char*)NULL)
#ifndef  CRUNCH_FILENAME
		/* Build a more explicit model name. */
		(void*)sprintf( ModelName, "inv_%ldx%ldx%ldx%ld%c_cl",
					                   DP_WIDTH              ,
					                  inv_width              ,
					                  inv_slice              ,
					                  inv_drive              ,
					                ((inv_msb0 ) ? 'm' : 'l'));
#else
		/* Build the crunched model name. */
		strcpy( ModelName, Dut_MakeCrunchModelName(
									    "iv"       ,
									8L,  DP_WIDTH-1,
									8L, inv_width-1,
									8L, inv_slice  ,
									8L, inv_drive  ,
									0L, inv_msb0   ));
#endif
	else
		strcpy( ModelName, inv_modelname);

	/* Generation of behaviorial view. */
	if (inv_vhdl)
		Dgn_VhdlInv( ModelName,
			   		 inv_width,
			   		 inv_slice,
			   		 inv_drive,
			   		 inv_msb0 );

	/* Generation of netlist view. */
	if (inv_netlist)
		Dgn_NetlistInv( ModelName,
						inv_width,
						inv_slice,
					    inv_drive,
						inv_msb0 );

	/* Generation of icone. */
	/* if (inv_icon) */
	
	/* Return name of the generated model. */
	return((inv_modelname == (char*)NULL) ?     ModelName 
		                                  : inv_modelname);
}


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

static void  Dgn_ErrorInv()
{
	Dut_AddError( E_INV_ERROR, E_INV_WIDTH,
				  "invalid bus width : %ld.");
	Dut_AddError( E_INV_ERROR, E_INV_DRIVE,
				  "invalid output drive : %ld.");
	Dut_AddError( E_INV_ERROR, E_INV_MODELNAME,
				  "Missing model name.");
	Dut_AddError( E_INV_ERROR, E_INV_NOVIEW,
				  "No view to generate.");
	Dut_AddError( E_INV_ERROR, E_INV_OPENVBE,
				  "Unable to create file : \"%s\".");
}


/*  Function  :  'Dgn_NetListInv'                                 */
/* -------------------------------------------------------------- */
/*  Generation of inverter/buffer behvioral view.                 */

static void  Dgn_VhdlInv(inv_modelname,
					      inv_width    ,
					      inv_slice    ,
						  inv_drive    ,
						  inv_msb0     )
	char *inv_modelname;  /* Nom du modele.           */
	long  inv_width;      /* Largeur du bus.          */
	long  inv_slice;      /* LSB starting slice.      */
	long  inv_drive;      /* Output drive power.      */
	long  inv_msb0;       /* Zero comme index du MSB. */
{
	FILE *InvFile;
	long  BitIndex,     LenString,      TmpTime;
	char  BusWide[256], TmpString[256];

	/* *** Creating the file holding behavioral view. *** */
	if ((InvFile=mbkfopen(inv_modelname,
						            "vbe",
						       WRITE_TEXT)) == (FILE*)NULL)
		Dut_PrintError( E_INV_ERROR, E_INV_OPENVBE,
					                  inv_modelname);

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

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

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

	/* Give the call used to generate the model. */
	sprintf(  TmpString, "\"invg %ld %ld %ld %ld%s -vhdl -o %s\"" ,
			                        DP_WIDTH                      ,
			                       inv_width                      ,
			                       inv_slice                      ,
			                       inv_drive                      ,
			                      (inv_msb0     ) ? " -msb0"  : "",
			                       inv_modelname                  );
    fprintf( InvFile  , "-- # Generator Call : %-45s  #\n", TmpString);

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


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


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

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

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

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


	/* *** Behavioral view *** */
	fprintf( InvFile, "ARCHITECTURE behaviour_data_flow OF %s IS\n\n",
			                                            inv_modelname);
	fprintf( InvFile, "BEGIN\n\n");
	fprintf( InvFile, "\to%s <= not i0%s;\n\n" , BusWide, BusWide);

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

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

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

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


/*  Function  :  'Dgn_NetListInv'                                 */
/* -------------------------------------------------------------- */
/*  Generation of inverter/buffer netlist view.                   */

static void  Dgn_NetlistInv(inv_modelname,
						    inv_width    ,
						    inv_slice    ,
							inv_drive    ,
						    inv_msb0     )
	char *inv_modelname;  /* Model name.            */
	long  inv_width;      /* Bus wide.              */
	long  inv_slice;      /* LSB starting slice.    */
	long  inv_drive;      /* Output drive capacity. */
	long  inv_msb0;       /* Zero as MSB index.     */
{
	long       BusIndex;
	long  LeafCellIndex;

	char *LeafCellSliceName;
	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];


	/* Select name of the leaf cell model. */
	/* (according to output drive power)   */
	LeafCellSliceName = TablLeafCellInv[inv_drive-1];

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

	/* Name of data bus terminals. */
	if (!inv_msb0)
	{
		sprintf( BusNameI0,"i0[%ld:%ld]", inv_width-1+inv_slice, inv_slice);
		sprintf( BusNameO , "o[%ld:%ld]", inv_width-1+inv_slice, inv_slice);
	}
	else
	{
		sprintf( BusNameI0,"i0[%ld:%ld]", DP_WIDTH-inv_slice
				                                  -inv_width  ,
				                          DP_WIDTH-inv_slice-1);
		sprintf( BusNameO , "o[%ld:%ld]", DP_WIDTH-inv_slice
				                                  -inv_width  ,
				                          DP_WIDTH-inv_slice-1);
	}

 
	/* Creation of figure terminals. */
	/* **** Control terminals **** */
	LOCON( BusNameI0, IN   , BusNameI0);
	LOCON( BusNameO ,   OUT, BusNameO );

	/* **** Data bus terminals **** */
	LOCON(     "vdd", INOUT,     "vdd"); 
	LOCON(     "vss", INOUT,     "vss"); 
	
	
	/* Creation of leaf cells instances. */
	/* ("normals" cells of column)       */
	for( LeafCellIndex=inv_slice;
		 LeafCellIndex<inv_slice+inv_width; LeafCellIndex++)
	{
		/* Build leaf cell name. */
		sprintf( LeafCellInstaName, "inv_%ld", LeafCellIndex);
		
		/* Compute terminal index. */
		if (!inv_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 ,
			          PinNameO  , "vdd", "vss", EOL);
	}

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