+ $stage++;
+ countballots();
+
+ my @maybe_elect = reverse sort total_history_cmp keys %cands;
+ my $nelect=0;
+ for (;;) {
+ my $nextcand = $maybe_elect[$nelect];
+ my $nextc = $cands{$nextcand};
+
+ # We certainly only consider those who meet quota
+ last unless $nextc->{Total} >= $quota;
+ last unless $nextc->{Total} > $quota && $nextel;
+ # ... if equal we can do them one by one, since order
+ # does not matter (SLGEO 49 talks about `two or more ... exceeds')
+
+ last if $nelect &&
+ (total_history_cmp $maybe_elect[0], $nextcand) > 0;
+ # ... only interested in those who compare equal
+ # according ot the history (SLGEO 49(2)); NB our history
+ # includes the current round.
+
+ $nelect++;
+ }
+
+ if ($nelect) {
+ my $elect;
+ if ($nelect > 1) {
+ my @all = @maybe_elect[0 .. $nelect-1];
+ my $elect = $tie{"@all"}{Win};
+ die "need tie break, want winner from @all" unless defined $win;
+ prf "electing %s due to tie break amongst %s\n",
+ $elect, "@all";
+ } else {
+ $elect = $maybe_elect[0];
+ prf "electing %s\n";
+ }
+
+ prf "*** ELECT %s ***\n", $elect;
+ $c->{Continuing} = 0;
+ votelog $_, "helped elect $elect" foreach @{ $c->{Votes} };
+
+ # SLGEO 48
+ my $c = $cands{$elect};
+ my $surplus = $c->{Total} - $quota;
+
+ if ($surplus <= 0) {
+ prf "no surplus\n";
+ next;
+ }
+
+ my $B = $c->{Weight};
+
+ foreach my $v (@{ $c->{Votes} }) {
+ my $A = $surplus * $v->{Weight};
+ my $F = 100000;
+ my $xfervalue = floor(($A * $F) / $B) / $f;
+ # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
+ # but always rounding down
+ votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
+ $v->{Weight} = $xfervalue;
+ sortballots $v;
+ }
+ $c->{Votes} = { }; # will crash if we access it again
+ next;
+ }
+