function [wmean,x,y]=depthaveuv(cdfin,tind,bounds)
% DEPTHAVEuv computes to depth-averaged variable in a given time
%        step of a ecomsi model run.  
%
%  Usage:  [cmean]=depthave(cdf,tstep)
%
%  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])
%          
%           ctot = total sum of scalar quantity c
%           cmean = mean value of ctot (ctot/volume)
%  
if(nargin==1),
  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< 3),
  ix=0;
  iy=0;
  nx=nxr;
  ny=nyr;
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;
end
depth=mexcdf('varget',cdfid1,'depth',[ix iy],[ny nx]);
x=mexcdf('varget',cdfid1,'x',[ix iy],[ny nx]);
y=mexcdf('varget',cdfid1,'y',[ix iy],[ny nx]);
ang=mexcdf('varget',cdfid1,'ang',[ix iy],[ny nx]);
sigma=mexcdf('varget',cdfid1,'sigma',[0],[nz]);
dsigma=-diff(sigma);
h1=mexcdf('varget',cdfid1,'h1',[ix iy],[ny nx]);
h2=mexcdf('varget',cdfid1,'h2',[ix iy],[ny nx]);
area=h1.*h2;
wmean=zeros(nx,ny);
for j=[1:nz-1],
  u=mexcdf('varget',cdfid1,'u',[tind-1 j-1 iy ix],[1 1 ny nx],1); %get a layer
  v=mexcdf('varget',cdfid1,'v',[tind-1 j-1 iy ix],[1 1 ny nx],1); %get a layer
  u=u(1:nx-1,:)+.5*diff(u);
  u(nx,:)=u(nx-1,:);
  v=v(:,1:ny-1)+.5*diff(v')';
  v(:,ny)=v(:,ny-1);
  w=u+sqrt(-1)*v;
  wmean=wmean+dsigma(j)*w;  %multiply layer values by normalized layer thickness
end
dind=find(depth==-99999 | depth==0);
wmean(dind)=wmean(dind)*NaN;
wmean=wmean.*exp(sqrt(-1)*ang);
mexcdf('close',cdfid1);
