#!/usr/bin/perl

# Break up and save the "chunks" of a Blorb file.
# Saves each chunk to a numbered file with prefix
# as first part of blorb file name and suffix as chunk type.
# You can then (for instance) just rename the zcode section and use
# it with a zcode-interpreter --- it will usually be a much smaller file.

# Hacked from Graham Nelson's "scanBlorb" (c) Graham Nelson 1998.
# Modifications (c) Bob Newell 2007, 2008.

print "Unblorb 1.1\n\n";
if ($#ARGV < 0) { die "No input filename"; }
$input_filename = $ARGV[0];
$base = substr($input_filename, 0, index($input_filename, "."));
open (BLORB, $input_filename) or die "Can't load $input_filename.";
binmode(BLORB);
read BLORB, $buffer, 12;
($w1, $w2, $w3) = unpack("NNN", $buffer);
if ($w1 != 0x464F524D) { die "Not a valid FORM file\n"; }
if ($w3 != 0x49465253) { die "Doesn't carry the Blorb magic word\n"; }
print "Begin.\n";
$posn = 12;
while ($posn < $w2)
{
    $headlength = read BLORB, $buffer, 8;
    if ($headlength != 8) { die "Incomplete chunk header at $posn"; }
    else
    {   ($junk, $size) = unpack("NN", $buffer);
        $type = substr($buffer, 0, 4);
	$type =~ s/^\s+//;
	$type =~ s/\s+$//;
        if ($size % 2 == 1) { $size = $size + 1; }
        $bodylength = read BLORB, $chunkdata, $size;
        if ($bodylength != $size) { die "Incomplete chunk at $posn"; }
        else
        {   
		$k=0;
		while ( -e ($ofile=$base.".".$k.".".$type) ) {$k++;}
		open(BLORBO, ">$ofile");
		binmode(BLORBO);
		print $ofile,"  ";
		print BLORBO $chunkdata;
		close BLORBO;
	        $posn = $posn + $size + 8;
        }
    }
}
close(BLORB);
print "\nEnd.\n";