function out = BCO_objective_zeroerosion(X,d,p,dFlag)

% This is the objective function for fitting exercise 1, which is assuming
% zero erosion and a fixed exposure time. 
%
% out = BCO_objective_zeroerosion(X,d,p,dFlag)
% 
% where X has the following params:
%   X(1) exposure age (Myr)
%   X(2) Ne closure age (Myr)
%   X(3) Lambda_sp (g/cm2) spallogenic e-folding length
%   X(4) Lambda_a (g/cm2) albedo e-folding length
%   X(5) f_a (nondimensional) albedo loss percent
%   X(6) fstar (nondimensonal * 1e-3) total negative muon capture likelihood
%   X(7) sigma0 (millibarns) fast muon cross-section
%
% d is data structure with core data
% p is additional struct with things like surface production rate, etc. 
% dflag is 0 for objective fctn; 1 for diagnostic struct
%
% Greg Balco - Berkeley Geochronology Center - 2018
% Not licensed for reuse or distribution

% Get in correct dimensions

t = X(1).*1e6; % to Ma
tc = X(2).*1e6; % to Ma
Lsp = X(3); % No conversion
La = X(4); % No conversion
fa = X(5).*0.01; % convert percent to fractional
fstar = X(6).*1e-3; % to correct fractional
sigma0 = X(7).*1e-27; % to cm2

% Nucleogenic

% Alpha production
d.a232perg = 6.*d.atsThperg.*(exp(p.l232.*tc) - 1);
d.a235perg = 7.*d.ats235perg.*(exp(p.l235.*tc) - 1);
d.a238perg = 8.*d.ats238perg.*(exp(p.l238.*tc) - 1);

% Ne-21 production
r.N21nuc = d.Ft.*( d.a232perg.*6.08e-8 + d.a235perg.*5.62e-8 + d.a238perg.*4.04e-8 );
r.delN21nuc = r.N21nuc.*p.dnfactor;

% Spallogenic

r.N21sp = t.*p.P0.*exp(-d.z./Lsp) - t.*p.P0.*fa.*exp(-d.z./La);

% Muons

r.N21neg = d.stub_mneg.*t.*fstar.*p.fC.*p.fD;
r.N21fast = d.stub_mfast.*t.*sigma0;

% Total

r.N21p = r.N21nuc + r.N21sp + r.N21neg + r.N21fast;
r.delN21p = r.delN21nuc;
r.miss = ((r.N21p - d.N21m)./sqrt((d.delN21m.*p.dmfactor).^2 + r.delN21p.^2));
r.missquared = r.miss.^2;
r.x2 = sum(r.missquared);

if dFlag == 0;
    out = r.x2;
elseif dFlag == 1;
    out = r;
end;

