%% genereate_cvc_grid
% generate the queries for cvc for the inputted grid.
%
% inputs:
%   grid:Grid - grid to generate conditions for.
%   level:int - count of the queries generated.
%
% outputs;
%   code:string - string representing code to generate including comments
%   query:cell array - contains string representing both the disjoint and
%   complete without the comments, used for validation report.
% Author: Colin Eles elesc@mcmaster.ca
% Organization: McMaster Centre for Software Certification

function [ code , query] = generate_cvc_grid( container , level, parent_cell, parent_cond)
if nargin == 2
    parent_cell = []
    parent_cond = ''
end

% generate the formulas for the main grid

if isempty(parent_cond);
    disjoint = 'QUERY (';
    complete = 'QUERY (';
else
    disjoint = ['QUERY ' CVC_checker.matlab_to_cvc_syntax_translation(parent_cond) ' => ('];
    complete = ['QUERY ' CVC_checker.matlab_to_cvc_syntax_translation(parent_cond) ' => ('];
end

for i=1:container.get_children_count(parent_cell)
    ith_cond = container.get_child_cell(parent_cell, i).get_matlab_string
  
    for j = i+1:container.get_children_count(parent_cell)
        % compare i to j
        disjoint = [disjoint 'NOT ( (' CVC_checker.matlab_to_cvc_syntax_translation(ith_cond) ') AND (' CVC_checker.matlab_to_cvc_syntax_translation(char(container.get_child_cell(parent_cell, j).get_matlab_string)) ') )'];

        if j~= container.get_children_count(parent_cell)
             disjoint = [disjoint ' AND ' char(10)];

        end

    end
  % need to do pairwise disjointness
    % otherwise doesn't work
    
    
    
    complete = [complete '(' CVC_checker.matlab_to_cvc_syntax_translation(ith_cond) ')'];
    
    if i < container.get_children_count(parent_cell)
        disjoint = [disjoint ' AND ' char(10)];
    end
    
    if i < container.get_children_count(parent_cell)
        complete = [complete ' OR '];
    end
end
disjoint = [disjoint ');'];
complete = [complete ');'];

query = [{disjoint} {complete}];

code = ['ECHO "begin' num2str(level+1) '";' char(10) 'PUSH;'  char(10) disjoint char(10) 'POP;' char(10) 'ECHO "end' num2str(level+1) '";' char(10)];
code = [code 'ECHO "begin' num2str(level+2) '";' char(10) 'PUSH;' char(10) complete  char(10) 'POP;' char(10) 'ECHO "end' num2str(level+2) '";' char(10)];



for i=1:container.get_children_count(parent_cell)
    child_cell = container.get_child_cell(parent_cell, i);
    if container.get_children_count(child_cell) ~= 0
        [new_code,new_queries] = CVC_checker.generate_cvc_grid(grid.cells(i).subgrid,level+2, child_cell);
        code = [code new_code];
        query = [query new_queries];
        level = size(query,2) - 2;
    end

end

    




end

