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

% This uses 'forwardTB.m to compute expected concentrations for a single
% period of exposure followed by mid/late Pleistocene glacial/interglacial
% exposure. Cover thickness fixed at 350. 
%
% Syntax is out = fit_midp1(X,s,p,m,mask,mids,plotFig)
%
% X is [initial exposure length (ka) interglacial length (ka) cover (g/cm2)]. 
% s,p,m sample, production, muon data structs
% mask tells which samples to consider (normally 1:7)
% mids is a vector with midpoints of defined interglaciations
% plotFig is output from plotGISPdata.m
%
% 
% Greg Balco -- Berkeley Geochronology Center -- May 2016


if nargin < 7; plotFig = 0; end; 

% Unpack

td = generate_et_struct(mids,X(2).*1000,X(1).*1000,0,350); % Note zero erosion

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 ~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));
    drawnow;
end;

