%
%  This script calculates and graphs the distribution of maximum point wind
%  speed for a storm, and contours the result in Google Earth.  Note that
%  for tracks filtered to a specific region, contours are only produced
%  near that region.
%
%  Note:  If discontinuities appear in the result, increase the parameter
%  "timelength" in params.m.
%       January, 2009
%       Copyright 2009 WindRiskTech L.L.C.
%  Last modified, December, 2018
%------------------------------------------------------------------------
trans=0.5;   % Transparency of filled contours
%------------------------------------------------------------------------
%
try
    kswath=kml('getempfile');
catch err
    errordlg('The free KML toolbox must be installed into MATLAB to use this script')
    return
end    
%
params    %  Load parameters
clear yq xq va ua g1 lat long v scale
%
load temp shape
if strcmp(randfac,'y')
    if exist('tmr4','var')
        stop(tmr4)
        delete(tmr4)
        clear tmr4
    end   
    tmr4=timer;
    set(tmr4,'startdelay',2);
    set(tmr4,'timerfcn','try; delete(hms); catch err; end')
    hms=msgbox('Caution: Random draw for wind radii turned on; results will differ with each call');
    start(tmr4)
end    
if exist('shearstore','var') == 0
    shape='circ';
    load('temp.mat')
elseif strcmp(shape,'poly')
    load temp polytype passe xint yint jint kint kfrac    
end
rmstore1=rmstore.*magfac;
rmsestore1=rmsestore.*magfac;
%  
% Randomize radii of maximum wind
%
if strcmp(randfac,'y')
    [nrm,mrm]=size(rmstore);
    rfac=outer(nrm,mrm);
    rmstore1=rmstore1.*rfac;
    rmsestore1=rmsestore1.*rfac;
end
clear utd vtd v rm vse rmse lat long
fs3='sorted';
load(fs3)
%load landtemp
pifac=acos(-1)./180;
%
if exist('nt','var') == 0
    if isempty(storm)
    prompt = {'Order by maximum at POI (1), maximum near POI (2), lifetime maximum (3), or by track number (4)?', ...
        'Track number'};
        dlg_title = 'Track Parameters';
        num_lines = 1;
        answer = inputdlg(prompt,dlg_title,num_lines);
        if isempty(answer) || isempty(answer{1})
            return
        end    
        nswitch=str2double(answer{1});
        if (strcmp(shape,'poly') || city_radius >= 2000) && nswitch == 1
            warndlg('Warning: Winds at POI not meaningful for this set; ordering by maximum near POI')
            nswitch=2;
        end        
        nttemp=str2double(answer{2});
    else    
       nswitch=3;
       prompt={'Track Number'};
       dlg_title='Track Specification';
       num_lines = 1;
       answer = inputdlg(prompt,dlg_title,num_lines);
       if isempty(answer) || isempty(answer{1})
            return
       end
       nttemp=str2double(answer{1});
    end  
    if nswitch == 1
       nt=nsortc(nttemp);
    elseif nswitch == 2
       nt=nsortp(nttemp);
    elseif nswitch == 3   
       nt=nsort(nttemp);
    else
       nt=nttemp;
    end   
end
ntstring=num2str(nt);
%
[~,jmaxd]=min(vstore,[],2);
jmaxd=jmaxd-1;
jmaxd=transpose(jmaxd);
%
[n,m]=size(vstore);
%
clear v lat long rm jmax utd vtd
[~,q]=min(abs(latstore(nt,:)));
q=q-1;
utd(1,:)=transpose(nonzeros(uinc(nt,:)));
vtd(1,:)=transpose(nonzeros(vinc(nt,:)));
lat(1,:)=transpose(nonzeros(latstore(nt,:)));
long(1,:)=transpose(nonzeros(longstore(nt,:)));
v(1,:)=transpose(nonzeros(vstore(nt,:)));
qv=max(size(v));
rm(1,:)=transpose(nonzeros(rmstore1(nt,:)));
vse(1,:)=vsestore(nt,1:qv);
rmse(1,:)=rmsestore1(nt,1:qv);
jmax(1,1)=jmaxd(1,nt);
for i=1:q
    if long(1) > 200 && long (i) < 50
        long(i)=long(i)+360;
    end
end  
%
if strcmp(bound,'auto')
    if (strcmp(shape,'circ') && city_radius > 2000) || (strcmp(shape,'poly') && strcmp(polytype,'closed'))
        bxmin=min(nonzeros(long))-deltax;
        bxmax=max(nonzeros(long))+deltax;
        bymin=min(nonzeros(lat))-deltay;
        bymax=max(nonzeros(lat))+deltay;
    else    
        if strcmp(bound,'auto')
            if strcmp(shape,'circ')
                bxmin=clong-deltax;
                bxmax=clong+deltax;
                bymin=clat-deltay;
                bymax=clat+deltay;
            else
                [~,xsize]=size(xint);
                vtemp=0;
                ixmax=1; 
                for ix=1:xsize
                    if kint(nt,ix) > 0 && vnet(nt,kint(nt,ix)) > vtemp
                        vtemp=vnet(nt,kint(nt,ix));
                        ixmax=ix;
                    end
                end    
                xm=xint(nt,ixmax);
                ym=yint(nt,ixmax);
                bxmin=xm-deltax;
                bxmin=max(bxmin,0);
                bxmax=xm+deltax;
                bymin=ym-deltay;
                bymax=ym+deltay;
            end
        end  
    end
end
%
bxmax=min(bxmax,360);
x=bxmin:dellatlongs:bxmax;
y=bymin:dellatlongs:bymax;
sx=max(size(x));
sy=max(size(y));
if sx == sy
    x(sx+1)=bxmax+dellatlongs;
    sx=sx+1;
end    
landtemp  = landcalc( x,y );
vmaxa=zeros(sx,sy);
[vs1, ~] = pointshortn(lat,long,v,rm,vse,rmse,utd,vtd,y,x,timeres);
vmaxa(:,:)=max(vs1(1,:,:,:),[],2);   
%vmaxa=vmaxa.*(1-0.2.*landtemp);
vmaxa=smoothb(vmaxa,sx-1,2,sy-1);
vmaxa=transpose(vmaxa);
vmaxa=vmaxa*wunitsfac;
%vmaxa=vmaxa.*1.15;  % Conversion to MPH
ld=landcolor;
%
vvm=max(max(vmaxa));
vvmm=10*ceil(0.1*vvm);
cint=floor((vvm-20)./10);
xm=repmat(x,max(size(y)),1);
if min(x) > 200
    xm=xm-360;
end
ym=repmat(y,max(size(x)),1);
ym=ym';
%
kswath.contourf(xm,ym,vmaxa,'numberOfLevels',ceil(vvmm/cint),'transparency',trans);
kswath.contour(xm,ym,vmaxa,'numberOfLevels',ceil(vvmm/cint),'lineWidth',2);
%
a=jet;
kswath.colorbar([0,max(max(vmaxa))],a);
%
if strcmp(plottrack,'y')
    kswath.plot(long(1:jmax),lat(1:jmax),'lineWidth',4,'lineColor','FF000000');
end    
%
z=vmaxa;
%
kswath.run
%
% Clean up
%
delete('Colorbar.png')
if strcmp(Clearvlbs,'y')
    clearvars('-except',protected_variables{:})
end 