#! /usr/local/bin/perl --	# -*-Perl-*-
    eval "exec /usr/local/bin/perl -S $0 $*"
	if $running_under_some_shell;
# $Id$
#
# $Log$

# Usage: relread [-d datafile] [-s salinc_dir] Relation

$SAT_DIR = $ENV{'SAT_DIR'} || '/usr/local/etc/sat';

require 'getopts.pl';

($program = $0) =~ s,.*/,,;

&Getopts('d:s:') || &usage;

if ($#ARGV != 0) {
    &usage;
    # not reached
}

$Relation = $ARGV[0];

if ($opt_d) {
    $data_file = $opt_d;
} else {
    $data_file = "$SAT_DIR/db/$Relation/data";
}

if ($opt_s) {
    $sal_dir = $opt_s;
} else {
    $sal_dir = "$SAT_DIR/salinclude";
}

&GetSpec;

&PrintData;

exit 0;

# --------------------------------------------------------------------------
# Get and read the sal definition file
# --------------------------------------------------------------------------
sub GetSpec {
    $sal_spec = $sal_dir . "/" . $Relation . "Def.sal";
    open(FILE,$sal_spec) || die "Can't open $sal_spec: $!\n";
    $line = -1;
    while (<FILE>) {
	if ($line >= 0) {
	    ($type[$line],$name[$line]) = /(\w+)\s+(\w+)/;
	}
	++$line;
    }
    close(FILE);


}

# --------------------------------------------------------------------------
# Print the data file
# --------------------------------------------------------------------------
sub PrintData {
    open(DFILE,$data_file) || die "Can't open $data_file: $!\n";
    binmode DFILE;
    &PrintRecords;
    close(DFILE);
}

# --------------------------------------------------------------------------
# Print Data Records
# --------------------------------------------------------------------------
sub PrintRecords {
    $len = &GetLength;
    for(;;) {
	last if ($len == 0);
	for ($i = 0; $i < $line; ++$i) {
	    print "$type[$i]\t$name[$i]\t";
	    &PrintValue($len - 1);
	    $len = &GetLength;
	}
	print "\n";
    }
}

# --------------------------------------------------------------------------
# Get the data length
# --------------------------------------------------------------------------
sub GetLength {
    if (read(DFILE, $zero, 1) != 1) {
	die "read() of length information failed.\n";
    }
    $zero = ord($zero);
    if ($zero != 0) {
	die "Expected NUL byte was not NUL! <$zero>\n";
    }
    if (read(DFILE, $dl, 1) != 1) {
	die "read() of length byte failed.\n";
    }
    $dl = ord($dl);
}

# --------------------------------------------------------------------------
# Print a single data value
# --------------------------------------------------------------------------
sub PrintValue {
    local($dl) = @_;
    if ($dl > 0) {
	if (read(DFILE, $ds, $dl) != $dl) {
	    die "read() of $dl bytes of data failed.\n";
	}
    } else {
	$ds = '';
    }
    print "<$ds>\n";
}

# --------------------------------------------------------------------------
# print out usage message and exit
# --------------------------------------------------------------------------
sub usage {
    warn "Usage: relread [-d datafile] [-s salinc_dir] Relation\n";

    exit 1;
}
