#!/usr/athena/bin/perl

$maxtype = 1;
print("--> ");
while(<STDIN>){
    chop;
    $this = $_;
    @words = split(" ", $_);
    foreach $w (@words){
	if(1){
	    foreach $kw (keys %kwords){
		next if $w eq $kw;
		$thisc = $this;
#	    print("Trying to replace $w with $kw\n");
		$thisc =~ s/$w/$kw/gi;
		if($ksent{$thisc}){
		    print("$kw and $w seem to be of the same type\n");
		    print("$w is know to be of types \"$types{$w}\"\n");
		    print("$kw is know to be of types \"$types{$kw}\"\n");
#		print("Induced from know sentance \"$thisc\" where $w has been replaced with $kw\n\n");
		    
		    # See if they already share a type
		    @wst = split(" ", $types{$w});
		    @kwst = split(" ", $types{$kw});
		    $shared = 0;
		    for $wt (@wst){
			for $kwt (@kwst){
			    if($wt eq $kwt){
				$shared = 1;
				print("These should be valid sentences...\n");
				&generate_sentences();
			    }
			}
		    }
		    $found =0; $unk=0;
		    @unk= ();
		    if(!$shared){
			foreach $nt (split(" ", $types{$kw})){
			    foreach $tw (split(" ", $typel{$nt})){
				$thisg = $this;
				$thisg=~ s/$w/$tw/g;
				if(!$ksent{$thisg}){
				    print ("T: $thisg\n");
				    push(@unk, $thisg);
				    $unk=1;
				}
			    }
			    if($unk){
				print("Are all these valid sentences? ");
				$ans = (<STDIN>);
				chop($ans);
			    }
			    else{
				$ans = "y";
			    }

			    if($ans =~/y/i){
				$found = 1;
				foreach $u (@unk){
				    $ksent{$u}=1;
				}
				$types{$w} .= "$nt ";
				$typel{$nt}.= "$w ";
			    }
			}
			if(!$found){
			    print("Making $w and $kw of type $maxtype\n");
			    $types{$w}.="$maxtype ";
			    $types{$kw}.="$maxtype ";
			    $typel{$maxtype} .= "$w $kw ";
			    $maxtype++;
			}
		    }
		}
	    }
	}
	$kwords{$w}=1;
	$ksent{$this}=1;
    }
    push(@ksent, $this);
    print("--> ");
}

sub generate_sentences {
    $thisg=$this;
    (@kwts) = split(" ", $types{$kw});
    foreach $kwt (@kwts){
	$thisg =~ s/$kw/$kwt/;
	print("Generating sentences based on the fact that $kw (type $kwt) is of the same type as words \"$typel{$kwt}\"\n");
	@wrds = split(" ", $typel{$kwt});
	foreach $r (@wrds){
	    $thisgc = $thisg;
	    $thisgc=~ s/$wt/$r/;
	    print "S: $thisgc\n";
	}
    }
}
