function [data units] = read_uwyo_data(fn)
% function [data units] = read_uwyo_data(fn)
% Read text files from /gea/data/towers/sbbe/YYYY/UWYO_S_YYYY.MM.DD.HH.txt
% data is a structure containing the data
% Two data type structures can be joined with join_uwyo_data.m
%
%                  2020.07.23
% Breno Imbiriba - 2022.07.19
%

%TEST ON FILES
%/gea/data/towers/sbbe/2019/UWYO_2019.01.01.txt
%/gea/data/towers/sbbe/2019/UWYO_2019.01.05.txt


  % Lines are:
  % First two lines (starting with **)
  % Data file dates
  % Headers 
  % If line starts with 'spaces then DD/HH' then it is units
  % Line with === signs indicate field sizes
  % Data starts with station name.

  fh = fopen(fn,'r');
  linn=0;

  % Declare structure
  fields = {'PRES','HGHT','TEMP','DWPT','RELH','MIXR','DRCT','SKNT','THTA','THTE','THTV'};
  units  = {'hPa','m','C','C','%','g/kg','deg','knot','K','K','K'};
  dtypes = {'double','double','double','double','double','double','double','double','double','double','double'};
  data = cell2struct(cell(1,numel(fields)), fields, 2);

  lin = fgetl(fh);
  linn=linn+1;

  % First Line - Station and date 
  if(numel(lin)<4 | lin(1:4)~='****')
    disp(['First line must start with ****']);
    disp([fn ' "' lin '"'])
    warning('Unexpected line');
    return
  end
  % Station 
  station_number=lin(7:11);
  to=strfind(lin,'Observations at');
  station_text=lin(12:to-1);
  sdate = datenum(lin(to+15:end),'HHZ DD mmm YYYY');

  % Next line
  lin=fgetl(fh);
  linn=linn+1;

  % Header Line
  lin=fgetl(fh);
  linn=linn+1;
  datahead={};
  strtmp='';
  for ii=1:numel(lin)
    if(lin(ii)==' ')
      if(numel(strtmp)==0)
	continue
      else 
	datahead{end+1}=strtmp;
	strtmp='';
      end
    else
      strtmp(end+1)=lin(ii);
    end
  end
  if(numel(strtmp)~=0)
    datahead{end+1}=strtmp;
    strtmp='';
  end

  % Units
  lin=fgetl(fh);
  linn=linn+1;
  dataunits={};
  strtmp='';
  for ii=1:numel(lin)
    if(lin(ii)==' ')
      if(numel(strtmp)==0)
	continue
      else 
	dataunits{end+1}=strtmp;
	strtmp='';
      end
    else
      strtmp(end+1)=lin(ii);
    end
  end
  if(numel(strtmp)~=0)
    dataunits{end+1}=strtmp;
    strtmp='';
  end

  % next line
  lin=fgetl(fh);
  linn=linn+1;

  % Start Reading loop

  notdone=true;
  idat=0;
  while(notdone)
    lin=fgetl(fh);
    linn=linn+1;
    if(lin(1:2)=='**')
      notdone=false;
      continue;
    end
    DATA=sscanf(lin,'%g');
    if(numel(DATA)~=numel(datahead))
      sprintf('ERROR READING File %s, Line %d: ', fn, linn);
      sprintf('READ %d COLUMNS BUT EXPECTD %d.',numel(DATA), numel(datahead));
      sprintf('Continuing...');
      continue;
    end
    idat=idat+1;
    for ii=1:numel(datahead)
      data.(datahead{ii})(idat,1)=DATA(ii);
    end
  end

  data.('mtime')=sdate;

  units = [datahead; units];
  fclose(fh);


end
