function [G] = generate_grid(varargin)
% generate_grid(dlon,dllat)
% generate_grid(dlon,dllat,lon0,lat0)
% generate_grid(dlon,dllat,lon0,lat0,mask)

switch nargin
 case {2}
  dlon=varargin{1};
  dlat=varargin{2};
  lon0=0;
  lat0=-90;
 case {4,5}
  dlon=varargin{1};
  dlat=varargin{2};
  lon0=varargin{3};
  lat0=varargin{4};
 otherwise
  error('Wrong number of arguments')
end

[G.xc,G.yc,G.xg,G.yg,G.rac,G.dxg,G.dyg]=grid_sphere(dlon,dlat,lon0,lat0);
%[G.xc,G.yc,G.xg,G.yg]=grid_sphere(dlon,dlat,lon0,lat0);

if nargin<=4
 return
end

G.mskc=mask(varargin{5});

if prod( size(G.mskc(:,:,1)) == [size(G.xc,1) size(G.yc,2)] )==0
 disp('Size of mask argument:');size(G.mskc(:,:,1))
 error('Mask argument (5) has incompatible dimensions with grid')
end

[xc,yc]=ndgrid(G.xc,G.yc);

xc( find(xc<0) )=xc( find(xc<0) )+360;

mskc=G.mskc(:,:,1);
j=[];
j=[j find( yc>-32.5 & xc>290 )'];
j=[j find( yc>-32.5 & xc<25 )'];
%j=[j find( yc>-32 & yc+xc>287 )'];
j=[j find( yc>9 & yc<60 & (yc-10)+(xc-276)>0 )'];
j=[j find( yc>17 & yc<60 & xc>261 )'];
j=[j find( yc>50 & (yc-70)-(xc-270)<0 )'];
j=[j find( yc>64 & xc<100 & xc>0 )'];
j=[j find( yc>31 & yc<44 & xc<38 & xc>0 )'];
matl=0*mskc;
matl(j)=1;
matl=matl.*mskc;
G.matl=matl;

mpac=(1-matl).*mskc;
j=[];
j=[j find( yc>-32.5 & yc<65 )'];
mpac=0*mskc;
mpac(j)=1;
mpac=mpac.*mskc.*(1-matl);
G.mpac=mpac;

msoc=(1-matl).*(1-mpac).*mskc;
j=[];
j=[j find( yc<0 )'];
G.msoc=msoc.*mskc.*(1-mpac).*(1-matl);
