% Program to demonstrate writing time-tagged KML information
% Plots the history of TA station installations.
% TA station coordinates and start and end dates obtained in Excel format
% from IRIS DMC.
%
clear
%
% read an Excel file which contains station names, coordinates and start
% and end dates
%
[tmp sta_name] = xlsread('talist.xls');
%
% The following date conversions did not work as advertised in the Matlab
% documentation for the xlsread command, so I adjusted them to work.
%
start_date = tmp(:,4)  + datenum('01-Jan-1900')-2; % read column 7 and convert to matlab date
end_date   = tmp(:,6) + datenum('01-Jan-1900')-2; % read column 12 and convert to matlab date
%
lat = tmp(:,1); % get latitude from column 1
lon = tmp(:,2); % get longitude from column 2

nsta = length(lat);
col  = zeros(nsta);
fprintf('Number of stations read: %d\n',nsta);
%
% set some dates we will use for changing station colors
%
tnow   = datenum('30-Aug-2011');
tend   = datenum('30-Sep-2013'); % end the movie here
%
% this next block of code just sets the style of placemark that I want to use
% for each station - depending on whether station is in the past, present
% or future
%
for k=1:nsta
    if end_date(k) > tend      % trim the year=2599 end dates so movie won't run forever
        end_date(k) = tend;
    end;
    col(k) = 2;               % default placemark #2 for currently operating stations - green
    if end_date(k) < tnow     % station already removed - use placemark #1 - red
        col(k) = 1;
    end
    if start_date(k) > tnow   % station not yet installed - placemark #3 - blue
        col(k) = 3;
    end
end;
fprintf('Finished processing stations\n');
%
% now write out the KML file
%
fid = fopen('taplot.kml','w'); % open the file
a   = write_kml_preamble(fid); % write the preamble
%
% write placemarks for each station
%
h1 = write_kml_locs(fid,sta_name,start_date,end_date,lat,lon,col);
%
% wrap up the KML file
%
fprintf(fid,'%s\n','</Document>');
fprintf(fid,'%s\n','</kml>');
%
% Close and exit
%
status     = fclose(fid);
fprintf('total frames %d:\n',k);