#!/usr/bin/perl

# create header for text document to return
print "Content-type: text/html\n\n";

# set filename for highscore database
$filename = "highscore.txt";

# read high score data
open(DATABASE,$filename) || exit;
@score_text = <DATABASE>;
close(DATABASE);

# get the server time
$server_time = time();

# how long to keep the scores
# (7 days * 24 hours * 60 minutes * 60 seconds)
$keep_time = 7*(24*60*60);

# open database file for writing
open(DATABASE,">" . $filename) || exit;

# loop through each score
foreach $score_line (@score_text) {
  # get score data
  @score_item = split(/&/,$score_line);
  # get score time
  $score_time = $score_item[2];
  # if the score is not old, write it back out again
  if ($score_time > ($server_time-$keep_time)) {
    print DATABASE "$score_line";
  }
}

#close database
close(DATABASE);

# sort scores
@score_text = sort { $b <=> $a } @score_text;

# determine number of scores to send
$num_scores = 10;
$score_count = 1;

# loop through first scores and send the data
print "highScoresText=";
foreach $score_line (@score_text) {

   # take post data and create an array of data
   @split_data = split("&",$score_line);
   # output the line number plus a period
   printf("%2i. ", $score_count);
   #output the player's name, left justified, padded to 18 spaces
   printf("%-18s ",$split_data[1]);
   #output the score, right justified, padded to 9 spaces
   printf("%9i\n",$split_data[0]);
   $score_count++;
   if ($score_count > $num_scores) { last; }
}

#exit script
exit;
