#!/usr/local/bin/perl
# Html Include Processor:
#
# search for tag <include src=file ...>
# and replace it by the content of "file"
#
# Arnaud Le Hors - lehors@w3.org
# $Id: hipp,v 1.5 2006-10-09 18:55:52 ihickson Exp $

# init search path
$paths[0] = ".";
# parse include flags and augment search path
while ($_ = $ARGV[0], /^-I(.*)/) {
    $paths[@paths] = $1;
    shift;
}

$PROGNAME = substr($0, rindex($0, "/") + 1);

if ($_ = $ARGV[0], /^-h|^-\?/) {
    die "Usage: $PROGNAME [-Idir1 -Idir2 ...] [src] [output]\n";
}
if ($ARGV[0]) {
    $file = $ARGV[0];
    shift;
} else {
    $file = "-";
}
if ($ARGV[0]) {
    $output = $ARGV[0];
} else {
    $output = "-";
}

# regexp
$wd = "[^ \t\n>]+";		# word
$qwd = "\"([^\"]*)\"";		# quoted word
$inctag = "<!--[ \t]*#include[ \t]*src=(?:$qwd|($wd)).*?-->([ \t]*\n)?";

# open file using the given search path
sub openfile {
    if ($_[0] eq "-") {
	open(INPUT, "-");
	return INPUT;
    }
    foreach $p (@paths) {
	$path = "$p/$_[0]";
	if (open(INPUT, $path)) {
	    return INPUT;
	}
    }
    return ();
}

# recursive sub routine extending include tags
# args: file exitflag
sub processf {
    # copy file in memory
    if (!openfile($_[0])) {
	print STDERR "$PROGNAME Error: Cannot open file: $_[0]\n";
	if ($_[1] == 1) {
	    exit 1;
	} else {
	    return "";
	}
    }
    my $buf = <INPUT>;
    close(INPUT);
    # then substitute include tags by the content of file they reference
    # only $1 or $2 will actually be non null
    $buf =~ s/$inctag/processf("$1$2",0)/sgieo;
    return $buf;
}

undef $/;			# read files as single blocks
$buf = processf($file,1);
open(OUTPUT, "> $output");
print OUTPUT $buf;
close(OUTPUT);
