#/usr/bin/perl

sub winner_mullin {
    my $my_stones        = $_[0] ;
    my $opponents_stones = $_[1] ;
    my $remaining_stones = $_[2] ;
    my $maximum_at_once  = $_[3] ;

    if ( $remaining_stones == 1 ) {   # If we have no choice...
        return 1 ;
    }

    # Make sure we have an odd number of stones and end the game
    if ( $maximum_at_once >= $remaining_stones ) {  
        if ( ($my_stones+$remaining_stones)%2 == 0 ) {
            return ($remaining_stones-1);
        } else {
            return $remaining_stones;
        }
    }

    # now we have to think about what we are doing
    # we construct a list of the losing positions and
    # try to pick a move that will leave the opponent
    # in one of them.  If we cannot, we are the losers
    # See README for more details.

    my $modulus,@losers,@targets;

    if ($maximum_at_once%2==0) {
        $modulus = $maximum_at_once+2;
        @losers = ([0,$maximum_at_once+1],[1]);
    } else {
        $modulus = 2*$maximum_at_once+2;
        @losers = ([0,$maximum_at_once+2],[1,$maximum_at_once+1]);
    }
    @targets = @{$losers[opponents_stones]};
    # now @targets holds the losing positions we want to put our opponent in
    $remaining_stones %= $modulus;
    @targets =
        grep((1+($remaining_stones-$_+$modulus-1)%$modulus)<=$maximum_at_once,
             @targets);
    # now @targets hold those losing positions we can actually reach
    # if there are none, we just return a random move; if there are
    # we return a random one of them
    if (!@targets) {
        return (1+(int rand($maximum_at_once)));
    } else {
        return 1+($modulus+$remaining_stones-
                  $targets[int rand($#targets+1)]-1)%$modulus;
    }
}
