function UCIT_batchGetDuinAfslag(command)
%UCIT_BATCHGETDUINAFSLAG   batch command for dune erosion calculations
%
%   This is the McTools batch routine for dune erosion. NB: BATCH dune 
%   erosion currently only works on JARKUS data 
%
%   syntax:
%   UCIT_batchGetDuinAfslag(command)
%
%   input: 
%       command     = options: 'makeList', 'start' 
%
%   See also getDuinAfslagLZK, getDuinAfslagBO, setCalcMeth
% 

% --------------------------------------------------------------------------
% Copyright (c) WL|Delft Hydraulics 2004-2007 FOR INTERNAL USE ONLY 
% Version:      Version 1.2, June 2005 (Version 1.0, February 2004)
% By:           <M. van Koningsveld (email: mark.vankoningsveld@wldelft.nl)>                                                            
% --------------------------------------------------------------------------

if nargin==0
    %Make the gui normal again and uncheck batchmode
    %This can be done by calling UCIT_batchCommand again
%     UCIT_batchCommand;
    
    %Open dialog window for necessary input
    openfig('UCIT_batchDuinafslagInput.fig','reuse');
    UCIT_batchCommand;

else
    switch command
        case 'makeList'
            % Make a batchlist of all to do computations containing 11 columns (numerical) as described below.
            % Each computation will have its own line, with only one transectID, year, area etc.
            
            % Get all yellow transects
            [check]    = UCIT_focusOn_Window('mapWindow');  % make mapWindow the current figure
            if check == 0
                return
            end
            
            % Find all yellow transects
            rayH=findobj(gca,'type','line','LineStyle','-','color',[1 1 0]);
            dpTs=strvcat(get(rayH,'tag'));
            for ii=1:size(dpTs,1);
                if strfind(dpTs(ii,:),'_')
                    res(ii)=1;
                end
            end
            try
                selection=get(rayH(find(res==1)),'tag');
            end
            if ~exist('selection','var')
                errordlg('Select transects first!','');
                return
            end
            
            % Parse the tag of the selected object
            [parts]    = parseStringOnToken(selection,'_'); 

            % Assign parts to proper variables
            DataType   = parts(:,1);
            area       = parts(:,2);
            transectID = parts(:,3);
            soundingID = parts(:,4);
            for ii = 1:length(area)
                kustVak(ii)    = vakNaam2Nummer(area{ii});
            end
            raaiNummer = transectID;

            % Make the batchlist in loops
            guiH=findobj('tag','UCIT_batchDuinafslagInput');
            startYear=str2num(get(findobj(guiH,'tag','UCIT_batchInputStartYear'),'string'));
            endYear=str2num(get(findobj(guiH,'tag','UCIT_batchInputEndYear'),'string'));
            if isempty(startYear)|isempty(endYear)
                errordlg('Incorrect years specified','');
                return
            end
            if startYear>endYear
                [startYear, endYear]=deal(endYear,startYear);
            end
            
            WorkDir = getINIValue('mctoolbox.ini','WorkDir');  
            
            %Specify batchlist file
            [name,pat]=uiputfile([WorkDir '*.*'],'Save batch-list file');
            if name==0
                return
            end
            
            % Via een scherm wordt gevraagd welke methode wordt verlangd
            warning on
            try
                [calcMeth,Norm,Scen]=UCIT_DuinafslagSelector(kustVak);
            catch
                [calcMeth,Norm,Scen]=deal([]);
            end
            
            if isnan(calcMeth) & isnan(Norm) & isnan(Scen)
                return
            end
            
            warning off
            
            try
                Norm = UCIT_ConvertNorm(Norm);
            end
            if isempty(calcMeth) & isempty(Norm) & isempty(Scen)
                errordlg('No input selected!!','UCIT: Error message');
                return
            end
            
            warning on
            
            % Set de huidige directory als werkdirectory, pat is hier altijd gevuld!
            setINIValue('mctoolbox.ini','WorkDir',pat);
            
            %Load the grainsize file
            try
                grainSize=load(getINIValue('mctoolbox.ini','grainSizeFile'));
            catch
                errordlg('Grainsize file incorrect, check mctoolbox.ini','Grainsize file incorrect');
                return
            end
            
            UCIT_batchCommand;
            
            guiH=findobj('tag','UCIT_batchDuinafslagInput');
            if get(findobj(guiH,'tag','WorstYear'),'value')==1
                [jaar,kustVak,raaiNummer] = UCIT_FindWorstRays(kustVak,raaiNummer);
                endYear=1990;
                startYear=1990;
            end
            
            fid=fopen([pat name],'w');
            
            wH=waitbar(0,'Please wait...');
            for iiNorm=1:size(Norm,1) % size rijen
                if size(Norm,1)~=1;
                    waitbar(iiNorm/size(Norm,1),wH,['Producing batchlist ...']);
                end
                if Norm(iiNorm) ~= 0 
                    
                    for iicM=1:size(calcMeth,1) %sie rijen
                        if size(calcMeth,1)~=1;
                            waitbar(iicM/size(calcMeth,1),wH,['Producing batchlist ...']);
                        end                    
                        for iiScen=1:size(Scen,2) % size kolommen
                            if calcMeth(iicM) ~= 0 & Scen(iicM,iiScen) ~= 0 & Scen(iicM,iiScen) ~= -2
                                
                                for yy=1:endYear-startYear+1
                                    for ii=1:length(raaiNummer);
                                        if length(raaiNummer)~=1;
                                            waitbar(ii/length(raaiNummer),wH,['Producing batchlist ...']);
                                        end                    
                                        
                                        % komend uit de batch mode is calcMeth hier met 1 opgehoogd tov normaal.
                                        cM=calcMeth(iicM)-1;
                                        
                                        % norm met een kleine letter is een andere dan Norm
                                        % norm gaat in de batch file
                                        if Norm(iiNorm,1)==1         %'1/100.000'
                                            norm=0.00001;
                                        elseif Norm(iiNorm,1)==2     %'1/40.000'
                                            norm=0.000025;
                                        elseif Norm(iiNorm,1)==3     %'1/20.000'
                                            norm=0.00005;
                                        elseif Norm(iiNorm,1)==4     %'1/10.000'
                                            norm=0.0001;
                                        elseif Norm(iiNorm,1)==5     %'1/5.000'
                                            norm=0.0002;

                                        elseif Norm(iiNorm,1)==6     %'1/100.000'
                                            norm=0.00001;
                                        elseif Norm(iiNorm,1)==7     %'1/40.000'
                                            norm=0.000025;
                                        elseif Norm(iiNorm,1)==8     %'1/10.000'
                                            norm=0.0001;
                                        elseif Norm(iiNorm,1)==9     %'1/4.000'
                                            norm=0.00025;
                                        elseif Norm(iiNorm,1)==10    %'1/1.000'
                                            norm=0.001;
                                        elseif Norm(iiNorm,1)==11    %'1/500'
                                            norm=0.002;
                                        elseif Norm(iiNorm,1)==12    %'1/100'
                                            norm=0.01;

                                        elseif Norm(iiNorm,1)==100   %'Det100'
                                            norm=100;
                                        elseif Norm(iiNorm,1)==1000  %'Det1000'
                                            norm=1000;
                                        elseif Norm(iiNorm,1)==10000 %'Det10000'
                                            norm=10000;
                                        end                    
                                        
                                        %Interpolate hydRVWs and grainSizes
                                        RVW=getRandvoorwaarden(kustVak(ii),str2num(raaiNummer{ii}),cM,Norm(iiNorm,1));
                                        try
                                            isnanRVW=isnan(RVW);
                                        catch
                                            isnanRVW=0;
                                        end
                                        if isnanRVW==0
                                            D=RVW.D;
                                            Rekenpeil=RVW.Rekenpeil;
                                            H0s=RVW.H0s;
                                            Tp=RVW.Tp;
                                            BOfactor=RVW.BOfactor;

                                            if ~isnan(BOfactor)
                                                BOfactor=(100+round(-(BOfactor*100-100)*((log10(norm)/2 + 1))))/100;
                                            end

                                            ScenBatch=nan;
                                            if Scen(iicM,iiScen)==-1
                                                ScenBatch=0;
                                            elseif Scen(iicM,iiScen)==1
                                                ScenBatch=1;
                                            elseif Scen(iicM,iiScen)==2
                                                ScenBatch=2;
                                            elseif Scen(iicM,iiScen)==3
                                                ScenBatch=3;
                                            end

                                            if get(findobj(guiH,'tag','WorstYear'),'value')==1
                                                %Year	Area	Transect	RVW(0)/BO(3)	Rekenpeil	H0s	Tp	D (grainSize)
                                                fprintf(fid,'%i   %i   %s   %i   %f   %f   %f   %f   %f   %f   %i\n',jaar(ii),kustVak(ii),raaiNummer{ii},cM,Rekenpeil,H0s,Tp,D,BOfactor,norm,ScenBatch);
                                            else
                                                %Year	Area	Transect	RVW(0)/BO(3)	Rekenpeil	H0s	Tp	D (grainSize)
                                                fprintf(fid,'%i   %i   %s   %i   %f   %f   %f   %f   %f   %f   %i\n',startYear+yy-1,kustVak(ii),raaiNummer{ii},cM,Rekenpeil,H0s,Tp,D,BOfactor,norm,ScenBatch);
                                            end
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
            close(wH);
            %Put the filename in the GUI
            set(findobj(gcbf,'tag','UCIT_batchDuinafslagFile'),'string',[pat name]);
            
            fclose(fid);
            
            
        case 'start'
            
            %Open file containing conditions made with the produce list
            %command (above)
            %This file must contain:
            %- 11 columns when it has all information needed in the file.
            %  Column order is: startRay; endRay; startArea; endArea;
            %  startYear; endYear; rvw(0)/behOordeel(1); D; Rekenpeil;
            %  H0s; Tp
            %  All this is numerical. Header lines should be preceeded by %
            
            try
                fileName=get(findobj(gcbf,'tag','UCIT_batchDuinafslagFile'),'string');
                if isempty(fileName)
                    errordlg('No batch list produced yet!','No batch list');
                    return
                end
                if ~exist(fileName,'file')
                    errordlg('Batch list file not found!','File not found');
                    return
                end
                rawScenarios=load(fileName);
            catch
                errordlg('File format incorrect','');
                return
            end
                       
            outputDir = getINIValue('mctoolbox.ini','WorkDir');  
            if isempty(outputDir)
                
                [name,outputDir]=uiputfile('dummy','Select output directory');
                if name==0
                    return
                end
                
                % Set de huidige directory als werkdirectory
                if ~isempty(outputDir)
                    setINIValue('mctoolbox.ini','WorkDir',outputDir);
                end 
            end
            
            batchfilename=clock;
            
            batchname=['batchresults.txt'];
            
            fid=fopen([outputDir batchname],'w');
            fprintf(fid,'%s\n','% Jaar  Kustvak   Raai   Methode   Rekenpeil   H0s   Tp   Xp   XpParijsCoordinaatX   XpParijsCoordinaatY   Xr   XrParijsCoordinaatX   XrParijsCoordinaatY   AVolume   TVolume   E   norm   Scen ');
            fclose(fid);
            
            year      = rawScenarios(:,1);
            area      = rawScenarios(:,2);
            ray       = rawScenarios(:,3);
            rvwBO     = rawScenarios(:,4);
            Rekenpeil = rawScenarios(:,5);
            H0s       = rawScenarios(:,6);
            Tp        = rawScenarios(:,7);
            D         = rawScenarios(:,8);
            BOfactor  = rawScenarios(:,9);
            
            for i=1:size(rawScenarios,1)
                switch rawScenarios(i,10)
                    case  0.00001
                        norm{i,1}=['1/100.000'];
                    case  0.000025
                        norm{i,1}=['1/40.000'];
                    case  0.00005
                        norm{i,1}=['1/20.000'];
                    case  0.0001
                        norm{i,1}=['1/10.000'];
                    case  0.0002
                        norm{i,1}=['1/5.000'];
                        
                    case  0.00025
                        norm{i,1}=['1/4.000'];
                    case  0.001
                        norm{i,1}=['1/1.000'];
                    case  0.002
                        norm{i,1}=['1/500'];
                    case  0.01
                        norm{i,1}=['1/100'];
                        
                    case  100
                        norm{i,1}=['Det100'];
                    case  1000
                        norm{i,1}=['Det1000'];
                    case  10000
                        norm{i,1}=['Det10000'];
                end
            end
            
            for i=1:size(rawScenarios,1)
                switch rawScenarios(i,11)
                    case 0
                        Scen{i,1}=['(-)'];
                    case 1
                        Scen{i,1}=['(min)'];
                    case 2
                        Scen{i,1}=['(mid)'];
                    case 3
                        Scen{i,1}=['(max)'];
                end
            end
            
            %Call getDuinafslag looped
            %E.g.:
            diaryname=clock;
            diary([outputDir 'UCIT LOG batchsession ' num2str(diaryname(1,1)) '-' num2str(diaryname(1,2)) '-' num2str(diaryname(1,3)) ' ' num2str(diaryname(1,4)) '.' num2str(diaryname(1,5)) '.txt']);
            
            startTime=now;
            disp(['Batchcalculations started at ' datestr(startTime,13)]);
            disp([' ']);
            
            for ii=1:length(year)
                disp(['Running scenario: ' num2str(ii)]);
                setINIValue('mctoolbox.ini','FrameTxt6',num2str(ii));

                % NB: BATCH dune erosion currently only works on JARKUS data 
                d              = readTransectData('Jarkus Data',vakNummer2Naam(area(ii)),ray(ii),year(ii));
                if isempty(d)
                    disp(['*** Transect ' num2str(ray(ii)) ' in area ' vakNummer2Naam(area(ii)) ' for ' num2str(year(ii)) ' not found...']);
                else
                    calcMeth   = setCalcMeth(rvwBO(ii),1);
                    
                    try 
                        result = getDuinAfslag(d,D(ii), -1,   Rekenpeil(ii),H0s(ii),Tp(ii),1,   calcMeth,outputDir,BOfactor(ii),norm{ii},Scen{ii},0);
                    catch
                        disp(['Failed to determine erosion point in scenario: ' num2str(ii)]);
                        disp(lasterr);
                        result = [];
                    end
                    
                    guiH=findobj('tag','UCIT_batchDuinafslagInput');
                    if get(findobj(guiH,'tag','UCIT_batchDuinafslagPlot'),'value')==1 & ~isempty(result)
                        UCIT_plotDuinAfslag(result);
                        UCIT_preparePlot('plotWindow');
                        UCIT_print;
                    end
                end
                pause(1);
            end
            
%             if ~strcmp(calcMeth,'Durosta - nu')&~strcmp(calcMeth,'Durosta - 50 jaar')&~strcmp(calcMeth,'Durosta - 100 jaar')&~strcmp(calcMeth,'Durosta - 200 jaar')
%                 UCIT_sortOutput('all','OnNorm')
%                 %ucit_GetConsolidationVolumes
%             end    

            disp(['Batch completed in ' datestr(now-startTime,13)]);
            disp([' '])
            
            diary('off')
            
            delete(findobj('tag','UCIT_batchDuinafslagInput'));
    end
end
