#!/usr/bin/env perl

use FindBin;
BEGIN { unshift @INC, $FindBin::Bin if -s "$FindBin::Bin/STD.pmc"; }

use strict;
use warnings;

use STD;
use utf8;
use feature 'say';

#let us play nice with others
use POSIX qw(nice); nice 19;

my @loc;

sub MAIN {
    my $output = 'ast';
    my $file = shift;

    my $txt = Encode::decode('utf8', `cat $file`);
    $loc[length($txt) - 1] = [];

    STD->parsefile($file, actions => 'Actions');

    my ($last_tree,$buffer) = ("","");
    for my $i (0 .. @loc-1) {
        say("Undefined $i"),next unless defined $loc[$i];
        my $c = substr($txt,$i,1);
        my $tree = "";
        for my $action_ref (@{$loc[$i]}) {
            $tree .= ${$action_ref} . " ";
        }
        if($tree ne $last_tree) {
            say "\n'$buffer'\n$last_tree" if $buffer ne '';
            $buffer = $c;
        } else {
            $buffer .= $c;
        }
        $last_tree = $tree;
    }
}

###################################################################

{ package Actions;

    our $AUTOLOAD;
    my %actions = ();
    sub AUTOLOAD {
        my $self = shift;
        my $C = shift;
        my $F = $C->{_from};
        my $P = $C->{_pos};
        $AUTOLOAD =~ s/^Actions:://;
        $loc[$P] = [] if $loc[$P];	# in case we backtracked to here
        my $action = $AUTOLOAD;
        my $action_ref = $actions{$action};
        if(!$action_ref) {
            $actions{$action} = $action_ref = \$action;
        }
        for ($F..$P-1) {
            unshift @{$loc[$_]}, $action_ref;
        }
    }

    sub stdstopper { }
    sub terminator { }
    sub unitstopper { }
    sub comp_unit { }
}

MAIN(@ARGV);

# vim: ts=8 sw=4
