#! /usr/bin/perl

$debug = 0;
$idlexec = 'idl';
$filename = 'BuildOrder';

$r_commands = [];
$pwd = $ENV{"PWD"};
resolveOrder($r_commands,$filename,"$pwd/");
$debug && print join("\n",@$r_commands);

$startup = $ENV{"IDL_STARTUP"};
if (defined($startup)) {
	open(STARTUP,">$startup");
	print STARTUP join("\n",@$r_commands) . "\n";
	close(STARTUP);
}

$savefile = $ARGV[0];
if (defined($savefile)) {
	open(IDL,'|' . $idlexec);
	print IDL join("\n",@$r_commands) . "\n";
	print IDL "SAVE, FILENAME='$savefile'\n";
	print IDL "EXIT\n";
	close(IDL);
}

sub resolveOrder {
	my ($r_commands,$filename,$directory) = @_;
	if (-f $filename) {
		$debug && print "Examining $filename\n";
		open(ORDER,$filename);
		my @lines = (<ORDER>);
		close(ORDER);
		$debug && print "$filename has " . scalar(@lines) . " lines\n";
		foreach $line (@lines) {
			$line =~ s/\s+$//;
			$line = $line;
			if (-f $directory . $line) {
				push(@$r_commands,".COMPILE $line");
			}
		}
		foreach $line (@lines) {
			$line =~ s/\s+$//;
			$line = $line;
			if (-d $directory . $line) {
				$debug && print "Searching directory $line\n";
				$filename = $line . 'BuildOrder';
				if (-f $directory . $filename) {
					$debug && print "Found Build Order $directory$filename\n";
					push(@$r_commands,"CD, '$directory$line'");
					resolveOrder($r_commands,$directory.$filename,$directory . $line);
				}
			}
		}
	}
}
