function failed = sudokucheck(map,possible)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function checks if the puzzle is solved properly.  Also works on
% incomplete puzzles to see if there is a logical flaw.
%
% MAP is the sudoku puzzle at the current state of completion
% POSSIBLE is the array of possible lovations for a particular value.
% It's logical but rather than using 0 and 1 it uses the NaN and the actual
% value.
% modified by Dave Campbell dac5@sfu.ca Mar 1, 2014
% 
% 
% This code is released under the GPLv3 license.
% See http://www.gnu.org/licenses/gpl.html for details.
% 
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
% 
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
% 
%     Find a copy of the GNU General Public License
%     here http://www.gnu.org/licenses/
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

failed = 0;
value = 0;

while value<9 && failed ==0
    value = value+1;
    for row = 1:9
        if sum(map(row,:)== value) <= 1 % value is ok in the row
            for column = 1:9
                if sum(map(:,column)== value) <= 1%value is ok in this column
                    block = (floor((row-1)/3) )*3+ceil(column/3);
                    blockuse = map(floor((block-1)/3)*3+(1:3), mod( (block-1)*3+(1:3)-1,9)+1);
                    if  sum(blockuse(:) ==value) > 1% value is NOT ok in the block
                        failed = failed+1
                        [value,row,column,block]
                    end
                else
                    failed = failed+1
                    [value,row,column]
                end
            end
        else
            [value,row]
            failed = failed+1
        end
    end
end
