%
% This script just plots the first points of each track (for which the
% winds speed > startv), filtered (if desired) to include only those 
% events whose winds speeds exceed some threshold. Points are plooted using
% Google Earth.
% Copyright 2009 WindRiskTech L.L.C.
% Last modified November, 2016
%------------------------------------------------------------------------
%
prompt = {'Add best track genesis points (y or n)'};
dlg_title = 'Add best track genesis points?';
num_lines = 1;
answer = inputdlg(prompt,dlg_title,num_lines);
if isempty(answer) || isempty(answer{1})
    return
end    
nswitch=answer{1};
%
try
    kgenpoints=kml('getempfile');
catch err
    errordlg('The free KML toolbox must be installed into MATLAB to use this script')
    return
end    
%
params    %  Load parameters
  
%
clear x y
if exist('shearstore','var') == 0
    shape='circ';
    load('temp.mat')
end    
load('sorted')
[nn,m]=size(vstore);
%
nm=min(nn,nmax); % Determine number of points to plot
%
x=zeros(1,nm);
y=zeros(1,nm);
%
vmask=ceil(max(vmax-peakv,0)); % Creak mask of NaNs for storms that are insufficinetly intense
vmask=min(vmask,1);
vmask(vmask == 0)=NaN;
u=repmat(vmask,m,1);
%
xi=randperm(nn);   % Ranndomize squence of genesis points
longrand=u'.*longstore(xi,:);
latrand=u'.*latstore(xi,:);
vrand=vnet(xi,:);
vmaxrand=vmax(xi);
%
[~,jmin]=min(max((startv-vrand),0),[],2); % Determine first points at which vnet exceeds startv
%
n=0;
for k=1:nm 
   if vmaxrand(k) >= peakv  % Find first points at which vnet exceeds startv for storms with vmax > peakv
      n=n+1;
      x(n)=longrand(k,jmin(k));
      y(n)=latrand(k,jmin(k));
   end   
end
x(n+1:nm)=[]; % Truncate series of lat-long points if necessary
y(n+1:nm)=[]; 
%
x=wrapTo180(x);  % This appears to be necessary for Google Earth plotting
%
sd=(strcat('FF',rgbconv(fliplr(ccol))));
kgenpoints.scatter(x,y,'iconcolor',sd,'iconscale',1,'altitude',0,'altitudemode','absolute');  % Plot points
%
if strcmp(nswitch,'y')
    clear x2 y2
    %
    bestproc   %  Process best tracks
    %
    [nn,~]=size(vbest);
    [~,jmax]=min(vbest,[],2);
    jmax=jmax-1;
    %
    [~,jmin]=min(max((startv-vbest),0),[],2);
    %
    x2=zeros(1,nn);
    y2=zeros(1,nn);
    n=0;
    load('temp','bas')
    for i=1:nn
        if vmaxb(i) >= peakv && vbest(i,jmin(i)) >= startv 
          n=n+1;
          x2(n)=longbest(i,jmin(i));
          y2(n)=latbest(i,jmin(i));
        end
    end
    x2(n+1:nn)=[];
    y2(n+1:nn)=[];
    x2=wrapTo180(x2);  % This appears to be necessary for Google Earth plotting
    %
    sd=(strcat('FF',rgbconv(fliplr([0 1 1]))));
    kgenpoints.scatter(x2,y2,'iconcolor',sd,'iconscale',1,'altitude',50000,'altitudemode','absolute');  % Plot points
end  
%
kgenpoints.run  % Run Google Earth
%
% Clean up
%
if strcmp(Clearvlbs,'y')
    clearvars('-except',protected_variables{:})
end 