#!/usr/bin/perl -w

use strict;

my %inc;
my @Inc = (".");

#################### Functions

sub Usage() {
  print STDERR "Usage:
	depend_ly [-I<dir>[:<dir>]...] ly-file(s)
Where
	<dir> is where to find included ly-files
";
  exit 0;
}

sub file_exist($) {
  my $file = shift;
  my $inc;

  foreach (@Inc) {
    if ($_ eq ".") {
      $inc = $file;
    } else {
      $inc = "$_/$file";
    }
    if (stat $inc ) {
      return $inc;
    }
  }
  return undef;
}

# find (recursively) included files
sub ly_inc($) {
  my $file = shift;

  my $fh;
  my %lst = (); # which files to recursively check

  # no file no dependancies
  open($fh, "<", $file) || return;
  while(<$fh>) {
    if (m/^%lys: /) {
      s/^%lys: //;
    } else {
      s/%.*$//; # get rid of comments
    }

    # this breaks for multiple \include per line
    m/\\include[ \t]+"([^\"]+)"/ || next;
    my $inc_file = $1;

    # consider only existing files as dependancies
    #$inc_file = file_exist $inc_file || next;

    # only add this file to %lst if we have not checked it for dependancies
    if (!$inc{$inc_file}) { $lst{$inc_file} = 1; }

    # add this as an dependancy
    $inc{$inc_file} = 1;
  }
  close($fh);

  foreach (keys(%lst)) {
    &ly_inc($_);
  }
}

sub hdr($) {
    my $stem = shift;

    my @hdr = ();

    for my $hdr (split(/\n/, `ls -1 *_header*.ily`)) {
	push @hdr, $hdr;
    }
    sort { length($a) <=> length($b) } @hdr;
}

#################### Main

if (@ARGV < 1) { Usage(); }

while ($ARGV[0] =~ m/^-I(.*)$/) {
  push @Inc, split(/:/, $1);
  shift @ARGV;
}

my $all = '';
my $file;
my $sep = "";
foreach $file (@ARGV) {
  # reset found dependancies for each new file to check
  %inc = ();
  &ly_inc($file);
  my $stem = $file;
  $stem =~ s/\.ly$//;
  my @lst = sort(keys(%inc));
  my @hdr = hdr($stem);
  unshift @lst, $file;
  my @hdr_full = grep { m/_header_full\.ily/ } @hdr;
  my @hdr_none = grep { m/_header_none\.ily/ } @hdr;

  print $sep; $sep = "\n";
  print "$stem.ps:\t"   , join(" ", @lst, $hdr_full[0]), "\n";
  if (@hdr_none) {
      print "$stem-1.eps:\t", join(" ", @lst, $hdr_none[0]), "\n";
  }

  $all .= " $stem.ps"
}

if ($all) {
  print "\nall:\t$all\n";
}
