clear all ;
close all ;
set(groot,'DefaultFigureColormap',jet)
bin_dir = '/home1/datahome/cpeureux/tools/SKIM/gridgen/bin';
ref_dir = '/home1/datahome/cpeureux/tools/SKIM/gridgen/reference';
nml_dir = '/home1/datahome/cpeureux/tools/SKIM/gridgen/namelist';
data_dir = '/home1/datahome/cpeureux/tools/SKIM/gridgen/data';
dx = 0.033;  dy = 0.033; 
lon_west = 15.2;
lon_east = 33.88;
lat_south = -40.44;
lat_north = -27.2;
lon1d = (lon_west:dx:lon_east);
lat1d = (lat_south:dy:lat_north); 
[lon,lat] = meshgrid(lon1d,lat1d);

addpath(bin_dir,'-END');

load([ref_dir,'/coastal_bound_full.mat'])

CUT_OFF = 0.0;        % Cut-off depth to distinguish between dry & wet cells
LIM_BATHY = 0.4;   % Base bathymetry cells needing to be wet for the target cell to be considered wet.
DRY_VAL = 999999;  % Depth value set for fry cells

ref_grid = 'gebco';  % Name of the file without the '.nc' extension
xvar = 'lon';  % Name of the variable defining longitudes in file
yvar = 'lat';  % Name of the variable defining latitudes in file
zvar = 'elevation';

depth = generate_grid('rect',lon,lat,ref_dir,ref_grid,LIM_BATHY,CUT_OFF,DRY_VAL,xvar,yvar,zvar);

m1 = ones(size(depth));
m1(depth == DRY_VAL) = 0;

lon_start = min(min(lon))-dx; 
lon_end = max(max(lon))+dx; 
lat_start = min(min(lat))-dy; 
lat_end = max(max(lat))+dy; 
coord = [lat_start lon_start lat_end lon_end]; 
MIN_DIST = 4;  % minimum distance between edge of polygon and boundary

[b,N] = compute_boundary(coord,bound) ;

SPLIT_LIM = 0.5; 
b_split = split_boundary(b,SPLIT_LIM,MIN_DIST) ;

LIM_VAL = 0.5;
OFFSET = 0.125;   % max([dx dy])
m2 = clean_mask(lon,lat,m1,b_split,LIM_VAL,OFFSET) ;

LAKE_TOL = 100;   
IS_GLOBAL = 0; 
[m4,mask_map] = remove_lake(m2,LAKE_TOL,IS_GLOBAL) ;

OBSTR_OFFSET = 1;
[sx1,sy1] = create_obstr(lon,lat,b,m4,OBSTR_OFFSET,OBSTR_OFFSET);

fname='ZA-2M';
depth_scale = 1000;
obstr_scale = 100;
d = round((depth)*depth_scale);
write_ww3file([data_dir,'/',fname,'.bot'],d); 
write_ww3file([data_dir,'/',fname,'.mask_nobound'],m4); 
d1 = round((sx1)*obstr_scale);
d2 = round((sy1)*obstr_scale);
write_ww3obstr([data_dir,'/',fname,'.obst'],d1,d2); 
write_ww3meta([data_dir,'/',fname],[nml_dir,'/gridgen.',fname,'.nml'],'RECT',lon,lat,1/depth_scale,1/obstr_scale,1.0);
