function x = shadeland(long,lat,land,col)

% SHADELAND (LONG,LAT,LAND)
%    Contour plot with shaded land area
%    LONG longitude vector (size of land)
%    LAT  latitude vector  (size of land)
%    LAND array of ones for land and zeros for water
%    COL  land color specification, default: 0.8*[1 1 1]
%
%  For correct results needs auxillary program INPOLYGON.M
%  See also CONTOURF, PLOTLAND, PLOTFUN
% Example of usage:
%  [c,h]=contourf(surfvar');             (surfvar      360x160)
%  shadeland([1:360],[1:160]',LANDsurf') (LANDsurf     360x160)

%landcolor=[.8 .8 .8];			% land is gray
landcolor=[.0 .0 .0];                   % land is black
watercolor=[1 1 1];     		% water is white

% check input arguments

if nargin < 3
  error ('function SHADELAND requires three input arguments')
elseif nargin == 4
  landcolor = col;
end

long=long(:); lat=lat(:); [m n]=size(land);
if (length(lat) ~= m) | (length(long) ~= n)
  error ('error in argument size of function SHADELAND')
end

% add thin layer of water around entire plot

long=[2*long(1)-long(2); long; 2*long(n)-long(n-1)];
lat=[2*lat(1)-lat(2); lat; 2*lat(m)-lat(m-1)];
land=[zeros(1,n+2);zeros(m,1) land zeros(m,1);zeros(1,n+2)];

c = contourc(long,lat,land,[.5 2]);

cs=1;                                   % contour start index
while cs<length(c)                      % repeat for all contours

  cl=c(2,cs);                           % contour length
  ci=(cs+1):(cs+cl);                    % contour indices
  x=c(1,ci); y=c(2,ci);                 % contour coordinates
  cs=cs+cl+1;                           % increment cs
  
  % find some points near the first contour coordinate
  
  [mx ix]=min(abs(long-x(1)));
  ix1=ix-1; if ix1<1, ix1=ix; end
  ix2=ix+1; if ix2>length(long), ix2=ix; end
  ix=[ix1 ix1 ix1 ix ix ix ix2 ix2 ix2]; mx=long(ix);
  
  [my iy]=min(abs(lat-y(1)));
  iy1=iy-1; if iy1<1, iy1=iy; end
  iy2=iy+1; if iy2>length(lat), iy2=iy; end
  iy=[iy1 iy iy2]; iy=[iy iy iy]; my=lat(iy);

  % determine coordinates of points is inside contour
  
  isin = inpolygon (mx,my,x,y);
  is=find(isin); iy=iy(is); ix=ix(is);
  
  % if inside is land, draw a gray patch, else white patch
  
  if land(iy(1),ix(1))
    h=patch(x,y,landcolor,'linewidth',.01);
  else
    patch(x,y,watercolor,'linewidth',.01);
  end
end
axis([  min([long(2) long(length(long)-1)]) ...
        max([long(2) long(length(long)-1)]) ...
        min([ lat(2)  lat(length( lat)-1)]) ...
        max([ lat(2)  lat(length( lat)-1)]) ]);
