#!/usr/bin/env perl

if (@ARGV != 3) { die "USAGE: trace.pl (input) (output) (trace)\n"; }

open (FILE, $ARGV[0]);
@list = <FILE>;
close (FILE);

open (OUT, ">$ARGV[1]");
open (TRC, ">$ARGV[2]");

&header;
$NL = 0;
$NLMAX = 53;

$Nv = 0;
foreach $line (@list) {
    if ($line =~ m|\\VER\{\S*\}\{.*\}|) {
	($start, $value, $stop) = $line =~ m|(.*\\VER\{\S*\})\{(.*)\}(.*)|;
	@words = split (" ", $value);
	$N = @words;

	print OUT "$start\{";
	for ($i = 0; $i < @words; $i++) {
	    $word = $words[$i];
	    $last = chop ($word);
	    if ($last ne ",") { $word = $word . $last; }
	    if ($word =~ m|TLR|) { $word = "\\ref\{$word\}"; }
	    print OUT "$word";
	    if ($i < $N - 1) { print OUT ", "; }

	    if ($Nv > 24) { 
		$Nr = $Nv - 24; 
		print TRC "\\ref{DRQ:$Nr} & & $word & \\\\ \\hline\n";
		$NL ++;
		if ($NL > $NLMAX) {
		    print TRC "\\end{tabular}\n";
		    print TRC "\\end{center}\n\n";
		    &header;
		    $NL = 0;
		}
	    } 	
	}
	print OUT "\}$end";
	if ($Nv > 24) { 
	    $Nr = $Nv - 24; 
	    print OUT "\\label{DRQ:$Nr}\n";
	} else {
	    print OUT "\n";
	}
	$Nv ++;
    } else {
	print OUT $line;
    }
}
print TRC "\\end{tabular}\n";
print TRC "\\end{center}\n\n";

close (OUT);
close (TRC);


sub header {
print TRC "\\begin{center}\n";
print TRC "\\footnotesize\n";
print TRC "\\begin{tabular}{|l|l|l|l|}\n";
print TRC "\\hline\n";
print TRC "\\multicolumn{2}{|c|}{\\bf Derived Subsystem Requirements} &  \n";
print TRC "\\multicolumn{2}{|c|}{\\bf Top-level Subsystem Requirements} \\\\ \\hline \n";
print TRC "\\FRN{\\bf Number} & \n";
print TRC "\\FRS{\\bf Caption} & \n";
print TRC "\\FRN{\\bf Number} & \n";
print TRC "\\FRS{\\bf Caption} \\\\ \\hline\n";
}
