function[stdt,mean_snn]=edge_stat(fy,snn,maxsig,t0,i0,stat);
%
% tstep=math time step, n=number of math time steps
% tau = peaking time (number of samples), sn=signal/noise ratio, 
%
[tstep,trise,tfall,gain,NPE,Qshot,G,nadc,bw,tau,T,R,fs,ts,apjit]=params();
[m,thresh,hyst]=edge_params(maxsig);
% [G,nadc,tau,elec_noise,tstep]=elec_params()
n=size(fy(1,:),2);
clear stdt;
clear figure(1);
clear mean_snn;
cumsn=0; sni=0; time=zeros(1,stat); t=zeros(stat,m); time=zeros(stat,m);
for i=1:stat
    disp('Evt '); i
       if snn(i)~=inf
           cumsn=cumsn+snn(i); sni=sni+1;
       end;
% Absolute thresholds. Multiple thresholds on signal-pedestal
%
tt=1;
% i=1:stat   j=1:size(thresh)
   for j=1:m
      ts=find(fy(i,(1:round(size(fy(i,:),2)/3))) >= thresh(j));
      tt=min(ts); round(size(fy(i,:),2)/4);
      if size(tt,2)==0;
          disp('Threshold too high');
          i
          return
      end
      t(i,j)=tt;
      % Remove NaN's
      p=1;
      if isnan(time(i,j));
        disp('isNaN');
        t(i:stat-1,j)=t(i+1:stat,j); t=t(1:stat-p,j);
        p=p+1;
      end
   end
   
   % Absolute time units
   xth=0:tstep:(size(fy,2)-1)*tstep;
   if i==stat
      % figure(1); 
      % plot(xth,fy(i,:)); hold;
      for j=1:m
          if m~=1
              p=t(i,j)*tstep;
              % plot(xth,0,'black'); plot(xth,thresh(j)); plot(p,thresh(j),'go');
          else
              % plot(xth,0,'black'); plot(xth,thresh(1)); plot(p,thresh(1),'go');
          end
      end
   end
    if m~=1
    [f zero_time(i)]=edge_time(thresh,t(i,:),m+1);
    else
       zero_time(i)=t(i,1);
    end
   if i==stat
      if m~=1
          % plot(zero_time(i)*tstep,0,'ro');    
          r=[zero_time(i):1:t(i,m)];
          rr=[0:(thresh(m)/(size(r,2))):2*thresh(m)-thresh(m-1)];
          %  plot(f(rr)*tstep,rr,'r');
          %  plot(polyval(f,rr)*tstep,rr,'r');
      else
          % plot(zero_time(i)*tstep,thresh(1),'ro');
     end
   end
end
%
% Checks
figure(2);
time=zero_time(1:stat)-t0(1:stat)-zero_time(1);
%
hist(tstep*(time(2:stat)));
% title('Errors distribution')
% 
stdt0=std(t0(2:stat))*tstep
stdt=std(time(2:stat))*tstep
mean_snn=cumsn/sni;
mean_snn
return
