function [ onLatencies, offLatencies ] = LSLEventTimingAnalysis(allDataStreams)

    eegStreamNumber = 1;
    eegChannelNumber = 1;
    stdThreshold = 7.5;
    markerStreamNumber = 2;
   % onEvent = '4';
    onEvent = '/Experiment Control/Synchronization/Trigger/Biosemi';
    preTime = .010;
   
    
    samplingRate = allDataStreams.item{eegStreamNumber}.samplingRate;

    eeg =  allDataStreams.item{eegStreamNumber}.data(:,eegChannelNumber); 
    eegTime = allDataStreams.item{eegStreamNumber}.timeStamp;
    eventLatencies = allDataStreams.item{markerStreamNumber}.timeStamp;
    eventVals = char(allDataStreams.item{markerStreamNumber}.event.label);
    eegStd = std(eeg);
    eeg = (eeg-mean(eeg));
    figure;
    hold all;
    plot(eegTime, eeg/eegStd, 'color', 'blue');
    leg = legend('EEG');
    set(leg,'Location', 'NorthEast');
    set(leg,'Interpreter', 'None');
    
    xlabel('Time (s)');
    ylabel('Amplitude / Standard Deviation');
    eegIndex = 1;
    
    onLatencies = zeros(1,length(eventLatencies));
    offLatencies = zeros(1,length(eventLatencies));
    onTimes = zeros(1,length(eventLatencies));
    onCount = 0;
    for i=1:(length(eventLatencies)) 
        if strcmp(strtrim(eventVals(i,:)),onEvent)
             
            onCount = onCount + 1;

            line([eventLatencies(i),eventLatencies(i)], get(gca,'Ylim'), 'color','r')
            while eegIndex < length(eeg) && (eegTime(eegIndex) < eventLatencies(i)-preTime || eeg(eegIndex)/eegStd < stdThreshold) 
                eegIndex = eegIndex + 1;
            end
            %interpolate
            onLatencies(onCount) = eegTime(eegIndex-1) + (eegTime(eegIndex) - eegTime(eegIndex-1))*(stdThreshold*eegStd-eeg(eegIndex-1))/(eeg(eegIndex)-eeg(eegIndex-1))-eventLatencies(i);
            %onLatencies(onCount) = eegTime(eegIndex) - eventLatencies(i);
            onTimes(onCount) = eegTime(eegIndex);
        end
        

        
        
    end
    
    onLatencies = onLatencies(1:onCount);
    onTimes = onTimes(1:onCount);
    line(get(gca,'Xlim'),[stdThreshold,stdThreshold],'color','red');
    hold off
    

    histFig( onLatencies*1000, 'Latency (ms)' );
    
    figure
    plot(onTimes,1000*(onLatencies));
    ylabel('Latency (ms)');
    xlabel('Time (s)');
    
end

