#!/usr/bin/perl -w
use strict;

#html_include.pl
#version 1.0
#Copyright 2004 John C. Vernaleo
#Unfortunately, I am not comfortable putting unobscured email addresses
#on the web, but these shouldn't be too hard to figure out.
#
#		(my_first_name)@netpurgatory.com
#				or
#		(my_last_name)@astro.umd.edu
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#    See readme_html_include.txt for more information and a copy of the GPL

#Get file to be included
my $include="web.inc";
my $startstring="<!--BEGININSERT-->";
my $endstring="<!--ENDINSERT-->";

open INC, "< $include" or die("cannot open $include: $!");
my @inc=<INC>;
close INC;
chomp(@inc);

#Get lists of files to include header in
my @html=glob "*.html";

#one file at a time, replace old included part with new one.
my $file;
my $filebackup;
my @data;
my @datanew;
my $i;
my $i_start;
my $i_stop;
foreach $file (@html)
{
    $filebackup=$file."~";
    open DATA, "< $file" or die("cannot open $file: $!");
    @data=<DATA>;
    close DATA;
    chomp(@data);
    $i=0;
    $i_start=0;
    $i_stop=0;
    foreach(@data)
    {
	if($data[$i]=~$startstring)
	{
	    $i_start=$i;
	}
	if($data[$i]=~$endstring)
	{
	    $i_stop=$i;
	}
	$i++;

    }
    if($i_stop!=0)
    {
	rename $file, $filebackup;
	open PAGE, ">$file" or die("Cannot create file: $!");
	select PAGE;
	for($i=0;$i<=$i_start;$i++)
	{
	    print $data[$i],"\n";
	}

	for($i=0;$i<=$#inc;$i++)
	{
	    print $inc[$i],"\n";
	}
	
	for($i=$i_stop;$i<=$#data;$i++)
	{
	    print $data[$i],"\n";
	}

	close PAGE;
	select STDOUT;
	print "updated $file \n";
    }
}
