% Written by Janet E. Lovett. Please cite J. E. Lovett, B. W. Lovett and J. Harmer, 
% DEER-Stitch: Combining three- and four-pulse DEER measurements for high 
% sensitivity, deadtime free data, Journal of Magnetic Resonance, 223, (2012) 98-106.

function minsq = DEERSminsq(x,d4p,deer3pRe,d3_3p,n,d,t,B_fit);


if B_fit == 0;

    minsq = sum ( ( x(2).*exp( -(t((n+1+d3_3p):length(d4p)).*x(1) ).^(d/3)).*d4p((n+1+d3_3p):length(d4p))-deer3pRe((n+1):(length(d4p)-d3_3p)) ) .^2);  

else 
   
    minsq = sum ( ( x(2).*exp( -(t((n+1+d3_3p):length(d4p)).*x(1) ).^(d/3)).*(d4p((n+1+d3_3p):length(d4p))+x(3))-deer3pRe((n+1):(length(d4p)-d3_3p)) ) .^2);  

end