function dcz=template_based_mini_detector(data,template)
%description: matlab implementation of the method of clements and bekkers (Biophys J, 1997), based on scaling the template, correcting for any offset, and calculating the fit
%called by: simulated_psc_in_noise, IQI_estimator,...
%calls: no custom functions
%notes: 
%code confirmed date: dec 28, 2012

templatelength=length(template); %has to be recreated here rather than passed in for when truncated template is used (and the template passed in thus differs in length from the original)

criterionlength=length(data)-templatelength;
dcz=zeros(1,criterionlength);
for i=1:criterionlength
    ddata=data(i:i+(templatelength-1));
    scale=(sum(template.*ddata)-(sum(template)*(sum(ddata)/templatelength)))/(sum(template.*template)-(sum(template)*(sum(template)/templatelength)));
    offset=(sum(ddata)-(scale*sum(template)))/templatelength;
    fitted_template=template*scale+offset;
    sse=sum((ddata-fitted_template).^2);
    standard_error=sqrt(sse/(templatelength-1));
    detection_criterion=scale/standard_error;       %analogous to signal/noise
    dcz(i)=detection_criterion;
end