#!/usr/bin/perl -w
# standings.cgi: show current standings
# usage: standings.cgi
# 20061125 erikt@xs4all.nl

BEGIN { open(STDERR, ">>/WWW/t/tjongkim/tmp/errorlog"); }

use shout;
use elib;
use Time::HiRes;

# standard lines for output
print "Content-type: text/html\n\n";

$time0 = [ Time::HiRes::gettimeofday( ) ];

$nbrOfCandidates = 10;
$maxShowShout = 10; # 20090312: was 9
$defaultShowTrades = 50;
$maxShowTrades = $defaultShowTrades;
#$maxShowTrades = 12;

# read arguments
$line = <STDIN>;
if (not defined $line) { $line = ""; }
if (defined $ENV{"QUERY_STRING"}) { $line .= '&' . $ENV{"QUERY_STRING"}; }

chomp($line);
@args = split(/\&+/,$line);
%args = ();
for ($i=0;$i<=$#args;$i++) {
   ($field,$value) = split(/=+/,$args[$i]);
   if (not defined $field or $field eq "") { next; }
   if (not defined $value) { $value = 0; }
   $args{$field} = $value;
   $args{$field} =~ s/\++$//; # remove trailing spaces
   $args{$field} =~ s/^\++$//; # remove initial spaces
}
# we always want to see all proposals
if (defined $args{"TRADED"}) { $maxShowTrades = 1000; }
if (defined $args{"MAX"} and $args{"MAX"} =~ /^\d+$/) {
   $maxShowTrades = $args{"MAX"};
   $maxShowShout = $maxShowShout + 
                   int(0.8*$maxShowShout*(-1+$maxShowTrades/$defaultShowTrades));
   if ($maxShowShout > 100) { $maxShowShout = 100; }
}

# resource specifications 
$baseDir = "/WWW/t/tjongkim/private/molbeurs";
$date = `date '+%Y.%m.%d.%H:%M:%S'`;
chomp($date);
$longDate = `date`;
chomp($longDate);
$nbrOfPlayers = 0;
$colorM = "#402000"; # 2009:664e28 / 64 48 48
$colorC = "#008000"; # 2009:orangered / 80 128 64
$colorU = "gray";
$bigAmount = 90;

# ip logger for visitor display: does not work here
# &ipLogger();

# current time
if (open(INFILE,"date '+%H:%M'|")) {
   $now = <INFILE>;
   chomp($now);
   close(INFILE);
} else { $now = ""; }

$head = "Molbeurs";
#if (not defined $args{"TRADED"} and not defined $args{"BIG"}) {
#   $head = "Molbeurs ($now)";
#}
# intro
print <<THEEND;
<html>
<head>
<title>$head</title>
<link rel="alternate" type="application/rss+xml" title="RSS Molbeurs" href="http://ifarm.nl/molbeurs/rss.xml">
<meta name="robots" content="nofollow">
THEEND



# 20110318 commented away because of end of game
#if (defined $args{"TRADED"}) {
#   print <<THEEND;
# <META HTTP-EQUIV="refresh" CONTENT="60; URL=http://ifarm.nl/molbeurs/index.traded.php">
#THEEND
# } elsif (not defined $args{"BIG"}) {
#   if (not defined $args{"BOT"}) {
#      print <<THEEND;
#<META HTTP-EQUIV="refresh" CONTENT="118; URL=http://ifarm.nl/molbeurs/">
#THEEND
#   } else {
#      print <<THEEND;
#<META HTTP-EQUIV="refresh" CONTENT="118; URL=http://ifarm.nl/molbeurs/index.bot.php">
#THEEND
#   }
#}




print <<THEEND;
</head>
<body bgcolor="#cccccc">
<p>
<div align="center">
<table>
<tr><td valign="top" align="right" width="180">
THEEND

$time1 = Time::HiRes::tv_interval($time0);
# show current users (commented away in elib.pm at end of game)
my $facebook = "yes";
if (defined $args{"BOT"}) { &ipShow("BOT"); }
else { &ipShow("facebook"); }

$time2 = Time::HiRes::tv_interval($time0);

print <<THEEND;
<td valign="top">
<table width="780" bgcolor="white" cellpadding="0" cellspacing="5">
<tr><td valign="top">
THEEND

# show navigation menu
&menu();

print <<THEEND;
<div style="background-color:#ffffff;">
<table cellspacing="5" align="center"><tr><td valign="top">
<table align="center"><tr><td>
<div style="background-color:$colorM;">
<table cellspacing="5">
<tr>
<th colspan="2" align="left" style="color:white;">Molmarkt
THEEND

# check for candidates that dropped out
%left = ();
%leftOrder = ();
$o = 0;
if (open(INFILE,"$baseDir/LEFT")) {
   while (<INFILE>) {
      $line = $_;
      chomp($line);
      $line =~ s/^\s+//;
      $line =~ s/\s+.*//;
      $line = lc($line);
      $left{"$line+mol"} = 1;
      $left{"$line+kandidaat"} = 1;
      $leftOrder{"$line+mol"} = $o;
      $leftOrder{"$line+kandidaat"} = $o;
      $o++;
   }
   close(INFILE);
}

# show mole market standings
&readPrices();
foreach $name (sort {&sortMarket($prices{$a},$prices{$b},$a,$b)} keys %prices) {
   if ($name =~ /mol$/) {
      $fancyName = &fancyStock($name,1);
      print "<tr><td style=\"color:white;\" align=\"left\"><small>$fancyName</small><td style=\"color:white;\" align=\"right\"><small>$prices{$name}</small>\n";
   }
}

# html code between mole market and candidate market tables
print <<THEEND;
</table></div>
<td valign="top">
<div style="background-color:$colorC;">
<table cellspacing="5">
<tr>
<th colspan="2" align="left" style="color:white;">Kandidatenmarkt
THEEND

# show candidate market (data collected by readPrices)
foreach $name (sort {&sortMarketReverse($prices{$a},$prices{$b},$a,$b)} keys %prices) {
   if ($name =~ /kandidaat$/) {
      $fancyName = &fancyStock($name,1);
      $fancyName =~ s/didaat</</;
      $fancyName =~ s/didaat\*/\*/;
      print "<tr><td style=\"color:white;\" align=\"left\"><small>$fancyName</small><td style=\"color:white;\" align=\"right\"><small>$prices{$name}</small>\n";
   }
}
print "</table></div>\n";

$time3 = Time::HiRes::tv_interval($time0);

# show game standings
&readRankings();

print "</td></tr></table>\n"; # 20090108

$time4 = Time::HiRes::tv_interval($time0);

# show recent trades
&checkTrades();

$time5 = Time::HiRes::tv_interval($time0);

# print "</table>\n</div>\n"; # 20090108
print "</td></tr><tr><td style=\"vertical-align: text-top;\">\n";

# check for trade stop
if (open(INFILE,"$baseDir/STOP")) {
   print <<THEEND;
<p>
<table cellpadding="5">
<tr><td style="background-color:red;"><small>
THEEND
   while (<INFILE>) { print; }
   print "</small></td></tr></table>\n";
   close(INFILE);
} 

# other messages
if (open(INFILE,"$baseDir/MOTD")) {
   print <<THEEND;
<p>
<table cellpadding="5">
<tr><td style="background-color:yellow;"><small>
THEEND
   while (<INFILE>) { print; }
   print "</small></td></tr></table>\n";
   close(INFILE);
} 

# web page introduction text
$playerText = $nbrOfPlayers == 1 ? "is op dit moment 1 actieve speler" :
                                   "zijn op dit moment $nbrOfPlayers actieve spelers";
$bottext = "<a href=\"/molbeurs/index.bot.php\" target=\"_top\">Molbeurshandel inclusief bots</a>";
if (defined $args{"TRADED"} and defined $args{"BOT"}) {
   $bottext = "<a href=\"/molbeurs/index.traded.php\" target=\"_top\">Molbeurshandel zonder bots</a>";
} elsif (not defined $args{"TRADED"} and defined $args{"BOT"}) {
   $bottext = "<a href=\"/molbeurs/\" target=\"_top\">Molbeurshandel zonder bots</a>";
} elsif (defined $args{"TRADED"} and not defined $args{"BOT"}) {
   $bottext = "<a href=\"/molbeurs/index.bot.traded.php\" target=\"_top\">Molbeurshandel inclusief bots</a>";
}
print <<THEEND;
<p>
Welkom! De Molbeurs is een spel waarin je kan handelen 
in aandelen van deelnemers aan het tv-programma 
<a href="http://www.wieisdemol.nl/" target="_top">Wie is de Mol?</a>. 
Iedereen die een geldig e-mail-adres heeft, mag meedoen. 
Deelname is gratis. We spelen niet met echt geld maar met dukaten.
<p>
De Molbeurs heeft twee markten: de Molmarkt en de Kandidatenmarkt. Als je
denkt dat iemand de Mol is, probeer dan zoveel mogelijk Molaandelen van
deze persoon te kopen. Verwacht je dat iemand binnenkort gaat
afvallen, koop dan zoveel mogelijk Kandidaataandelen van hem of haar.
<p>
Als een deelnemer aan het programma uitvalt dan zijn diens Molaandelen 
niks meer waard. De waarde van het bijbehorende Kandidaataandeel wordt 
dan precies 100 dukaten. Aan het einde van het programma zijn er maar tien 
aandelen die meetellen voor de eindscore: het Molaandeel van de Mol 
(heeft als eindwaarde ook 100 dukaten) en de Kandidaataandelen van de negen 
andere kandidaten. De eindscore van een speler is gelijk aan het totaal van 
de waarden van diens aandelen plus het aantal dukaten dat een speler heeft.
<p>
Het doel van het spel is om een groot mogelijke waarde in dukaten en
aandelen te verzamelen. De vijf deelnemers met de hoogste scores
aan het einde van het spel, winnen een prachtig t-shirt. Succes!
<p>
In de twee tabellen linksboven staan de huidige waarden van de aandelen.
Daarnaast staat de huidige stand in het spel.
<p>
De Molbeurs is gestart op 1 januari 2012, 00:00. 
Recente koerschommelingen kan je bekijken op het
<a href="/molbeurs/week.html" target="_top">weekoverzicht</a>
en de pagina met alle
<a href="/molbeurs/graphs.html" target="_top">grafieken</a>.
Je kan ook kijken naar de
<a href="/molbeurs/history.html" target="_top">koersgeschiedenis</a>
gedurende het hele spel. Er $playerText.

</td></tr></table> <!-- 20090108 -->
<p>
<hr>
<small>
<a href="/molbeurs/graphs.html" target="_top">Grafieken</a> |
<a href="/molbeurs/week.html" target="_top">Weekoverzicht</a> |
<a href="/molbeurs/history.html" target="_top">Koersgeschiedenis</a>
</small>
<hr>
<address>
Generated at $longDate. erikt(at)xs4all.nl
</address>
</table>
<td valign="top">
THEEND

&showShoutText($maxShowShout);

$time6 = Time::HiRes::tv_interval($time0);
printf "<!-- %0.3f %0.3f %0.3f %0.3f %0.3f %0.3f -->\n",$time1,$time2,$time3,$time4,$time5,$time6;

print <<THEEND;
</table>
</div>
</body>
</html>
THEEND

&count();

exit(0);

sub menu {
   print <<THEEND;
<div align="center">
<img src="/molbeurs/images/molbeurs.jpg" width="760" height="80" alt="molbeurs">
<form action="/molbeurs/cgi-bin/user.cgi" target="_top">
<a href="/molbeurs/" target="_top">Home</a> |
<a href="/molbeurs/faq.html" target="_top">Uitleg</a> |
<a href="/molbeurs/register.html" target="_top">Registreren</a> |
Naam: <input type="text" size="16" name="NICKNAME"> 
<input type="submit" value=" Zoek ">
| <a href="http://www.wieisdemol.com/molbeurs/" target="_top">Forum</a>
| <a href="/demol/category/molbeurs/" target="_top">Blog</a>
| <a href="/molbeurs/submit.html" target="_top">Idee&euml;nbus</a>
| <a href="/molbeurs/contact.html" target="_top">Contact</a>
| <a href="/molbeurs/rss.xml" target="_top">RSS</a>
| <a href="/molbeurs/rankings2011.html" target="_top">2011</a>
</form>
</div>
THEEND
}

sub fancyName {
   my ($line) = shift(@_);
   my ($upper);

   if ($line =~ /^([a-z])/) {
      $upper = $1;
      $upper =~ tr/a-z/A-Z/;
      $line =~ s/^./$upper/;
   }
   return($line);
}

sub readPrices {
   %prices = ();
   $file = "$baseDir/prices";
   if (not open(INFILE,$file)) { print "Fout: prijzenbestand onleesbaar\n"; }
   else {
      $noPrices = 1;
      %prices = ();
      while (<INFILE>) {
         $line = $_;
         chomp($line);
         $line =~ /^(\S+)\s(\S+)\s/;
         $prices{$1} = $2;
         $noPrices = 0;
      }
      close(INFILE);
      if ($noPrices) {
         if (not open(INFILE,$file)) { print "Fout: prijzenbestand onleesbaar\n"; }
         else {
            sleep(1);
            while (<INFILE>) {
               $line = $_;
               chomp($line);
               $line =~ /^(\S+)\s(\S+)\s/;
               $prices{$1} = $2;
            }
            close(INFILE);
         }
      }
   }
}

sub fancyStock {
   my ($s,$noHTML) = @_;
   my ($color,@s,$stock,$left);

   if (not defined $noHTML) { $noHTML = 0; }
   $stock = $s;
   $stock =~ /^(.)(.*)\+(.)(.*)$/;
   @s = ($1,$2,$3,$4);
   $s[0] =~ tr/a-z/A-Z/;
   $s[2] =~ tr/a-z/A-Z/;
   if ($s[1] =~ /-([a-z])/) {
      $upper = $1;
      $upper =~ tr/a-z/A-Z/;
      $s[1] =~ s/-./-$upper/;
   }
   if ($stock =~ /mol$/) { $color = $colorM; }
   else { $color = $colorC; }
   $stock = "$s[0]$s[1]&nbsp;$s[2]$s[3]";
   if (defined $left{$s}) { $left = "*"; } else { $left = ""; }
   if (not $noHTML) { $stock = "<a href=\"/molbeurs/stock.php?STOCK=$s\" style=\"color:$color;\" target=\"_top\">$stock$left</a>"; }
   else { $stock = "<a href=\"/molbeurs/stock.php?STOCK=$s\" style=\"color:white;\" target=\"_top\">$stock$left</a>"; }
   return($stock);
}

sub fancyUser {
   my ($user,$html) = @_;
   my ($fancyUser);

   $fancyUser = $user;
   $fancyUser =~ s/\+/&nbsp;/g;
   $fancyUser = lc($fancyUser);
#  if (defined $html and $html >= 0) {
#     $fancyUser = "<a href=\"/molbeurs/user.php?NICKNAME=$user\" style=\"color:white;\" target=\"_top\">$fancyUser</a>";
#  } else {
      $fancyUser = "<a href=\"/molbeurs/user.php?NICKNAME=$user\" target=\"_top\">$fancyUser</a>";
#  }
   return($fancyUser);
}

sub readRankings {
   my ($i,$place,$score,$nickname,$baseUser);

   print <<THEEND;
<td valign="top">
<div style="background-color:$colorU;">
<table cellspacing="5">
<tr>
<th colspan="3" align="left" style="color:white;">Stand <small>(<a href="/molbeurs/rankings.html" style="color:white;" target="_top">compleet</a>)</small>
THEEND
   if (open(INFILE,"$baseDir/www/rankings.html")) {
      $i = 1;
      while (<INFILE>) {
         $line = $_;
         chomp($line);
         if ($line =~ /^<!--\s+(\d+)\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)\s+(.*)\s+-->$/) {
            $place = $1;
            $score = int($2);
            $nickname = $6;
            $nickname =~ s/\s+\d+\.\d+\s*$//;
            # $nickname =~ s/\s/\+/;
            $nickname =~ tr/A-Z/a-z/;
            $baseUser = $nickname;
            $baseUser =~ s/\s/\+/g;
            $nickname =~ s/\s/&nbsp;/g;
            print "<tr><td style=\"color:white;\" align=\"right\"><small>$place.</small><td style=\"color:white;\" align=\"left\"><small><a href=\"/molbeurs/user.php?NICKNAME=$baseUser\" style=\"color: white;\" target=\"_top\">$nickname</a></small><td style=\"color:white;\" align=\"right\"><small>$score</small>\n" if ($i <= $nbrOfCandidates);
            $i++;
            #if ($i > 10) { last; }
         }
      }
      for ($j=$i;$j<=$nbrOfCandidates;$j++) { 
         $j = ($j < $nbrOfCandidates) ? " $j" : $j;
         print "<tr><td style=\"color:white;\" align=\"right\"><small>$j.</small>\n";
      }
#     while (<INFILE>) { 
#        $line = $_;
#        chomp($line);
#        if ($line =~ /^<!--\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(.*)\s+-->$/) { $i++; } 
#     }
#     close(INFILE);
      $nbrOfPlayers = $i-1;
   }
   print "</table></div>\n";
}

sub readTrades {
   my (@files,$dir,$file,$line,$n,$s,$a,$p,$action,@out,$i);
   my $count = 0;
   my $nicknameSpace;

   @out = ();
   %bestBuyProp = ();
   %bestBuyPrice = ();
   %bestSellProp = ();
   %bestSellPrice = ();
   if (not open(INFILE,"grep . /dev/null $baseDir/trades/* 2>/dev/null |")) {
      print "Fout: kan transactiebestanden niet lezen\n";
   } else {
      while (<INFILE>) {
         $line = $_;
         chomp($line);
         $line =~ s/^([^:]*:[^:]*:[^:]*)://;
         $file = $1;
         $file =~ s/.*\///;
         ($d,$action,$n,$s,$a,$p) = split(/\s+/,$line);
         push(@out,"$file $d $action $n $s $a $p -");
         if ($action =~ /buy/i and
             (not defined $bestBuyPrice{$s} or $p > $bestBuyPrice{$s})) {
            $bestBuyPrice{$s} = $p;
            $bestBuyProp{$s} = $#out;
         }
         if ($action =~ /sell/i and
             (not defined $bestSellPrice{$s} or $p < $bestSellPrice{$s})) {
            $bestSellPrice{$s} = $p;
            $bestSellProp{$s} = $#out;
         }
      }
      close(INFILE);
   }
   foreach $i (keys %bestBuyProp) { $out[$bestBuyProp{$i}] =~ s/.$/\+/; }
   foreach $i (keys %bestSellProp) { $out[$bestSellProp{$i}] =~ s/.$/\+/; }
   return(@out);
}

sub checkTrades {
   my (@buy,@sell,@buyPrice,@sellPrice,%othersBuy,%othersSell,@trades,
       $dir,$file,$line,$n,$s,$c,$p,$action,$i,$message);

   %othersBuy = ();
   %othersSell = ();
   #if (open(INFILE,"date '+%H:%M'|")) {
   #   $now = <INFILE>;
   #   chomp($now);
   #    close(INFILE);
   #} else { $now = ""; }
   if (not defined $args{"TRADED"}) {
      @trades = &readPastTrades();
# 20090312
# Recent verhandeld ($now):
# Laatste handelingen:
      if (not defined $args{"BOT"}) {
         if (not defined $args{"BIG"}) {
            $message = "Recent verhandeld ($now): (<a href=\"http://ifarm.nl/molbeurs/index.traded.php\" target=\"_top\">voorstellen</a>, <a href=\"http://ifarm.nl/molbeurs/index.big.php\" target=\"_top\">groot</a>)";
         } else {
            $message = "Recent verhandeld ($now): (<a href=\"http://ifarm.nl/molbeurs/index.traded.php\" target=\"_top\">voorstellen</a>, <a href=\"http://ifarm.nl/molbeurs/\" target=\"_top\">alles</a>)";
         }
      } else {
          if (not defined $args{"BIG"}) {
             $message = "Recent verhandeld ($now): (<a href=\"http://ifarm.nl/molbeurs/index.bot.traded.php\" target=\"_top\">voorstellen</a>, <a href=\"http://ifarm.nl/molbeurs/index.bot.big.php\" target=\"_top\">groot</a>)";
          } else {
             $message = "Recent verhandeld ($now): (<a href=\"http://ifarm.nl/molbeurs/index.bot.traded.php\" target=\"_top\">voorstellen</a>, <a href=\"http://ifarm.nl/molbeurs/index.bot.php\" target=\"_top\">alles</a>)";
          }
      }
   } else {
      @trades = &readTrades();
      if (not defined $args{"BOT"}) {
         $message = "Recente voorstellen ($now): (<a href=\"http://ifarm.nl/molbeurs/\" target=\"_top\">handelingen</a>, <a href=\"http://ifarm.nl/molbeurs/index.big.php\" target=\"_top\">groot</a>)";
      } else {
         $message = "Recente voorstellen ($now): (<a href=\"http://ifarm.nl/molbeurs/index.bot.php\" target=\"_top\">handelingen</a>, <a href=\"http://ifarm.nl/molbeurs/index.bot.big.php\" target=\"_top\">groot</a>)";
      }
   }
   $stock = lc($stock);
   print "<td rowspan=\"2\" valign=\"top\">\n<div>\n<table cellspacing=\"5\" width=\"290\">\n";
#  if ($#trades >= $maxShowTrades) {
      print "<tr><td><small>$message\n";
      for ($i=$#trades;$i>=$#trades-$maxShowTrades;$i--) {
         if ($i<0) { last; }
         ($_,$orgDate,$action,$n,$s,$c,$p,$best) = split(/\s+/,$trades[$i]);
         $n = lc($n);
         $d = &summarizeDate($orgDate);
         $best = ($best eq "-") ? "" : " <font style=\"color:green;\">*</font>";
         if (not defined $args{"TRADED"}) {
            if ($action =~ /buy/i) { $action = "<a href=\"/molbeurs/user.php?NICKNAME=$n\">gekocht</a>"; }
            elsif ($action =~ /sell/i) { $action = "<a href=\"/molbeurs/user.php?NICKNAME=$n\">verkocht</a>"; }
         } else {
            if ($action =~ /buy/i) { $action = "<a href=\"/molbeurs/user.php?NICKNAME=$n\">gezocht</a>"; }
            elsif ($action =~ /sell/i) { $action = "<a href=\"/molbeurs/user.php?NICKNAME=$n\">te koop</a>"; }
            else {
               $action = "";
               if (defined $args{"TRADED"} and $n ne "nobody") { 
                  $best = " (" . &fancyUser($n) . ")"; 
               }
            }
         }
         $fancyStock = &fancyStock($s,0);
         $fancyStock =~ s/didaat(\*?)</$1</; ###
         # trade skipping for slowalfie # 20090108: removed
         # if ($c < 0 and $n eq "slowalfie") { $maxShowTrades++; }
         if (0 and not defined $args{"BOT"} and defined $bots{$n} and $c < 20) { $maxShowTrades++; } 
         else {
            if ($c >= $bigAmount) { $c = "<strong>${c}x</strong>"; }
            else { $c .= "x"; }
            printf "<br> %s: %s $c %s &agrave; %0.2f",
               $d,$action,$fancyStock,$p;
            # check for koopstop
            if (open(INFILE,"grep \"^skipping $orgDate\" $baseDir/logs/logfile|")) {
               $kline = <INFILE>;
               if (defined $kline and $kline =~ /molecount/ and defined $args{"TRADED"}) { 
                  print " &nbsp;<strong><font color=\"red\"><small>M</small></font></strong>"; 
               } elsif (defined $kline and $kline ne "" and defined $args{"TRADED"}) { 
                  print " &nbsp;<strong><font color=\"red\"><small>K</small></font></strong>"; 
               }
               close(INFILE);
            }
            print "\n";
         }
      }
      # for ($i=$maxShowTrades-$#trades;$i>=0;$i--) { print "<br>\n"; }
      if (not defined $args{"TRADED"} and not defined $args{"BIG"} and 
          not defined $args{"MAX"}) {
         print "<br><a href=\"/molbeurs/cgi-bin/standings.cgi?MAX=500\">(meer)</a>\n";
      }

      # added 20100131
      if (defined $args{"TRADED"}) {
         $proposedTrades = $#trades+1;
         @trades = &readPastTrades();
         for ($i=0;$i<10-$proposedTrades;$i++) { print "<br>"; }
         print "<br><br><br><br><br><br>Recent verhandeld ($now):\n";
         $lastDate = "";
         for ($i=$#trades;$i>=0;$i--) {
            if ($i<0) { last; }
            ($_,$d,$action,$n,$s,$c,$p,$best) = split(/\s+/,$trades[$i]);
            $n = lc($n);
            $d = &summarizeDate($d);
            if ($lastDate ne "" and $d ne $lastDate) { last; }
            $lastDate = $d;
            $best = ($best eq "-") ? "" : " <font style=\"color:green;\">*</font>";
            if ($action =~ /buy/i) { $action = "<a href=\"/molbeurs/user.php?NICKNAME=$n\">gekocht</a>"; }
            elsif ($action =~ /sell/i) { $action = "<a href=\"/molbeurs/user.php?NICKNAME=$n\">verkocht</a>"; }
            $fancyStock = &fancyStock($s,0);
            $fancyStock =~ s/didaat(\*?)</$1</; ###
            if ($c >= $bigAmount) { $c = "<strong>${c}x</strong>"; }
            else { $c .= "x"; }
            printf "<br> %s: %s $c %s &agrave; %0.2f\n",
               $d,$action,$fancyStock,$p;
         }
      }
      print "</small>\n";
#  }
   print "</table>\n</div>\n";
}

sub summarizeDate {
   my ($date) = shift(@_);

   if ($date =~ /^.....(..).(..).(..):(..):..$/) {
      $date = "$2-$1 $3:$4";
   }
   return($date);
}

sub readPastTrades {
   my ($line,$date,$stock,$count,$price,$name,@pastTrades);

   @pastTrades = ();
   if (open(INFILE,"$baseDir/logs/logfile")) {
      # input line format: 2007.01.28.00:45:01 dick+mol total: 2 350 151 189
      #                    2007.12.29.21:20:01 edo+mol total: 1 49.99 49.99 49.99 -
      $i = 0;
      while (<INFILE>) {
         $line = $_;
         chomp($line);
         $i++;
         # 20090118 skip early trades to speed up software: does not help
         # if ($i < 8000) { next; }
         if ($line =~ /^20.* (buy|sell) /) {
            ($date,$stock,$action,$count,$price,$_,$_,$name) = split(/\s+/,$line);
            if (not defined $price or $action !~ /^(buy|sell)$/ or 
                $count <= 0) { next; }
            if (defined $args{"BIG"} and $count < $bigAmount) { next; }
            if (not defined $name) { $name = "nobody"; }
            $price /= $count;
            # output line format: $_,$d,$action,$n,$s,$c,$p,$best
            push(@pastTrades,"x $date $action $name $stock $count $price -");
         }
      }
      close(INFILE);
      #splice(@pastTrades,0,$#pastTrades-$maxShowTrades);
   }
   return(@pastTrades);
}

# access counter
sub count {
   my $baseDir = "/WWW/t/tjongkim/htdocs/counter";
   my $pageName = "molbeurs";
   my $count;

   # read counter value
   if (open(INFILE,"$baseDir/$pageName.js")) {
      $count = <INFILE>;
      if (not defined $count) { $count = 0; }
      $count =~ s/^[^"]*"//;
      $count =~ s/"[^"]$"//;
   } else { $count = 0; }
   $count++;

   # write counter value
   open(OUTFILE,">$baseDir/$pageName.js") or exit(0);
   print OUTFILE "document.write(\"$count\");\n";
   close(OUTFILE);
   return();
}

# ip logger
#sub ipLogger {
#   open(OUTFILE,">>$baseDir/logs/ips/now") or return();
#   if (@_) { printf OUTFILE "%d %s %s\n",time(),$ENV{"REMOTE_ADDR"},$_[0]; }
#   else { printf OUTFILE  "%d %s\n",time(),$ENV{"REMOTE_ADDR"}; }
#   close(OUTFILE);
#   return();
#}

