function [nstate flag] = getpacemakerstate( iTP, iIM, cstate, act )
%Gets the next state from the PACEMAKER model
% iTP - input transition matrix
% iIM - input pointer matrix
% act - input actions
% nstate - output the next state
% flag - if flag=0 then synchronize if flag=1 the imediate action

% Get the index of the state
idx = iIM(cstate+1);
nstate = -1;
imm_nstate = -1;

flag=0;

% Array for indices arr(1)=Aget, arr(2)=Vget, arr(3)=AP, arr(4)=VP
arr=ones(5,1).*-1;

while iTP(idx,1)==cstate,
    
    % Check for the immediate action tau, AS, VS
    if iTP(idx,3)==5 || iTP(idx,3)==6 || iTP(idx,3)==7,
        imm_nstate = iTP(idx,2);
    end
    
    % Check for the synchronization action
    %if act==4 && iTP(idx,3)==2,
    %    nstate=iTP(idx,2);
    %    break;
    %elseif act==3 && iTP(idx,3)==1,
    %    nstate=iTP(idx,2);
    %    break;
    %elseif iTP(idx,3)==act,
    %    nstate=iTP(idx,2);
    %    break;
    %end
    if iTP(idx,3)==1,
        arr(1)=idx;
    elseif iTP(idx,3)==2,
        arr(2)=idx;
    elseif iTP(idx,3)==3,
        arr(3)=idx;
    elseif iTP(idx,3)==4,
        arr(4)=idx;
    elseif iTP(idx,3)==0,
        arr(5) = idx;
    end
    idx=idx+1;
end

% Give priority to the immediate action
if imm_nstate~=-1,
    nstate=imm_nstate;
    flag=1;    
else
    if act==2 && arr(2)~=-1,
        nstate=iTP(arr(2),2);
        flag=2;
    elseif act==1 && arr(1)~=-1,
        nstate=iTP(arr(1),2);
        flag=2;
    elseif act==4 && arr(4)~=-1,
        nstate=iTP(arr(4),2);
    elseif act==3 && arr(3)~=-1,
        nstate=iTP(arr(3),2);
    elseif act==0 && arr(5)~=-1,
        nstate=iTP(arr(5),2);
        flag=2;
    end
end

    %    nstate=iTP(idx,2);
    %    break;
    %end
    
end
    
% If there is no synchronization return the possible immediate action
%if nstate==-1 && imm_nstate~=-1,
%    nstate=imm_nstate;
%    flag=1;
%end
