
%..... file I/O example
%
%   J. Raeder, 09/14/2019  J.Raeder@unh.edu
%
%  data from UNH weather page http://www.weather.unh.edu/graph_page.pl
%  download http://www.weather.unh.edu/data/2019/255.txt


filename='weather_data_2019_255.txt';
if isfile(filename)   %.... check, so you don't download only once
    fprintf('already have the file |%s|\n',filename);
else  %  get the file from the web
    url='http://www.weather.unh.edu/data/2019/255.txt';
    outname=websave(filename,url);
    fprintf('got weather data file |%s|\n',outname);
end

%  return;  %  end script
%  exit;  % don't do this, it closes MATLAB alltogether
fid1=fopen(filename);  %.... open the file, MATLAB assigns an ID
count=-1;              %     line counter
while ~feof(fid1)      %     test for end of file (EOF)
    line=fgetl(fid1);  %     get the next line
    disp(line); %     show the line
    count=count+1;
    % if count>100; break; end;  %  only for debugging
    if count==0; continue; end   %  skip the header line 
    %  header line in the file:
    %  Datetime,RecNbr,WS_mph_Avg,PAR_Den_Avg,WS_mph_S_WVT,WindDir_SD1_WVT,AirTF_Avg,Rain_in_Tot,RH,WindDir_D1_WVT
    la=split(line,',');     %.... split the line on commas, store in array la
    t1(count)=la(1);        %     save the time tag
    F(count)=str2double(la(7));     %       convert the string to a number
    t2(count)=posixtime(datetime(la(1)));  %..... epoch time seconds since 1/1/1970 00:00
    %  return;  %... stops script right here
end
fclose(fid1);
%F  %... take a look
taxis=datetime(t1);  %...... convert to MATLAB  date/time format (it's a bit smart about this) 
plot(taxis,F);

%..... save variables for later (this is much faster than reading and
%      parsing the original file again.
%  see https://www.mathworks.com/help/matlab/matlab_env/save-load-and-delete-workspace-variables.html

save('lec08_weather_2019_255','taxis','F');  %  save, but only variables F and taxis
%   this will be a binary file with a '.mat' extension
%   load('lab08_weather_2019_255')  will restore (read back) the variable



