function minCOT = computeCOT(path1,mass)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% computeCOT computes the metabolic cost of transport (MCOT) of
% walking at each input speed.  It then fits a cubic spline to the
% data and computes the walking speed at which the MCOT is
% minimal.  A plot is created and saved and a .mat file with costs
% and error bars is saved.  Note that .xls has to be in Excel 5.0/
% Windows 95 format for this to work, at least on my Mac.
%
% Inputs:
% path1 - subject identifier for the study.
% mass  - subject mass (in kg, for normalization).
%
% Outputs:
% MCOT plot, values, speed where MCOT is minimal.
%
% Jared Markowitz
% Fall 2012
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

metCOT = [];
speeds = 200;
%speeds = [75 100 125 150 175 200];

addpath('./grant_code/filetools');
addpath('./grant_code/measurement');
addpath('./grant_code/metabolics');

% Analyze metabolic data:

for i=1:numel(speeds)
  if speeds(i) == 75;
    numstr = '075';
  else
    numstr = num2str(speeds(i));
  end;
  eval(['[analysis,errors]  = ProcessMetabolics(''./' path1 '/WALK' numstr '.xls'');']);
  if exist('mass')
    metCOT = cat(1,metCOT,analysis.Results.NormalizedPower*100/speeds(i));    
  else
    fprintf('No mass input; should have input to Cosmed!\n');
  end;
end;

% Fit and plot metCOT:   
speeds    = speeds/100;
just_mean = 65/mass*metCOT.Value;
just_unc  = 65/mass*metCOT.Uncertainty;
xx = 0.75:.01:2;
yy = interp1(speeds,just_mean, xx,'spline');

[val1,ind1] = min(yy);

fprintf(['Minimum MCOT speed is ' num2str(xx(ind1)) 'm/s.\n']);

figure;
Measurement.errorBar(speeds,metCOT);
hold on;
plot(xx,yy,'linewidth',2);
plot(xx(ind1),val1,'r+','markersize',12,'linewidth',3);
grid on;
xlabel('Walking Speed (m/s)','fontsize',14);
ylabel('Metabolic COT (W/kg/(m/s))','fontsize',14);
title('Metabolic Cost of Transport vs. Walking Speed','fontsize',14);
outplot = ['./' path1 '/metcost.png'];
eval(['print -dpng ' outplot ]);

eval(['save(''./' path1 '/metabolics.mat'',''speeds'',''just_mean'',''just_unc'',''xx'',''yy'');']);

return
% Not worth it to do full ChiSq analysis.

%keyboard;
%fitfun = @(x,a) a(1) + a(2)*x + a(3)*x.^2 + a(4)*x.^3;

% Initial guess comes from Pandy and Anderson plot or Excel?
%[a,chisq] =  Measurement.fit(speeds,metCOT,fitfun,[]) 

%b = value(a);
%x = 0.7:.01:2.05;
%y = b(1)*x.^ + b(2)*x.^ + b(3)*x.^ + b(4)*x.^ + b(5)*x.^ + ...
%[val,ind] = min(y)
%minCOT = x(ind);    
    
%figure
%Measurement.errorBar(speeds,metCOT);
%hold on;
%plot(x,y,'linewidth',2);
%plot(minCOT,val,'r+','markersize',12,'linewidth',3);
%grid on;
%xlabel('Walking Speed (m/s)');
%ylabel('Metabolic COT (W/kg/(m/s))');
%title('Metabolic Cost of Transport vs. Walking Speed');
%outfile = ['
%print -dpng 

%[val,ind] = min(y)
%minCOT = x(ind);