#!/usr/bin/perl

if(scalar(@ARGV)==0 || $ARGV[0] eq "--help" || $ARGV[0] eq "-h"){
	print "usage:\n";
	print "texcheck-en [inputfile] \n";
	print " to search the sentences following NOT capital alphabet.\n";
	exit;
}
$targetfilename=shift(@ARGV);
open (FH, "<$targetfilename");
	@allfile=<FH>;
close FH;
@allfile2=();

#convert codeset into EUC_________________________

#omit inside of equation, eqnarray, figure _______
$inequation=0;
$linevalid=1;
$i=0;
foreach $line (@allfile){
	$i=$i+1;
	$line="<$i> $line";
	if($line =~ /\\begin\{(equation|eqnarray|figure)\}/){
		$inequation=1; $linevalid=0;
	}
	elsif($line =~ /\\end\{(equation|eqnarray|figure)\}/){
		$inequation=0; $linevalid=0;
	}else{
		$linevalid=1;
	}
	if($inequation==0 && $linevalid==1){
		push(@allfile2,$line);
	}
}
&renewallfile();

#omit tex commands __________________
foreach $line (@allfile){
	$line =~ s/\%.*//g;
	$line =~ s/\\(caption|vspace|hspace|begin|end|label|section|subsection|subsubsection|description|itemize)\{.*?\}//g;
	$line =~ s/\$.*?\$/#inlineeq#/g;
	$line =~ s/\\(cite)\{(.*?)\}/#cite#/g;
	$line =~ s/\\(ref)\{eqn\:(.*?)\}/#refeqn#/g;
	$line =~ s/\\(ref)\{(.*?)\}/#ref#/g;
	$line =~ s/\\par\{\}/ /g;
	$line =~ s/\\(bf|item|hline|em|it|small|large)//g;
	$line =~ s/\{\}//g;
	$line =~ s/(\t|\s\s)/ /g;
	
	$line =~ s/(i\.e\.|ie)/ /g;
	$line =~ s/(e\.g\.|eg)/ /g;
	push(@allfile2,$line);
}
&renewallfile();

#extract illegular lines__________________
$lineprev=".";
foreach $line (@allfile){
	if($line =~ /\.\ (\ )*([a-z])/){
			$line =~ s/\.\ (\ )*([a-z])/. $1---$2---/g;
			push(@allfile2,"Sentence is not began from capital alphabet.\n$line\n");
	}
	if($lineprev =~/\.\s*$/ && $line =~ /^<\d*>[\s]*([a-z])/){
			$line =~ s/(^<\d*>[\s]*)([a-z])/$1---$2---/g;
			push(@allfile2,"Sentence is not began from capital alphabet.\n$line\n");
	}
	$lineprev=$line;
}

&renewallfile();
$errorflag=0;
#output __________________________________
foreach $line (@allfile){
	chomp $line;
	unless($line =~ /^<\d*>[\s]*$/){
		$errorflag++;
		print "$line\n";
	}
}
if($errorflag==0){
	print "no mistake is found.\n"
}else{
	print "$errorflag mistakes are found.\n"
}
#functions _______________________________
sub renewallfile{
	@allfile = ();
	foreach $line (@allfile2){
		push(@allfile,$line);
	}
	@allfile2 = ();
}

