function allmean2(cdfsin,cdfout)
%function allmean2(cdfsin,cdfout)
%
% ALLMEAN2 computes mean from step 0 multiple cdf files
%   used for computing the mean from several monthly means.
%     
%  tind is the indices of time steps to average over (1 is first step)
% 
%  varin is the variable ('conc' if not supplied);

mexcdf('setopts',0);
cdfid2=mexcdf('open',cdfout,'write');
[m,n]=size(cdfsin);
cdfid1=mexcdf('open',cdfsin(1,:),'nowrite');
[nam,nx]=mexcdf('diminq',cdfid1,'xpos');
[nam,ny]=mexcdf('diminq',cdfid1,'ypos');
[nam,nz]=mexcdf('diminq',cdfid1,'zpos');
mexcdf('close',cdfid1);
for i=1:m,
  cdfid(i)=mexcdf('open',cdfsin(i,:),'nowrite');
end
for j=[1:nz-1],
  stot=zeros(nx,ny);
  ttot=zeros(nx,ny);
  ctot=zeros(nx,ny);
  utot=zeros(nx,ny);
  vtot=zeros(nx,ny);
  wtot=zeros(nx,ny);
% smax=zeros(nx,ny);
% smin=32*ones(nx,ny);
  for i=1:m,
    s=mexcdf('varget',cdfid(i),'salt',[0 j-1 0 0],[1 1 ny nx]);
    t=mexcdf('varget',cdfid(i),'temp',[0 j-1 0 0],[1 1 ny nx]);
    c=mexcdf('varget',cdfid(i),'conc',[0 j-1 0 0],[1 1 ny nx]);
    u=mexcdf('varget',cdfid(i),'u',[0 j-1 0 0],[1 1 ny nx]);
    v=mexcdf('varget',cdfid(i),'v',[0 j-1 0 0],[1 1 ny nx]);
    w=mexcdf('varget',cdfid(i),'w',[0 j-1 0 0],[1 1 ny nx]);
    stot=stot+s;
    ttot=ttot+t;
    ctot=ctot+c;
    utot=utot+u;
    vtot=vtot+v;
    wtot=wtot+w;
  end
  smean=stot/m;
  tmean=ttot/m;
  cmean=ctot/m;
  umean=utot/m;
  vmean=vtot/m;
  wmean=wtot/m;
% store mean field in 1st time step of cdfout
  mexcdf('varput',cdfid2,'salt',[0 j-1 0 0],[1 1 ny nx],smean);
  mexcdf('varput',cdfid2,'temp',[0 j-1 0 0],[1 1 ny nx],tmean);
  mexcdf('varput',cdfid2,'conc',[0 j-1 0 0],[1 1 ny nx],cmean);
  mexcdf('varput',cdfid2,'u',[0 j-1 0 0],[1 1 ny nx],umean);
  mexcdf('varput',cdfid2,'v',[0 j-1 0 0],[1 1 ny nx],vmean);
  mexcdf('varput',cdfid2,'w',[0 j-1 0 0],[1 1 ny nx],wmean);
  
% store max  salinity field in 2nd time step of cdfout
% mexcdf('varput',cdfid2,varout,[1 j-1 0 0],[1 1 ny nx],smax);
% store min  salinity field in 3rd time step of cdfout
% mexcdf('varput',cdfid2,varout,[2 j-1 0 0],[1 1 ny nx],smin);
end
etot=zeros(nx,ny);
tauxtot=0.;
tauytot=0.;
timetot=0.;
for i=1:m,
  e=mexcdf('varget',cdfid(i),'elev',[0 0 0],[1 ny nx]);
  etot=etot+e;
  taux=mexcdf('varget',cdfid(i),'taux',[0],[1]);
  tauxtot=tauxtot+taux;
  tauy=mexcdf('varget',cdfid(i),'tauy',[0],[1]);
  tauytot=tauytot+tauy;
  time=mexcdf('varget',cdfid(i),'time',[0],[1]);
  timetot=timetot+time;
end
emean=etot/m;
mexcdf('varput',cdfid2,'elev',[0 0 0],[1 ny nx],emean);
tauxmean=tauxtot/m;
mexcdf('varput',cdfid2,'taux',[0],[1],tauxmean);
tauymean=tauytot/m;
mexcdf('varput',cdfid2,'tauy',[0],[1],tauymean);
timemean=timetot/m;
base_date=mexcdf('attget',cdfid1,'GLOBAL','base_date');
mexcdf('attput',cdfid2,'GLOBAL','base_date','long',3,base_date);
mexcdf('varput',cdfid2,'time',[0],[1],timemean);
mexcdf('close',cdfid2);
for i=1:m,
  mexcdf('close',cdfid(i));
end
