function [St,Co,Alg] = StateStructure(x)
%script for automatic modular state structure computation (outputs St and Co)
%[St,Co] = StateStructure(xst)
%inputs:
%xst: state structure enetered in getNetworkPars
%outputs:
%St: state assignment to modules; St(i,:) = [ni1 ni2], where x(ni1) is the
%first state of module i and x(ni2) is the last state of module i
%Co: is the connection matrix; Co(i,:) = [mod1 st1 mod2 st2], where mod1 and mod2 
%are two modules sharing states that are enumerated st1 and st2 in their
%respective modules
%Alg: vector of logical values; Alg(i) = 0 if state x(i) is algebraic

St = zeros(size(x,1),2); 
ni = 0;
for i = 1:size(x,1)
    St(i,:) = [ni+1,ni + length(x{i,1})];
    ni = St(i,2);
end

ni = 0;
for i = 1:size(x,1)
    for j = 1:length(x{i,1})
        for k = i+1:size(x,1)
            if sum(strcmp(x{i,1}{j},x{k,1})) > 0
                checked = 0;
                for k2 = 1:i-1
                    if sum(strcmp(x{i,1}{j},x{k2,1})) > 0
                        checked = 1;
                    end
                end
                if checked == 0
                    ni = ni + 1;
                    Co(ni,:) = [i j k find(strcmp(x{i,1}{j},x{k,1}))];
                end
            end
        end
    end
end

%reorganize system algebraic and continuous states
Alg = [];
for i = 1:size(x,1)
    Alg = [Alg strcmp(x{i,2},'C')];
end