#!/usr/bin/perl -w
# pcd2html module pcd2html_create_makefile
# Copyright Andreas Tille <tille@debian.org>
#
# This module creates Makefiles in each subdirectory from a rules file
use pcd2html_uti;
use strict ;

my ( @deps,    ## dependencies
     $prevdep, ## previous dependency line
     $dep,     ## current dependency line
     $nextdep, ## next dependency line
     $i        ## counter for valid lines
   );

OpenRules(); # We do not need the %keys dictionary which is returned by OpenRules in this module

open(MAKEFILE, ">Makefile" ) || die "Unable to open Makefile\n" ;
select (MAKEFILE) ;

$_ = `pwd` ;
chomp ;
s/.*\/([^\/]*)$/$1/;
my $dir = $_ ;

print "# Makefile in $dir created by pcd2html_create_makefile\n" ;

print "SOURCES= " ;

@deps = () ;
$i    = 0 ;

my $cur ;

while ( <RULES> ) {
  unless ( /\s*#/ ) {
    chomp ;
    if ( /(\w*):(\w*)/ ) {
      $cur = "$1_$2" ;
      print "\\\n\t$cur " ;
      system("touch $cur.img");
    }
    if ( $i > 0 ) {
      # other than first valid entry

      @deps = (@deps, $dep . "$cur.jpg" );
      $dep = "$cur.html: $nextdep.jpg " . "$cur.jpg " ;
    } else {
      $dep = "$cur.html: $cur.jpg " ;
    }
    $nextdep = $cur ;
    $i++ ;
  }
}

@deps = (@deps, $dep );

close RULES ;


print "\n" ;
print ".SUFFIXES: .img .jpg .html\n\n" ;

print ".jpg.html:\n" ;
print "	\@${datadir}/pcd2html_create_html `basename \$< jpg`img\n\n" ;

print ".img.jpg:\n" ;
print "	\@${datadir}/pcd2html_create_jpg \$<\n\n" ;

print "all: \$(SOURCES:%=%.html) Makefile\n\n" ;

foreach $dep (@deps) {
  print "$dep\n" ;
}

print "\nMakefile: rules\n" ;
print "	\@touch *.img\n" ;
print "	\@rm -rf *~\n" ;
print "	\@${datadir}/pcd2html_create_makefile\n\n" ;

print "\ncleanhtml:\n" ;
print "	\@rm -rf *.html *~\n\n" ;

print "clean:\n" ;
print "	\@rm -rf *.img *~\n" ;
print "	\@make cleanhtml\n\n" ;

print "distclean:\n" ;
print "	\@make clean\n" ;
print "	\@rm -rf *.img *.jpg Makefile\n" ;

select (STDOUT) ;
close(MAKEFILE) ;


