%% evaluate_counter_grid
%    function will evaluate a counter example for a given grid.
% inputs:
%   object:GUI - current GUI object
%   grid:Grid - the grid to evaluate
%   counter:string - string representing the counter example, ie.
%       'x = 3\ny = 5'
% outputs:
%   problem:boolean - 1 if grid has overlapping or underspecified
%       cells, 0 if not.
% Author: Colin Eles elesc@mcmaster.ca
% Organization: McMaster Centre for Software Certification
function problem = evaluate_counter_grid(object,grid,counter)
% split the list of inputs to get inputs seperatly
inputs = get(object.function_inputs_control,'String');
inputs2 = [];
for i=1:size(inputs,1)
    inputs2 = [inputs2 inputs(i,:)];
end
inputs2 = regexprep(inputs2,'\s','');
inputs = regexp(inputs2,',','split');
check_string = [];

% keep track of the number of condtitions that evaulate to true
true_conds = 0;
sub_problem = 0;
problem = 0;
empty_cell = 0;
% initialize inputs to zero
% functions are assumed to be total, so 0 is just for
% convienence
for i=1:size(inputs,2)
    % set to zero
    
    %need to parse the types out of the inputs
    inputi = regexp(char(inputs(i)),'\w*','match','once');
    check_string = [check_string sprintf('%s=0;\n',char(inputi))];
end

check_string = [check_string counter sprintf('\n')];
for i=1:size(grid.cells,2)
    condition_string = get(grid.cells(i).cond,'string');
    
    if size(condition_string,1) > 0
        s = [condition_string(1,:)];
        for j = 2:size(condition_string,1)
           s = [s ' ' condition_string(j,:)];
        end
        condition_string = s;
    end
    
    if(~isempty(condition_string))
        
        eval([check_string  'result =(' char(condition_string) ');'])
        if(result == 0)
            grid.cells(i).flag_cell(1);
        else
            true_conds = true_conds + 1;
            
            grid.cells(i).flag_cell(2);
        end
    else
        empty_cell = 1;
    end
end

if (true_conds == 1)
    for i=1:size(grid.cells,2)
        condition_string = get(grid.cells(i).cond,'string');
        if(~isempty(condition_string))
            
            eval([check_string  'result =(' char(condition_string) ');'])
            if(result == 0)
                grid.cells(i).flag_cell(1);
            else
                
                if (~isempty(grid.cells(i).subgrid))
                    sub_problem = object.evaluate_counter_grid(grid.cells(i).subgrid,counter);
                end
                grid.cells(i).flag_cell(2);
            end
        else
            empty_cell = 1;
        end
    end
end


if (true_conds ~= 1 || sub_problem == 1)
    problem = 1;
end

if (empty_cell)
    problem = 0;
end

end