function [basin_id,longitude,latitude] = get_basin(longitude,latitude,flag);
% [basin_id,longitude,latitude] = get_basin(longitude,latitude,flag);
%
% Determine oceanic basin at (lon,lat) coordinates.
%
% Inputs longitude and latitude are in degrees East and North,
% respectively and must have the same dimension.
% Optional flag:
%    0: return ocean basin and land points (default)
%    1: return closest ocean basin
%
% Output basin_id has same dimension as longitude and latitude:
%    0: Land
%    1: Pacific Ocean
%    2: Atlantic Ocean
%    3: Indian Ocean
%    4.01: Southern Ocean, Pacific Sector
%    4.02: Southern Ocean, Atlantic Sector
%    4.03: Southern Ocean, Indian Ocean Sector
%    5: Arctic Ocean
%    6: Mediterranean Sea
%    7: Sea of Japan  
%    8: Other body of water     
%
% Basin determination is based on a coarse 1x1 degree map.

load /home/dimitri/matlab/plotfun/ocean_basin/basin

if nargin < 2
  longitude=lon;
  latitude=lat;
  basin_id=basin;
  return
elseif nargin < 3
  flag=0;
end

if any( size(longitude) ~= size(latitude) )
  error('Size of latitude and longitude arrays must be the same')
end

basin_id=latitude;

if (length(lon)*length(lat)) > (length(latitude(:))*2)

  for i=1:length(latitude(:))
    basin_id(i) = basin( ...
        closest(latitude(i),lat), closest(longitude(i),lon) );
  end

else
  
  for i = 1:length(lon)
    ix = find( longitude >= (lon(i)-.5) & longitude < (lon(i)+.5) );
    for j = 1:length(lat)
      jx = find( latitude(ix) >= (lat(j)-.5) & latitude(ix) < (lat(j)+.5) );
      basin_id(ix(jx)) = basin(j,i);
    end
  end
  
end

% find closest ocean basin for land points
if flag == 1
  [X Y]=meshgrid(lon,lat);
  il=find(~basin_id);
  for i=il(:)'
    n=1;
    tmp2=[];
    while isempty(tmp2)
      n=n+1;
      ix=closest(longitude(i),lon,n);
      iy=closest(latitude(i),lat,n);
      tmp1=basin(iy,ix);
      tmp2=tmp1(find(tmp1));
    end
    if length(tmp2)==1
      basin_id(i)=tmp2;
    elseif max(diff(tmp2))>0
      in=find(tmp1)';
      lat2=Y(iy,ix);
      lon2=X(iy,ix);
      range=dist2([latitude(i) lat2(in)],[longitude(i) lon2(in)]);
      [yy ii]=min(range);
      basin_id(i)=tmp2(ii);
    else
      basin_id(i)=tmp2(1);
    end
  end
end


% $$$ for i=1:length(latitude(:))
% $$$   if ~isnan(latitude(i))
% $$$     iy = closest(latitude(i),lat);
% $$$     jx = find(latitude==latitude(i));
% $$$     latitude(jx)=nan;
% $$$     for j=1:length(jx)
% $$$       basin_id(jx(j)) = basin( iy, ...
% $$$           closest(longitude(jx(j)),lon) );
% $$$     end
% $$$   end
% $$$ end
