% Input:
% string: string (containing the textual encoding of a locations flow)

% Output:
% variables: cell array of strings (containing the names of the flow
% variables)
% euqations: cell array of strings
% input: cell array of strings (containing the names of the input
% variables)
% C: matrix (row-wise constraints of the invariant - from C*x <= d)
% d: vector (values d from the invariant description C*x <= d)

% Description:
% Divides a string encoding the flow in a set of flow-variables, equations
% and input-variables (U) and extracts the invariants

function [variables,equations,input,C,d] = parseFlow(string)

parts= splitInput(string,',');
if length(parts) == 2
    string = parts{2};
elseif length(parts) ~= 1
    error('A state contains too many ,');
end;

lines = splitInput(string,'&');
input = cell(1);

% extract variable names
variables = cell(1);
equations = cell(1);
expression = '[abcdefghijklmnopqrstuvwxyz]\w*"';
exp = sprintf('[a-zA-Z]+([0-9a-zA-Z]*)');
for i=1:1:length(lines)
    
    lines{i} = simplesyntaxcheck(lines{i});
    
    [c,~,e] = regexp(lines{i},expression,'match','ignorecase');
    
    if isempty(c)
        error(sprintf('Syntax error in the flow definition at %s',lines{i}));
    else
        name = c{1};
        variables{i} = name(1:length(name)-1);
        equations{i} = lines{i}(e+3:length(lines{i}));
    end;    
end;

% extract names of input variables
for i=1:1:length(equations)
    
    text = regexp(equations{i},exp,'match');
    
    %the entries from text not being in variablesare added to input
    for j=1:1:length(text)
        hit = false;
        
        for k=1:1:length(variables)
            if strcmp(text{j},variables{k})
                hit = true;
                break;
            end;
        end;
        
        if ~hit
            if isempty(input{1})
                input{1} = text{j};
            else
                input{length(input)+1} = text{j};
            end;
        end;
    end;
end;

% read invariants
if length(parts) == 2
    [C,d] = transformExplicitPolyhederInputSet(parts{1},variables,false);
else
    C = [];
    d = [];
end;

