#vim: ts=4

package EGFRating;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(rating_delta);
@EXPORT_OK = qw(con_by_gor a_by_gor $par_e);

our $par_e = 0.016; # Old: 0.014
our $maxdrop = 100; #not used here

sub con_by_gor {
	my $gor = shift;
	if ($gor >= 2700) {
		return 10;
	} else {
		my @data = (116, 110, 105, 100, 95, 90, 85,
			80, 75, 70, 65, 60, 55, 51, 47, 43, 39,
			35, 31, 27, 24, 21, 18, 15, 13, 11, 10);
		my $base = int ($gor / 100) - 1;
		return $data[$base] + (($gor % 100) / 100) *
			($data[$base + 1] - $data[$base]);
	}
}
	
sub a_by_gor {
	my $gor = shift;
	if ($gor >= 2700) {
		return 70;
	} else {
		return (4100 - $gor) / 20;
	}
}

sub rating_delta {
	my $gor1 = shift;
	my $gor2 = shift;
	my $result = shift;
	my $handicap = shift;
	my ($a, $winexp);
	if ($handicap != 0) {
		if ($gor1 < $gor2) {
			$a = a_by_gor($gor1);
			$winexp = 1 / (exp(($gor2 - $gor1 + ($handicap-0.5)*100)
				/ $a) + 1);
		} else {
			$a = a_by_gor($gor2);
			$winexp = 1 - $par_e - 1 / (exp(($gor1 - $gor2 -
				($handicap-0.5)*100) / $a) + 1);
		}
	} else {
		if ($gor1 < $gor2) {
			$a = a_by_gor($gor1);
			$winexp = 1 / (exp(($gor2 - $gor1) / $a) + 1);
		} else {
			$a = a_by_gor($gor2);
			$winexp = 1 - $par_e - 1 / (exp(($gor1 - $gor2) / $a) + 1);
		}
	}
	return con_by_gor($gor1) * ($result - $winexp);
}
