#!/usr/bin/perl

# in my other programs i use $var{key}=$value. in this one i use 
# the array form of the same thing @{key}=$value. this allows me to have
# many variables with the same name, they are referenced @{key}[$i]


$ENV{ROOTSYS}="/hires_soft/dst2k/root"; ### this stuff allows you to use
$ENV{ROOTDIR}="/hires_soft/dst2k/root"; ### root "programs" with cgi
$ENV{LD_LIBRARY_PATH}="$ENV{LD_LIBRARY_PATH}:$ENV{ROOTSYS}/lib/";



@datetime=localtime(time);
$monimplant='';
$dayimplant='';
if($datetime[4]+1 < 10)
{
    $monimplant='0';
}
if($datetime[3]<10)
{
    $dayimplant='0';
}
$today=join('', ($datetime[5]+1900),$monimplant,($datetime[4]+1),$dayimplant,($datetime[3]));

#get the query string


if($ENV{REQUEST_METHOD} eq 'GET')
{
    $query=$ENV{QUERY_STRING};
}
if($ENV{REQUEST_METHOD} eq 'POST')
{
    read(STDIN,$query,$ENV{CONTENT_LENGTH});
}
$query=~s/\+/ /g;
$query=~ s/%(..)/chr(hex($1))/ge ;
#decode query string into variable list
##### set defalt values #####


##### get query #########
if (defined($query))
{
    @list=split('&', $query);
    foreach (@list)
    {
	my ($key,$value) = split /=/;
	push @{$key},$value;
    }
}
$thisyear=substr $today,0,4;



#@{group}[0] = "groups";
#@{moregroup}[0] = "Institute";
#@{moremoregroup}[0] = "all";
#@{begin}[0] = "20030903";
#@{end}[0] = "20040903";
#@{year}[0] = "all";
#@{period}[0] = "Plot checked years";

########################
## get prsnl info ######
########################
$done=0;
open(SUSP, "<../private/workfiles/emplist");
foreach(<SUSP>)
{
    chomp;
    if($_=~m/Other/){$done=1;}
    if(!$done)
    {
	if(!($_=~m/Reti/)and!($_=~m/Location/)and!($_=~m/Other/))
	{
	    $location="";
	    ($intl,$name,$career,$citizenship,$location,$comm)=split('#',$_);
	    if($location ne "")
	    {
		if($location =~m/Mexico/){$location="N.Mexico";}
		if($location=~m/Montana/){$location="Montana";}
                # wfh fix
                if($location =~ m/\?/) {$location="X";}
		$intl=uc $intl;
                # wfh fix
                if($career =~ m/\?/) {$career="X";}
		$car{$intl}=$career;
		$cit{$intl}=$citizenship;
		$loc{$intl}=$location;
		$num{$intl}=0;
		$in{$intl}=0;
	    }
	}
    }
}
foreach(keys %loc)
{
    if(($_ ne "")and($loc{$_}ne ""))
    {
	$location{$loc{$_}}=0;
    }
}
foreach(keys %car)
{
    $career{$car{$_}}=0;
}
$everybody=join(',',keys %loc);
$locs=join(',',keys %location);
$cars=join(',',keys %career);

print("Content-type: text/html\n\n");

print "<HTML><HEAD><TITLE>HiRes schedule editing site</TITLE></HEAD>\n";
print "<BODY bgcolor=ffffff><TABLE bgcolor=ffaaff>\n";

################ Help Bar #########################
open(HELP, "<helpbar");
foreach(<HELP>)
{
    chomp;
    if(!($_=~m/stat.pl/)or !($_=~m/href/))
    { 
	print"$_";
    }
    elsif($_ =~m/stat.pl/)
    {
	($first,$second)=split('>',$_);
	print"$first ><FONT color=ff0000>$second ></FONT>\n";
    }
}
close(HELP);
print '</FROM>';
print"</FORM></TABLE><TABLE>\n";
###########################################################

#################################  STEP 1!
if(!defined(@{group}[0]))
{
    print"<h3>To make a work statistics plot, go through 4 info steps</h3><BR>\n";
    
    
    print"<H1> STEP 1<\H1>";
    print"<FORM methd=GET ACTION=stat.pl>";
    print"I want to make a plot of <INPUT type=submit name=group value=groups><INPUT type=submit name=group value=individuals>\n";
}
###########################################   STEP 2!!
elsif(!defined(@{moregroup}[0]))
{
    print"<FORM methd=GET ACTION=stat.pl>";
    print"<INPUT type=hidden name=group value=@{group}>";
    print"<h1>STEP 2</h1>\n";
    if(@{group}[0] eq "groups")
    {
	
	print"<h2>I want to plot groups of";
	print"<INPUT type=submit name=moregroup value=Institute>(s)<INPUT type=submit name=moregroup value=Career>(s)";
	
	
    }
    if(@{group}[0] eq "individuals")
    {
	print"<h2>I want to make plots of individuals that are from certain\n";
	print"<INPUT type=submit name=moregroup value=Institute>(s)<INPUT type=submit name=moregroup value=Career>(s).<BR>\n";
	print"</FORM><FORM methd=GET ACTION=stat.pl>";
	print"<INPUT type=hidden name=group value=@{group}>";
	print"<INPUT type=hidden name=moremoregroup value=all>";
	print"I want to plot <INPUT type=submit name=moregroup value=all> hires individuals\n";
    }
    print"</FORM>";
    print"<FORM method =GET ACTION = stat.pl>";
    print'<h3> Back to <INPUT type=submit value="STEP 1">';
    print"</FORM>";
    
}

#################################### STEP 3!!!
elsif(!defined(@{moremoregroup}[0]))
{
    print"<FORM methd=GET ACTION=stat.pl>";
    print"<INPUT type=hidden name=group value=@{group}>";
    print"<INPUT type=hidden name=moregroup value=@{moregroup}>";
    print"<h1>STEP 3</h1>\n";
    
    if(@{moregroup}[0] eq "Institute")
    {
	print"Check all institutes you want in the plot<BR>\n";
	if(@{group}[0] eq "individuals")
	{
	    print"(individuals will have their own colum if they belong to the selected institutes)";
	}
	if(@{group} eq "groups")
	{
	    print"(each selected instituted will have its own bar in the histogram)";
	}
	
	print"<INPUT type=checkbox name=moremoregroup value=all>All<BR>";
	foreach(keys %location)
	{
	    print"<INPUT type=checkbox name=moremoregroup value=$_>$_<BR>";
	    
	}
	
    }
    if(@{moregroup}[0] eq "Career")
    {
	print"Check all Careers you want to plot\n";
	if(@{group}[0] eq "groups")
	{
	    print"(each checked career will apear as a columb in the plot)<BR>";
	}
	if(@{group}[0] eq "individuals")
	{
	    print"(individuals will have their own columb only if they belong to the selected career(s))<BR>";
	}
	print"<INPUT type=checkbox name=moremoregroup value=all>All<BR>";
	foreach(keys %career)
	{
	    print"<INPUT type=checkbox name=moremoregroup value=$_>$_<BR>";
	    
	}
	
    }
    print"<INPUT type=submit value=NEXT>";
    print"</FORM>";
    print"<FORM method =GET ACTION = stat.pl>";
    print'<h3> Back to <INPUT type=submit value="STEP 2">';
    print"<INPUT type=hidden name=group value=@{group}>";
    print"</FORM>";
}

###################################### STEP 4!!!!
elsif(!defined(@{period}))
{
    
    print"<FORM methd=GET ACTION=stat.pl>";
    print"<INPUT type=hidden name=group value=@{group}>";
    print"<INPUT type=hidden name=moregroup value=@{moregroup}>";
    foreach(@{moremoregroup})
    {
	print"<INPUT type=hidden name=moremoregroup value=$_>";
	
    }
    print"<h1>STEP 4</h1>\n";
    print"</TABLE><TABLE border=2><TR><TD>";
    print'<h2>I want to plot work schedules from<INPUT type=submit name=period value="This Year"><INPUT type=submit name=period value="Last Year"></TD></TR><TR><TD><h2>';
    $oneyearago=$today - 10000;
    print"I want to plot from begin date:<INPUT type=text size=8 maxlength=8 name=begin value=$oneyearago maxlength=8> to end date:<INPUT type=text maxlength=8 size=8  name=end value=$today><INPUT type=submit name=period value=GO>(dates are in the form YYYYMMDD)</TD></TR><TR><TD><h2>\n";
    @rns=split("\n",`ls ../private/runs/` );
    foreach(@rns)
    {
	$yr=substr $_, 0,4;
	$years{$yr}=0;
    }
    print"<INPUT type=checkbox name=year value=all>All Years<BR>";
    foreach(sort keys %years)
    {
	if($_ <= $thisyear)
	{
	    print"<INPUT type=checkbox name=year value=$_>$_<BR>";
	}
    }
    print'<INPUT type=submit name=period value="Plot checked years"></TD></TR></TABLE>';
    print"</FORM>";
    print"<TABLE><FORM method =GET ACTION = stat.pl>";
    print'<h3> Back to <INPUT type=submit value="STEP 3">';
    print"<INPUT type=hidden name=group value=@{group}>";
    print"<INPUT type=hidden name=moregroup value=@{moregroup}>";
    print"</FORM></TABLE>";
    
}

else    ##########################################
{
    print"<TABLE>";
    @rns=split("\n",`ls ../private/runs/` );
    
    foreach(@rns)
    {

        $yr=substr $_, 0,4;
        $years{$yr}=0;
	$start=substr $_,0,8;
	$end=substr $_,9,16;
	if($start<=$today)
	{
	    $pastrun{$start}=$end;
	}
    }
    foreach(sort keys %years)
    {
        if($_ <= $thisyear)
        {
            push @allyrs, $_;
        }
    }
    
    if(@{period}[0] eq "This Year")
    {
	@{year}[0]=$thisyear;
    }
    if(@{period}[0] eq "Last Year")
    {
	@{year}[0]=$thisyear-1;
    }
    if(@{year}[0] eq "all")  ## changed "year" to "period" 06-09-03
    {
	foreach(@allyrs)
	{
	    push @{year}, $_;
	}
    }
    if(@{period}[0] eq "Plot checked years") 
    {
	# @{year} is allready filled;
    }
    if(!defined(@{year}[0]))
    {
	@{year}[0]=$thisyear;
    }
    
    
    $allyears=join(",",@{year});
    
    $var=@{group}[0];
    $moremoregroup=join(",",@{moremoregroup});
    print"group=$var<BR> moregroup= @{moregroup} <BR>moremoregroup=$moremoregroup<BR> period=@{period}<BR>allyears = $allyears<BR>";
    
    if(@{period}[0] eq "GO")
    {
	$begyear = substr @{begin}[0],0,4;
	$endyear = substr @{end}[0],0,4;
	foreach(@rns)
	{
	    $beg=substr $_, 0,8;
	    $end=substr $_, 9,16;
	    $b=@{begin}[0];
	    $e=@{end}[0];
	    if(($beg < @{end}[0]) and ($end > @{begin}[0]))
	    {
		push @runs, $_;
		#print"$beg $_ $end $b $e <BR>";
	    }
	}
    }
    else
    {
	
	@allruns=split("\n",`ls ../private/runs` );    
	foreach(@allruns)
	{
	    $year=substr $_,0,4;
	    if($allyears =~ m/$year/)
	    {
		push @runs, $_;
	    }
	}
    }
    
############ replace "All" with all of what ever its suposed to be
    if(@{moremoregroup}[0] eq "all")
    {
	$n=0;
	if(@{moregroup}[0] eq "Institute")
	{
	    foreach(keys %location)
	    {
		@{moremoregroup}[$n] = $_;
		$n++;
		print"location$_<BR>";
		
	    }
	}
	if(@{moregroup}[0] eq "Career")
	{
	    foreach(keys %career)
	    {
		@{moremoregroup}[$n] = $_;
		$n++;
	    }
	}
	
    }

    
    
    
    $allbars=join(",",@{moremoregroup});  #### each coma seperated value coresponds to one bar in the histogram
    
    print"allbars = $allbars<BR>";
    if(@{group}[0] eq "groups")
    {
	if(@{moregroup}[0] eq "Institute")
	{
	    foreach(keys %location)
	    {
		if( $allbars =~ m/$_/ )
		{
		    $count{$_}=0;
		}
	    }
	}
	if(@{moregroup}[0] eq "Career")
	{
	    foreach(keys %career)
	    {
		if($allbars =~ m/$_/)
		{
		    $count{$_}=0;
		}
	    }
	    
	}
	#$allbars=join(",", keys %count);
    }
    
    if(@{group}[0] eq "individuals")
    {
	if(@{moregroup}[0] eq "Institute")
	{
	    foreach(keys %loc)
	    {
		if($allbars=~ m/$loc{$_}/)
		{
		    $count{$_}=0;
		}
	    }
#	    print "ok<br>";
	}
	
	
	if(@{moregroup}[0] eq "Career")
	{
	    foreach(keys %car)
	    {
		if($allbars=~ m/$car{$_}/)
		{
		    $count{$_}=0;
		}
	    }
	}
	if(@{moregroup}[0] eq "all")
	{
	    foreach(keys %loc)
	    {                    # no if selection
		$count{$_}=0;
	    }
	}
	
	
	
    }
    
#    $allbars=join(",", keys %count);    ### dont know
    
    
    foreach(@runs)
    {
# print"Looking at run $_<br>\n";
	$run = $_;
	$done=0;
	open(RUN, "<../private/runs/$_");
	foreach $line (<RUN>)
	{
	    if($run eq "20030520-20030605")
	    {
#	    print"$line<br>";
	    }
	    if(!$done)
	    {
		chop;
		($date{lt},$moon{lt},$moon{ut},$length,$jday,$hires1,$hires2,$hires3,$comm,@waste)=split("#",$line);
		if($date>=$today)
		{
		    $done=1;
		}
		@hr1=split("/", $hires1);
		@hr2=split("/", $hires2);
		@hr3=split("/", $hires3);
		@hr=(@hr1,@hr2,@hr3);
#	    print" date = $date{lt} hires1 = $hires1 hires2 = $hires2 comment = $comm<br>\n";
		foreach(@hr)
		{
		    if(defined($loc{$_} and $_ ne ""))
		    {
			if(@{group}[0] eq "individuals")
			{
			    if( ($allbars =~ m/$loc{$_}/ and @{moregroup}[0] eq "Institute") or ($allbars =~ m/$car{$_}/ and @{moregroup}[0] eq "Career") or (@{moregroup}[0] eq "all" and defined($loc{$_}) ) )
			    {
				$count{$_}++;
			    }
			}
			if(@{group}[0] eq "groups")
			{
			    if($allbars =~ m/$loc{$_}/ and @{moregroup}[0] eq "Institute")
			    {
				$count{$loc{$_}}++;
			    }
			    elsif($allbars =~ m/$car{$_}/ and @{moregroup}[0] eq "Career")
			    {
				$count{$car{$_}}++;
			    }
			}
		    }
		}   	    
	    }	
	}
	close(RUN);
    }
    print"<FORM method=GET ACTION=stat.pl>\n";
    print'<INPUT type=submit value="New Plot">';
    print"</FORM>\n";
    #print"<BR>count only $allbars<BR>\n";
    foreach(keys %count)
    {
	#print"$_";
	if($count{$_} > $max)
	{
	    $max = $count{$_};
	}
    }
    print"</TABLE><TABLE border=2>\n";
    for($i=$max; $i>0; $i--)
    {
	print"<TR>\n";
	foreach(sort keys %count)
	{
	    if( ($_ ne "") and ($_ ne " ") and ($_ ne "  ") and ($_ ne "   ") )
	    {
		if($count{$_} >=$i)
		{
		    print"<TD>$_ $count{$_}</TD>\n";
		}
		else
		{
		    print"<TD></TD>\n";
		}
	    }
	}
	print"</TR>\n";
    }
}

print"</TABLE>\n";
print"\n</HTML>";
