function [ TH, c_state_HEART ] = transitions( C_STATE, N_STATES, AS, VS )
% Form the transition matrix for the HEART
% Initialize the transition matrix
% A_GET = 1
% V_GET = 2
% time = 0

TH=zeros(N_STATES,3);

% Create the transition matrix
cnt_A=1;
cnt_V=1;
A_V_event=0;

% counter for the rows of the transition matrix
cnt_th=1;
cnt_state=C_STATE;
for i=1:N_STATES-1,
    
    % Check for both Atrium and Ventricle starting event
    if cnt_A<=size(AS,1) && cnt_V<=size(VS,1),
        if i+1==AS(cnt_A) && i+1==VS(cnt_V),
            error('Error: two events at the same time');
        end
    end
    
    % Check for the Atrium starting event
    if cnt_A<=size(AS,1) && A_V_event==0,
        if i+1==AS(cnt_A),
            % Predecessor state
            TH(cnt_th,1)=cnt_state;
            
            % Successor state
            TH(cnt_th,2)=cnt_state+1;
            
            % Action
            TH(cnt_th,3)=1;

            cnt_th=cnt_th+1;
            
            cnt_A=cnt_A+1;
            A_V_event=1;
        end
    end
    
    % Check for the Ventricle starting event
    if cnt_V<=size(VS,1) && A_V_event==0,
        if i+1==VS(cnt_V),
            % Predecessor state
            TH(cnt_th,1)=cnt_state;
            
            % Successor state
            TH(cnt_th,2)=cnt_state+1;
            
            % Action
            TH(cnt_th,3)=2;

            cnt_th=cnt_th+1;
            
            cnt_V=cnt_V+1;
            A_V_event=1;
        end
    end
    
    if A_V_event==0,
            % Predecessor state
            TH(cnt_th,1)=cnt_state;
            
            % Successor state
            TH(cnt_th,2)=cnt_state+1;
            
            % Action
            TH(cnt_th,3)=0;

            cnt_th=cnt_th+1;
    end
    A_V_event=0;
    
    % increment the state number
    cnt_state=cnt_state+1;
end

% Add a transition from the last state to the first state

% Predecessor state
TH(cnt_th,1)=cnt_state;
            
% Successor state
TH(cnt_th,2)=C_STATE;
            
% Action
TH(cnt_th,3)=0;

% Set the initial state of the HEART to 0
c_state_HEART=C_STATE;
end
