% Matlab Script to initialize ICA workspace
% This script is executed by the PLOT_ICA.M script

cnof='PANIC: Can not find/open file: ';
fname_ml = 'mass_lookup.mat';

cached = 0;
if exist(fname_ml,'file')
    pac=1;
    sw=2;
    f1 = dir(fullfile(rootpath,'CALIB','MASS_LOOKUP',sprintf('ICA_MASS_LOOKUP_TABLE%d_V%02d.TAB', pac, sw)));
    f2 = dir(fname_ml);
    if datenum(f1.date) < datenum(f2.date)
        load(fname_ml); % load LookUp
        cached = 1;
    end
end
if ~cached
    LookUp=nan(3,9,14,96);
    for pac=1:3
        for sw=2:9
            fname = fullfile(rootpath,'CALIB','MASS_LOOKUP',sprintf('ICA_MASS_LOOKUP_TABLE%d_V%02d.TAB', pac, sw));
            % dir(fname)
            fid=fopen(fname,'r');
            if fid == -1
                disp([cnof fname]);
            else
                LookUp0=fscanf(fid,'%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d',[14,inf]);
                LookUp(pac, sw, :, 1:size(LookUp0,2)) = LookUp0(:, :);
                fclose(fid);
            end
        end
    end
    clear LookUp0;
    save(fname_ml, 'LookUp');
end

fname_e = 'energy.mat';

cached = 0;
if exist(fname_e,'file')
    pac=1;
    sw=2;
    f1 = dir(fullfile(rootpath,'CALIB','ENERGY',sprintf('ICA_ENERGY_TABLE_V%02d.TAB', sw)));
    f2 = dir(fname_e);
    if datenum(f1.date) < datenum(f2.date)
        load(fname_e); % load E
        cached = 1;
    end
end
if ~cached
    E=nan(9,2,96);
    for sw=2:9
        fname = fullfile(rootpath,'CALIB','ENERGY',sprintf('ICA_ENERGY_TABLE_V%02d.TAB', sw));
        % dir(fname)
        fid=fopen(fname,'r');
        if fid == -1
            disp([cnof fname]);
        else
            E0=fscanf(fid,'%d,%f',[2,inf]);
            E(sw, :, 1:size(E0,2)) = E0(:, :);
            fclose(fid);
        end
    end
    clear E0;
    save(fname_e, 'E');
end

