%
% This script contours the number density of all 2 hour track points,  
% filtered (if desired) to include only those events whose winds speeds 
% exceed some threshold, peakv. It requires installation of the
% "m_map" routines.
% Copyright 2009 WindRiskTech L.L.C.
% Last modified April, 2024 to take advantage of "ismembertol"
%------------------------------------------------------------------------
%
params    %  Load parameters
%
clear latscat longscat y x z 
clf('reset')
set(gcf,'visible','off')
if exist('shearstore','var') == 0
    shape='circ';
    load('temp.mat')
end
load('sorted')
[nn,m]=size(vstore);
if strcmp(bas,'GB')
    projection=gproject;
end    
if exist('yearstore','var') == 0
    yearstore=2000+zeros(1,nn);
    freqyear=freq;
end
%
pi=acos(-1);
pifac=pi/180;
%
longstore=min(longstore,359.99);
latmask=min(ceil(abs(latstore)),1);
if strcmp(bas,'MT') %  For Mediterranean basin, rectify longitudes
    longstore = wrapTo180(longstore);
end 
%
if strcmp(mapmode,'auto')
    xmin=min(nonzeros(longstore))-dellong;
    xmax=max(nonzeros(longstore))+dellong;
    ymin=min(nonzeros(latstore))-dellat;
    ymax=max(nonzeros(latstore))+dellat;
    xmin=mres*floor(xmin/mres);
    xmax=mres*ceil(xmax/mres);
    ymin=mres*floor(ymin/mres);
    ymax=mres*ceil(ymax/mres);
else
    xmin=longmin;
    xmax=longmax;
    ymin=latmin;
    ymax=latmax;
end 
if strcmp(bas,'GB')
    xmin=0;
    xmax=360;
    ymin=-84;
    ymax=84;
end    
if (strcmp(bas,'AL') && max(latstore(:,1)) < 55) || strcmp(bas,'EW')
    xmin=max(xmin,200);
    xmax=min(xmax,360);
    ymin=max(ymin,0);
end
x=xmin:mres:xmax;
y=ymin:mres:ymax;
an=max(size(y));
am=max(size(x));
z=zeros(an,am);
%
vmax2=ceil(min(max(vmax-peakv,0),1));
[dum1,dum2]=size(vmax2);
if dum2 > dum1
    vmax2=vmax2';
end    
vmax3=repmat(vmax2,[1,m]);
atemp=ismember((min(yearstore):max(yearstore)),yearstore);
atemp=cast(atemp,'like',yearstore);
yearset=nonzeros(atemp.*(min(yearstore):max(yearstore)));
[~,nyy]=ismember(yearstore,yearset);
freqmask=freqyear(nyy);
freqmask2=repmat(freqmask,[1,m]);
dum=nonzeros(vmax3'.*latstore'.*latmask');
[latl,ay]=ismembertol(dum,y,1,'DataScale',0.5*mres);
dum=nonzeros(vmax3'.*(longstore+0.001)'.*latmask');
[longl,ax]=ismembertol(dum,x,1,'DataScale',0.5*mres);
clear dum
vl=ceil(min(max((nonzeros(vmax3'.*vnet'.*latmask')-minv),0),1));
%
ax=max(ax,1);
ay=max(ay,1);
%
N=max(size(vl));
den=freqmask2(1:N)'.*vl(1:N).*latl(1:N).*longl(1:N)./cos(pifac*latl(1:N));
%
for i=2:N
    if ay(i) ~= ay(i-1) || ax(i) ~= ax(i-1) % This test insures that each track is counted only once per lat-long box
                                            % though it will count tracks that leave a box and then re-enter it
        z(ay(i),ax(i))=z(ay(i),ax(i))+den(i);
    end    
end
z=z./(nn*mres^2);
%
% Calculate new map limits
%
imin=1;
imax=an;
kmin=1;
kmax=am;
if strcmp(mapmode,'auto')
    xmin1=xmax;
    xmax1=xmin;
    ymin1=ymax;
    ymax1=ymin;
    kmin=am;
    kmax=1;
    imin=an;
    imax=1;
    zcrit=0.01*max(max(z));
    for j=1:an
        for k=1:am
            if z(j,k) > zcrit
                xmin1=min(xmin1,x(k));
                xmax1=max(xmax1,x(k));
                ymin1=min(ymin1,y(j));
                ymax1=max(ymax1,y(j));
                kmin=min(kmin,k);
                kmax=max(kmax,k);
                imin=min(imin,j);
                imax=max(imax,j);
            end    
        end
    end    
    xmin=xmin1;
    ymin=ymin1;
    xmax=xmax1;
    ymax=ymax1;
end    
%gh=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(z(imin:imax,kmin:kmax)), ...
   'Latlim', [ymin ymax], 'Lonlim', [xmin xmax]);
%
geoback(xmin, xmax, ymin, ymax)
mlabel('south')
%
colormap(wmap)
if strcmp(wfill,'y')
    [C,h]=contourm(z(imin:imax,kmin:kmax),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(z(imin:imax,kmin:kmax),R,15,'linewidth',1);
end
%
set(gcf,'visible','on')
%
cb=colorbar;
set(cb,'fontname',axisfont,'fontweight','bold')
yvec=get(cb,'ylim');
yvec(1,1)=0.1*yvec(1,2);
set(cb,'ylim',yvec)
cbIm = findobj(cb,'Type','image');
alpha(cbIm,wtrans)
if isempty(storm)
    datea(1)=upper(datea(1));
    tit1=datea;
else
    tit1=[storm(1:2) ' ' storm(3:4) ' ' datea(1:4) ' ' datea(5:6) ' ' datea(7:8)...
    ' ' datea(9:10) ' GMT'];
end    
tita='Track Density';
tittot={tita;tit1};
title(tittot,'fontsize',12,'fontweight','bold','interpreter','none')
tightmap
%
if strcmp(bas,'MT')    %  For Mediterranean basin, reset longitudes
    load temp longstore
end 
%
% 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 