%
%  This script calculates and graphs the distribution of maximum point
%  wind speed for a storm.
%  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
%------------------------------------------------------------------------
%
params    %  Load parameters
%
clear yq xq va ua g1 lat long v scale
clf('reset')
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 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
%
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);
%for i=1:sx,
%    for j=1:sy,
%        if vmaxa(j,i) < 50
%            vmaxa(j,i)=NaN;
%        end
%    end
%end    
%vmaxa=vmaxa.*1.15;  % Conversion to MPH
%
%gh=figure('Visible','off');
axesm('MapProjection',projection,'MapLatLimit',[bymin bymax],'MapLonLimit',[bxmin bxmax], ...
     'frame','on','ffacecolor',oceancolor,'fontname',axisfont,'fontsize',axisfontsize, ...
     'fontweight',axisfontweight,'labelrotation','on')
delx=floor((bxmax-bxmin)/5);
dely=floor((bymax-bymin)/5);
gridm('mlinelocation',delx,'plinelocation',dely,'mlabellocation',delx,'plabellocation',dely,'mlabelparallel','south')
if strcmp(gridline,'none')
    gridm('off')
end 
plabel('fontweight','bold'); mlabel('fontweight','bold');
axis off
R = georasterref('RasterSize', size(vmaxa), ...
   'Latlim', [bymin bymax], 'Lonlim', [bxmin bxmax]);
%
geoback(bxmin, bxmax, bymin, bymax)
tightmap
%set(gh,'visible','on')
%
load bathymetry
%
colormap(wmap)
if strcmp(wfill,'y')
    [C,h]=contourm(wunitsfac*vmaxa,R,15,'fill','on');
    hPatch = findobj(h,'Type','patch');
    set(hPatch,'facealpha',wtrans); 
    qh=max(size(hPatch));
    set(hPatch(qh,1),'facealpha',0)
else
    [C1,h1]=contourm(wunitsfac*vmaxa,R,15,'linewidth',1);
end
%
if strcmp(plottrack,'y')
    g=geoshow(lat(1:jmax),long(1:jmax));
    set(g,'linewidth',3)
    set(g,'color','k')
    ua=long(jmax)-long(jmax-1);
    va=lat(jmax)-lat(jmax-1);
    xq=long(jmax-1);
    yq=lat(jmax-1);
    scale=1.2/sqrt(ua^2+va^2);
    ua=ua*scale;
    va=va*scale;
    g1=quiverm(yq,xq,va,ua,0);
    set(g1,'linewidth',3)
    set(g1,'color','k')  
end    
cb1=colorbar;
cb = findobj(gcf,'Type','axes','Tag','Colorbar');
cbIm = findobj(cb,'Type','image');
alpha(cbIm,wtrans)
set(cb1,'fontname',axisfont,'fontweight','bold')
set(get(cb1,'ylabel'),'String',wunitslabel,'fontweight','bold','rotation',0,'horizontalalignment','left');
yvec=get(cb,'ylim');
yvec(1,1)=20;
set(cb,'ylim',yvec)
if isempty(storm)
    datea(1)=upper(datea(1));
    tit1=datea;
    if exist('yearstore','var') == 1 
        tit1={tit1; ['Track number ' ntstring ', year ' char(num2str(yearstore(nt)))]};
    else
        tit1={tit1;['Track number ' ntstring]};
    end    
else
    tit1=[storm(1:2) ' ' storm(3:4) ' ' datea(1:4) ' ' datea(5:6) ' ' datea(7:8)...
    ' ' datea(9:10) ' GMT'];
    titstring2=['Track number ' ntstring  ];
    tit2=titstring2;
    tit1=[tit1 '  ' tit2];
end    
title(tit1,'fontsize',12,'fontweight','bold','interpreter','none')
z=vmaxa;
%
% Add button to access documentation of script
%
if strcmp(Docdisp,'y')
    tempname=mfilename;
    mname = strcat('graphics_docs/html/',tempname,'_doc.html');
    comstr=['open ',mname,';delete(hButton)'];
    labelStr = '<html><center><a href="">Doc';
    hButton = uicontrol('string',labelStr,'pos',[10,10,50,20],'callback',comstr); 
end
%
% Clean up
%
if strcmp(Clearvlbs,'y')
    clearvars('-except',protected_variables{:})
end 