%function [data] = converter;

%
% function [data] = converter;
%
% convert autec met station html files into plain ascii format.
% convert temperatures to degrees C.
% put times in ascending order using decimal julian day
% convert pressures to mbar
% correct pressures for antenna height asl.  Met station is 10 masl, 
% antenna is ~5 masl
%

% get filenames
[s,files]=unix('ls -1 98*.html')
nliof = 19;

% get number of files
no_files = length(files)/nliof

for i = 1:no_files
  
  % current file name
  filename = files((i-1)*19+1:i*19);
  
  % open file
  fid = fopen(filename,'r');

  thisyear=clock;thisyear=thisyear(1);
  
  % read in header junk until you get to the data
  junk = [];
  while isempty(junk)
    tmp = fgetl(fid);
    junk = findstr(tmp,num2str(thisyear));
  end

  datastring = tmp;

  tmp = 1;
  while ~isempty(tmp);
   tmp = fgetl(fid);
   if ~isempty(tmp)
     datastring = [datastring ; tmp];
   else
     tmp = [];
   end
  end

  data.month = str2num(datastring(:,1:2));
  data.day = str2num(datastring(:,4:5));
  data.year = str2num(datastring(:,7:10));
  data.hour = str2num(datastring(:,12:14));
  data.minute = str2num(datastring(:,16:17));
  data.temp_f = str2num(datastring(:,41:45));
  data.pres_hg = str2num(datastring(:,48:55));
  data.rh = str2num(datastring(:,64:67));
  
  % close file
  fclose(fid);

  % convert temperature to Celsius
  data.temp_c = 100*(data.temp_f-32)/180;
  % convert pressure to mbar
  data.pres_mb = data.pres_hg*33.8639;

  % adjust pressures for met station/antenna height difference
  %  met station is ~10 masl
  %  antenna is ~5 masl
  % using trop ref profile, dp/dz at surface =110 mbar/km =0.110mbar/m
  data.dp = 0.110 * (10-5);
  data.cor_pres_mb = data.pres_mb + data.dp;
  
  % compute decimal julian day
  data.jd = zeros(length(data.year),1);
  for i = 1:length(data.year)
    data.jd(i) = julday(data.year(i),data.month(i),data.day(i)) + ...
                (data.hour(i)*60*60 + data.minute(i)*60)/(24*60*60);
  end

  % sort data in ascending time order
  [data.jd,ind] = sort(data.jd);
  data.month=data.month(ind);
  data.day=data.day(ind);
  data.year=data.year(ind);
  data.hour=data.hour(ind);
  data.minute=data.minute(ind);
  data.temp_f=data.temp_f(ind);
  data.pres_hg=data.pres_hg(ind);
  data.rh=data.rh(ind);
  data.temp_c=data.temp_c(ind);
  data.pres_mb=data.pres_mb(ind);
  data.cor_pres_mb=data.cor_pres_mb(ind);

  % save results to ascii file
  outfile = [datastring(1,1:10) '.asc'];
  mmm = [data.jd data.pres_mb data.cor_pres_mb data.temp_c data.rh];
  eval(['save ' outfile ' -ascii mmm'])  
  
end
