% Function to calculate the mean of a model field in the z-direction.

% Two ways to do the average, depending on the distribution of land. If the land is in
% random places use the (slower) for loop, otherwise, use the second option.

% Author Tom, 31/10/94.

function result = meanxy(data,spacing,mask) ;

global NX NY NZ 

if(length(spacing) ~= NZ)
  fprintf(1,' ERROR !  Wrong spacing vector supplied to meanxy function. \n') ;
  return ;
end

fprintf(1,' Averaging in z-direction ... ') ;

% Mean = integral(data*width) / integral(width)  in direction of integration.
% First method. Need to remove land values from average, use mask variable.

slice = zeros(NY,NX) ;
dist  = zeros(NY,NX) ;
for i = 1:NZ
  temp  = getxy(data,i) ;
  temp2 = getxy(mask,i) ;
  slice = slice + (temp.*temp2.*spacing(i)) ; 
  dist  = dist  + (spacing(i).*temp2) ;
end
result = slice ./ dist ;

% Second way.
%temp = meshgrid(spacing,[1:NY*NX]) ;
%data   = reshape(data',NY*NX,NZ) ;
%result = mean((data.*temp)')' ./ sum(spacing) ;
%result = reshape(result,NY,NX) ;

fprintf(1,' done. \n') ;
