#!/usr/bin/perl -w

# Builds hex "SPI" files from logic analyser listings
#
# Author: Emil
# Last modified: 11 August 2004

$progname = $0;
$progname =~ s+^.*/++;
$usage = "\nUsage: $progname text_file(s)\n";

die $usage if( $#ARGV < 0 );

while( @ARGV )
{
  my $tmp = shift;
  SW:
  {
    die "Error ($tmp)\n\n$usage" if( $tmp =~ /^-/ );
    push( @tfl, $tmp );
  }
}

foreach $txtfile( @tfl )
{
  printf( "Reading file $txtfile ...\n" );
  $tgz = 0;
  open( IFILE, "$txtfile" ) || die "open $txtfile - $!\n";
  $txtfile = $1 if( $txtfile =~ /(.*)\.spi/ );

  $binfile = $txtfile . ".acc";
  open( WRFILE, "> $binfile" ) || die "open file - $!\n";

	$mem = "";
	$mc = 0;
  while( $ln = <IFILE> )
  {
		if( $ln =~ /^MEM (\w\w) (\w\w)/ )
		{
			$o = hex($1) ; $i = hex($2);
			if( $o == 0x52 && $i == 0xff )
			{
				printf( WRFILE "MEM %04x:%02x < $mem\n", $page , $off ) if( $mem ne "" );
	      $mem = "";
       	$mc = 0;
			}
			$page = $o << 7 if( $mc == 1 );
			$page |= $o >> 1 if( $mc == 2 );
			$off = $o if( $mc == 3 );
			$mem .= sprintf( "%02x ", $i ) if( $mc >= 8 );
			$mc++;
		}
		else
		{
			if( $mem ne "" )
			{
				printf( WRFILE "MEM %04x:%02x < $mem\n", $page , $off );
	      $mem = "";
       	$mc = 0;
			}
			print( WRFILE "$ln" );
		}
  }
  close( IFILE ) || die "close $txtfile $!\n";
  close( WRFILE );
}
exit;

# end
