function UCIT_sortOutput(RayNumber,Method)
%UCIT_SORTOUTPUT  This routine sorts the output from the batchresults.txt file
%
% This routine sorts the output from the batchresults.txt file. Nu is batch output gesorteerd per jaar.
% Deze file opent een batchfile en produceert een nieuwe file gesorteerd op een of meer ingegeven raainummers 
% Wanneer geen input wordt gegeven of 'all' wordt van alle files een nieuwe output gemaakt plus een totaal overzicht
%
%     syntax:       
%                   UCIT_SortOutput([3000 3025 3050 3075 4000])
%                   UCIT_SortOutput('all','OnNorm')
%
%     input:
%                   Method = 'OnRay', 'OnNorm'
%     output:       Input komt uit de directory 'd:\UCIT_Projects\Output\batchresults'
%                   Uiteindelijke output komt onder een nieuwe naam in diezelfde directory terecht
%
%     See also getDuinAfslagLZK, getDuinAfslagBO, setCalcMeth
% 

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

%Load the output file
WorkDir = getINIValue('mctoolbox.ini','WorkDir');  

try
    OutputFile=load([WorkDir 'batchresults.txt']);
catch
    errordlg('Output file incorrect','Output file incorrect');
    return
end

if nargin == 0
    RayNumber = 'all';
else
    RayArray = RayNumber;
end

if strcmp(lower(RayNumber),'all')
    RayArray = unique(OutputFile(:,3));
    NormArray = unique(OutputFile(:,17));
end

% batchresult output format:
% Jaar  Kustvak   Raai   Methode   Rekenpeil   H0s   Tp   Xp   XpParijsCoordinaatX   XpParijsCoordinaatY   Xr   XrParijsCoordinaatX   XrParijsCoordinaatY   AVolume   TVolume   E   norm   Scen 


% Sort on exceedance frequency
if strcmp(Method,'OnNorm')
    for ii=1:max(size(NormArray));
        % find calculations where norm is a given normfrequency
        Ray=OutputFile(find(OutputFile(:,17)==NormArray(ii)),:);
        
        % sort these on year and put into a new variable OutputRay
        [dum, id]=sort(Ray(:,1));
        OutputRay=Ray(id,:);
        
        % sort OutputRay on raynumber
        [dum, id]=sort(OutputRay(:,3));
        OutputRay=OutputRay(id,:);
        
        % sort these on method (leidraad vs beheerdersoordeel etc)
        [dum, id]=sort(OutputRay(:,4));
        OutputRay=OutputRay(id,:);
        
        % Find the unique climate scenarios that are available in the output
        ClimateScenarioArray = unique(OutputRay(:,18)); % 0=none; 1=min; 2=mid; 3=max 
        
        % For each climate scenario (0=none; 1=min; 2=mid; 3=max) ...
        for mm=1:max(size(ClimateScenarioArray))
            % Initialise variables
            xP=[];
            xR=[];
            idClim=[];
            idMethPerScen=[];
            
            % Find the result ids with that particular scenario (0=none; 1=min; 2=mid; 3=max) ...
            idbla=find(OutputRay(:,18)==ClimateScenarioArray(mm));  
            
            % Then find the unique methods for this particular scenario (0-7, Leidraad Duinafslag - Beheerdersoordeel)
            MethodArray = unique(OutputRay(idbla,4));              
            
            % (still for each climatescenario) and for each available method ...
            for nn=1+size(xP,2):max(size(MethodArray))+size(xP,2)
                try
                    % ... find result ids with a given method and a given climate (each column represents an individual method from the MethodArray)
                    idMethPerScen(:,nn)=find((OutputRay(:,4)==MethodArray(nn) & OutputRay(:,18)==ClimateScenarioArray(mm)));

                    % ... from those result ids store xP and xR values (each column represents values for an individual method from the MethodArray)
                    xP(:,nn)=OutputRay(idMethPerScen(:,nn),8);
                    xR(:,nn)=OutputRay(idMethPerScen(:,nn),11);
                end
            end
            
            % If the current climate from the ClimateScenarioArray is not zero (none) ...
            if ClimateScenarioArray(mm)~=0
                % ... find the result ids where the climate scenario is zero
                idClim0=[];
                if isempty(find(OutputRay(:,18)==0));
                    idClim0=[];
                else
                    idClim0(:,1)=find(OutputRay(:,18)==0);
                end
            
                % If the variable with these result ids is not empty ...
                if ~isempty(idClim0)
                    % ... store for these result ids the xP and xR values 
                    xP0(:,1)=OutputRay(idClim0(:,1),8);
                    xR0(:,1)=OutputRay(idClim0(:,1),11);
                    
                    % add the result ids with climate scenario equal to zero (and thus the method equal to 0 or 4) to the other method ids for this scenario 
                    idMethPerScen=[idClim0(:,1) idMethPerScen(:,:)];
                    xP=[xP0 xP];
                    xR=[xR0 xR];
                end
            end
            
            
            Analysis=[OutputRay(idMethPerScen(:,1),1) OutputRay(idMethPerScen(:,1),2) OutputRay(idMethPerScen(:,1),3) xP(:,:) xR(:,:)];
%             [dum, id]=sort(Analysis(:,3));
%             Analysis=Analysis(id,:);
            
            koptekst=['% Climate scenario: ' UCIT_convertScen(ClimateScenarioArray(mm)) ' Fields: jaar vak raai '];
            
            %xP kopjes
            if ~isempty(find((OutputRay(:,4)==0|OutputRay(:,4)==4) & OutputRay(:,18)==0));
                koptekst=[koptekst 'xP0 '];
            end
            for m=1:max(size(MethodArray))
                if (MethodArray(m)==1|MethodArray(m)==5)&~isempty(find(OutputRay(:,4)==MethodArray(m)&OutputRay(:,18)==ClimateScenarioArray(mm)));
                    koptekst=[koptekst 'xP50 '];
                elseif (MethodArray(m)==2|MethodArray(m)==6)&~isempty(find(OutputRay(:,4)==MethodArray(m)&OutputRay(:,18)==ClimateScenarioArray(mm)));
                    koptekst=[koptekst 'xP100 '];
                elseif (MethodArray(m)==3|MethodArray(m)==7)&~isempty(find(OutputRay(:,4)==MethodArray(m)&OutputRay(:,18)==ClimateScenarioArray(mm)));
                    koptekst=[koptekst 'xP200 '];
                end
            end
            
            %xR kopjes
            if ~isempty(find((OutputRay(:,4)==0|OutputRay(:,4)==4) & OutputRay(:,18)==0))
                koptekst=[koptekst 'xR0 '];
            end
            for m=1:max(size(MethodArray))
                if (MethodArray(m)==1|MethodArray(m)==5)&~isempty(find(OutputRay(:,4)==MethodArray(m)&OutputRay(:,18)==ClimateScenarioArray(mm)))
                    koptekst=[koptekst 'xR50 '];
                elseif (MethodArray(m)==2|MethodArray(m)==6)&~isempty(find(OutputRay(:,4)==MethodArray(m)&OutputRay(:,18)==ClimateScenarioArray(mm)))
                    koptekst=[koptekst 'xR100 '];
                elseif (MethodArray(m)==3|MethodArray(m)==7)&~isempty(find(OutputRay(:,4)==MethodArray(m)&OutputRay(:,18)==ClimateScenarioArray(mm)))
                    koptekst=[koptekst 'xR200 '];
                end
            end
            
            if mm==1
                fid=fopen([WorkDir 'AnalysisResults' num2str(NormArray(ii)) '.txt'],'w');
                fprintf(fid,'%s\n',koptekst);
                fclose(fid);
            else
                fid=fopen([WorkDir 'AnalysisResults' num2str(NormArray(ii)) '.txt'],'a');
                fprintf(fid,'%s\n',koptekst);
                fclose(fid);
            end
            
            actualmatches=(size(Analysis,2)-3); %4 is (1) jaar (2) vak (3) raai 
            format = '%i   %i   %i';
            for m=1:actualmatches
                format = [format '   %8.2f'];
            end
            format = [format '\n'];
            
            fid=fopen([WorkDir 'AnalysisResults' num2str(NormArray(ii)) '.txt'],'a');
            for jj=1:size(Analysis,1);
                fprintf(fid,format,Analysis(jj,:));
            end
            fclose(fid);
        end
        fid=fopen([WorkDir 'batchresults' num2str(NormArray(ii)) '.txt'],'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);
        
        fid=fopen([WorkDir 'batchresults' num2str(NormArray(ii)) '.txt'],'a');
        for jj=1:size(OutputRay,1);
            fprintf(fid,'%i   %i   %i   %i   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.5f    %i\n',OutputRay(jj,:));
        end
        fclose(fid);
        
        %         if strcmp(RayNumber,'all');
        %             fclose(fid);
        %             fid=fopen([WorkDir 'batchresultsnorm_all.txt'],'a');
        %             
        %             for jj=1:size(OutputRay,1);
        %                 fprintf(fid,'%i   %i   %i   %i   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.5f\n',OutputRay(jj,1),OutputRay(jj,2),OutputRay(jj,3),OutputRay(jj,4),OutputRay(jj,5),OutputRay(jj,6),OutputRay(jj,7),OutputRay(jj,8),OutputRay(jj,9),OutputRay(jj,10),OutputRay(jj,11),OutputRay(jj,12),OutputRay(jj,13),OutputRay(jj,14),OutputRay(jj,15),OutputRay(jj,16),OutputRay(jj,17));
        %             end
        %             
        %             fclose(fid);
        %         end
    end
end

% Sort on ray
if strcmp(Method,'OnRay')
    for ii=1:max(size(RayArray));
        Ray=OutputFile(find(OutputFile(:,3)==RayArray(ii)),:);
        % sort on raynumber
        [dum, id]=sort(Ray(:,1));
        OutputRay=Ray(id,:);
        
        fid=fopen([WorkDir 'batchresults' num2str(RayArray(ii)) '.txt'],'a');
        
        for ii=1:size(OutputRay,1);
            fprintf(fid,'%i   %i   %i   %i   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.5f\n',OutputRay(ii,1),OutputRay(ii,2),OutputRay(ii,3),OutputRay(ii,4),OutputRay(ii,5),OutputRay(ii,6),OutputRay(ii,7),OutputRay(ii,8),OutputRay(ii,9),OutputRay(ii,10),OutputRay(ii,11),OutputRay(ii,12),OutputRay(ii,13),OutputRay(ii,14),OutputRay(ii,15),OutputRay(ii,16),OutputRay(ii,17));
        end
        
        if strcmp(RayNumber,'all');
            fclose(fid);
            fid=fopen([WorkDir 'batchresults_all.txt'],'a');
            
            for ii=1:size(OutputRay,1);
                fprintf(fid,'%i   %i   %i   %i   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.2f   %8.5f\n',OutputRay(ii,1),OutputRay(ii,2),OutputRay(ii,3),OutputRay(ii,4),OutputRay(ii,5),OutputRay(ii,6),OutputRay(ii,7),OutputRay(ii,8),OutputRay(ii,9),OutputRay(ii,10),OutputRay(ii,11),OutputRay(ii,12),OutputRay(ii,13),OutputRay(ii,14),OutputRay(ii,15),OutputRay(ii,16),OutputRay(ii,17));
            end
            
            fclose(fid);
        end
    end
end
