function S = BuildSupervisor(Gobs,SGobs,R,SR)
%Gsup = BuildSupervisor(Gobs,SGobs,G,SG)
%INPUTS:
%Gobs = observer automata (as imported by UMDES2MATLAB)
%SGobs = state names of observer automata (as imported by UMDES2MATLAB)
%G = original automata from which observer was created
%SG = state names of R (as imported by UMDES2MATLAB)
%OUTPUTS:
%Gsup = supervisor FSA, state are in the same order as in Gobs

nG = length(Gobs);
nR = length(R);

S = Gobs;
StNumR = zeros(nR,1);
for i = 1:nR
    StNumR(i) = str2num(SR{i});
end

for i = 1:nG
    cS = regexp(SGobs{i},',','split');
    %find states in R
    for j = 1:length(cS)
        cSj = str2num(cS{j});
        cSR = find(StNumR==cSj);
        for k = 1:length(cSR)
            for k2 = 1:length(R(cSR(k)).events)
                if R(cSR(k)).obs(k2) == 0
                    flag = 0;
                    nCES = length(S(i).events);
                    for k3 = 1:nCES
                        if strcmp(S(i).events{k3},R(cSR(k)).events{k2})
                            flag = 1;
                        end
                    end
                    if flag == 0
                        S(i).events{nCES+1} = R(cSR(k)).events{k2};
                        S(i).ter(nCES+1) = i;
                        S(i).con(nCES+1) = R(cSR(k)).con(k2);
                        S(i).obs(nCES+1) = 0;
                    end
                end
            end
        end
    end
end