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

#
# Creates a toplevel makefile from picking up the RESULTSER, RESULTSCR, and
# 	RESULTSNR variables from subdirectories.
#
# Joel Schroeder: adapted from Matthias Schwab's makecake
#
# keywords make redoc report 

$usage = "Usage: $0 - \n";
$selfdoc = "Creates a makefile from picking up the RESULTSER, RESULTSCR, and RESULTSNR variables from all lowercase subdirectories of your current directory. I wish the GNUmakefile would up-date itself by running this script.\n";

if( $#ARGV < 0 ||$#ARGV > 1 ) {
  print $usage;
  die $selfdoc;
  }

$notice = "# **** MACHINE MADE MAKEFILE (by makemake) ****";

# Check if makefile exists and if it is made by makemake
$makename = "";
if (-e "Makefile")    {$makename = "Makefile";}
if (-e "makefile")    {$makename = "makefile";}
if (-e "GNUmakefile") {$makename = "GNUmakefile";}
if ("$makename" ne "") {
  $first_line = `sed 1q< $makename`;
  if ("$first_line" ne "$notice"."\n") {
    $dir = `pwd`;
    chop($dir);
    print "$dir";
    print ": $makename exists and it is not made by makemake. I quit.\n";
    die;
    }
  }
else {	# use default makename
  $makename = "Makefile";
  }

open(DODIR, "ls -d [a-z]* |") || die "Can't see $dir\n";
while ($dir = <DODIR>) { 
  chop $dir;
  if ( -d $dir ) {
    $dirlist = join(" ",$dirlist,$dir);
    }
  }

  # all?r is a compilation of ?-correspondingly-reproducible results from all
  #    the subdirectories' makefiles.
  # reslist is an associative array keyed on the subdirectories, and contains
  #    all the result names of the indexed subdirectory's makefile
  # sepinc is the last (in the order of $dirlist) non-null value of SEPINC
  # resdir  is the last (in the order of $dirlist) non-null value of RESDIR
$aller = ''; $allcr = ''; $allnr = '';
$sepinc = '/usr/local/lib/share/make';	# initialize to default value
$resdir  = './Fig';			# initialize to default value
foreach $dir (split(" ",$dirlist)) {
  $lister  = &tokenize(&submake($dir,"RESULTSER.varvalue"));
  $listcr  = &tokenize(&submake($dir,"RESULTSCR.varvalue"));
  $listnr  = &tokenize(&submake($dir,"RESULTSNR.varvalue"));
  $reslist{$dir} = &tokenize($lister." ".$listcr." ".$listnr);
  $tmp = &tokenize(&submake($dir,"SEPINC.varvalue"));
  if ("$tmp" ne "") { $sepinc = $tmp; }
  $tmp = &tokenize(&submake($dir,"RESDIR.varvalue"));
  if ("$tmp" ne "") { $resdir  = $dir."/".$tmp; }

  $aller = $aller." ".$lister;
  $allcr = $allcr." ".$listcr;
  $allnr = $allnr." ".$listnr;
}
$aller = &tokenize($aller);
$allcr = &tokenize($allcr);
$allnr = &tokenize($allnr);

`echo "$notice"                                                   > $makename`;
`echo '
# This makefile is generated by executing the "makemake" perl script
# in this directory. To generate a makefile for all chapter directories 
# in a book, you execute "Tour makemake" in the Adm directory.'  >> $makename`;
`echo ''			                                 >> $makename`;
`echo 'include \${SEPINC}/SEP.top'                               >> $makename`;
`echo 'RESDIR = '$resdir	                                 >> $makename`;
`echo ''			                                 >> $makename`;
`echo 'RESULTSER = '$aller		                         >> $makename`;
`echo 'RESULTSCR = '$allcr		                         >> $makename`;
`echo 'RESULTSNR = '$allnr		                         >> $makename`;
`echo ''			                                 >> $makename`;
`echo '$makename : ;'		                                 >> $makename`;
#`echo '  # always automatically recreate $makename'              >> $makename`;
#`echo 'REMAKEFLAG = junk.dontremake'                             >> $makename`;
#`echo '.PHONY : $makename'					 >> $makename`;
#`echo '$makename :'						 >> $makename`;
#`echo '\t\if [ ! -f \${REMAKEFLAG} ] ;\t\t\t\\'			 >> $makename`;
#`echo '\t  then makemake - ; \${TOUCH} \${REMAKEFLAG} ;\t\\'	 >> $makename`;
#`echo '\t  else rm \${REMAKEFLAG} ;\t\t\t\\'			 >> $makename`;
#`echo '\tfi'			                                 >> $makename`;
`echo ''			                                 >> $makename`;

#remake_file = junk.dontremake
#Makefile : FORCE_REMAKE
#        if [ ! -f ${remake_file} ] ; \
#        then makemake - ; touch ${remake_file} ; \
#        else rm ${remake_file} ; \
#        fi
#
#.PHONY : FORCE_REMAKE 
#FORCE_REMAKE : ; 


foreach $dir (split(" ",$dirlist)) {
foreach $tar (split(" ",$reslist{$dir})) {
  $cmd = $tar;
  $tar =~ s/(\S+)/$1\.%/g;
  $cmd =~ s/(\S+)/$1\.\$\*/g;

  if ("$tar" ne "") {
    `echo '$tar : '                                              >> $makename`;
    `echo '\t\@-cd $dir; \$(MAKE) $cmd;'                         >> $makename`;
    `echo ''			                                 >> $makename`;
  }
}}
`echo 'clean : texclean'	                                 >> $makename`;
foreach $dir (split(" ",$dirlist)) {
`echo '\t\@-cd $dir; \$(MAKE) clean;'                            >> $makename`;
}
`echo ''			                                 >> $makename`;
`echo 'include \${SEPINC}/SEP.bottom'                           >> $makename`;


  # change to directory $dir and do gmake $maketarget
sub submake{
  local($dir, $maketarget) = @_;
  return `cd $dir ; gmake $maketarget`;
}

  # change a string of words to one line with one space between each word
sub tokenize{
  local($str) = @_;
  $str =~ s/\s+/ /g;	# change strings of whitespace to " "
  $str =~ s/^\s+//g;    # change any initial whitespace to null
  $str =~ s/\s+$//g;    # change any final whitespace to null
  return $str;
}
