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

% This uses 'forwardTB.m' to compute expected concentrations for a simple
% two-stage burial history with added surface cover. Returns misfit to
% data. 
% 
% Syntax:
% out = fit_tE_tB_zz(X,s,p,m,mask,plotFig,returnPred)
% 
% X is [texp(ka) tburial(Ma) cover thickness(g/cm2)]
% s is sample data struct
% p is production rate data struct
% m is muon data struct
% mask tells which data to consider (normally [1:7])
% plotFig is output of plotGISPdata.m
% returnPred is 0 or 1 to return misfit or predicted values respectively
%
% 
% Greg Balco -- Berkeley Geochronology Center -- May 2016

if nargin < 7; returnPred = 0; end;
if nargin < 6; plotFig = []; end; 

% Unpack

texp = X(1).*1e3; 
tbur = X(2).*1e6;
zz = X(3);

td.tt = [texp+tbur tbur];
td.ee = 0;
td.zz = zz;

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;

if returnPred == 1;
    out = pred;
else
    out = sum(miss(mask)); 
end;

if ~isempty(plotFig);
    axes(plotFig(2));
    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;
    
    plottb(td.tt,plotFig(3));
    
end;

drawnow;