#!/usr/bin/perl
#
# acpixtract - extract raw table from acpidump output
# usage: acpixtract [-n instance_number] <table> [input text file]
#
# Example: cat mail.txt | ./acpixtract [-n instance_number] DSDT > DSDT
# iasl -d DSDT
#

my $instance = 1;	# default: print first instance of target table

($ME = $0) =~ s|.*/||;

# Process switches.
while ($ARGV[0] =~ /^-/) {
    $_ = shift;
    if (/^-n/) {
	$instance = ($1 ? $1 : shift);
	if ($instance <= 0) {
		die "-n number cannot be less than 0\n";
	}
    }
    else {
	die "Unrecognized switch: $_\n";
    }
}

$table = uc(shift(@ARGV) || "");

if(@ARGV)
{
    my($file);
    for $file (@ARGV)
    {
	if(open(IN, "$file"))
	{
	    &process(IN, STDOUT, $table);
	    close(IN);
	}
	else
	{
	    print STDERR "$ME: $file: $!\n";
	}
    }
}
else
{
    &process(STDIN, STDOUT, $table);
}

exit(0);

sub
process
{
    local(*IN, *OUT, $table) = @_;
    my($interior) = 0;
    my($inst) = 0;

    while(<IN>)
    {
	if(!$interior && /$table \@ 0x/)
	{
	    $inst++;
	    if ($inst == $instance)
	    {
		$interior = 1;
	    }
	}
	elsif($interior && /\s+[\dA-Fa-f]{4}:\s+/)
	{
            $_ = $';
            /\s{2}/;
            $length = ((length($`) + 1) / 3) - 1;
	    print OUT pack('C*', map(hex, (split(/\s/, $`))[0..$length]));
	}
	elsif($interior)
	{
	    while(<IN>) {}
	    return;
	}
    }
}
