#!/usr/bin/perl -w

use strict;

my $DEBUG = 0;
my $new_score = int(rand(10000));
my $new_name = "Newbie" . int(rand(23));

## get current high score list
open (LIST, "scores.log");
my $str = <LIST>;
close LIST;

## split list into score:name
my @pairs = split(/\^/, $str);
print "pairs[0] = $pairs[0]\n" if $DEBUG;
print "pairs[1] = $pairs[1]\n" if $DEBUG;
print "pairs[2] = $pairs[2]\n" if $DEBUG;

## add new entry to list
my $new_pair = $new_score . ":" . $new_name;
print "new_pair = $new_pair\n" if $DEBUG;
push @pairs, $new_pair;

## sort list
my @sorted = sort{$b <=> $a} @pairs;
if ($DEBUG) {
	my $count = 0;
	while ($sorted[$count]) {
		print "$count = $sorted[$count]\n";
		$count++;
	}
}

## drop lowest
pop (@sorted);
if ($DEBUG) {
	my $count = 0;
	while ($sorted[$count]) {
		print "post pop: $count = $sorted[$count]\n";
		$count++;
	}
}

## split and print score/name pairs
my @tmp;

print "Rankings:	Score:	Name:\n";

foreach my $loop (0..9) {
	@tmp = split(/\:/, $sorted[$loop]);
	my $rank = $loop+1;
	if ($rank == 10) {
		print "Rank $rank\:	$tmp[0]	$tmp[1]\n";
	} else {
		print "Rank $rank\:		$tmp[0]	$tmp[1]\n";
	}
}

## clear current highs.log
open(TMP, "+>scores.log");
close TMP;

## write new high score list
my $new_str = join('^', @sorted);
$new_str =~ s/\n//;

open(NEW, "+>>scores.log");
print NEW "$new_str"; 
close NEW;
