% Matlab script to read ICA / IMA data for one day
% Start by executing this script first
%
% Set icapath to the directory where the ica data is located
% Tested with Matlab R2011a

%% Find rootpath of archive where directory DATA is located
rootpath = '';
for i=1:5
    if exist(fullfile(rootpath, 'DATA'),'file')
        break
    else
        rootpath = fullfile('..', rootpath);
    end
end
fprintf('rootpath: %s\n', rootpath);

%% Get path to data
icapath=fullfile(rootpath, 'DATA', 'EDITED');
data_date=input('Date of data to import yyyy-mm-dd:  ','s');
dn = datenum(data_date);


cdir=fullfile(icapath, ...
    datestr(dn,'yyyy'), ...
    upper(datestr(dn,'mmm')), ...
    ['D' datestr(dn,'dd')]);
fprintf('cdir: %s\n', cdir);

%% Get files
fcdir=fullfile(cdir, '/RPCICA*.TAB');
filelist=dir(fcdir);

%% initialize matrices
iontime=[]; 
badhvmask=[]; 
shadowmask=[]; 
promsection=[]; 
pacclevel=[];
mtable=[]; 
azim=[]; 
masschannel=[]; 
elev=[]; 
ionspectra=[];

%% Find function to call
if (exist('IMPORT_L2') == 2)
    import = str2func('IMPORT_L2');
else
    import = str2func('import_l2');
end

%% Read data
if ~isempty(filelist)
    for jj=1:length(filelist)
        if ~isempty(strfind(filelist(jj).name,'_HK.TAB'))
            continue;
        end
        if ~isempty(strfind(filelist(jj).name,'_GEOM.TAB'))
            continue;
        end
        disp(filelist(jj).name);
        if ~isempty(strfind(filelist(jj).name,'_08L2.TAB'))
            %% Read 8 e_levels
            disp(' skipping')
            % table = import(fullfile(cdir, filelist(jj).name), 8);
            % Possibly stretch 8 levels to 96 levels
            % But for now skip
            continue;
        elseif ~isempty(strfind(filelist(jj).name,'_32L2.TAB'))
            %% Read 32 e_levels
            disp(' skipping')
            %table = import(fullfile(cdir, filelist(jj).name), 32);
            % Possibly stretch 32 levels to 96 levels
            % But for now skip
            continue;
        elseif ~isempty(strfind(filelist(jj).name,'_96L2.TAB'))
            %% Read 96 e_levels
            table = import(fullfile(cdir, filelist(jj).name), 96);
        else
            % No support for other files
            continue;
        end
        
        iontime=[iontime table.iontime'];
        badhvmask=[badhvmask table.badhvmask'];
        shadowmask=[shadowmask table.shadowmask'];
        promsection= [promsection table.promsection'];
        pacclevel=[pacclevel table.pacclevel'];
        mtable=[mtable table.mtable'];
        azim=[azim table.azim'];
        masschannel=[masschannel table.masschannel'];
        elev=[elev table.elev'];
        ionspectra=[ionspectra table.ionspectra'];
    end
    save(['ica' data_date '.mat']);
    disp('Now run the PLOT_ICA matlab script.');
else
    disp(['Can not find data file: ' fcdir]); 
end
