% Finds the arrival time of a cluster of waves, by finding where the pulses
% cross a constant fraction threshold

function [atime,FWHM,risetime,aindex] = findCFThreshold(signal,time,CFthreshold)
%    plot(signal)
%    display(time)
    atime=1;
    FWHM=1;
    risetime=1;
    aindex=1;
    [size_a,size_b] = size(signal);
 
    if( (size_a>1) && (size_b>1) )
       
        error('Array is not a 1-D time series!! Cannot find max!');
        
    end
    
    size1 = size_a;
    if(size_b>size_a) 
        size1=size_b;
    end
    
    [vmax,imax] = max(signal);

    realthreshold=CFthreshold*vmax;
    halfthreshold=0.5*vmax;
    lowthreshold=0.25*vmax;
    highthreshold=0.9*vmax;
    
%    if(size_a>max(signal)) 
%        size1=size_a;
%    end


%    preston=threshold
%    qbert=size1

    gotThresh=0;
    gotUpHalf=0;
    gotDownHalf=0;
    gotLowCross=0;
    gotHighCross=0;
    icross=0;
    ilowcross=0;
    ihighcross=0;
    ihalfcross1=0;
    ihalfcross2=0;
     

    for j=1:size1;

        
 %       kadie=signal(j)

        if( ( signal(j) > realthreshold ) && (gotThresh==0) )
            icross=j;
            gotThresh=1;
        end
        
        if( ( signal(j) > lowthreshold ) && (gotLowCross==0) )
            ilowcross=j;
            gotLowCross=1;
        end
                
        if( ( signal(j) > highthreshold ) && (gotHighCross==0) )
            ihighcross=j;
            gotHighCross=1;
        end

        if( ( signal(j) > halfthreshold ) && (gotUpHalf==0) )
            ihalfcross1=j;
            gotUpHalf=1;
        end
        
        if( ( signal(j) < halfthreshold ) && (gotUpHalf==1) && (gotDownHalf==0))
            ihalfcross2=j;
            gotDownHalf=1;
        end

    end
    
%    FWHM = (time(ihalfcross2) - time(ihalfcross1));
    FWHM = 1;
    risetime = (time(ihighcross) - time(ilowcross));
    atime = time(icross);
    aindex = icross;
    
 end