%runReg
function [Cd, AM, errMat] = runReg(tDat, pDat, bFor,sysMass)

    %calculate total system mass (includes external weights)

    startMass =0; %kg
    endMass = sysMass*1.5; %kg;
    massRes = 20; %resolution of guesses to check
    
    startCd = 0.01;
    endCd = 2.5;
    CdRes = 20;

    % determine the time step
    bFor = [tDat bFor'];
    tIn = tDat;
    dIn = pDat;

    % run simulation using timestep specified by tIn
    checkMass = linspace(startMass,endMass,massRes);
    checkCd = linspace(startCd,endCd,CdRes);
    
    L2err = ones(CdRes,massRes)*inf;
    L1err = ones(CdRes,massRes)*inf;
    minL2 = inf;
    minL1 = inf;
%     hmap = gcf();
    count = 0;
    for mi = 1:massRes
        for ci = 1:CdRes
            count = count+1;
            massGuess = checkMass(mi);
            cdGuess = checkCd(ci);
            R=sim('U:\matlabCalcs\updatedAddedMassSimulationNS.slx'...
                ,'srcworkspace','current');
            a = R.get('posOut');
            if mi == 1
                if ci == 1
%                     input('now? ');
                end
            end
            posDat = a.signals.values;
            L1err(ci,mi) = sum(abs(posDat-dIn));
            L2err(ci,mi) = sum((posDat - dIn).^2);
            locfig = gcf();
            figure(locfig);
            subplot(4,1,1); hold on
            plot(tIn,posDat,'r--');
%             M(count) = getframe(hmap);
            if L1err(ci,mi) < minL1
                minL1 = L1err(ci,mi);
                AM = massGuess;
                Cd = cdGuess;
                l1ind = [ci mi];
                plot(tIn,posDat,'m--');
            end
             if L2err(ci,mi) < minL2
                minL2 = L2err(ci,mi);
                AM = massGuess;
                Cd = cdGuess;
                plot(tIn,posDat,'c--');
             end
        end
    end
%     movie2avi(M,'regreesion.avi','compression','none')
  
    figure('color','w');
    imagesc(checkMass,checkCd,log(L2err));
    hold on;
    plot(AM,Cd,'rx')
    colorbar;
    title(['Sys Mass: ' num2str(sysMass)]);
    set(gca,'YDir','normal')
    xlabel('Guessed Mass (kg)')
    ylabel('Guessed Cd')
    massGuess = AM;
    cdGuess = Cd;
    R=sim('U:\matlabCalcs\updatedAddedMassSimulationNS.slx'...
        ,'srcworkspace','current');
    a = R.get('posOut');
    posDat = a.signals.values;
    figure(locfig); subplot(4,1,1); hold on
    plot(tIn,posDat,'g--');
    
    [x,y]= meshgrid(checkMass,checkCd);
    errMat(:,:,1) = x;
    errMat(:,:,2) = y;
    errMat(:,:,3) = L2err;
end