function out = fit_tE_tB_e_zz(X,s,p,m,mask,plotFig)

% This uses 'forwardTB.m' to compute expected concentrations for two-stage
% exposure history with four free parameters -- exposure time, burial time,
% erosion rate during exposure, and cover thickness. 
%
% Syntax: out = fit_tE_tB_e_zz(X,s,p,m,mask,plotFig)
% 
% X is [texp(ka) tbur(ka) erosion_rate(m/Myr) cover_thickness(g/cm2)]
% s,p,m are sample, production rate, muon data structs
% mask tells which samples to consider (normally 1:7)
% plotFig is output of plotGISPdata
%
% 
% Greg Balco -- Berkeley Geochronology Center -- May 2016

if nargin < 6; plotFig = 0; end; 

% Unpack

% Unpack

texp = X(1).*1e3; % ka
tbur = X(2).*1e6; % Ma
td.ee = X(3).*1e-4.*2.7; % in m/Myr
td.zz = X(4); % 100 g/cm2

td.tt = [texp+tbur tbur];


pred = forwardTB(td,s,p,m,plotFig);

for a = 1:length(s);
    miss(a) = ((pred.sum(a) - s{a}.N)./s{a}.dN).^2;
end;

out = sum(miss(mask)); 

if plotFig > 0;
    figure(plotFig);
    for a = 1:length(s);
        xx = [pred.sum(a) pred.sum(a)];
        for b = 1:length(s{a}.td);
            yy = [s{a}.td(b) s{a}.bd(b)];
            if isempty(findobj('tag',['predN' int2str(a) int2str(b)])); 
                plot(xx,yy,'g','tag',['predN' int2str(a) int2str(b)]);
                set(findobj('tag',['predN' int2str(a) int2str(b)]),'LineWidth',2);
            else
                set(findobj('tag',['predN' int2str(a) int2str(b)]),'xdata',xx,'ydata',yy);
            end;
        end;
    end;
end;

drawnow;