#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define ARCH_NAME			"data"
#define ENT_NAME			"rom"
#define JTAG_ADDR_WIDTH		16

// --------------------------------------------------------------
void basename(char *pSrc, char *pDst)
{
	int i, size;

	size = strlen(pSrc);

	while(pSrc[size] != '.')
		size--;

	for (i=0; i < size; i++)
		pDst[i] = pSrc[i];

	pDst[i] = 0;

}

int SaveROM(char *pFilenameIn, char *pFilenameOut, char *pArchName, char *pEntName, int nbits_addr, int nbits_data)
{
	FILE *pFileIn, *pFileOut;
	long start, end;
	int i, word, filesize, romsize;

	pFileIn = fopen(pFilenameIn, "rb");
	if (!pFileIn)
	{
		fprintf(stderr, "Error opening file %s\n", pFilenameIn);
		return 1;
	}

	pFileOut = fopen(pFilenameOut, "wb");
	if (!pFileOut)
	{
		fprintf(stderr, "Error opening file %s\n", pFilenameOut);
		return 1;
	}

	fseek(pFileIn, 0, SEEK_SET);
	start = ftell(pFileIn);
	fseek(pFileIn, 0, SEEK_END);
	end = ftell(pFileIn);
	fseek(pFileIn, 0, SEEK_SET);

	filesize = (end-start);
	romsize = (int)pow(2, nbits_addr+2);

	// -------------------------------------------------------------------------
	// Header

	// -------------------------------------------------------------------------
	fprintf(pFileOut, "LIBRARY IEEE;\n");
	fprintf(pFileOut, "USE IEEE.STD_LOGIC_1164.ALL;\n");
	fprintf(pFileOut, "USE IEEE.NUMERIC_STD.ALL;\n");
	fprintf(pFileOut, "\n");

	fprintf(pFileOut, "ENTITY %s IS\n", ENT_NAME);
	fprintf(pFileOut, "\tPort\n");
	fprintf(pFileOut, "\t(\n");
	fprintf(pFileOut, "\t\tclk\t\t: in  STD_LOGIC;\n");
	fprintf(pFileOut, "\t\tce\t\t: in  STD_LOGIC;\n");
	fprintf(pFileOut, "\t\taddr\t\t: in  unsigned(%d downto 0);\n", nbits_data-1);
	fprintf(pFileOut, "\t\tdout\t\t: out unsigned(%d downto 0)\n", nbits_data-1);
	fprintf(pFileOut, "\t);\n");
	fprintf(pFileOut, "END %s;\n", ENT_NAME);
	fprintf(pFileOut, "\n");


	fprintf(pFileOut, "ARCHITECTURE %s OF %s IS\n", ARCH_NAME, ENT_NAME);
	fprintf(pFileOut, "\n");

	fprintf(pFileOut, "\tsubtype word_t is unsigned(%d downto 0);\n", nbits_data-1);
	fprintf(pFileOut, "\ttype word_array_t is array (0 to %d) of word_t;\n", romsize/4-1);

	fprintf(pFileOut, "\tconstant word_array : word_array_t :=\n");
	fprintf(pFileOut, "\t(\n");
	fprintf(pFileOut, "\n");

	// -------------------------------------------------------------------------
	// ROM part
	// -------------------------------------------------------------------------
	for (i=0; i < filesize; i += sizeof(int))
	{
		fread(&word, 1, sizeof(int), pFileIn);
		fprintf(pFileOut, "\t\tX\"%8.8X\"", word);
		if (i < (romsize-sizeof(int)))
			fprintf(pFileOut, ", -- %8.8X\n", i);
		else
			fprintf(pFileOut, "  -- %8.8X\n", i);
	}
	word = 0;
	for (; i < romsize; i += sizeof(int))
	{
		fprintf(pFileOut, "\t\tX\"%8.8X\"", word);
		if (i < (romsize-sizeof(int)))
			fprintf(pFileOut, ", -- %8.8X\n", i);
		else
			fprintf(pFileOut, "  -- %8.8X\n", i);
	}
	fprintf(pFileOut, "\t);\n");
	fprintf(pFileOut, "\n");

	// -------------------------------------------------------------------------
	// Trailer
	// -------------------------------------------------------------------------
	fprintf(pFileOut, "begin\n", ARCH_NAME);
	fprintf(pFileOut, "\n");
	fprintf(pFileOut, "PROM_READ:\n", ARCH_NAME);
	fprintf(pFileOut, "\tprocess(clk)\n");
	fprintf(pFileOut, "\tbegin\n");
	fprintf(pFileOut, "\t\tif rising_edge(clk) and ce = '1' then\n");
	fprintf(pFileOut, "\t\t\tdout <= word_array(to_integer(addr(%d downto 2)));\n", nbits_addr+1);
	fprintf(pFileOut, "\t\tend if;\n");
	fprintf(pFileOut, "\tend process;\n");
	fprintf(pFileOut, "\n");
	fprintf(pFileOut, "end %s;\n", ARCH_NAME);

	return 0;
}

int SaveROM_V4LD(char *pFilenameIn, char *pFilenameOut, char *pArchName, char *pEntName, int nbits_addr, int nbits_data)
{
	FILE *pFileIn, *pFileOut;
	long start, end;
	int i, word, filesize, romsize;

	char tpl[] = {"--------------------------------------------------------------------------\n-- Virtex-4: JTAG Loader\n--------------------------------------------------------------------------\n\ti00_BUFG : BUFG\n\tport map\n\t(\n\t\tO => bs_clk1,\n        I => bs_clk0\n\t);\n\t\n\ti01_BUFG : BUFG\n\tport map\n\t(\n\t\tO => bs_update1,\n        I => bs_update0\n\t);\n\n\tBSCAN_VIRTEX4_inst1 : BSCAN_VIRTEX4 \n\tgeneric map\n\t(\n\t\tJTAG_CHAIN => 1 -- Value to set BSCAN site of device. Possible values: (1,2,3 or 4)\n\t)\n\tport map \n\t(\n\t\tCAPTURE => bs_capture, -- CAPTURE output from TAP controller\n\t\tDRCK => bs_clk0,       -- Data register output for USER functions\n\t\tRESET => bs_rst,       -- Reset output from TAP controller\n\t\tSEL => bs_sel,         -- USER active output\n\t\tSHIFT => bs_shift,     -- SHIFT output from TAP controller\n\t\tTDI => bs_tdi,        -- TDI output from TAP controller\n\t\tUPDATE => bs_update0,   -- UPDATE output from TAP controller\n\t\tTDO => bs_tdo         -- Data input for USER function\n\t);\n\n\tjtag_ld_addr <= user_regi(user_regi'left downto jtag_ld_dout'length);\n\tjtag_ld_din <= user_regi(jtag_ld_dout'length-1 downto 0);\n\tjtag_ld_clk <= bs_update1;\n\tjtag_ld_we <= bs_sel;\n\t\nsipo:\n\tprocess (bs_rst, bs_clk1, bs_tdi, bs_shift)\n\tbegin\n\t\tif bs_rst = '1' then\n\t\t\tuser_regi <= (others => '0');\n\t\telsif rising_edge(bs_clk1) then\n\t\t\tif bs_shift = '1' then\n\t\t\t\tuser_regi <= bs_tdi & user_regi(user_regi'left downto 1);\n\t\t\tend if;\n\t\tend if;\n\tend process;\t\n\npiso:\n\tprocess (bs_rst, bs_clk1, bs_shift, user_rego)\n\tbegin\n\t\tbs_tdo <= user_rego(0);\n\t\tif bs_rst = '1' then\n\t\t\tuser_rego <= (others => '0');\n\t\telsif rising_edge(bs_clk1) then\n\t\t\tif bs_shift = '1' then\n\t\t\t\tuser_rego <= user_rego(0) & user_rego(user_rego'left downto 1);\n\t\t\telse\n\t\t\t\tuser_rego <= (user_rego'left downto jtag_ld_dout'length => '0') & jtag_ld_dout;\t\n\t\n\t\t\tend if;\n\t\tend if;\n\tend process;\n\n"};

	pFileIn = fopen(pFilenameIn, "rb");
	if (!pFileIn)
	{
		fprintf(stderr, "Error opening file %s\n", pFilenameIn);
		return 1;
	}

	pFileOut = fopen(pFilenameOut, "wb");
	if (!pFileOut)
	{
		fprintf(stderr, "Error opening file %s\n", pFilenameOut);
		return 1;
	}

	fseek(pFileIn, 0, SEEK_SET);
	start = ftell(pFileIn);
	fseek(pFileIn, 0, SEEK_END);
	end = ftell(pFileIn);
	fseek(pFileIn, 0, SEEK_SET);

	filesize = (end-start);
	romsize = (int)pow(2, nbits_addr+2);

	// -------------------------------------------------------------------------
	// Header

	// -------------------------------------------------------------------------
	fprintf(pFileOut, "LIBRARY IEEE;\n");
	fprintf(pFileOut, "USE IEEE.STD_LOGIC_1164.ALL;\n");
	fprintf(pFileOut, "USE IEEE.NUMERIC_STD.ALL;\n");
	fprintf(pFileOut, "\n");

	fprintf(pFileOut, "library UNISIM;\n");
	fprintf(pFileOut, "use UNISIM.VComponents.all;\n");
	fprintf(pFileOut, "\n");

	fprintf(pFileOut, "ENTITY %s IS\n", ENT_NAME);
	fprintf(pFileOut, "\tPort\n");
	fprintf(pFileOut, "\t(\n");
	fprintf(pFileOut, "\t\tclk\t\t: in  STD_LOGIC;\n");
	fprintf(pFileOut, "\t\tce\t\t: in  STD_LOGIC;\n");
	fprintf(pFileOut, "\t\taddr\t\t: in  unsigned(%d downto 0);\n", nbits_data-1);
	fprintf(pFileOut, "\t\tdout\t\t: out unsigned(%d downto 0)\n", nbits_data-1);
	fprintf(pFileOut, "\t);\n");
	fprintf(pFileOut, "END %s;\n", ENT_NAME);
	fprintf(pFileOut, "\n");


	fprintf(pFileOut, "ARCHITECTURE %s OF %s IS\n", ARCH_NAME, ENT_NAME);
	fprintf(pFileOut, "\n");

	fprintf(pFileOut, "\tsubtype word_t is unsigned(%d downto 0);\n", nbits_data-1);
	fprintf(pFileOut, "\ttype word_array_t is array (0 to %d) of word_t;\n", romsize/4-1);

	fprintf(pFileOut, "\tsignal jtag_ld_clk\t\t: STD_LOGIC;\n");
	fprintf(pFileOut, "\tsignal jtag_ld_we\t\t: STD_LOGIC;\n");
	fprintf(pFileOut, "\tsignal jtag_ld_addr\t\t: unsigned (%d downto 0);\n", JTAG_ADDR_WIDTH-1);
	fprintf(pFileOut, "\tsignal jtag_ld_dout\t\t: unsigned (%d downto 0);\n", nbits_data-1);
	fprintf(pFileOut, "\tsignal jtag_ld_din\t\t: unsigned (%d downto 0);\n", nbits_data-1);
	fprintf(pFileOut, "\tsignal bs_rst, bs_sel, bs_shift, bs_tdi, bs_tdo : std_logic;\n");
	fprintf(pFileOut, "\tsignal bs_capture, bs_clk0, bs_clk1, bs_update0, bs_update1 : std_logic;\n");
	fprintf(pFileOut, "\tsignal user_regi, user_rego : unsigned (%d downto 0);\n", 31 + JTAG_ADDR_WIDTH);
	fprintf(pFileOut, "\n");

	fprintf(pFileOut, "\tsignal word_array : word_array_t :=\n");
	fprintf(pFileOut, "\t(\n");
	fprintf(pFileOut, "\n");

	// -------------------------------------------------------------------------
	// ROM part
	// -------------------------------------------------------------------------
	for (i=0; i < filesize; i += sizeof(int))
	{
		fread(&word, 1, sizeof(int), pFileIn);
		fprintf(pFileOut, "\t\tX\"%8.8X\"", word);
		if (i < (romsize-sizeof(int)))
			fprintf(pFileOut, ", -- %8.8X\n", i);
		else
			fprintf(pFileOut, "  -- %8.8X\n", i);
	}
	word = 0;
	for (; i < romsize; i += sizeof(int))
	{
		fprintf(pFileOut, "\t\tX\"%8.8X\"", word);
		if (i < (romsize-sizeof(int)))
			fprintf(pFileOut, ", -- %8.8X\n", i);
		else
			fprintf(pFileOut, "  -- %8.8X\n", i);
	}
	fprintf(pFileOut, "\t);\n");
	fprintf(pFileOut, "\n");

	fprintf(pFileOut, "begin\n", ARCH_NAME);

	fprintf(pFileOut, "\n");
	fprintf(pFileOut, "PROM_READ:\n", ARCH_NAME);
	fprintf(pFileOut, "\tprocess(clk)\n");
	fprintf(pFileOut, "\tbegin\n");
	fprintf(pFileOut, "\t\tif rising_edge(clk) and ce = '1' then\n");
	fprintf(pFileOut, "\t\t\tdout <= word_array(to_integer(addr(%d downto 2)));\n", nbits_addr+1);
	fprintf(pFileOut, "\t\tend if;\n");
	fprintf(pFileOut, "\tend process;\n");
	fprintf(pFileOut, "\n");

	// -------------------------------------------------------------------------
	// Trailer
	// -------------------------------------------------------------------------
	fprintf(pFileOut, "\n");
	fputs(tpl, pFileOut);

	fprintf(pFileOut, "PROM_WRITE:\n", ARCH_NAME);
	fprintf(pFileOut, "\tprocess(jtag_ld_clk, jtag_ld_we)\n");
	fprintf(pFileOut, "\tbegin\n");
	fprintf(pFileOut, "\t\tif rising_edge(jtag_ld_clk) then\n");
	fprintf(pFileOut, "\t\t\tif jtag_ld_we = '1' then\n");
	fprintf(pFileOut, "\t\t\t\tword_array(to_integer(jtag_ld_addr(%d downto 0))) <= jtag_ld_din;\n", nbits_addr-1);
	fprintf(pFileOut, "\t\t\telse\n");
	fprintf(pFileOut, "\t\t\t\tjtag_ld_dout <= word_array(to_integer(jtag_ld_addr(%d downto 0)));\n", nbits_addr-1);
	fprintf(pFileOut, "\t\t\tend if;\n");
	fprintf(pFileOut, "\t\tend if;\n");
	fprintf(pFileOut, "\tend process;\n");
	fprintf(pFileOut, "\n");

	fprintf(pFileOut, "end %s;\n", ARCH_NAME);
	return 0;
}

int SaveROM_TCL(char *pFilenameIn, char *pFilenameOut, char *pArchName, char *pEntName, int nbits_addr, int nbits_data)
{
	FILE *pFileIn, *pFileOut;
	long start, end;
	int i, word, word_addr, filesize, romsize;
	char binstr_addr[33];
	char binstr_data[33];

	char tpl[] = {"# ---------------------------------------------------------------------\n# For Chipscope 9.1\n# ---------------------------------------------------------------------\n# Source JTAG/TCL frame work\ncd $env(CHIPSCOPE)\\\\bin\\\\nt\nsource csejtag.tcl\n\nnamespace import ::chipscope::*\n\n# Platform USB Cable\nset PLATFORM_USB_CABLE_ARGS [list \"port=USB2\" \"frequency=6000000\"]\n# frequency=\"24000000 | 12000000 | 6000000 | 3000000 | 1500000 | 750000\"\n\n# Create session\nset handle [::chipscope::csejtag_session create 0]\n\n# Open JTAG and lock\nset open_result [::chipscope::csejtag_target open $handle $CSEJTAG_TARGET_PLATFORMUSB 0 $PLATFORM_USB_CABLE_ARGS]\nset lock_result [::chipscope::csejtag_target lock $handle 1000]\n\nset devlist [::chipscope::csejtag_tap autodetect_chain $handle $CSEJTAG_SCAN_DEFAULT]\n\n# Get Device ID\nset devtype \"Virtex-4SX\"\nset devid 2\nset irlength [::chipscope::csejtag_tap get_irlength $handle $devid]\nset idcode [::chipscope::csejtag_tap get_device_idcode $handle $devid]\n\nset CSE_OP $CSEJTAG_SHIFT_READWRITE\nset CSE_ES $CSEJTAG_RUN_TEST_IDLE\n\n# Write Program\n"};

	pFileIn = fopen(pFilenameIn, "rb");
	if (!pFileIn)
	{
		fprintf(stderr, "Error opening file %s\n", pFilenameIn);
		return 1;
	}

	pFileOut = fopen(pFilenameOut, "wb");
	if (!pFileOut)
	{
		fprintf(stderr, "Error opening file %s\n", pFilenameOut);
		return 1;
	}

	fseek(pFileIn, 0, SEEK_SET);
	start = ftell(pFileIn);
	fseek(pFileIn, 0, SEEK_END);
	end = ftell(pFileIn);
	fseek(pFileIn, 0, SEEK_SET);

	filesize = (end-start);
	romsize = (int)pow(2, nbits_addr+2);

	// -------------------------------------------------------------------------
	// Header

	// -------------------------------------------------------------------------
	fputs(tpl, pFileOut);

	// -------------------------------------------------------------------------
	// ROM part
	// -------------------------------------------------------------------------
	fprintf(pFileOut, "# Assembled from %s\n", pFilenameIn);
	fprintf(pFileOut, "# ---------------------------------------------------------------\n");
	fprintf(pFileOut, "# Shift the USER1 Instruction (b1111000010) into the Instruction Register of FPGA\n");
	fprintf(pFileOut, "# User 1\n");
	fprintf(pFileOut, "set result [::chipscope::csejtag_tap shift_device_ir $handle $devid $CSE_OP $CSE_ES 0 $irlength \"3C2\"]\n\n");

	word_addr = 0;
	for (i=0; i < filesize; i += sizeof(int))
	{
		fread(&word, 1, sizeof(int), pFileIn);
		fprintf(pFileOut, "::chipscope::csejtag_tap shift_device_dr $handle $devid $CSE_OP $CSE_ES 0 %d \"%4.4X%8.8X\"\n", nbits_data + JTAG_ADDR_WIDTH, word_addr, word);
		word_addr++;
	}
	fprintf(pFileOut, "\n");

	// -------------------------------------------------------------------------
	// Trailer
	// -------------------------------------------------------------------------
	fprintf(pFileOut, "::chipscope::csejtag_target unlock $handle\n");
	fprintf(pFileOut, "::chipscope::csejtag_target close $handle\n");
	fprintf(pFileOut, "::chipscope::csejtag_session destroy $handle\n");
	fprintf(pFileOut, "exit\n");

	return 0;
}

int main(int argc, char *argv[])
{
	char *pFilenameIn;
	char name_prj[1024];
	char name_rom[1024];
	char name_rom_v4ld[1024];
	char name_rom_tcl[1024];

	FILE *pFileIn;
	int filesize, romsize, nbits_addr, nbits_data;
	long start, end;
	int word, i;

	if (argc < 2)
	{
		fprintf(stderr, "Usage: romgen <input file> <num. word address bits>\n");
		return 1;
	}

	pFilenameIn = argv[1];
	if (argc == 3)
		nbits_addr = atoi(argv[2]);


	basename(pFilenameIn, name_prj);
	sprintf(name_rom, "%s.vhd", name_prj);
	sprintf(name_rom_v4ld, "%s_ld.vhd", name_prj);
	sprintf(name_rom_tcl, "%s.tcl", name_prj);

	SaveROM(pFilenameIn, name_rom, ARCH_NAME, ENT_NAME, nbits_addr, 32);
	SaveROM_V4LD(pFilenameIn, name_rom_v4ld, ARCH_NAME, ENT_NAME, nbits_addr, 32);
	SaveROM_TCL(pFilenameIn, name_rom_tcl, ARCH_NAME, ENT_NAME, nbits_addr, 32);


	return 0;
}

