#! /usr/bin/perl

package Parser;
use SentenceParse;
use PhraseStruct;

sub new {
    my ($class) = @_;
    my $self = {};
    $self->{GRAMMAR} = {};
    $self->{LEXICON} = {};
    bless $self=>$class;
    return $self;
}

sub load_grammar(){
    my ($self,$grammar_file) = @_;
    $self->{GRAMMAR} = {};
    my $constituents;
    open(GRAMMAR, "$grammar_file") or die"can't find grammar file";
    push(@{$self->{GRAMMAR}{'#'}}, new PhraseStruct('#',['S']));
  RULE: while(<GRAMMAR>){
      my @rule = split(':', $_);
      next RULE if($rule[0] =~ s/^#//);
		   $rule[0] =~ s/[\s]//g;
		   $constituents = [];
		   push( @{$constituents},split(' ',$rule[1]));
		   #print "@constituents\n";
		   push(@{$self->{GRAMMAR}{$rule[0]}}, new PhraseStruct($rule[0],$constituents ));
		   
  }
  1;
}

sub add_to_grammar(){
    my ($self, $new_rule) = @_;
    my @rule = split(':',$new_rule);
    $rule[0] =~ s/[\s]//g;
    my $constituents = [];
    push( @{$constituents},split(' ',$rule[1]));
    #print "@constituents\n";
    push(@{$self->{GRAMMAR}{$rule[0]}}, new PhraseStruct($rule[0],$constituents ));
}


sub load_lexicon(){
    my ($self,$lexicon_file) = @_;
    my $constituents;
    open(LEXICON, "$lexicon_file");

    while(<LEXICON>){
	my @rule = split(':', $_);
	$rule[0] =~ s/[\s]//g;
	$constituents = $self->{LEXICON}{$rule[0]}{CONSTITUENTS};
	push(@{$constituents},split(' ',($rule[1])));
	$self->{LEXICON}{$rule[0]} = new PhraseStruct($rule[0],$constituents );
    }
    1;
}

sub add_to_lexicon(){
    my ($self,$new_item) = @_;
    my @rule = split(':', $new_item);
    $rule[0] =~ s/[\s]//g;
    my $constituents = $self->{LEXICON}{$rule[0]}{CONSTITUENTS};
    push(@{$constituents},split(' ',($rule[1])));
    $self->{LEXICON}{$rule[0]} = new PhraseStruct($rule[0],$constituents );
}

sub get_new_parse(){
    my($self,$sentence) = @_;
    chomp($sentence);
    $sentence =~ s/[.!?]*$//;
#    return new SentenceParse([split(' ',lc($sentence))],$self);
    return new SentenceParse([split(' ',$sentence)],$self);
}
sub print_grammar(){
    my ($self) = @_;
    print "GRAMMAR:\n";
    foreach my $phrase (sort keys %{$self->{GRAMMAR}}){
	foreach my $rule (@{$self->{GRAMMAR}{$phrase}}){
	    print ($rule->{PRODUCT},"\t",join(' ',@{$rule->{CONSTITUENTS}}),"\n");
	    
	}
    }
}

sub print_lexicon(){
    my ($self) = @_;
    print "LEXICON:\n";
    foreach my $thing (sort keys %{$self->{LEXICON}}){
	print ($self->{LEXICON}{$thing}->{PRODUCT},"\t",join(' ',@{$self->{LEXICON}{$thing}->{CONSTITUENTS}}),"\n");
    }
}


1;

