function winner = iswinner(turn, table)
%  ISWINNER  Check the end condition of the game.
%  ISWINNER(TURN, TABLE), where TURN specifies the current player, and
%  TABLE represents the current table configuration of Seven, returns
%  the player's number if the game is over and 0 otherwise.
%  THIS FUNCTION UPDATES GLOBAL VARIABLES.


global PLAYER;


%
%  The game ends if a player runs out of cards or if a player can can play
%  every card in his/her hand, aka "going out". 
%
winner = 0;
tmphand = PLAYER{turn};
tmptable = table;

%
%  Pretend there is only one player, and check whether he/she could
%  play all of his/her cards, so that the hand becomes empty.
%
moves = findmoves(tmphand, tmptable);
while ~isempty(moves)
    [X, Y] = size(moves);
    for i = 1:Y
        [tmphand, tmptable] = makeplay(tmphand, tmptable, moves(i));
    end
    moves = findmoves(tmphand, tmptable);
end

%
%  If the hand is empty after playing a mock single player game,
%  then the player can "go out" and so he/she wins.
%
if isempty(tmphand)
    winner = turn;

%
%  Otherwise, check if any players have empty hands.  If so, assign
%  that player the winner state.
%
else
    for i = 1:3
        if (isempty(PLAYER{turn}) & (winner == 0))
	    winner = turn;
	end
        turn = mod(turn, 3) + 1;    
    end
end
