#!/usr/bin/perl -w
# syntax httmplate.pl tmplfile skelfile createfile
# Example:
# > httmplate.pl tmplfile links.tmpl links.shtml
# creates links.shtml out of links.tmpl

$tmplfile = $ARGV[0];
open(TMPL,"< $tmplfile") || die("can't open templatefile `$tmplfile'");

$datafile = $ARGV[1];
open(DATA,"< $datafile") || die("can't open datafile `$datafile'");

$outfile =  $ARGV[2];
open(OUT,"> $outfile") || die("can't open new file `$outfile'");

#read datafile
my $n = 0;
while (<DATA>) {
  push @datalines, $_;
  #search for <!-- tmpl: <div id="insertme"> -->
  if (/<\!-- tmpl: (.*) -->/) {
    $insertpoint[$n] = $1;
    $n++;
  }
}

#$n holds # of insertpoint
#$j is position in datafile
#$h counts from one insertionpoint to the next
#$insertioncounts is the number of succesfull insertions
my $insertioncounts = 0;
while (<TMPL>) {
  print OUT $_;
  for my $n (0..$#insertpoint) {
    if (/$insertpoint[$n]/) {
      $insertioncounts++;
      my $j = 0;
      foreach (@datalines) {
	if (/<\!-- tmpl: $insertpoint[$n] -->/) {
	  my $h = $j+1;
	  while (($h <= $#datalines) && ($datalines[$h] !~ /<\!-- tmpl: (.*) -->/)) {
	    print OUT $datalines[$h];
	    $h++;
	  }
	}
	$j++;
      }
    }
  }
}

if ($insertioncounts != $#insertpoint+1) {
  print "could not insert all sections\n";
  exit 1;
}

