clear all
win=7-1;
valid=150;
posOld=0;
th1=25;
th2=75;
fid=fopen('putty.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;
i=2;
while(i<length(data1))
    if (data1(i)>= data1(i-1) && data1(i)>= data1(i+1)) %local maximum
        mymax=data1(i);
        if mymax-mymin>valid
        %light up a led here
            i
            th1
            th2
         %  pause
            % 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=25;  %change back to previous thresholds
                th2=75;
                valid=150;
            end
            posOld=i;
            
            if (j==5) %five regular pulses in a row, light up a led here
                j=0;
                th1=sum(intv)/5-10;
                th2=sum(intv)/5+10;
                valid=sum(amp)/5*1/3;
                for mm=1:5
                    ff(pos(mm))=1;
                end
                    
            end
        end
        i=i+3; %solution for flat top 
    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)


            
            

