function [ctot,cmean]=ctotal(cdfin,varin,tind,bounds,z1,z2)
% CTOTAL computes to total amount of tracer present in a given time
%        step of a ecomsi model run.  
%
%  Usage:  [ctot,cmean]=ctotal(cdfin,varin,[tind],[bounds],z1,z2)
%
%  where:  cdfin = ecomsi.cdf run
%          tind = single index of time (defaults to [1])
%          bounds = [imin imax jmin jmax] limits  
%                   (defaults to [1 nx 1 ny])
%          bounds may also be a 1 d array containg the indices
%            of the matrix 
%            (just make sure it has more than 4 elements!) 
%           ctot = total sum of scalar quantity c
%           cmean = mean value of ctot (ctot/volume)
%  
if(nargin==2),
  tind=1;
end
cdfid1=mexcdf('open',cdfin,'nowrite');
[nam,nxr]=mexcdf('diminq',cdfid1,'xpos');
[nam,nyr]=mexcdf('diminq',cdfid1,'ypos');
[nam,nz]=mexcdf('diminq',cdfid1,'zpos');
if(nargin< 4),
  ix=0;
  iy=0;
  nx=nxr;
  ny=nyr;
  ind=1:(nx*ny);
elseif (length(bounds)>4),
  ix=0;
  iy=0;
  nx=nxr;
  ny=nyr;
  ind=bounds;
else
  if(bounds(2)>nxr|bounds(4)>nyr),disp('out of bounds'),return,end
  ix=bounds(1)-1;
  nx=bounds(2)-bounds(1)+1;
  iy=bounds(3)-1;
  ny=bounds(4)-bounds(3)+1;
  ind=1:(nx*ny);
end
d=mexcdf('varget',cdfid1,'depth',[iy ix],[ny nx]);
sigma=mexcdf('varget',cdfid1,'sigma',[0],[nz]);
dsigma=-diff(sigma);
sigma2=.5*(sigma(1:nz-1)+sigma(2:nz));
d=replace(d,-99999,0.);
h1=mexcdf('varget',cdfid1,'h1',[iy ix],[ny nx]);
h2=mexcdf('varget',cdfid1,'h2',[iy ix],[ny nx]);
area=h1.*h2;
ctot=zeros(nx,ny);
vol=zeros(nx,ny);
for j=[1:nz-1],
  dmask=((d*sigma2(j)) < z1 & (d*sigma2(j)) > z2);
  c=mexcdf('varget',cdfid1,varin,[tind-1 j-1 iy ix],[1 1 ny nx],1); %get a layer
  ctot=ctot+dsigma(j)*c.*dmask.*h1.*h2.*d;   %multiply layer values by normalized layer thickness
  vol=vol+dmask.*h1.*h2.*d.*dsigma(j);   %multiply layer values by normalized layer thickness
end
ctot=sum(ctot(:));
cmean=ctot/sum(vol(:));
mexcdf('close',cdfid1);
