%
%  This script creates maps of the power dissipation index. The quantity 
%  mres specifies the resolution of the maps. 
%  November, 2008
%  Copyright 2009 WindRiskTech L.L.C. 
%  Last modified April, 2024 to take advantage of "ismembertol"
%-------------------------------------------------------------------------
%
params    %  Load parameters
%
shape='circ';
if exist('shearstore','var') == 0 || exist('yearstore','var') == 0
    shape='circ';
    load temp
end
load sorted
clear z
clf('reset')
set(gcf,'visible','off')
%
[n,m]=size(vnet);
%
[~,jmax]=min(vnet,[],2);
jmax=jmax-1;
if exist('yearstore','var') == 0
    yearstore=2000+zeros(1,n);
    freqyear=freq;
end
%
longstore=min(longstore,359.999);
latmask=min(ceil(abs(latstore)),1);
if strcmp(bas,'MT') || strcmp(bas,'AL') %  For Mediterranean and Atlantic basins, rectify longitudes
    longstore = wrapTo180(longstore);
end    
%
pi=acos(-1);
pifac=pi/180;
fac=2*3600*(1852/3600)^3; % Factor to convert power dissipation rate to m^3/s^2
fac=fac/mres^2;
%
if strcmp(bas,'GB')
   projection=gproject;
end   
%
if strcmp(mapmode,'auto')
    mask=ceil(min(max(vnet-30,0),1));  % Added to further restrict area over which computations performed
    xmin=min(nonzeros(mask.*longstore));
    xmax=max(nonzeros(mask.*longstore));
    ymin=min(nonzeros(mask.*latstore));
    ymax=max(nonzeros(mask.*latstore));
    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=-87;
    ymax=87;
end 
xmin2=xmin-mres;
xmax2=xmax+mres;
ymin2=ymin-mres;
ymax2=ymax+mres;
%
y=ymin2:mres:ymax2;
x=xmin2:mres:xmax2; 
%
nx=max(size(x));
ny=max(size(y));
%
yearmin=min(yearstore);
yearmax=max(yearstore);
qy=yearmax-yearmin+1;
year=yearmin:yearmax;
%
dum=nonzeros(latmask.*(longstore+0.01))-0.01;
[longl,ax]=ismembertol(dum,x,1,'DataScale',0.5*mres);
clear dum
%
dum=nonzeros(latmask.*latstore);
[latl,ay]=ismembertol(dum,y,1,'DataScale',0.5*mres);
%
vmr=nonzeros(latmask.*(vnet+0.01))-0.01;
%vmr=nonzeros(vnet);
dum=repmat(max(yearstore',1),[1,m]);
yr=nonzeros(double(dum).*latmask);
if max(size(freqyear)) > 1
    %freqmask=freqyear(yr+1-min(yr));
    atemp=ismember((min(yr):max(yr)),yr);
    atemp=cast(atemp,'like',yr);
    yearset=nonzeros(atemp.*(min(yr):max(yr)));
    [~,nyy]=ismember(yr,yearset);
    freqmask=freqyear(nyy);
else
    freqmask=freq;
end    
clear dum
%
[yearl,an]=ismember(yr,year);
ax=max(ax,1);
ay=max(ay,1);
an=max(an,1);
%
z3=zeros(nx,ny,qy);
N=max(size(latl));
pdi=vmr.^3.*freqmask'.*latl.*longl.*yearl./cos(pifac*latl);
for i=1:N
    z3(ax(i),ay(i),an(i))=z3(ax(i),ay(i),an(i))+pdi(i);
end
% 
z(:,:)=sum(z3,3);
z=1e-4.*z.*fac./n;
%
% Calculate new map limits
%
imin=1;
imax=ny;
kmin=1;
kmax=nx;
if strcmp(mapmode,'auto')
    xmin1=xmax;
    xmax1=xmin;
    ymin1=ymax;
    ymax1=ymin;
    kmin=nx;
    kmax=1;
    imin=ny;
    imax=1;
    zcrit=0.01*max(max(z));
    for j=2:ny-1
        for k=2:nx-1
            if z(k,j) > 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 
%
z=transpose(z);
%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')
    a=colormap(wmap);
    for i=1:8
        a(i,:)=oceancolor;
    end
    colormap(a)
    [C,h]=contourm(z(imin:imax,kmin:kmax),R,12,'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);
end    
%
set(gcf,'visible','on')
%
jj=colorbar;
set(jj,'fontname',axisfont,'fontweight','bold')
cbIm = findobj(jj,'Type','image');
alpha(cbIm,wtrans)
yvec=get(jj,'ylim');
yvec(1,1)=0.1*yvec(1,2);
set(jj,'ylim',yvec)
%
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='Power Dissipation Index Density';
tittot={tita;tit1};
title(tittot,'fontsize',12,'fontweight','bold','interpreter','none')
tightmap
clear latr longr yr longl latl yearl ax ay an pdi freqmask
%
if strcmp(bas,'MT') || strcmp(bas,'AL')  %  For Mediterranean and Atlantic basins, 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 