function[eventliston,eventlistoff] = tagevents(pvec,triglevel,detrig,dtoff)
% given the power file, do a hysterisis trigger
%   [eventliston, eventlistoff] = tagevents(pvec,triglevel,detrig,dtoff)
%      inputs:  pvec the power vector
%               triglevel  power limit to identify an event
%               detrig   don't untrigger unless drop below this
%                  detrig should be lower than triglevel
%               dtoff time in samples allowed between off of previous and
%                       on of next event;
%      outputs:  eventliston  the list of events each one
%                   listed by index in timevec so each entry is an index
%                eventlistoff off indices
% problem, two events are going to be confused

ns = length(pvec);
k=1;
trigger = 0;
eventliston = pvec*0.0;
eventlistoff = pvec*0.0;

%dtrig = triglevel*0.1;
for i =1:ns;
    if ((pvec(i) > triglevel) & (trigger == 0));
        if  (((k>1) & (i>eventlistoff(k-1) + dtoff)) | (k==1));
            trigger = 1;
            eventliston(k) = i;  % store indexes for event starts
            k=k+1; % next event
        end
    end
    if (trigger ==1); 
        if (pvec(i) < detrig);
            trigger = 0;
            eventlistoff(k-1)=i;
        end
    end  
end
if (trigger == 1) 
    eventlistoff(k-1) = ns;
end
eventliston = eventliston(1:k-1);
eventlistoff = eventlistoff(1:k-1);
length(eventliston)