%**************************************************************************
% CLUSTER project: Mainprogram                     Autor: Christian Maszl 
% Unit System = [SI]                  Mail: e0025754@student.tuwien.ac.at 
%**************************************************************************
%
% Version 1.0 - 20.08.2004
%

% Reset Variables
clear all;
tic
%**************************************************************************
% Load configuration data like paths, constants, date, ...
%**************************************************************************

% Load configuration data and check the entries.
    syscheck;
  
%**************************************************************************
% Read data from datafiles / [B]=nT [r]=km / Coord. system=GSE 
% [OK] Write a subroutine that detects the files. Style of the filenames: 
% [yymmdd]0000[type].[satellite]
% Example: 0203040000fn.01
%**************************************************************************

% Create filelist of valid files if opmode='a' automatic
    filelist;

% Ask the user a few questions depending on opmode.
    userinput;

%**************************************************************************
% The "BIG LOOP" for all packages or a manual range entry
%**************************************************************************

for lauf=startloop:1:endloop
if (op_mode=='ve')
% Skip yuri at this place and do it in switch
else
% Get the satellite data using the program of Yuri Kothjaintsev (IRFU).
    [D1, D2, D3, D4, B_ok_r_ff,no_B,no_r,B_ff_r_ok,B_ff_r_ff,cell_name,doit]...
    =yuri(instrument,datapath,tempdirpath,myfilelist{lauf,1},...
	 advanced,isdat_db,option);
% Output processing status, remove in the real program
    text1=sprintf('\n%s\n','Data loaded to RAM. Proceed in execution!');
          disp(text1);
% If there is no data in D1 or ... - D4 skip the sorting routine
% and the splitting into B1-B4 and r1-r4 store the not empty data
% to the harddisk.
    if (isempty(find(no_B)) & isempty(find(no_r)))
% [Ok] Sort the data of the four satellites according to the date
% and the satellite numbers
% [Ok] Write a function for the sort routine 
        [D1, D2, D3, D4] = sorting(D1,D2,D3,D4,timeacc);
% Output processing status, remove in the real program
        message=['. data-package sorted. Proceed in execution!'];
        text1  =sprintf('%u%s\n',lauf,message);
        disp(text1);
	% Store the time information for the output-datafile.
        T = D1(:,1);
        % Remove compiled functions in yuri.m from system memory (This should
        % solve the problem of "no data" after more than 30 days.)
        clear functions;
        errorflag_nodata=0;
        if (sum(sum(B_ok_r_ff,2),1)==0 & sum(sum(B_ff_r_ok,2),1)==0)
            errorflag_message=0;
        else
            errorflag_message=1;
        end
        clear dimension filename readin i;
    else
        if (doit=='y')
	    % doit='y' - Empty array filld with zeros and a time line
            [D1, D2, D3, D4] = sorting(D1,D2,D3,D4,timeacc);
            % Output processing status, remove in the real program
            message=['. data-package sorted. Proceed in execution!'];
            text1  =sprintf('%u%s\n',lauf,message);
            disp(text1);
	    message=['Warning: NO DATA ' ...
	              'in at least one of the packages!'] ;  
            text1  =sprintf('%s\n',message);
                    disp(text1);
            disp('Proceed in execution!');
            disp(' ');
	    errorflag_message=1;
            errorflag_nodata =1;
            clear dimension filename readin i;
	else
	    message=['. data-package not sorted. NO DATA ' ...
	              'in at least one of the packages!'] ;  
            text1  =sprintf('%u%s\n',lauf,message);
                    disp(text1);
            disp('Proceed in execution!');
            disp(' ');
            errorflag_message=1;
            errorflag_nodata =1;
            clear dimension filename readin i;
	end
    end	  
end
% Create report according to the errorflags of routine yuri
if (errorflag_message==1)
    report( B_ok_r_ff,no_B,no_r,B_ff_r_ok,B_ff_r_ff,...
    myfilelist,lauf,advanced,mode,nolog,outputspath,varname);
else
end
% If there is no data in D1 or ... - D4 skip the sorting routine
% and the splitting into B1-B4 and r1-r4 store the not empty data
% to the harddisk.
if (isempty(find(no_B)) & isempty(find(no_r)))
%**************************************************************************    
%**************************************************************************
% Here starts the place for the "PLUGINS". Put your subroutines
% into the desired division. SEE BOTTOM of the mainprogram for
% necessary steps!
%**************************************************************************    
%**************************************************************************    

    switch op_mode
       case 'nr'
       % FGM -  4 sec data (fluxgate magnetometer)
       % Check also: cell_name for var. included in DX
            jav_fgm;
	    
       case 'hr'
       % FGM - 45msec data (fluxgate magnetometer)
       % Check also: cell_name for var. included in DX
            jav_fgm;
	    
       case 'vi'
       % CIS - vcis data (cluster ion spectrometry)
       % DATAFORMAT: DX=[t VCp1(:,3) t VCh1(:,3) rXx rXy rXz]
       % Check also: cell_name for var. included in DX
       
       case 've'
       % CIS -  vce data (cluster ion spectrometry)
       % DATAFORMAT: DX=[t VCEp1(:,3) t VCEh1(:,3) rXx rXy rXz]
       % OPERATION ORDER: vcis -> b -> vce (option='nosave')!
       % Check also: cell_name for var. included in DX
       
       % Create mB.mat
            yuri('vcis',datapath,tempdirpath,myfilelist{lauf,1},...
	         advanced,isdat_db,1);    
            clear functions;
            yuri('b',datapath,tempdirpath,myfilelist{lauf,1},...
	         advanced,isdat_db,1);
            clear functions;
            % Use mB.mat and mCIS.mat to get D1 - D4
            [D1, D2, D3, D4, B_ok_r_ff,no_B,no_r,B_ff_r_ok,B_ff_r_ff] = ...
            yuri('vce',datapath,tempdirpath,myfilelist{lauf,1},...
	         advanced,isdat_db,option);
        % Output processing status, remove in the real program
          text1=sprintf('\n%s\n','Data loaded to RAM. Proceed in execution!');
                disp(text1);
       % Remove compiled functions in yuri.m from system memory (This should
       % solve the problem of "no data" after more than 30 days.)
       clear functions;
       
       case 'ni'
       % CIS - ncis data (cluster ion spectrometry)
       % DATAFORMAT: DX=[t NCp1 t NCh1 rXx rXy rXz]
       % Check also: cell_name for var. included in DX
       
       case 'ed'
       % EDI - data (electron drift)
       % DATAFORMAT: DX=[t EDI1(:,3) rXx rXy rXz]
       % Check also: cell_name for var. included in DX
     
       case 'ef'
       % EFW - data (Electric Field and Wave Experiment) 
       % DATAFORMAT: DX=[t weXp12 t weXp34 rXx rXy rXz]
       % Check also: cell_name for var. included in DX
       
       case 'lo'
       % POSITION data
       % DATAFORMAT: DX=[time rXx rXy rXz rXx rXy rXz]
       % Check also: cell_name for var. included in DX
       
       case 'ph'
       % PHASE data
       % DATAFORMAT: DX=[time p rXx rXy rXz]
       % Check also: cell_name for var. included in DX
       
       case 'sa'
       % SAX - Spin Axis Orientation
       % DATAFORMAT: DX=[o1 o2 o3 rXx rXy rXz]
       % Check also: cell_name for var. included in DX
       
       case 'wp'
       % WHISPER - Wave of High Frequency and Sounder for Probing 
       %           of Electron Density by Relaxation
       % DATAFORMAT: DX=[time wX rXx rXy rXz]
       % Check also: cell_name for var. included in DX
       
       case 'sp'
       % PROBE potential (ASPOC)
       % DATAFORMAT: DX=[t P10Hz1p1 P10Hz1p2 P10Hz1p3 P10Hz1p4
       %                   P10Hz1   P1       NVps1(:,2)]
       % Check also: cell_name for var. included in DX  
       
       otherwise
    end
else
end
%**************************************************************************    
%**************************************************************************
% Report succesfull storage of data to the harddisk     
if (lauf~=endloop)
    else
    counter=endloop-startloop+1;
    message=['Computation of ' int2str(counter) ' data-packages ready.'...
	     ' End of execution!'];
    text1  =sprintf('\n%s \n',message);
                disp(text1)                
    end
    clear error* r* B*;
end
%**************************************************************************
% The end of the "BIG LOOP" for all packages or a manual range entry
%**************************************************************************
t=toc;
% Show the computation time
t=num2str(sec2hm(t));
l=size(t,2);
if (l<=2)
    h='0';
    m=t;
else
    h=t(1,1:l-2);
    m=t(1,l-1:l);
end
    text1=sprintf('\n%s%s%s%s\n','Computation time: ',h,':',m);
          disp(text1);
% Clear data in the temporary directory
delete([tempdirpath '*']);
% Free memory and unlock functions
clear a* co* d* e* h* i* m* n* l* o* s* t* y* v* plot_*;
try
munlock sorting;
munlock curlB;
munlock report;
munlock filelist;
catch
% Don't care if one of the files isn't locked.
end
clear functions;

% How to: Implement your subroutine

% 0) Check the end of yuri.m for supported datatypes. The format of
%    D1-D4 is always in the following way: time data position!

% 1) D1-D4 contain all the data (time,position, magnetic field ...)
%    DX=[time yourdata rx(position)]

%    => Split the data in suitable variables (choose the proper case!)

%    NOTE: Check also the variable cell_name. It's possible that
%          there are gaps in DX! (time and r is always
%          included. time at the beginning, r at the end)

% 2) Insert the correct variable name in syscheck.m. This name is
%    used when report display errormessages on the screen. eg. 
%    FGM: D1=[time B1 r1] => varname='B'

%    => Set varname in syscheck.m

%    (Check also if the other settings in syscheck.m suit you!)

% 3) Write a program that perform your calculations

%    => Put this program in the proper case!

% 4) => Store your data to the harddisk!

% 5) => Write a program the plot the data on the screen

% Have a look at the FGM mode (nr & hr) as an example:
% (This mode is tested and hopefully works in a proper way)

% Steps: configfile -> syscheck -> yuri -> sorting -> report
%        jav_fgm    -> datatodisk

%**************************************************************************
% SUPPORTED DATA TYPES
%**************************************************************************
% POSITION data [GSE]

% [parameter]   [output]   [names in {1,1}]   [size]   [format]    [option]
%  r             Cell       R1                 : x 4   t x y z      nosave 
% Comment: Interpolate with av_interp to an arbitrary timeline.
%**************************************************************************
% PHASE data

% [parameter]   [output]   [names in {1,1}]   [size]   [format]    [option]
%  a             Cell       A1                 : x 2    t a         nosave
% Comment: Interpolate with av_interp to an arbitrary timeline.
%**************************************************************************
% SPIN axis vector [GSE]

% [parameter]   [output]   [names in {1,1}]   [size]   [format]    [option]
%  sax           Cell       SAX1               : x 3    x y z       nosave
% Comment: 
%**************************************************************************
% FGM magnetometer data [GSE+DSI]

% [parameter]   [output]   [names in {1,1}]   [size]   [format]    [option]
%  b             Cell       BPP1               : x 4    t x y z     nosave
% Comment: 4sec data

% [parameter]   [output]   [names in {1,1}]   [size]   [format]    [option]
%  bfgm          Cell       B1                 : x 4    t x y z     nosave
% Comment: 45msec data
%**************************************************************************
% CIS (Cluster Ion Spectrometry [GSE+DSI]

% [parameter]   [output]   [names in {1,1}]   [size]   [format]    [option]
%  ncis          Cell       NCp1               : x 2   t p          nosave
%                           NCh1               : x 2   t h         

%  vcis          Cell       VCp1               : x 4   t x y z      nosave
%                           VCh1               : x 4   t x y z     

%  vce           Cell       VCEp1              : x 4   t x y z      nosave
%                           VCEh1              : x 4   t x y z     
% Comment: VCE will only work if you run VCIS and B before! Note
%          that the option 'nosave' has to be disabled in this
%          case. VCE reads the data from mB.mat and mC.mat 
%**************************************************************************
% WHISPER (Wave of HIgh frequency and Sounder for Probing of Electron 
%          density by Relaxation)

% [parameter]   [output]   [names in {1,1}]   [size]   [format]    [option]
%  whip          Cell       WHIP1              : x 2    t w         nosave
%**************************************************************************
% EDI (Electron Drift instrument)

% [parameter]   [output]   [names in {1,1}]   [size]   [format]    [option]
%  edi           Cell       EDI1               : x 4    t x y z     nosave
%**************************************************************************
% ASPOC (Active Spacecraft Potential Control) -> Probe potential

% [parameter]   [output]   [names in {1,1}]   [size]   [format]    [option]
%  p             Cell       P10Hz1p1           : x 2    t x         nosave
%                           P10Hz1p2           : x 2    t x         
%                           P10Hz1p3           : x 2    t x         
%                           P10Hz1p4           : x 2    t x         
%                           P10Hz1             : x 2    t x         
%                           P1                 : x 2    t x         
%                           NVps1              : x 3    t x y
%**************************************************************************
% EFW (Electron Field and Wave instrument)

% [parameter]   [output]   [names in {1,1}]   [size]   [format]    [option]
%  e             Cell       we[X]p12           : x 2    t x         nosave
%                           we[X]p34           : x 2    t x         
%**************************************************************************
