#!perl -w
# Version 0.01
use strict;
use Getopt::Std;
use RISCOS::Throwback;
use RISCOS::Chunkfile qw(load_chunkfile index_chunkfile);
use RISCOS::Filespec;
use RISCOS::Chunk;
# use RISCOS::AOF qw (aof_stringtable aof_symboltable);
use RISCOS::ALF qw (alf_directory);
use RISCOS::Time qw (time2utc time2local);

use vars qw(%opt);
getopts ('d', \%opt);
$opt{'d'} = 0 unless keys %opt;

# Try to make the entry the longest comma free string possible
my ($file, $entry) = (shift);

# Found a comma? If so separate as it's probably a $file,$entry for ALF
($file, $entry) = $file =~ /^(.*?),?([^,]*)$/ if $file =~ tr/,//;

$entry = shift unless $entry;

my $output = shift;

die "$0 <ALF File> <Entry> [<Output>]" unless defined $entry;

if ($output) {
    open (STDOUT, ">$output") or die "Couldn't open '$output': $!";
}

do_file ($file, $file, $entry);

exit 0;

sub do_file
{
    my $file = shift;
    my @chunks = load_chunkfile shift;
    # So that name and data source can differ
    my $entry = shift;
    my $index = index_chunkfile @chunks;

    unless (@chunks) {
        warn "'$file' is not a chunkfile";
    }
    elsif (defined $$index{OBJ_SYMT})
    {
	# izza AOF
	warn "Attempting to read entry '$entry' from AOF file '$file'\n";
    }
    elsif (defined $$index{LIB_DIRY})
    {
	my $directory  = $$index{LIB_DIRY};
	    if (@$directory > 1)
	{
	warn "Multiple directories in ALF file '$file' - chunks "
	  . join ',', @$directory;
	next;
	}
	$directory = alf_directory $chunks[$directory->[0]];
	# izza ALF
	
	if ($entry) {
	    &do_chunk (\@chunks, $file, $directory->{$entry});
	} else {
	    &do_chunk (\@chunks, $file, values %$directory);
	}
    }
    else
    {
        warn "'$file' is not a recognised ALF file - contains "
          . join (', ', keys %$index) . ' chunks';
    }
}
    
sub do_chunk ($$;@) {
    my $chunks = shift;
    my $file = shift;
   
    die "Can't dump library out yet :-(" if $opt{d};

    foreach (@_) {
        # Reference to chunk data means "treat this as file to load"
	print ($chunks->[$_->Index()]->Data);
    }
}

