%%
OPT = struct(...
    'id', 0,...
    'irun', 8,...
    'maindir', fullfile('p:\1002266-xbeach\wave_angle', 'simulations'),...
    'WL', 5,...
    'Hsig', 9,...
    'Tp', 12,...
    'D50', 225e-6,...
    'duration', 5*3600+1000,...
    'angle', 220:10:270,... 
    'thetarange', 180,...
    'dtheta', 5,...
    'remote', false);

[x z] = SimpleProfile;
[x ix] = sort(-x);
z = z(ix);

z = repmat(z, 1, 2)';

morfac = 5;
zsea = min(floor([min(OPT.WL(:)) - max(OPT.Tp(:))/.55 -20]));
xb_setpref('grid_finalise', {'zmin', zsea})

basepath = fullfile(OPT.maindir, sprintf('%08i', OPT.id), 'xbeach', sprintf('run%02i', OPT.irun));

for iangle = 1:length(OPT.angle)
    relang = max(abs(diff([OPT.angle(iangle) 270])), 5);
    y = roundoff([0; tand(relang)*3000/.3], -2);
    xb = xb_generate_model(...
        'bathy', {'x', x, 'y', y, 'z', z, 'ygrid', {'dymin', 5}, 'xgrid', {'dxmin', 5}, 'finalise', {'seaward_extend'}},...
        'tide', {'front' OPT.WL},...
        'waves', {...
        'type', 'jonswap',...
        'Hm0', OPT.Hsig,...
        'Tp', OPT.Tp,...
        'mainang', OPT.angle(iangle),...
        'duration', 3600*morfac},...
...        'wavegrid', {'nbins' 1},...
        'settings', {...
        'morfac', morfac,...
        'epsi', -1,...
        'posdwn', -1,...
        'tintg', 200,...
        'tintm', 1000,...
        'tstop', ceil(OPT.duration/morfac)*morfac,...
        'D50', OPT.D50,...
        'D90', OPT.D50*1.5,...
        'random' 0,...
        'depthscale', 1/6,...
        'outputformat', 'netcdf',...
        'globalvars', {'H' 'ee' 'zs' 'zb' 'sedero' 'ue' 've' 'u' 'v' 'Susg' 'Svsg' 'Subg' 'Svbg' 'ccg' 'dzav' 'ceqsg' 'thetamean' 'D' 'Qb'},...
        'meanvars', {'H' 'ee' 'zs' 'ue' 've' 'u' 'v' 'Susg' 'Svsg' 'Subg' 'Svbg' 'ccg' 'ceqsg' 'thetamean' 'D' 'Qb'},...
        });
    wl = xb_bc_extractwl(xb);
    xb = xb_set_start_time(xb, 'waterlevel', wl);
    
    tstart = xb_get(xb, 'tstart');
    xb = xb_set(xb, 'tstart', tstart+1000, 'morstart', tstart+1000);
    
    mainangle = xb_get(xb, 'bcfile.mainang');
    remainer = mod(.5*OPT.thetarange-.5*OPT.dtheta, OPT.dtheta);
    thetarange = mainangle + [-1 1] * .5 * (OPT.thetarange-2*remainer);
    
    xb = xb_set(xb,...
        'thetamin', thetarange(1),...
        'thetamax', thetarange(2),...
        'dtheta', OPT.dtheta);
    
%     xb = xb_del(xb, 'swtable', 'rt', 'dtbc');
    
    casename = sprintf('angle%03i', OPT.angle(iangle));
    calcdir = fullfile(basepath, casename);
    mkpath(calcdir)
    xb_write_input(calcdir, xb);
end
