% 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
icapath='.';
monthlist=['JAN';'FEB';'MAR';'APR';'MAY';'JUN';'JUL';'AUG';'SEP';'OCT';'NOV';'DEC'];
data_date=input('Date of data to import YYYYMMDD:  ','s');
if length(data_date)==8
    dyear=data_date(1:4);
    dmonth=monthlist(str2num(data_date(5:6)),:);
    dday=['D' data_date(7:8)];
else
    disp('Wrong date format');
    exit
end
fcdir=[icapath '/' dyear '/' dmonth '/' dday '/RPCICA*.TAB'];
filelist=dir(fcdir);
cdir=[icapath '/' dyear '/' dmonth '/' dday ];
iontime=[]; badhvmask=[]; shadowmask=[]; promsection=[]; pacclevel=[];
mtable=[]; azim=[]; masschannel=[]; elev=[]; ionspectra=[];
if ~isempty(filelist)
    for jj=1:length(filelist)
	if ~isempty(strfind(filelist(jj).name,'_HK.TAB'))
	    continue;
	end
        disp(filelist(jj).name);
        fid=fopen([cdir '/' filelist(jj).name]);
        indata=fscanf(fid,['%4d %*c %2d %*c %2d %*c %2d %*c %2d %*c %f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f' ...
  ',%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f' ...
  ',%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f' ...
  ',%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f' ...
  ',%f,%f,%f,%f,%f,%f,%f'],[113,inf]);
               iontime=[iontime datenum(indata(1:6,:)')'];
               badhvmask=[badhvmask indata(7,:)];
               shadowmask=[shadowmask indata(8,:)];
               promsection= [promsection indata(9,:)];
               pacclevel=[pacclevel indata(10,:)];
               mtable=[mtable indata(11,:)];
               azim=[azim indata(12:13,:)];
               masschannel=[masschannel indata(14:15,:)];
               elev=[elev indata(16:17,:)];
               ionspectra=[ionspectra indata(18:113,:)];
	fclose(fid);
    end
    save(['ica' data_date '.mat']);
    disp('Now run the PLOT_NRM matlab script.');
else
    disp(['Can not find data file: ' fcdir]); 
end
