#!/usr/bin/perl
#
# $Id: hex2rom4.pl,v 1.1 2006/02/01 21:31:47 cnguyen Exp $
#
# Take a hex file which is continuous 32-bit words and split 
# it into four 16-bit wide files, two for the top 1024 words
# of rom and two for the bottom 1024 words.
#
# IN_FILE is the input hex file and OUT_FILE[0:3] are the 
# four output files.
#
$outfile="outfile";
$numArgs = $#ARGV + 1;
if ( $numArgs == 0) {
    printf "hex2rom4.pl input.hex [output]\n";
    exit;
} else {
    $infile=$ARGV[0];
    if ( $numArgs > 1 ) {
	$outfile=$ARGV[1];
    }
}

open (IN_FILE, $infile) or die "$infile not found or bad permissions\n";

#
# Generate four output files.
#
for ( $i = 0; $i < 4; $i++ ) {
    @outfile[$i]="$outfile$i.hex";
    SWITCH: {
	if ( $i == 0 ) {
	    printf "output file $i @outfile[$i] D[31:16]; low 1k x 32 memory\n";
	    last SWITCH;
	}
	if ( $i == 1 ) {
	    printf "output file $i @outfile[$i] D[15:0]; low 1k x 32 memory\n";
	    last SWITCH;
	}
	if ( $i == 2 ) {
	    printf "output file $i @outfile[$i] D[31:16]; high 1k x 32 memory\n";
	    last SWITCH;
	}
	if ( $i == 3 ) {
	    printf "output file $i @outfile[$i] D[15:0]; high 1k x 32 memory\n";
	    last SWITCH;
	}
	$nothing = 0;
    }
}
open (OUT_FILE0, ">@outfile[0]") or die "@outfile[0] not found or bad permissions\n";
open (OUT_FILE1, ">@outfile[1]") or die "@outfile[1] not found or bad permissions\n";
open (OUT_FILE2, ">@outfile[2]") or die "@outfile[2] not found or bad permissions\n";
open (OUT_FILE3, ">@outfile[3]") or die "@outfile[3] not found or bad permissions\n";

#
# This counts the words in the input file.
#
$word_count=0;

#
# This shows what output file we are using.
#
$file_count=0;

#
# Write the actual data to the files.
#
while ( <IN_FILE> ) {
    $word = hex($_);
    if ( $word_count < 1024 ) {
	printf OUT_FILE0 "%04x\n", ($word & 0xffff0000) >> 16;
	printf OUT_FILE1 "%04x\n", $word & 0x0000ffff;
    } else {
	printf OUT_FILE2 "%04x\n", ($word & 0xffff0000) >> 16;
	printf OUT_FILE3 "%04x\n", $word & 0x0000ffff;
    }
    $word_count++;
    if ( $word_count == 1024 ) {
	$file_count=2;
    }
}

#
# Write trailing data to the files
#
if ( $word_count < 1024 ) {
    do {
	printf OUT_FILE0 "%04x\n", 0;
	printf OUT_FILE1 "%04x\n", 0;
	$word_count++;
    } while ($word_count < 1024 );
}
if ( $word_count < (2 * 1024) ) {
    do {
	printf OUT_FILE2 "%04x\n", 0;
	printf OUT_FILE3 "%04x\n", 0;
	$word_count++;
    } while ($word_count < (2 * 1024) );
}

# eof
