%
% This script contours the number density of best track genesis points,  
% defined as the first point of each track where wind speeds exceed startv,
% filtered (if desired) to include only those events whose winds speeds 
% exceed some threshold, peakv, and filtered in the same way as the 
% synthetic tracks. Gendensitymt must be run first. This requires 
% installation of the "m_map" routines.
% Copyright 2009 WindRiskTech L.L.C.
% Last modified April, 2024 to take advantage of "ismembertol"
%------------------------------------------------------------------------
%
if exist('shape','var') == 0 || exist('R','var') == 0
    f=msgbox('Need to run gendensitybesttrackmt before running this script');
    return
end   
%
params    %  Load parameters
figure
%
clear latscat longscat z2
%
pifac=acos(-1)/180;
coslat=1./(0.001+cos(pifac.*y));
%
bestproc   %  Process best tracks
%
if strcmp(bas,'GB')
    projection=gproject;
end 
%
longbest=min(longbest,359.99);
if strcmp(bas,'MT') || strcmp(bas,'AL') %  For Mediterranean and Atlantic basins, rectify longitudes
    longbest = wrapTo180(longbest);
end 
%
[nn,m]=size(vbest);
%
[~,jmax]=min(vbest,[],2);
jmax=jmax-1;
%
[~,jmin]=min(max((startv-vbest),0),[],2);
%
yearbeg=min(bestyears);
yearend=max(bestyears);
%
n=0;
latscat=zeros(1,nn);
longscat=zeros(1,nn);
for i=1:nn
    if vmaxb(i) >= peakv 
      n=n+1;
      longscat(n)=longbest(i,jmin(i));
      latscat(n)=latbest(i,jmin(i));
    end   
end
%
longscat(n+1:nn)=[];
latscat(n+1:nn)=[];
%
an=max(size(y));
am=max(size(x));
z2=zeros(an,am);
%
[latl,ay]=ismembertol(latscat,y,1,'DataScale',0.5*gres);
[longl,ax]=ismembertol(longscat,x,1,'DataScale',0.5*gres);
ax=max(ax,1);
ay=max(ay,1);
N=max(size(latl));
ga=latl.*longl./(0.001+cos(pifac*latl));  
for i=1:N
    z2(ay(i),ax(i))=z2(ay(i),ax(i))+ga(i);
end
qp=max(size(bestyears));
z2=z2/(qp*gres^2);
%
gh1=figure('Visible','off');
axesm('MapProjection',projection,'MapLatLimit',[ymin ymax],'MapLonLimit',[xmin xmax], ...
     'frame','on','ffacecolor',oceancolor,'fontname',axisfont,'fontsize',axisfontsize, ...
     'fontweight',axisfontweight,'labelrotation','on')
delx=floor((xmax-xmin)/5);
dely=floor((ymax-ymin)/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(z2(imin:imax,kmin:kmax)), ...
   'Latlim', [ymin ymax], 'Lonlim', [xmin xmax]);
cmax=(max(max(z2(imin:imax,kmin:kmax))));
cint=cmax/15;
colormap(wmap)
if strcmp(wfill,'y')
    a=colormap(wmap);
    for i=1:8
        a(i,:)=oceancolor;
    end
    colormap(a)
    [C,h]=contourm(z2(imin:imax,kmin:kmax),R,cint:cint:cmax,'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(z2(imin:imax,kmin:kmax),R,15);
end    
%
set(gh1,'visible','on')
tightmap
%
geoback(xmin, xmax, ymin, ymax)
mlabel('south')
%
cb=colorbar;
cbIm = findobj(cb,'Type','image');
alpha(cbIm,wtrans)
set(cb,'fontweight','bold')
yvec=get(cb,'ylim');
yvec(1,1)=0.1*yvec(1,2);
set(cb,'ylim',yvec)
%
titbest=['Best track genesis density from ' num2str(yearbeg) ' to ' num2str(yearend)];
title(titbest,'fontsize',12,'fontweight','bold','interpreter','none')
%
% Add button to access documentation of script
%
if strcmp(Docdisp,'y')
    try
        delete(hButton)
    catch    
    end    
    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 