#! /usr/bin/perl

use strict;
use warnings;

my @INCPATH;
my @FILES;

# expandfile() {
# 	  for i in $INCPATH
# 	  do
# 		  if [ -f $i/$1 ] 
# 		  then
# 			  echo $i/$1
# 			  exit 0
# 		  fi
# 	  done
# 	  echo "Error: Include file \`$1' does not exist" > /dev/stderr
# #	echo "Fehler: Includedatei $1 existiert nicht" > /dev/stderr
# 	  exit 1
# }
# 

sub expandfile
{
    my $f = shift;
    my %var = @_;
    my $p;
    my $pivot;

    if ($f =~ m,\$\((.*)\),) {
	$pivot = $1;
	$f =~ s,\$\($1\),$var{$pivot},;
    }

    return "$f" if (-f "$f");

    foreach $p (@INCPATH) {
	return "$p/$f" if (-f "$p/$f");
    }

    printf STDERR "Error: Include file `$f' does not exist.\n"
}

sub findincludes
{
    my $f = shift;
    my %var = @_;
    my @lines = ();
    my ($l, $foo, $p);
    my ($v, $e, $pivot);

    open (F, $f) || printf STDERR "Error: Can't open $f, $!\n";
    while (<F>) {
	push (@lines, $_) if (m,^#(include|read)\s+[<"][^><"]*[>"].*,);
    }
    close (F);

    foreach $l (@lines) {
	if ($l =~ m,^#(include|read)\s+[<"]([^>"]*)[><"]\s+(.*),) {
	    $p = $2;
	    $foo = expandfile ($p, %var);
	    if ($3 =~ m,(\S+)="([^"]*)",) {
		$v=$1; $e=$2;
		if ($e =~ m,\$\((.*)\),) {
		    $pivot = $1;
		    $e =~ s,\$\($1\),$var{$pivot},;
		}
		$var{$v} = $e;
	    }
	} elsif ($l =~ m,^#(include|read)\s+[<"]([^><"]*)[>"].*,) {
	    $p = $2;
	    $foo = expandfile ($p, %var);
	}
	printf " \\\n\t%s", $foo;
	findincludes ($foo, %var);
    }
}

# Argument parsing
#
while (my $foo = shift (@ARGV)) {
    if ($foo =~ m,-I(.*),) {
	push (@INCPATH, $1);
    } else {
	push (@FILES, $foo);
    }
}

my %var;
foreach my $f (@FILES) {
    my $foo = $f;
    $foo =~ s/\.wml$/\.php/;
    printf "%s: %s", $foo, $f;
    findincludes ($f, %var);
    print "\n";
}
