#! /bin/perl

#   Kludge to emulate server-side file includes (*just* file
#   includes, none of the other fancy stuff).  This is
#   intended for when you want to assemble a collection
#   of documents from a set of components, but can't
#   afford the overhead of having the server do it on
#   the fly.

#   This doesn't handle recursive include, and ought to.
#   See /files/kelvin/webdev/evil_empires/psmerge.pl for
#   how it should be done.

#   Input is STDIN, output is STDOUT.

    $line = 0;
    while (<>) {
        $line++;
        chop;
        $sub = 0;
        $right = $_;
        while ($right =~ s/<!--#include\s+(file="[^"]+".*)-->//) {
            $sub++;
            $left = $`;
            $f = $1;
            $right = $';
            if ($left !~ m/^\s*$/) {
                print("$left\n");
            }
            while ($f =~ s/file="([^"]+)"\s*//) {
                $fn = $1;
                if (open(IF, "<$fn")) {
                    while (<IF>) {
		    	next if m/<extract>/;
                        print;
                    }
                    close(IF);
                } else {
                    print(STDERR  "Error on input line $line: cannot open $fn, $!\n");
                }
            }
        }
	
        while ($right =~ s/<!--#excerpt\s+(file="[^"]+".*)-->//) {
            $sub++;
            $left = $`;
            $f = $1;
            $right = $';
            if ($left !~ m/^\s*$/) {
                print("$left\n");
            }
            while ($f =~ s/file="([^"]+)"\s*//) {
                $fn = $1;
                if (open(IF, "<$fn")) {
                    while (<IF>) {
		    	next if m/<img\s/;
		    	s/<h3[^>]*>/<li>/;
			s:</?extract>::g;
			$el = s:</h3>:</li>:;
                        print;
			last if $el;
                    }
                    close(IF);
                } else {
                    print(STDERR  "Error on input line $line: cannot open $fn, $!\n");
                }
            }
        }
	
	
        if ($sub) {
            if ($right !~ m/^\s*$/) {
                print("$right\n");
            }
        } else {
            print("$right\n");
        }
    }
