function cz=decim2(x,y,z,cx,cy,fl)

% cz=decim2(x,y,z,cx,cy,fl)
%             decimate a 2-D field using bin averages
%
%       x   x-coordinate of z
%       y   y-coordinate of z
%       z   input fine resolution 2-D field
%       cx  coarse x-coordinate
%       cy  coarse y-coordinate
%       fl  flag: 1 = bin-average (default)
%                 2 = bin-maximum
%                 3 = bin-minimum
%       cz  output coarse resolution 2-D field

if nargin < 5, error('need five input arguments'); end
if nargin < 6, fl=1; end
[m n]=size(z);
cm=length(cy);
cn=length(cx);
transFlag=0;
if length(x)~=n, z=z'; [m n]=size(z); transFlag=1; end
if length(x)~=n | length(y)~=m, error('x/y/z argument size mismatch'); end

cz=zeros(cm,cn);
tmp=zeros(m,cn);
cx=[2*cx(1)-cx(2);cx(:);2*cx(cn)-cx(cn-1)];
cx=(cx(1:(cn+1))+cx(2:(cn+2)))/2;
cy=[2*cy(1)-cy(2);cy(:);2*cy(cm)-cy(cm-1)];
cy=(cy(1:(cm+1))+cy(2:(cm+2)))/2;

switch fl
  
  case 1
    for i=1:cn
      ix = find ( x >= cx(i) & x <= cx(i+1) );
      if ~isempty(ix), tmp(:,i)=mean(z(:,ix),2); end
    end
    for i=1:cm
      ix = find ( y >= cy(i) & y <= cy(i+1) );
      if ~isempty(ix), cz(i,:)=mean(tmp(ix,:),1); end
    end
  
  case 2
    for i=1:cn
      ix = find ( x >= cx(i) & x <= cx(i+1) );
      if ~isempty(ix), tmp(:,i)=max(z(:,ix),[],2); end
    end
    for i=1:cm
      ix = find ( y >= cy(i) & y <= cy(i+1) );
      if ~isempty(ix), cz(i,:)=max(tmp(ix,:),[],1); end
    end
  
  case 3
    for i=1:cn
      ix = find ( x >= cx(i) & x <= cx(i+1) );
      if ~isempty(ix), tmp(:,i)=min(z(:,ix),2); end
    end
    for i=1:cm
      ix = find ( y >= cy(i) & y <= cy(i+1) );
      if ~isempty(ix), cz(i,:)=min(tmp(ix,:),1); end
    end

end

if transFlag, cz=cz'; end
