#!/usr/bin/perl -w

use strict;

my $outputFileName = "code.tex";
my @ignoreFilePatterns=(".*[/]?package.lisp",".*/external/.*",".*-tables\.lisp");
my $codePath = "code/";
my @systems = ("wvu-lib","nova","nova-web","mymodel","xomo");
my $licenceLineLength = 17;

open OFILE,">",$outputFileName or die $!;
print OFILE "\\lstset{language=Lisp,tabsize=2,frame=single,basicstyle=\\tiny,lineskip=3pt}\n";

sub checkFilePath {
    my ($filePath) = @_;
    for my $ignoreFilePattern (@ignoreFilePatterns) {
	if($filePath=~ m/($ignoreFilePattern)/) {
	    return 0;
	}
    }
    return 1;
}

sub printListingCommand {
    my ($filePath) = @_;
    my $title = $filePath;
    $title =~ s/($codePath)(.*)/$2/;
    print OFILE "\\lstinputlisting[title=$title,firstline=$licenceLineLength]{$filePath}\n";
}

sub printSystemHeading {
   my($system) = @_;
   print OFILE "\\section{$system}\\label{src-$system}\n";
}

sub processDirectory {
    my($path) = @_;
    my @directories = ();
    for my $file (<$path/*>) {
	if (-d $file) {
	    push(@directories,$file);
	} else {
	    if (checkFilePath($file)) {
		printListingCommand($file);
	    }
	}
    }
    for my $dir (@directories) {
	processDirectory($dir)
    }

}

sub printSystemFooter {
   my($system) = @_;
   print OFILE "\\newpage\n";
}

for my $system (@systems) {
    printSystemHeading($system);
    processDirectory($codePath . $system);
    printSystemFooter($system);
}

close OFILE;
