% Program tape5_to_rtp.m
%
% Read in tape5*mat files anc convert to a single RTPv105 file
%

% Created: 29 January 2009, Scott Hannon
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


addpath /asl/matlab/h4tools    % rtpwrite
addpath /asl/matlab/science    % utc2tai

allfname = dir('tape5*mat');

nemisin = 325;
iemisout = [2,65:2:171, 173:3:263, 324];
%%% [2,64:2:172, 174:3:264, 324];
nemisout = length(iemisout);

sitelat = 36.606;
sitelon = -97.485;
sitealt = 315;
sitelandfrac = 1;
sitesolzen = 179;

yearind = 7:10;
monthind = 11:12;
dayind = 13:14;
hourind = 15:16;

maxlev = 96;
zobs = 705000;

fout = 'tape5ip.rtp';

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

nfiles = length(allfname);

head.ptype = 0;   % levels profile
head.pfields = 1; % profile data
head.ngas = 2;
head.glist = [1; 3];
head.gunit = [20; 20];
head.nchan = 2378;
head.ichan = (1:2378)'; %' want all AIRS channels

prof.plat = sitelat*ones(1,nfiles);
prof.plon = sitelat*ones(1,nfiles);
prof.ptime = zeros(1,nfiles);
%
prof.stemp = zeros(1,nfiles);
prof.salti = sitealt*ones(1,nfiles);
prof.spres = zeros(1,nfiles);
prof.landfrac = sitelandfrac*ones(1,nfiles);
prof.nemis = nemisout*ones(1,nfiles);
prof.efreq = zeros(nemisout,nfiles);
prof.emis = zeros(nemisout,nfiles);
prof.nrho = prof.nemis;
prof.rfreq=prof.efreq;
prof.rho = prof.emis;
%
prof.nlevs = zeros(1,nfiles);
prof.plevs = zeros(maxlev,nfiles);
prof.ptemp = zeros(maxlev,nfiles);
prof.gas_1 = zeros(maxlev,nfiles);
prof.gas_3 = zeros(maxlev,nfiles);
prof.co2ppm = zeros(1,nfiles);
%
prof.pobs = zeros(1,nfiles);
prof.zobs = zobs*ones(1,nfiles);
prof.upwell = ones(1,nfiles);
prof.scanang = zeros(1,nfiles);
prof.solzen = sitesolzen*ones(1,nfiles);
%
prof.rlat = prof.plat;
prof.rlon = prof.plon;

% Loop over files
for ii=1:nfiles
   fname = allfname(ii).name;
   year = str2num(fname(yearind));
   month = str2num(fname(monthind));
   day = str2num(fname(dayind));
   dhour = str2num(fname(hourind));
   %
   prof.ptime(ii) = utc2tai(year,month,day, dhour);

   load(fname);
   nlev = length(profile.pres);
ind = nlev:-1:1;
   prof.nlevs(ii) = nlev;
   prof.plevs(ind,ii) = profile.pres;
   prof.ptemp(ind,ii) = profile.temp;
   prof.gas_1(ind,ii) = profile.water;
   prof.gas_3(ind,ii) = profile.ozone;
   prof.co2ppm(ii) = mean(profile.co2);
   %
   prof.spres(ii) = profile.pres(1);
   prof.stemp(ii) = surfT;
   prof.efreq(:,ii) = surfEwn(iemisout);
   prof.emis(:,ii) = surfE(iemisout);
   prof.rfreq(:,ii) = prof.efreq(:,ii);
   prof.rho(:,ii) = (1 - prof.emis(:,ii))/pi;
   %
   prof.scanang(ii) = 180.0 - zenith_angle;
end

rtpwrite(fout,head,[],prof,[]);

%%% end of program %%%
