clear all
win=18-1;
valid=50;  %a very small initial value
posOld=0;
th1=120;  %corresponding to 120bpm
th2=240; %corresponding to 50bpm
fid=fopen('putty2.log','r');

data=fscanf(fid, ['%d' ' ']);

fclose(fid);
figure(1)
plot(data)
%%

%
for i=1:(length(data)-win)
    data1(i)=sum(data(i:(i+win)));
end
figure(2)
plot(data1)

ff=zeros(1,length(data1));
j=0;

mymax=0;
mymin=0;
tolerance = 300; 
i=2;
while(i<length(data1))
    vv(i)=valid;
    if (tolerance>0)
        tolerance=tolerance-1;
    end
    
    if tolerance==0  %after 1.5 seconds, could not detect any valid pulse
        if valid > 100
            valid=valid-100;  %decrease valid
        end
    end
    if (data1(i)>= data1(i-1) && data1(i)>= data1(i+1)) %local maximum
        mymax=data1(i);
        if mymax-mymin>valid
            tolerance=300;
            valid=(mymax-mymin)/2;  % update valid as the 1/2 of the current difference
            %light up a led here
            % check whether it is regular pulse
            if i-posOld>th1 && i-posOld< th2
                j=j+1;
                amp(j)=mymax-mymin;
                pos(j)=i;
                intv(j)=i-posOld;
            else
                j=0;
                th1=120;  %change back to previous thresholds
                th2=240;
                valid=50;  %keep this or not?
            end
            posOld=i;
            
            if (j==3) %three regular pulses in a row, light up a led here
                j=0;
                th1=sum(intv)/3-30;
                th2=sum(intv)/3+30;
             %   valid=sum(amp)/5*1/3;
                for mm=1:3
                    ff(pos(mm))=1;
                end
                    
            end
        end
        i=i+3; %solution for flat top 
        if i>=length(data1)
            break;
        end
    end
        
    if (data1(i)<= data1(i-1) && data1(i)<= data1(i+1)) %local minimum
        mymin=data1(i);
        i=i+3; %solution for flat bottom
    end
    i=i+1;
end

figure(3)
plot(ff)

figure(4)
plot(vv)


            
            

