#!perl -lw
# Version 0.01
use strict;
use Getopt::Std;
use RISCOS::Throwback;
use RISCOS::Chunkfile;
use RISCOS::File ':DEFAULT', '/glob/';
use RISCOS::Filespec;
use RISCOS::Chunk;
use RISCOS::AOF;
use RISCOS::ALF;
use RISCOS::Time qw (time2utc time2local);
# Keep paths intact (eg Unix:o.UnixLib
glob_control (&fileglob_PrintOriginalPath);

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

sub do_file
{
    my $file = shift;
    my $chunks = new RISCOS::Chunkfile shift;
    # So that name and data source can differ
    my $entry = shift;
    my $directory;

    unless ($chunks) {
	warn "'$file' is not a chunkfile";
    }
    elsif ($chunks->Lookup ('OBJ_HEAD'))
    {
	# izza AOF
	if ($entry) {
	warn "Attempting to read entry '$entry' from AOF file '$file'\n";
	} else {
	    &do_aof ($chunks, $file);
	}
    }
    elsif ($chunks->Lookup ('LIB_DIRY'))
    {
	if (my $library = new RISCOS::ALF $chunks) {
	    # izza ALF
	    if ($entry) {
		&do_alf ($library, $file, $library->Dir_Lookup ($entry));
	    } else {
		    &do_alf ($library, $file, values %{$library->Dir});
	    }
	}
    }
    else
    {
	warn "'$file' is not a recognised chunkfile - contains "
	  . join (', ', keys %{$chunks->Keys()}) . ' chunks';
    }
}
    
sub do_alf ($$;@) {
   my $library = shift;
   my $file = shift;

    foreach (@_) {
	# Reference to chunk data means "treat this as file to load"
	do_file ("$file," . $_->Name(),
		 \($library->By_Number($_->Index())->Data), '');
    }
}

sub do_aof ($$) {
    my $chunks = new RISCOS::AOF shift;
    my $file = shift;

    print "# from $file";

    foreach my $symbol (@{$chunks->Symbols}) {
	print $symbol->Name() if $opt{'d'} and $symbol->Scope eq '';
	print $symbol->Name() if $opt{'x'} and $symbol->Scope eq 'extern';
    }
    print '';
}

foreach (@ARGV)
{
    # Try to make the entry the longest comma free string possible
    my ($file, $entry) = ($_);

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

    my @files = glob ($file);

    @files = $file unless @files;	# Push pattern if unmatched

    foreach $file (@files)
    {
	do_file ($file, $file, $entry);
    }
}

__END__
	$stringtable = aof_stringtable $chunks[$stringtable->[0]] ->Data();

	while (($key, $val) = each %$stringtable) {
	    print "$key: '$val'";
	}
----
	    foreach (keys %$directory) {
		print $_, "\t", scalar time2local ($directory->{$_}->Time()->Time());
