#!/usr/local/bin/perl
eval "exec /usr/local/bin/perl -S $0 $*"
    if $running_under_some_shell;
			# this emulates #! processing on NIH machines.
			# (remove #! line above if indigestible)

$dirs = "../builtin ../class ../fstream \\\
	 ../loader ../mathematics ../primitive \\\
	 ../table ../utils";

open (LINE, "find $dirs -name '*.[cy]' -print | sort |");
open (OBJS, "> OBJS");
open (SRCS, "> SRCS");
open (DEPS, "> DEPS");

while (<LINE>) {
	chop;
	($dot,$dir,$src) = split ("/");
	next if ($src eq "parse.c");
	if ($src eq "parse.y") {
		$obj = "parse.o";
		$src = "parse.c";
	}
	else {
		($obj = $src) =~ s|\.c|\.o|;
		print SRCS "$dot/$dir/$src\n";
	}
	print OBJS "$obj\n";
	print DEPS "$obj: $dot/$dir/$src", "\n";
	print DEPS "\t\${CC} -c \${CFLAGS} $dot/$dir/$src\n";
}

close (LINE);
close (OBJS);
close (SRCS);
close (DEPS);

open (OLD, "< Makefile.in");
open (NEW, "> Makefile.new");

$mark = "# DO NOT DELETE THIS LINE -- pasmkmake uses it";

while (<OLD>) {
  $line = $_;
  if ($line =~ /^OBJS/) {
    while (<OLD>) {
      if (/^$/) {
	$line = <OLD>;
	last;
      }
    }
    do copy_into_Makefile ("OBJS");
  }
  if ($line =~ /^SRCS/) {
    while (<OLD>) {
      if (/^$/) {
	$line = <OLD>;
	last;
      }
    }
    do copy_into_Makefile ("SRCS");
  }
  last if (/^$mark/);
  print NEW $line;
}

print NEW $mark, "\n\n";
open (DEPS, "< DEPS");
while (<DEPS>) {
  print NEW;
}

close (OLD);
close (NEW);
system ("rm OBJS SRCS DEPS");
system ("mv Makefile.in Makefile.bak");
system ("mv Makefile.new Makefile.in");

sub copy_into_Makefile {
  $input = $_[0];
  open (tempfile, "< $input");
  $record = "$input =";
  while (<tempfile>) {
    chop;
    if (length ($record) > 55) {
      print NEW $record, " \\\n";
      $record = "    " . $_;
    }
    else {
      $record .= " " . $_;
    }
  }
  print NEW $record, "\n\n";
  close (tempfile);
}
