function[ref]=ref_gen(stat,i0_0,t0_0);
%
% Generates MCP reference signal and derivative
%
[tstep,trise,tfall,gain,NPE,Ishot,G,nadc,bw,tau,taus,T,R,fs,ts,apjit]=params();
%
% Reference generation
%
% t0max=floor(4*tau);
% new
t0max=floor(tau)
[y]=wave(tstep,trise,tfall,t0max,1);
% plot(y); return
% n=round(25*tau);
n=round(20*tau);
%
i0=i0_0;
t0=t0_0;
t=1:n;
% sh(1:n)=(2.718.*(t-(t0max+t0))/tau).*exp(-(t-(t0max+t0))/tau);
% sh(1:t0max+t0-1)=0;
t=1:n;
sh(1:n)=(2.718.*(t-(t0max+t0))/tau).*exp(-(t-(t0max+t0))/tau);
sh(1:t0max+t0-1)=0;
sh=conv(sh,sh);
sh=sh(1:2:size(sh,2));
nsh=size(sh,2);
%
%
% Check reference
% scalex=(1:nsh)*tstep;
% figure(100); plot(scalex,sh); title('Reference from ref gen'); 
%
% Spectrum
%
% figure(101); title('ref_gen');
% h=hamming(nsh); nf=round(nsh/2);
% nshf=round((fs/10+fs/2)*tstep*nsh);
% hsh=h.*sh(1:nsh)'; fhsh=abs(fft(hsh));
% scalef=(1:nshf)*qf;
% loglog(scalef,fhsh(1:nshf),'green'); title('Reference spectrum');
%
insig=y; qin=sum(y)*tstep;
if (size(insig,2)>5e20) | (size(sh,2)>1e20)
    disp('Convolution out of range > 5e20 points '); return
end
% py=conv(insig,p); 
% py=py(t0max:n);
py=conv(insig,sh);
py=py(t0max+1:n); npy=size(py,2);
% figure(2); subplot(1,3,1); plot(py); subplot(1,3,2); plot(dpy); 
% subplot(1,3,3); plot(dsh); return
% Scale reference by i0
py=i0(1)*py/max(abs(py));
%
% Anti-alias filter
%
% Smoothed Shannon
nsh=size(py,2);
qf=1/(nsh*tstep); nfsh=floor(fs/qf);
w=zeros(1,nsh);  
wslope=4; w(1:floor(nfsh/2)-wslope)=1; 
w(floor(nfsh/2)-(wslope-1):floor(nfsh/2))=1-[0:1/wslope:1-(1/wslope)];
w=w+fliplr(w); % plot(w); 
%
% Anti-aliased signal+noise
%
fpy=fft(py); p=fpy.*w; 
py=real(ifft(p));
%
%
dpy=([py(2:n-t0max) 0]-py(1:n-t0max));
dpy=fliplr(dpy); dpy(1)=0; dpy=fliplr(dpy);
ref(1,1:size(py,2))=py;
ref(2,1:size(dpy,2))=dpy;
%
% Check shaper response to detector and derivative shifted
% figure(102);
% title('Shaper response (reference) and derivative shifted by t0max-t0');
% scalex=tstep*(1:size(py,2)); 
% subplot(2,1,1); plot(scalex,-py);
% subplot(2,1,2); plot(scalex,dpy); 
return