#!/usr/bin/perl -CDS

#
# Live code finder for MetaPost files
# Copyright (C) 2011, 2012  Matthew Skala
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# As a special exception, if you create a document which uses this font, and
# embed this font or unaltered portions of this font into the document, this
# font does not by itself cause the resulting document to be covered by the
# GNU General Public License. This exception does not however invalidate any
# other reasons why the document might be covered by the GNU General Public
# License. If you modify this font, you may extend this exception to your
# version of the font, but you are not obligated to do so. If you do not
# wish to do so, delete this exception statement from your version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Matthew Skala
# http://ansuz.sooke.bc.ca/
# mskala@ansuz.sooke.bc.ca
#

$maincode='';

$find_unused=0;
if ($ARGV[0] eq '-d') {
  $find_unused=1;
  shift;
}

@fns=@ARGV;
$inmac='';
while (@fns) {
  $_=shift @fns;
  if (m!^(.*)/([^/]+)$!) {
    $prefix=$1;
  } else {
    $prefix='.';
  }
  open(MP,$_);
  while (<MP>) {
    next if $_ eq "\n";
    if (/^(var)?def\s+([A-Za-z0-9_.]+)\s*(\(|=| text )/) {
      $macdef{$2}.=$_;
      $inmac=$2 unless /enddef/;
    } elsif (($inmac ne '') && /^enddef/) {
      $macdef{$inmac}.=$_;
      $inmac='';
    } elsif (/^input\s+(.*);/) {
      push @fns,"$prefix/$1";
    } elsif (/^include_late\s*\("(.*)"\);/) {
      push @fns,"$prefix/$1";
    } elsif (/^\%/) {
      # skip comments
    } elsif ($inmac ne '') {
      $macdef{$inmac}.=$_;
    } else {
      $maincode.=$_;
      if (/^(.*)code="(.*)/) {
        $maincode.="% $1code=\"hangul.$2\n";
      }
    }
  }
  close(MP);
  print "FFFOOOOOO! $inmac\n" if $inmac ne '';
}

$towrite='';
%seen=();
while ($maincode ne '') {
  $newdefs='';
  foreach (sort keys %macdef) {
    if ((!$seen{$_}) && (index($maincode,$_)>=0)) {
      $newdefs.=$macdef{$_};
      $seen{$_}=1;
    }
  }
  $towrite=$maincode.$towrite;
  $maincode=$newdefs;
}

if ($find_unused) {
  foreach (sort keys %macdef) {
    print "$_\n" if !$seen{$_};
  }
} else {
  print $towrite;
}
