#!/usr/local/bin/perl -w
#!  Keep the -w switch and fix your bugs instead.
#!##############################################################
#!
#! Bin-cris: get the binary stuff from a CRIS linked file
#!
#! Check some historic parameters, weed out outfile and infile, and get
#! the binary file from the infile, write it to outfile.
#!  The "weeding" consists of checking the magic number for a
#! completely-linked cris-a.out-file, getting the .text and .data sizes, and
#! getting the binary contents of that size after the 32-byte header.
#!
#! Apr 07 1997  H-P Nilsson   Initial.  Not in SCCS yet...
#!
#!##############################################################
# %Z% %M% %I% %G%

$program_name = $0;

require "getopts.pl";

# "-wN" used to be width of proms, "-bN" used to be the block number,
# "-o file" still is the outfile.
Getopts('w:b:o:');

if ((defined($opt_w) && (($badopt = "-w$opt_w"),($opt_w != 1 && $opt_w != 2)))
    || (defined($opt_b) && (($badopt = "-b$opt_b"),($opt_b != 0 && $opt_b != 1)))
    || ($badopt = $ARGV[0]),$ARGV[0] =~ /^-/)
{
  die ("$ARGV[0]: Illegal option: $badopt\n");
}

$infile = $ARGV[0];

if (!defined($opt_o)) { die ("$program_name: No output file specified\n"); }
$outfile = $opt_o;
$bin = "";

open (IN, "<$infile") || die ("$program_name: Could not open \"$infile\" for input: $!\n");
read (IN,$bin,4) == 4 || die("$program_name: Could not read 4 bytes from \"$infile\": $!\n");
($magi) = unpack("V",$bin);

die ("$program_name: Bad magic for \"$infile\"\n")
 unless ($magi == 0x01ff010b || $magi == 0x010b);

read(IN,$bin,4) || die("$program_name: Could not read 4 bytes from \"$infile\": $!\n");
($tlength) = unpack("V",$bin);

read(IN,$bin,4) || die("$program_name: Could not read 4 bytes from \"$infile\": $!\n");
($dlength) = unpack("V",$bin);

read(IN,$bin,5*4) || die("$program_name: Could not read 20 bytes from \"$infile\": $!\n");

read(IN,$bin,$tlength+$dlength) || die("$program_name: Could not read the rest from \"$infile\": $!\n");

# If to just use high or low
if (defined($opt_w) && $opt_w == 2)
{
  if ($opt_b == 0)
  {
    $bin = pack "C*",(unpack "v*",$bin); # Get the low byte of a LE-word
  }
  else
  {
    $bin = pack "C*",(unpack "n*",$bin); # Get the high byte of a BE-word
  }
}
open(OUT,">$outfile") || die("$program_name: Could not open \"$outfile\" for output: $!\n");
print OUT $bin || die("$program_name: Could not write the binary to \"$outfile\": $!\n");

close(OUT) || die("$program_name: Could not close \"$outfile\": $!\n");
