%
restoredefaultpath

clear
close all
clc

pwdStr = pwd;
addpath(fullfile(pwdStr,'fileio'))
addpath(fullfile(pwdStr,'viz'))
addpath(fullfile(pwdStr,'tools'))

HORIZON = fullfile(pwdStr(1:min(findstr(pwdStr,filesep))),...
    getenv('COMPUTERNAME'),'synchronized','horizon');

addpath(fullfile(HORIZON,'tools'))
addpath(fullfile(HORIZON,'soda-ssp-mo'))
soda -docinstall

load('./../../20110930a/worker001/water-balance-components.mat','vInnTrue',...
    'vSinkTrue','vSeepTrue')

while true
    
    sodaWorkerWait()
    

    for r = 1:size(evalResultsPart,1)

        if ~all(isnan(evalResultsPart(r,:))) && ~evalResultsPart(r,sodaPar.evalCol)
            % the model has not been evaluated with...
            % the parameters in the current row

            % read a line from the matrix containing rows of parameter vectors
            parVec = evalResultsPart(r,sodaPar.parCols);

            % call the ensemble Kalman Filter:
            if sodaPar.crashAndBurn
                [ensemblePred,mStatesInn,mStatesNOKF,sodaPar] = sodaEnKF(sodaPar,parVec);

                % compare the model result with the measurements and calculate the...
                % corresponding score according to an objective function:
                for iObj = 1:sodaPar.nObjs
                    eval(sodaPar.objCallStrs{iObj})
                    if isnan(objScore)
                        warning('SODA:objectiveScoreEqualsNaN',...
                            'Objective score is NaN')
                    end
                    evalResultsPart(r,sodaPar.objCols(1,iObj)) = objScore;
                end                
            else
                try
                    [ensemblePred,mStatesInn,mStatesNOKF,sodaPar] = sodaEnKF(sodaPar,parVec);

                    % compare the model result with the measurements and calculate the...
                    % corresponding score according to an objective function:
                    for iObj = 1:sodaPar.nObjs
                        eval(sodaPar.objCallStrs{iObj})
                        if isnan(objScore)
                            warning('SODA:objectiveScoreEqualsNaN',...
                                'Objective score is NaN')
                        end
                        evalResultsPart(r,sodaPar.objCols(1,iObj)) = objScore;
                    end                
                catch
                    evalResultsPart(r,sodaPar.objCols) = sodaPar.badScore;
                end
            end

            % Set the 'model evaluated' flag to true:
            evalResultsPart(r,sodaPar.evalCol) = true;

        end
    end


    save('job.mat','evalResultsPart')

    sodaSspSetStatus('d')
    
end

