OPT = struct(...
    'id', 0,...
    'maindir', fullfile(fileparts(which(mfilename)), '..', 'simulations'),...
    'models', {{'durosplus' 'durosta' 'xbeach'}},...
    'variables', {{'WL' 'Hsig' 'Tp' 'D50'}},...
    'sqlfilename', 'results.sqlite');

[dirs dircont] = dirlisting(OPT.maindir, '.svn');
id  = ~cellfun(@isempty, {dircont.content});
dirs = dirs(id);
dircont = dircont(id);


%% Open database
if ~ismember(fullfile(oetroot, 'io', 'sqlite', 'sqlite-jdbc-3.7.2.jar'), javaclasspath)
	javaaddpath(fullfile(oetroot, 'io', 'sqlite', 'sqlite-jdbc-3.7.2.jar'))
end
driver = 'org.sqlite.JDBC';
dbfile = fullfile(OPT.maindir, '..', 'sql', OPT.sqlfilename);
databaseName = ''; %leave blank
userName = ''; %leave blank
password = ''; %leave blank
databaseURL = sprintf('jdbc:sqlite:%s', dbfile);
table = 'data';
sqlexists = exist(dbfile, 'file');

if sqlexists
    % Empty existing database
    query = ['delete from ' table];
else
    % Open new database
    query = ['create table ' table ' (model char, run integer, variable char, WL float, Hsig float, Tp float, D50 float, EV float)'];
end

conn = database(databaseName, userName, password, driver, databaseURL);
cursor = exec(conn, query);
fetch(cursor);
close(conn);

for imodel = 1:length(OPT.models)
    model = OPT.models{imodel};
    idmodel = ~cellfun(@isempty, strfind(dirs, model));
    for ivar = 1:length(OPT.variables)
        variable = OPT.variables{ivar};
        idvar = ~cellfun(@isempty, strfind(dirs, variable));
        selectedcases = dirs(idmodel & idvar);
        if isscalar(selectedcases)
            temp = dir(fullfile(selectedcases{:}, '*.mat'));
            selectedcases = repmat(selectedcases, size(temp));
            for i = 1:length(temp)
                selectedcases{i} = fullfile(selectedcases{i}, temp(i).name);
            end
        end
        for i = 1:length(selectedcases)
            irun = str2double(regexp(selectedcases{i}, '(?<=run)\d{2}', 'match'));
            switch model
                case 'durosplus'
                    load(selectedcases{i}) % load result structure
                    
                    EV = result(1).Volumes.Erosion;
                    
                    WL = result(1).info.input.WL_t;
                    Hsig = result(1).info.input.Hsig_t;
                    Tp = result(1).info.input.Tp_t;
                    D50 = result(1).info.input.D50;
                case 'durosta'
                    [fpath fname] = fileparts(selectedcases{i});
                    D = readDUROSTAResult(fullfile(selectedcases{i}, [fname '.inp']));
                    x = D.Output.FinalProfileX;
                    z0 = D.Output.InitialProfileZ;
                    z1 = D.Output.FinalProfileZ;
                    [dummy result] = jarkus_getVolume(-x, z0, 'x2', -x, 'z2', z1);
                    
                    EV = result.Volumes.Erosion;
                    
                    WL = D.Input.WL;
                    Hsig = D.Input.Hs;
                    Tp = D.Input.Tp;
                    D50 = D.settings.Params.DSED;
                case 'xbeach'
                    xbi = xb_read_input(fullfile(selectedcases{i}, 'params.txt'));
                    xbo = xb_read_output(fullfile(selectedcases{i}, 'xboutput.nc'));
                    x = xs_get(xbo, 'DIMS.globalx_DATA');
                    zb = xs_get(xbo, 'zb');
                    z0 = squeeze(zb(1,1,:));
                    z1 = squeeze(zb(end,1,:));
                    if irun == 1 && strcmp(variable, 'D50')
                        dzav = xs_get(xbo, 'dzav');
                        z1 = z1 - squeeze(dzav(end,1,:));
                    end
                    [dummy result] = jarkus_getVolume(-x, z0, 'x2', -x, 'z2', z1);
                    
                    EV = result.Volumes.Erosion;
                    
                    WL = xs_get(xbi, 'zs0');
                    Hsig = xs_get(xbi, 'bcfile.Hm0');
                    Tp = xs_get(xbi, 'bcfile.Tp');
                    D50 = xs_get(xbi, 'D50');
            end
            conn = database(databaseName, userName, password, driver, databaseURL);
            query = ['insert into ' table ' (model, run, variable, WL, Hsig, Tp, D50, EV) values (' sprintf('''%s'', %i, ''%s'', %g, %g, %g, %g, %g', model, irun, variable, WL, Hsig, Tp, D50, EV) ')'];
            cursor = exec(conn, query);
            fetch(cursor);
            close(conn);
        end
    end
end

