#!/usr/bin/perl
use strict;

#
# perform just the #include feature of the cpreprocessor
# this is handy for building self-contained adobe extendscript
# scripts for release. Its nice when each script is self-contained.
# dvb07
#

sub getPath($$)
{
    my ($ownerFile,$includeFile) = (@_);

    # starts with slash = absolute, keep as is.
    if($includeFile =~ /^\/.*$/)
    {
        return $includeFile;
    }

    if($ownerFile =~ /^(.*\/)[^\/]*$/)
    {
        my $ownerDir = $1;
        my $result = $ownerDir . $includeFile;
        return $result;
    }
}

sub printComment($)
{
    my ($comment) = (@_);
    return "/* $comment */\n";
}
sub printComment1($)
{
    my ($comment) = (@_);
    return "// $comment\n";
}

sub preprocess1File($)
{
    my ($srcPath) = (@_);
    my $result = "";

    open SRC,$srcPath;
    my $contents;
    read(SRC,$contents,10000000) or die "could not read $srcPath";

    $contents =~ s/\r\n/\n/gm;
    $contents =~ s/\r/\n/gm;
    my @lines = split(/[\n]/m,$contents);
    foreach my $line (@lines)
    {
        if($line =~ /^#include +['"](.*)['"]$/)
        {
            my $includeFile = $1;
            my $includeFileAbs = getPath($srcPath,$includeFile);
            $result .= printComment1("-----------------------------------------");
            $result .= printComment1($line);
            $result .= printComment1("-----------------------------------------");
            $result .= preprocess1File($includeFileAbs);
            $result .= printComment1("thus ends $includeFile");
            $result .= printComment1("-----------------------------------------");
        }
        else
        {
            $result .= $line . "\n";
        }
    }
    return $result;
}


sub preprocess($)
{
    my ($src) = (@_);
    my $date = `date`;
    chomp($date);
    my $header = <<EOP
File: $src
Date: $date
Author: David Van Brink
This script is part of the omino adobe script suite.
The latest version can be found at http://omino.com/pixelblog/.

I write these because I like to. Please enjoy as you see fit.

Questions to poly\@omino.com, subject line should start with
"plugins" so my spam filter lets it in.

This file has been preprocessed to be
standalone.  I develop them against some
reusable libraries -- such as for dialog
layout -- but for distribution it's nicer to
have just one file. dvb 2007.
EOP
;
    my $result = printComment($header);
    $result .= preprocess1File($src);

    return $result;
}

1;
# the end
