function [error] = monitor(MX, max_tolerance_bra, max_tolerance_tach)
% The monitor function is used to check that there have been the right
% number of heart beats, which is between 60 and 100, in a window of 1
% minute

% MX = matrix to check

% Labels
% Aget = 1
% Vget = 2
% AP = 3
% VP = 4
% time = 0
% tau = 5
% AS = 6
% VS = 7
% AR = 8

% error - boolean value telling if an error has been found
% delta = discretization step, in our case, 2ms
delta = 2;

% window = number of time steps in 1 minute
window = (1*60*1000)/delta;

% count = variable containing the number of Vgets in the last minute
count=0;

% Setting the variable error to false
error=0;

% Storing rows and columns of MX
[rows column] = size(MX);

% first = starting point of the window
first = 1;

% Check on the first window
for i=1:window
    if((MX(i,3)==2 || MX(i,3)==4)), count=count+1;
    end
 end

if(count<max_tolerance_bra || count>max_tolerance_tach), error=1;
end

% Start to check the one minute window from the first time step
for i=window+1:rows
    if((MX(i,3)==2 || MX(i,3)==4) && (MX(first,3)~=2 && MX(first,3)~=4 )), count=count+1;
    end
    if((MX(i,3)~=2 && MX(i,3)~=4) && (MX(first,3)==2 || MX(first,3)==4)), count=count-1;
    end
    if(count<max_tolerance_bra || count>max_tolerance_tach), error=1;
    end
   first=first+1; 
end
