#!/usr/bin/env perl
# A script to make running STD.pmc easier,
# by providing it input, and isolating it's Match yaml output.
use strict;
use warnings;

sub print_usage_and_exit {
    print STDERR <<"END"; exit(2);
$0 [-fo] GRAMMAR_RULE [ INPUT_FILE | -e INPUT ]

Examples:
  $0 noun -e 42
END
}

my $fo = '';
$fo = shift if $ARGV[0] eq '-fo';

sub main {
    print_usage_and_exit if @ARGV < 2 || $ARGV[0] eq '--help';
    my $rule = shift(@ARGV);
    print_usage_and_exit if $rule !~ /^\w+$/;
    my $input;
    if($ARGV[0] eq '-e') {
	shift(@ARGV);
	print_usage_and_exit if not @ARGV;
	$input = shift(@ARGV);
	#$input = 'qq{'.quotemeta($input).'}';
    }
    else {
	my $fn = shift(@ARGV);
	print_usage_and_exit if !-f $fn;
	$input = "`cat $fn`";
    }
    if(-e 'STD.pm' and -e 'gimme5') { # We're in the right place.
	# pretend we're 'make'
	if(!-e 'STD.pmc' or
		-M 'STD.pmc' > -M 'STD.pm' or
		-M 'STD.pmc' > -M 'gimme5') {
	    system("$^X gimme5 $fo STD.pm >STD.pmc");
	    system("rm -rf lex");
	}
    }
    #my $cmd = qq/perl -w -I . -MSTD5 -e 'print STD::Dump(STD->new(orig=>$input)->${rule}(["$rule"]));'/;
    #warn "# ",$cmd,"\n";
    #system "$cmd 2>try5.err";
    unshift(@INC,'.');
    require "STD.pmc";
    my $err = "try5.err";
    my $perl = STD->new($input);
    if(!$perl->can($rule)) { die "\nERROR: Unknown rule: $rule\n"; }
    open(STDERR,">$err") or die;
    my $result = eval { $perl->${rule}(); };
    if($result) { 
      print $result->dump();
#      print STD::Dump($result);
    } else {
      print "Parse failed.  See $err.\n";
    }
}
main;

__END__
