#!/usr/bin/perl
#

use 5.006;
use DBI;
use CGI;
use lib qw(/mnt/sda/tmm/handlers/genc);
use TClubMD5;

my $server = "127.0.0.1";
my $user = $primary_user;
my $passwd = $primary_passwd;
my $dbase = $primary_dbase;
my $port = $primary_port;

my $query = new CGI;

print "Content-Type: text/html; charset=UTF-8\n\n";

my $who = $query->param('who');
my $token = $query->param('token');
my $ru_en = $query->param('l');
my $language = $query->param('lang');
my $curr_sport = $query->param('cat');

my $utf = 1;

my $session = TClubMD5::md5_hex($who.$salt);

die("read_stats.pl: token is $token, session is $session!\n") if ($token ne $session);
die("psssooff!\n") if (in_list($who,$pssoff_guys_string));

my $rr = $ru_en; $rr = "ru" if ( $ru_en eq "ru_THR" || $ru_en eq "ru_BRL" );

($dbase,$server,$port,$user,$passwd,$hourshift) = TClubMD5::get_connect_req($rr);

$dbase = $db if ($db);
my $dbconn=DBI->connect("dbi:Pg:dbname=$dbase;port=$port;host=$server",$user, $passwd);

my $global_AND = " and sport='$curr_sport'";
$global_AND = " and true" if ($curr_sport eq '0');

my $c = $query->param('count');

my $chel = "ppl."; my $thsnd = "ths."; my $mnths = "mon."; my $ofrs = "offers"; my $j_j = "from"; my $l_s = "matches"; my $v_z = "played";
my $pph = "price/hour";$court_labels{'hard'} = 'Hard';$court_labels{'taraflex'} = 'Taraflex';$court_labels{'brick'} = 'Clay';

$chel = "ppl.";
$chel = " Ñ‡ÐµÐ»." if ( $language eq 'russian');
$chel = "ÞÅÌ." if ( ( $language eq 'russian') && !$utf);

$thsnd = "th.";
$thsnd = "Ñ‚Ñ‹Ñ�." if ( $language eq 'russian');
$thsnd = "ÔÙÓ." if ( ( $language eq 'russian') && !$utf);

$mnths = "mon.";
$mnths = "Ð¼ÐµÑ�." if ( $language eq 'russian');
$mnths = "ÍÅÓ." if ( ( $language eq 'russian') && !$utf);

$ofrs = "offers";
$ofrs = "Ð¿Ñ€ÐµÐ´Ð»." if ( $language eq 'russian');
$ofrs = "ÐÒÅÄÌ." if ( ( $language eq 'russian') && !$utf);

$j_j = "from";
$j_j = "Ð¾Ñ‚" if ( $language eq 'russian');
$j_j = "ÏÔ" if ( ( $language eq 'russian') && !$utf);

$l_s = "matches";
$l_s = "Ð¼Ð°Ñ‚Ñ‡ÐµÐ¹" if ( $language eq 'russian');
$l_s = "ÍÁÔÞÅÊ" if ( ( $language eq 'russian') && !$utf);

$v_z = "played";
$v_z = "Ð¸Ð³Ñ€Ð°Ð»Ð¸" if ( $language eq 'russian');
$v_z = "ÉÇÒÁÌÉ" if ( ( $language eq 'russian') && !$utf);

$pph = "Ð¡Ñ€. Ñ†ÐµÐ½Ð°" if ( $language eq 'russian');
$pph = "óÒ. ÃÅÎÁ" if ( ( $language eq 'russian') && !$utf);

$court_labels{'hard'} = "Ñ…Ð°Ñ€Ð´" if ( $language eq 'russian');
$court_labels{'hard'} = "ÈÁÒÄ" if ( $language eq 'russian' && !$utf);

$court_labels{'taraflex'} = "Ñ‚-Ñ„Ð»ÐµÐºÑ�" if ( $language eq 'russian');
$court_labels{'taraflex'} = "ÆÌÅËÓ" if ( $language eq 'russian' && !$utf);

$court_labels{'brick'} = "Ð³Ñ€ÑƒÐ½Ñ‚" if ( $language eq 'russian');
$court_labels{'brick'} = "ÇÒÕÎÔ" if ( $language eq 'russian' && !$utf);

$r_ch = "\$/h";
$r_ch = "RUR/h" if ($ru_en =~ /^ru/);
$r_ch = "Ñ€ÑƒÐ±/Ñ‡" if ($language eq 'russian' && $ru_en =~ /^ru/);
$r_ch = "ÒÕÂ/Þ" if ($language eq 'russian' && $ru_en =~ /^ru/ && !$utf);

$new_tournament_logo = koitoutf8("15 ÁÐÒ. íÏÎÔÅ-ëÁÒÌÏ");
$new_tournament_name = koitoutf8("1/32");
$new_tournament_dates = koitoutf8("äÁ×ÙÄÅÎËÏ - âÒÁÎÄÓ");
$new_tournament_link = koitoutf8("&nbsp;6/3,6/4");

my $tablo = '';
my $mt = "-2px"; 

my $addon = 0;

if ($addon) {
$c = $c + 2;
$c = 1 if ($c == 9);
$c = $c + 2;
$c = 1 if ($c == 9);
$c = $c + 2;
$c = 1 if ($c == 9);
}

if ( (int($c/11))*11 == $c) { #unreached

if (0) {
$tablo = "<div id=tablo style=\"color:#369;font-family:Arial;margin-top:$mt;background:#fafaf0;padding:3px;-webkit-box-shadow: 1px 1px 3px #9cf;-moz-box-shadow: 1px 1px 3px #9cf;box-shadow: 1px 1px 3px #9cf;\">
<div style=\"border-color:#9cf;border-style:dotted;border-width:1px;padding:2px;\">
<div id=tablo_str1 style=\"font-size:10px;white-space:nowrap;\" align=right>&nbsp;$new_tournament_logo</div>
<div id=tablo_str2 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;font-size:10px;white-space:nowrap;font-weight:bold;color:#963;\" align=right>$new_tournament_name</div>
<div id=tablo_str3 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;font-size:10px;white-space:nowrap;font-style:italic;\">$new_tournament_dates</div>
<div id=tablo_str4 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;font-size:10px;white-space:nowrap;\">$new_tournament_link</div>
</div></div>" if (( $ru_en =~ /^ru/ || $language eq 'russian' || $language eq 'english') && $addon);

$tablo = "<div id=tablo style=\"color:#369;font-family:Arial;font-size:12px;margin-top:12px;background:#fafaf0;padding:3px;-webkit-box-shadow: 1px 1px 3px #9cf;-moz-box-shadow: 1px 1px 3px #9cf;box-shadow: 1px 1px 3px #9cf;\">
<div style=\"border-color:#9cf;border-style:dotted;border-width:1px;padding:2px;text-align:center;\">
<img src=/icon/no_war.png width=82>
</div></div>";
}

($n_matches, $sum90, $counted, $sumtime_s, $fulltime_s, $n_f_s) = count_money('matches',0,92,'taraflex');
($n_doubles, $sum90_d, $counted_d, $sumtime_d, $fulltime_d, $n_f_d) = count_money('doubles',0,92,'taraflex');

my $n_all = $n_matches+$n_doubles; my $sum = $sum90 + $sum90_d; my $ttime = $sumtime_s + $sumtime_d;
my $pph_hard = ($ttime > 0) ? sprintf("%.0f",$sum/$ttime) : 0;

$tablo = "<div id=tablo style=\"color:#369;font-family:Arial;font-size:12px;margin-top:$mt;background:#fafaf0;padding:3px;-webkit-box-shadow: 1px 1px 3px #9cf;-moz-box-shadow: 1px 1px 3px #9cf;box-shadow: 1px 1px 3px #9cf;\">
<div style=\"border-color:#9cf;border-style:dotted;border-width:1px;padding:2px;\">
<div id=tablo_title style=\"background:#fafaf0;color:#369;margin:2px 2px 5px 2px;white-space:nowrap;\"><!-- img src=/icon/$sport_icons{$curr_sport}.png width=16 -->$pph 3 $mnths</div>
<div id=tablo_str1 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;margin:3px;font-size:12px;white-space:nowrap;\" align=right>$court_labels{'taraflex'} <b>$pph_hard</b>&nbsp;$r_ch</div>
<div id=tablo_str2 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;margin:3px;font-size:12px;\" align=right>$l_s <b>$n_all</b></div>
</div></div>";
	
} elsif ((int(($c+6)/11))*11 == $c+6) {

my ($n_m,$n_m_loc,$n_m_p, $n_p,$n_m_p1, $n_p1,$n_m_p2, $n_p2) = count_maxes(1); 

$tablo = "<div id=tablo style=\"color:#369;font-family:Arial;margin-top:-9px;background:#fafaf0;padding:3px;-webkit-box-shadow: 1px 1px 3px #9cf;-moz-box-shadow: 1px 1px 3px #9cf;box-shadow: 1px 1px 3px #9cf;\">
<div style=\"border-color:#9cf;border-style:dotted;border-width:1px;padding:2px;\">
<div id=tablo_str1 style=\"font-size:10px;white-space:nowrap;\" align=right><b>MAX $l_s</b> 12 $mnths<br><!-- img src=/icon/$sport_icons{$curr_sport}.png width=16 --><font color=#333>".&court_lookup($n_m_loc)." ($n_m)</font></div>";
$tablo .= "<div id=tablo_str2 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;font-size:10px;white-space:nowrap;color:#ec8102;\">1.".&nkname_lookup($n_p)." ($n_m_p)</div>" if ($n_m_p);
$tablo .= "<div id=tablo_str3 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;font-size:10px;white-space:nowrap;color:#45b261;\">2.".&nkname_lookup($n_p1)." ($n_m_p1)</div>" if ($n_m_p1);
$tablo .= "<div id=tablo_str4 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;font-size:10px;white-space:nowrap;color:#3e9bd0;\">3.".&nkname_lookup($n_p2)." ($n_m_p2)</div>" if ($n_m_p2);
$tablo .= "</div></div>";

} elsif ((int(($c+8)/11))*11 == $c+8) {
my ($n_chal,$n_chal_people) = count_chals(1); 

$tablo = "<div id=tablo style=\"color:#369;font-family:Arial;font-size:12px;margin-top:$mt;background:#fafaf0;padding:3px;-webkit-box-shadow: 1px 1px 3px #9cf;-moz-box-shadow: 1px 1px 3px #9cf;box-shadow: 1px 1px 3px #9cf;\">
<div style=\"border-color:#9cf;border-style:dotted;border-width:1px;padding:2px;\">
<div id=tablo_title style=\"background:#fafaf0;color:#369;margin:2px 2px 5px 2px;\"><!-- img src=/icon/$sport_icons{$curr_sport}.png width=16 --> [12 $mnths]</div>
<div id=tablo_str1 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;margin:3px;font-size:12px;white-space:nowrap;\" align=right>$ofrs <b>$n_chal</b></div>
<div id=tablo_str2 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;margin:3px;font-size:12px;\" align=right>$j_j <b>$n_chal_people</b> $chel</div>
</div></div>";

} elsif ((int(($c+10)/11))*11 == $c+10) {

my $people_list = ();
my @l = &count_unique_players(0,1);
@people_list = ($people_list,@l);
@people_list = xDel('',@people_list);
my @unique_peoples = keys %{{ map { $_ => 1 } @people_list }};
my $n_all_peoples = $#unique_peoples; $n_all_peoples = 0 if ($n_all_peoples < 0);

my $sum_365 = 0;my $counted = 0; my $n_matches = 0; my $sumtime_s = 0; my $sumtime_d = 0;
my $sum_365_d = 0;my $counted_d = 0; my $n_doubles = 0; my $fulltime_s = 0; my $fulltime_d = 0; my $n_f_s = 0; my $n_f_d = 0;
	
($n_matches, $sum_365, $counted, $sumtime_s,$fulltime_s,$n_f_s) = count_money('matches',0,366);
($n_doubles, $sum_365_d, $counted_d, $sumtime_d,$fulltime_d, $n_f_d) = count_money('doubles',0,366);
my $n_all = $n_matches + $n_doubles;
	

$tablo = "<div id=tablo style=\"color:#369;font-family:Arial;font-size:12px;margin-top:$mt;background:#fafaf0;padding:3px;-webkit-box-shadow: 1px 1px 3px #9cf;-moz-box-shadow: 1px 1px 3px #9cf;box-shadow: 1px 1px 3px #9cf;\">
<div style=\"border-color:#9cf;border-style:dotted;border-width:1px;padding:2px;\">
<div id=tablo_title style=\"color:#369;margin:2px 2px 5px 2px;\"><!-- img src=/icon/$sport_icons{$curr_sport}.png width=16 --> [12 $mnths]</div>
<div id=tablo_str1 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;margin:2px;font-size:12px;\" align=right>$l_s <b>$n_all</b></div>
<div id=tablo_str2 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;margin:2px;font-size:12px;\" align=right>$v_z <b>$n_all_peoples</b> $chel</div>
</div></div>";

}  elsif ((int(($c+2)/11))*11 == $c+2) {


($n_matches, $sum90, $counted, $sumtime_s, $fulltime_s, $n_f_s) = count_money('matches',0,92,'brick');
($n_doubles, $sum90_d, $counted_d, $sumtime_d, $fulltime_d, $n_f_d) = count_money('doubles',0,92,'brick');

my $n_all = $n_matches+$n_doubles; my $sum = $sum90 + $sum90_d; my $ttime = $sumtime_s + $sumtime_d;
my $pph_hard = ($ttime > 0) ? sprintf("%.0f",$sum/$ttime) : 0;

$tablo = "<div id=tablo style=\"color:#369;font-family:Arial;font-size:12px;margin-top:$mt;background:#fafaf0;padding:3px;-webkit-box-shadow: 1px 1px 3px #9cf;-moz-box-shadow: 1px 1px 3px #9cf;box-shadow: 1px 1px 3px #9cf;\">
<div style=\"border-color:#9cf;border-style:dotted;border-width:1px;padding:2px;\">
<div id=tablo_title style=\"background:#fafaf0;color:#369;margin:2px 2px 5px 2px;white-space:nowrap;\"><!-- img src=/icon/$sport_icons{$curr_sport}.png width=16-->$pph 3 $mnths</div>
<div id=tablo_str1 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;margin:3px;font-size:12px;white-space:nowrap;\" align=right>$court_labels{'brick'} <b>$pph_hard</b>&nbsp;$r_ch</div>
<div id=tablo_str2 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;margin:3px;font-size:12px;\" align=right>$l_s <b>$n_all</b></div>
</div></div>";

}  elsif ((int(($c+4)/11))*11 == $c+4) {

($n_matches, $sum90, $counted, $sumtime_s, $fulltime_s, $n_f_s) = count_money('matches',0,92,'hard');
($n_doubles, $sum90_d, $counted_d, $sumtime_d, $fulltime_d, $n_f_d) = count_money('doubles',0,92,'hard');

my $n_all = $n_matches+$n_doubles; my $sum = $sum90 + $sum90_d; my $ttime = $sumtime_s + $sumtime_d;
my $pph_hard = ($ttime > 0) ? sprintf("%.0f",$sum/$ttime) : 0;

$tablo = "<div id=tablo style=\"color:#369;font-family:Arial;font-size:12px;margin-top:$mt;background:#fafaf0;padding:3px;-webkit-box-shadow: 1px 1px 3px #9cf;-moz-box-shadow: 1px 1px 3px #9cf;box-shadow: 1px 1px 3px #9cf;\">
<div style=\"border-color:#9cf;border-style:dotted;border-width:1px;padding:2px;\">
<div id=tablo_title style=\"background:#fafaf0;color:#369;margin:2px 2px 5px 2px;white-space:nowrap;\"><!-- img src=/icon/$sport_icons{$curr_sport}.png width=16 -->$pph 3 $mnths</div>
<div id=tablo_str1 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;margin:3px;font-size:12px;white-space:nowrap;\" align=right>$court_labels{'hard'} <b>$pph_hard</b>&nbsp;$r_ch</div>
<div id=tablo_str2 style=\"background:url(/icon/blue_under2.png) bottom left repeat-x;padding:1px;margin:3px;font-size:12px;\" align=right>$l_s <b>$n_all</b></div>
</div></div>";


}

print $tablo;
$dbconn->disconnect;
$query->delete_all;
exit;


sub dBaseError {

    my ($check, $message) = @_;
    print "<H4><FONT COLOR=BLACK><P>$message<BR>Error: ".$check->errstr."</FONT></H4>";
    die("Action failed on command:$message  Error_was:$DBI::errstr");
};

sub count_unique_players {

my $par = shift;
my $y = shift;

my $courts_type = shift; $courts_type = $courts_type ? $courts_type : 'all';
my $start_date = shift; $start_date = $start_date ? $start_date : $default_start_date;
my $end_date = shift; $end_date = $end_date ? $end_date : $default_end_date;

my $court_type_filter = $courts_type eq 'all' ? '' : " and court_type ~ '^$courts_type'";

my $p_list = ();

my $and = $par ? "court_location='$par' and score is not null and score != 'w/o' and score != '' and score != 'n/a'" : "score is not null and score != 'w/o' and score != '' and score != 'n/a'";
$and .= $global_AND; $and .= $court_type_filter;

#my $year = $y ? "match_date >= '$start_date' and match_date < '$end_date'" : 'true';
my $year = $y ? "current_date - match_date < 366" : 'true';

			my $c = "select distinct participant1 from matches, courts_location where courts_location.oid::text = matches.court_location and courts_location.category != 'O' and $and and $year";
	my $r=$dbconn->prepare($c);
    	$r->execute;
	&dBaseError($r, $c."  (".$r->rows()." rows found)") if ($r->rows() == -2);
	my $ls = $r->fetchall_arrayref; my $nt = $r->rows();
	
	for (my $j = 0; $j < $nt; $j++) {
		push @p_list, ${${$ls}[$j]}[0];
	}

		my $c = "select distinct participant2 from matches, courts_location where courts_location.oid::text = matches.court_location and courts_location.category != 'O' and $and and $year";
	my $r=$dbconn->prepare($c);
    	$r->execute;
	&dBaseError($r, $c."  (".$r->rows()." rows found)") if ($r->rows() == -2);
	my $ls = $r->fetchall_arrayref; my $nt = $r->rows();
	
	for (my $j = 0; $j < $nt; $j++) {
		push @p_list, ${${$ls}[$j]}[0];
	}

		my $c = "select distinct participant1 from doubles, courts_location where courts_location.oid::text = doubles.court_location and courts_location.category != 'O' and $and and $year";
	my $r=$dbconn->prepare($c);
    	$r->execute;
	&dBaseError($r, $c."  (".$r->rows()." rows found)") if ($r->rows() == -2);
	my $ls = $r->fetchall_arrayref; my $nt = $r->rows();
	
	for (my $j = 0; $j < $nt; $j++) {
		my ($f,$s) = split('/',${${$ls}[$j]}[0]);
		push @p_list, $f if (length($f)); push @p_list, $s if (length($s));
	}

		my $c = "select distinct participant2 from doubles, courts_location where courts_location.oid::text = doubles.court_location and courts_location.category != 'O' and $and and $year";
	my $r=$dbconn->prepare($c);
    	$r->execute;
	&dBaseError($r, $c."  (".$r->rows()." rows found)") if ($r->rows() == -2);
	my $ls = $r->fetchall_arrayref; my $nt = $r->rows();
	
	for (my $j = 0; $j < $nt; $j++) {
		my ($f,$s) = split('/',${${$ls}[$j]}[0]);
		push @p_list, $f if (length($f)); push @p_list, $s if (length($s));
	}
return @p_list;
}

sub count_chals {

my $y = shift;

my $year = $y ? "current_date - date_and_time::date < 366" : 'true';

			my $c = "select count(id) from challenges where $year $global_AND";
	my $r=$dbconn->prepare($c);
    	$r->execute;
	&dBaseError($r, $c."  (".$r->rows()." rows found)") if ($r->rows() == -2);
	my $ls = $r->fetchall_arrayref; 
	
my $n_ch =  ${${$ls}[0]}[0];

			my $c = "select distinct owner from challenges where $year $global_AND";
	my $r=$dbconn->prepare($c);
    	$r->execute;
	&dBaseError($r, $c."  (".$r->rows()." rows found)") if ($r->rows() == -2);
	my $n_ch_p =  $r->rows(); 

return ($n_ch,$n_ch_p);
}

sub count_maxes {

my $y = shift;

my $year = $y ? "current_date - match_date < 366" : 'true';


			my $c = "select count(matches.oid) as m, court_location from matches, courts_location where courts_location.oid::text = matches.court_location and courts_location.category != 'O' 
			and score is not null and score != 'w/o' and score != '' and score != 'n/a' and $year $global_AND 
			group by court_location order by m, court_location asc";
#print STDERR "Here c is $c!\n";

	my $r=$dbconn->prepare($c);
    	$r->execute;
	&dBaseError($r, $c."  (".$r->rows()." rows found)") if ($r->rows() == -2);
	my $ls = $r->fetchall_arrayref; my $n = $r->rows() ? $r->rows()-1 : 0;
	
my $n_m =  $r->rows() ? ${${$ls}[$n]}[0] : 0;
my $n_m_loc =  $r->rows() ? ${${$ls}[$n]}[1] : 0;
my $n_d = 0;

if ($n_m_loc) {
			my $c = "select count(doubles.oid) from doubles, courts_location where courts_location.oid::text = doubles.court_location and courts_location.category != 'O'  
			and score is not null and score != 'w/o' and score != '' and score != 'n/a' and court_location = '$n_m_loc' and $year $global_AND ";
	my $r=$dbconn->prepare($c);
    	$r->execute;
	&dBaseError($r, $c."  (".$r->rows()." rows found)") if ($r->rows() == -2);
	my $ls = $r->fetchall_arrayref; $n_d =  ${${$ls}[0]}[0];
}

			my $c = "select proj_code, num_of_played_matches_period(proj_code,365,$curr_sport) + num_of_played_good_doubles_period(proj_code,365,$curr_sport) as m 
			from members group by proj_code order by m";	
	my $r=$dbconn->prepare($c);
    	$r->execute;
	&dBaseError($r, $c."  (".$r->rows()." rows found)") if ($r->rows() == -2);
	my $ls = $r->fetchall_arrayref; my $n = $r->rows() ? $r->rows()-1 : 0;
	
my $n_p =  $r->rows() ? ${${$ls}[$n]}[0] : 0;
my $n_m_p =  $r->rows() ? ${${$ls}[$n]}[1] : 0;
my $n_p1 =  $r->rows()>1 ? ${${$ls}[$n-1]}[0] : 0;
my $n_m_p1 =  $r->rows()>1 ? ${${$ls}[$n-1]}[1] : 0;
my $n_p2 =  $r->rows()>2 ? ${${$ls}[$n-2]}[0] : 0;
my $n_m_p2 =  $r->rows()>2 ? ${${$ls}[$n-2]}[1] : 0;
return ($n_m+$n_d,$n_m_loc, $n_m_p, $n_p, $n_m_p1, $n_p1, $n_m_p2, $n_p2);
}

sub count_money {

my $table = shift;
my $par = shift;
my $y = shift;

my $courts_type = shift; $courts_type = $courts_type ? $courts_type : 'all';
my $start_date = shift; $start_date = $start_date ? $start_date : $default_start_date;
my $end_date = shift; $end_date = $end_date ? $end_date : $default_end_date;

my $court_type_filter = $courts_type eq 'all' ? '' : " and $table.court_type ~ '^$courts_type'";

my $and = $par ? "$table.court_location='$par' and $table.score is not null and $table.score != 'w/o' and $table.score !~ 'Cancel' and $table.score != '' and $table.score != 'n/a'" : "$table.score is not null and $table.score != 'w/o' and $table.score !~ 'Cancel' and $table.score != '' and $table.score != 'n/a'";
$and .= $global_AND; $and .= $court_type_filter;

#my $year = $y ? "$table.match_date >= '$start_date' and $table.match_date < '$end_date' and $table.total_time > 0" : 'true';
my $year = $y ? "current_date - $table.match_date < $y" : 'true';

		my $c = "select $table.court_type, $table.total_time from $table, courts_location where courts_location.oid::text = $table.court_location and courts_location.category != 'O' and $and and $year";
#print STDERR $c."\n";
	my $r=$dbconn->prepare($c);
    	$r->execute;
	&dBaseError($r, $c."  (".$r->rows()." rows found)") if ($r->rows() == -2);
	my $ls = $r->fetchall_arrayref;my $n = $r->rows();
	
	my $sum = 0;my $counted = 0;my $sumtime = 0;my $fulltime = 0; my $free_matches = 0;
	
	for (my $j=0; $j < $n;$j++) {
		my $chunk = ${${$ls}[$j]}[0];  $chunk =~ /^\s*\w+\s*(\[\d+\])?\s*$/; my $p = $1; my $old_p = $p;
		if (length($p)) { 
			$free_matches++ if ($p eq '[0]');
			$p =~ /\[(\d+)\]/;
			$p = ($old_p ne $1) ? $1 : 0;
		};
		my $nhours = ${${$ls}[$j]}[1] ? ${${$ls}[$j]}[1] : 1.5;
		if ($p && ${${$ls}[$j]}[1]) {
			$sum += $p*$nhours;$sumtime += $nhours;$counted++;
		}
		
		$fulltime += $nhours; 
		
	}
return ($n,$sum,$counted,$sumtime,$fulltime,$free_matches);	
}

sub court_lookup {

local ($code) = shift;
return '+++++++' if ($code eq '0');

	my $comm = "select a_name from courts_location where oid = '$code'";

	my $result=$dbconn->prepare($comm);
    	$result->execute;
	&dBaseError($result, $comm."  (".$result->rows()." rows found)") if ($result->rows() ==
	-2);
	
	my $l = $result->fetchall_arrayref;

		return ${${$l}[0]}[0];

return $code;
}

sub nkname_lookup {

local ($code) = shift;


	my $comm = "select a_nkname from members where proj_code = '$code'";

	my $result=$dbconn->prepare($comm);
    	$result->execute;
	&dBaseError($result, $comm."  (".$result->rows()." rows found)") if ($result->rows() ==
	-2);
	
	my $l = $result->fetchall_arrayref;

		return ${${$l}[0]}[0];

return $code;
}

sub xDel {

    my ($element, @in) = @_;
    my (@out);

    foreach my $name (@in) {
        push @out, $name unless $element eq $name;
    }
    @out;
}

sub koitoutf8 {
my $pvdcoderwin=shift;
$pvdcoderwin=~ s/³/E/g;
$pvdcoderwin=~ s/£/e/g;
$pvdcoderwin=~ s/Ñ/Ñ�/g;
$pvdcoderwin=~ s/Ð/Ð¿/g;

$pvdcoderwin=~ s/á/Ð�/g;
$pvdcoderwin=~ s/â/Ð‘/g;
$pvdcoderwin=~ s/÷/Ð’/g;
$pvdcoderwin=~ s/ç/Ð“/g;
$pvdcoderwin=~ s/ä/Ð”/g;
$pvdcoderwin=~ s/å/Ð•/g;
$pvdcoderwin=~ s/ö/Ð–/g;
$pvdcoderwin=~ s/ú/Ð—/g;
$pvdcoderwin=~ s/é/Ð˜/g;
$pvdcoderwin=~ s/ê/Ð™/g;
$pvdcoderwin=~ s/ë/Ðš/g;
$pvdcoderwin=~ s/ì/Ð›/g;
$pvdcoderwin=~ s/í/Ðœ/g;
$pvdcoderwin=~ s/î/Ð�/g;
$pvdcoderwin=~ s/ï/Ðž/g;
$pvdcoderwin=~ s/ð/ÐŸ/g;
$pvdcoderwin=~ s/ò/Ð /g;
$pvdcoderwin=~ s/ó/Ð¡/g;
$pvdcoderwin=~ s/ô/Ð¢/g;
$pvdcoderwin=~ s/õ/Ð£/g;
$pvdcoderwin=~ s/æ/Ð¤/g;
$pvdcoderwin=~ s/è/Ð¥/g;
$pvdcoderwin=~ s/ã/Ð¦/g;
$pvdcoderwin=~ s/þ/Ð§/g;
$pvdcoderwin=~ s/û/Ð¨/g;
$pvdcoderwin=~ s/ý/Ð©/g;
$pvdcoderwin=~ s/ø/Ð¬/g;
$pvdcoderwin=~ s/ù/Ð«/g;
$pvdcoderwin=~ s/ÿ/Ðª/g;
$pvdcoderwin=~ s/ü/Ð­/g;
$pvdcoderwin=~ s/à/Ð®/g;
$pvdcoderwin=~ s/ñ/Ð¯/g;

$pvdcoderwin=~ s/Á/Ð°/g;
$pvdcoderwin=~ s/Â/Ð±/g;
$pvdcoderwin=~ s/×/Ð²/g;
$pvdcoderwin=~ s/Ç/Ð³/g;
$pvdcoderwin=~ s/Ä/Ð´/g;
$pvdcoderwin=~ s/Å/Ðµ/g;
$pvdcoderwin=~ s/Ö/Ð¶/g;
$pvdcoderwin=~ s/Ú/Ð·/g;
$pvdcoderwin=~ s/É/Ð¸/g;
$pvdcoderwin=~ s/Ê/Ð¹/g;
$pvdcoderwin=~ s/Ë/Ðº/g;
$pvdcoderwin=~ s/Ì/Ð»/g;
$pvdcoderwin=~ s/Í/Ð¼/g;
$pvdcoderwin=~ s/Î/Ð½/g;
$pvdcoderwin=~ s/Ï/Ð¾/g;
$pvdcoderwin=~ s/Ò/Ñ€/g;
$pvdcoderwin=~ s/Ó/Ñ�/g;
$pvdcoderwin=~ s/Ô/Ñ‚/g;
$pvdcoderwin=~ s/Õ/Ñƒ/g;
$pvdcoderwin=~ s/Æ/Ñ„/g;
$pvdcoderwin=~ s/È/Ñ…/g;
$pvdcoderwin=~ s/Ã/Ñ†/g;
$pvdcoderwin=~ s/Þ/Ñ‡/g;
$pvdcoderwin=~ s/Û/Ñˆ/g;
$pvdcoderwin=~ s/Ý/Ñ‰/g;
$pvdcoderwin=~ s/Ø/ÑŒ/g;
$pvdcoderwin=~ s/Ù/Ñ‹/g;
$pvdcoderwin=~ s/ß/ÑŠ/g;
$pvdcoderwin=~ s/Ü/Ñ�/g;
$pvdcoderwin=~ s/À/ÑŽ/g;


return $pvdcoderwin;
}

sub in_list {
my $guy = shift;
my $str = shift;
my $comma = shift;

if (defined($comma)) {
return 1 if ($str eq $guy || $str =~ /^$guy\,/ || $str =~ /\,$guy\,/ || $str =~ /\,$guy$/);
return 0;
} else {
return 1 if ($str eq $guy || $str =~ /^$guy\#/ || $str =~ /\#$guy\#/ || $str =~ /\#$guy$/);
return 0;
}
}
