#!/usr/bin/perl

# Use Separately caluclated p(w|c) 
$head = $ARGV[0];
$parameter_file = $head.".parameter.txt";
$MeanSD_file = $head.".meansd.txt";
$testfile = $ARGV[1];
$class = 4;
@slots = ("AB","TI");
$min_word_count = 5;
$max_word_count = 40;
require "subroutin.pl";
########### read parameter 
open IN, "temp/$parameter_file";
while (<IN>){
	chomp;
	split(/\t/);
	if(/^PC\t/){
		@ps = @_[1..$class];
	}
	elsif(/^PWC:(\w+)/){
		$slot = $1;
	}
	else{
		for($i=0;$i<$class;$i++){
			$tmp = $i+1;
			$pwc[$i]->{$slot}->{$_[0]} = $_[$tmp];
			$wordset{$_[0]} = 1;
		}
	}
}
close IN;
######## SD mean file
open IN, "temp/$MeanSD_file";
while (<IN>){
	chomp;
	split(/\t/);
	$mean[$_[0]] = $_[1];
	$sd[$_[0]] = $_[2];
}
close IN;
############################
$c = 0;
open IN, "temp/$testfile";
open OUT, ">temp/$head.$testfile.score.txt";
while (<IN>){
	chomp;
	if(/^PMID\-\s+(\d+)/){
		$pmid = $1;
		$word_c = 0;
		@{$text{'AB'}} = ();
		@{$text{'TI'}} = ();
	}
	elsif(/^(AB|TI)\s+\-\s+(.+)/){
		$text = $2;
		$flag = $1;
	}
	elsif(/^[A-Z]+/){
		$flag = undef;
	}
	if($flag){ #elsifではない
		if(!$text){
			s/^\s+//;
			$text = $_;
		}
		@words = &TokenizeText($text);
		foreach $word (@words){
			$word = &WordTrim($word);
			unless($wordset{$word}){
				#print "$word\n";
				next;
			}
			if($word_c >= $max_word_count){
				next;
			}
			push(@{$text{$flag}},$word);
			$word_c++;
		}
		$text = "";
	}
	elsif(!$_ and $pmid){
		next if $word_c < $min_word_count;
		$c++;
		$output = "$c\t$pmid\t$word_c";
		#$output = "$c\t$pmid";
		@pdc = @ps;
		foreach $slot (@slots){
			$wc = 0;
			foreach $word (@{$text{$slot}}){
				$wc++;
				for($i=0;$i<$class;$i++){
					$pdc[$i] += $pwc[$i]->{$slot}->{$word};
				}
			}
			#$output .= "\t$wc";
		}
		$pd = undef;
		for($i=0;$i<$class;$i++){
			$pd = &AddLogVal($pd,$pdc[$i]);
			$output .= "\t$pdc[$i]";
		}
		$pd2 = ($pd-$mean[$word_c])/$sd[$word_c] if $mean[$word_c];
		$output .= "\t$pd\t$pd2\n";
		print OUT $output;
		$pmid = "";
	}
}
close IN;
close OUT;
