function [T,Tmin,Tmax,Pytd,year,month,day] = loadDailyData(fname)
% loadDailyData  Read data from NOAA-formatted CSV file
%
% Synopsis:  loadDailyData
%            loadDailyData(fname)
%            T = loadDailyData(...)
%            [T,Tmin] = loadDailyData(...)
%            [T,Tmin,Tmax] = loadDailyData(...)
%            [T,Tmin,Tmax,Pytd] = loadDailyData(...)
%            [T,Tmin,Tmax,Pytd,year] = loadDailyData(...)
%            [T,Tmin,Tmax,Pytd,year,month] = loadDailyData(...)
%            [T,Tmin,Tmax,Pytd,year,month,day] = loadDailyData(...)
%
% Input:  fname = Name of NOAA data file.  Default: fname='877262.csv'
%
% Output:  T = average temperature for each day of the year (C)
%          Tmin, Tmax = average minimum and average maximum temperature
%                       for each day of the year (C)
%          Pytd = average year-to-date precipitation  (mm)
%          year, month, day = 4-digit year, 2-digit month, and 2-digit
%                             day for each row in the data file.

if nargin<1, fname='877262.csv'; end

% -- Load the data in two steps
%    (1) Scan the first line and extract column names
fileID = fopen(fname);
firstLine = fgets(fileID);            %  Store 1st line in a single string
fclose(fileID);
firstText = strsplit(firstLine,',');  %  Separate 1st line into strings

%    (2) Read all the numerical data by skipping the first line
fid = fopen(fname);
ncol = length(firstText);
fstring = ['%s%s%8d',repmat('%f',1,ncol-3)];
D = textscan(fid, fstring, 'Headerlines', 1, 'Delimiter',',');
fclose(fid);
fprintf('\t%d rows of data read from %s\n',size(D{1,1},1),fname);

% -- Parse data column requested by the calling function
if nargout>0
  iT = strcmp('DLY-TAVG-NORMAL',firstText);
  T = D{1,iT};
end
if nargout>1
  iTmin = strcmp('DLY-TMIN-NORMAL',firstText);
  Tmin = D{1,iTmin};
end
if nargout>2
  iTmax = strcmp('DLY-TMAX-NORMAL',firstText);
  Tmax = D{1,iTmax};
end
if nargout>3
  iPytd = strcmp('YTD-PRCP-NORMAL',firstText);
  Pytd = D{1,iPytd};
end
if nargout>4
  dval = D{1,3};             %  Date column in YYYYMMDD format
  year = floor(dval/10000);  %  Shift four decimal places and truncate
end
if nargout>5
  month = floor( (dval - 10000*year)/100);
end
if nargout>6
  day = floor(dval - 10000*year - 100*month);
end

end