%
%  This script calculates and graphs the distribution of accumulated
%  precipitation, in mm, for a given individual storm, and contours the
%  result in Google Earth. Note that for tracks filtered to a specific
%  region, contours are only produced near that region. 
%       January, 2009
%       Copyright 2009 WindRiskTech L.L.C.
%       Revised December 2020 to remove cos(latitude) factor from hy and to
%       allow for higher resolution topography
%
%------------------------------------------------------------------------
trans=0.5;   % Transparency of filled contours
%------------------------------------------------------------------------
%
try
    krainswath=kml('getempfile');
catch err
    errordlg('The free KML toolbox must be installed into MATLAB to use this script')
    return
end    
%
params    %  Load parameters
%
if strcmp(randfac,'y')
    if exist('tmr7','var')
        stop(tmr7)
        delete(tmr7)
        clear tmr7
    end   
    tmr7=timer;
    set(tmr7,'startdelay',2);
    set(tmr7,'timerfcn','try; delete(hms); catch err; end')
    hms=msgbox('Caution: Random draw for wind radii turned on; results will differ with each call');
    start(tmr7)
end 
%
clear lat long v rm vse rmse ush vsh jmax y x h hx hy
if exist('shearstore','var') == 0
    shape='circ';
    clear T600store u850store v850store
    load('temp.mat')
else
    load('temp.mat','vt')
    load('temp.mat','ut')    
    if strcmp(shape,'poly')
        load temp polytype passe xint yint jint kint kfrac 
    end    
end    
fs3='sorted';
load(fs3)
%
if strcmpi(topores,'high')
    load bathymetry_high
else
    load bathymetry
end    
[ntopo,~]=size(bathy);
topores=360/ntopo;
toporesi=1/topores;
%
clear rain v
%
pifac=acos(-1)/180;
dfac=60.*1.852;
knotfac=1852./3600;
sfac=1./(topores.*60.*1852);
c1=0.622.*2.5e6./1e3;
c2=2.5e6.^2./(1e3.*461);
m_to_mm=1000;
rowa_over_rowl=0.00117;
%
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);
if bxmin < 0
    bxmin=bxmin+360;
end
if bxmax < 0
    bxmax=bxmax+360;
end    
%
[n,m]=size(vstore);
%
clear utd vtd
latsize=size(nonzeros(latstore(nt,:)));
utd(1,:)=ut(nt,1:latsize);
vtd(1,:)=vt(nt,1:latsize);
ush=0.*utd;
vsh=ush;
vdrift=1.5.*3600./1852;
vdrift=vdrift.*latstore(1,1)./(abs(latstore(1,1))+1e-8);
if exist('u850store','var') == 1
    ush(1,:)=5.*knotfac.*(utd-u850store(nt,1:latsize));
    vsh(1,:)=5.*knotfac.*(vtd-vdrift.*cos(pifac.*latstore(nt,1:latsize))- ...
        v850store(nt,1:latsize));
end    
lat(1,:)=latstore(nt,1:latsize);
long(1,:)=longstore(nt,1:latsize);
v(1,:)=vstore(nt,1:latsize);
vse(1,:)=vsestore(nt,1:latsize);
%  
% Scale and randomize radii of maximum wind
%
[nrm,mrm]=size(rmstore);
[~, jmaxd]=min(vstore,[],2);
jmaxd=jmaxd-1;
jmaxd=transpose(jmaxd);
rfac=zeros(nrm,mrm)+1;
if strcmp(randfac,'y')
    rfac=outer(nrm,mrm);
end  
%
rm(1,:)=transpose(nonzeros(magfac.*rfac(nt,:).*rmstore(nt,:)));
nrm=max(size(rm));
rmse(1,:)=magfac.*rfac(nt,1:nrm).*rmsestore(nt,1:nrm);
jmax(1,1)=jmaxd(1,nt);
for i=1:jmaxd(nt)
    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));
%  This statement added because in pointwshort it is assumed that if sx=sy
%  POI's are a vector rather than a grid.
if sx == sy
    sx=sx+1;
    x=[x bxmax+dellatlongs];
end    
%
h=zeros(sx,sy);
hx=zeros(sx,sy);
hy=zeros(sx,sy);
%
bathy=max(bathy,-1);
dhdx=sfac*(circshift(bathy,-1,1)-circshift(bathy,0,1));
dhdy=sfac*(circshift(bathy,-1,2)-circshift(bathy,0,2));
%
for i=1:sx
    plong=x(i);
    for j=1:sy
        plat=y(j);
        %
        ib=1+floor(toporesi.*plong);
        ibp=ib+1;
        if ibp > ntopo
            ibp=ibp-ntopo;
        end    
        ibs=1+floor(toporesi.*plong-0.5);
        ibsp=ibs+1;
        plongs=plong;
        if ibs < 0
            ibs=ntopo;
            plongs=plong+360;
        end    
        if ibsp > ntopo
            ibsp=ibsp-ntopo;
        end
        jb=1+floor(toporesi.*(plat+90));
        jbs=1+floor(toporesi.*(plat+90)-0.5);
        b1=bathy(ib,jb);
        b2=bathy(ib,jb+1);
        b3=bathy(ibp,jb);
        b4=bathy(ibp,jb+1);
        dely=1+toporesi.*(plat+90)-jb;
        delx=1+toporesi.*plong-ib;
        d1=(1.-delx).*(1.-dely);
        d2=dely.*(1.-delx);
        d3=delx.*(1.-dely);
        d4=delx.*dely;
        h(i,j)=exp(d1.*log(b1+11)+d2.*log(b2+11)+d3.*log(b3+11)+d4.*log(b4+11))-11;
        %
        b1=dhdx(ibs,jbs);
        b2=dhdx(ibs,jbs+1);
        b3=dhdx(ibsp,jbs);
        b4=dhdx(ibsp,jbs+1);
        dely=0.5+toporesi.*(plat+90)-jbs;
        delx=0.5+toporesi.*plongs-ibs;
        d1=(1.-delx).*(1.-dely);
        d2=dely.*(1.-delx);
        d3=delx.*(1.-dely);
        d4=delx.*dely;
        hx(i,j)=(b1.*d1+b2.*d2+b3.*d3+b4.*d4)./cos(pifac.*plat);
        %
        b1=dhdy(ibs,jbs);
        b2=dhdy(ibs,jbs+1);
        b3=dhdy(ibsp,jbs);
        b4=dhdy(ibsp,jbs+1);
        hy(i,j)=(b1.*d1+b2.*d2+b3.*d3+b4.*d4);    
        %
    end
end   
%
if exist('T600store','var')
    clear q900 q600
    [ q900, q600 ] = qs900b( T600store(nt,:), vstore(nt,:) );
    wq = pointwshortnq(lat,long,q900,v,rm,vse,rmse,utd,vtd,ush,vsh,y,x,h,hx,hy,timeres,wrad);
else
    w = pointwshortn(lat,long,v,rm,vse,rmse,utd,vtd,ush,vsh,y,x,h,hx,hy,timeres);
    wq=max(w-wrad,0).*q900;
    clear w
end    
temp=eprecip.*m_to_mm.*timeres.*3600.*rowa_over_rowl.*sum(wq,2);
rain(:,:)=temp;
z=rain;
clear temp
%rain=smooth2(rain);
rain=transpose(rain);
%rain=min(rain,300);
%
xm=repmat(x,max(size(y)),1);
if min(x) > 200
    xm=xm-360;
end
ym=repmat(y,max(size(x)),1);
ym=ym';
%
krainswath.contourf(xm,ym,runitsfac*rain,'numberOfLevels',runitsfac*raincntrs,'transparency',trans);
krainswath.contour(xm,ym,runitsfac*rain,'numberOfLevels',runitsfac*raincntrs,'lineWidth',2);
%
a=jet;
krainswath.colorbar([0,max(max(runitsfac*rain))],a);
%
if plottrack == 'y'
    krainswath.plot(long(1:jmax),lat(1:jmax),'lineWidth',4,'lineColor','FF000000');
end    
%
if exist('tmr7','var')
    stop(tmr7)
    delete(tmr7)
    clear tmr7
end
%
krainswath.run
%
% Clean up
%
delete('Colorbar.png')
if strcmp(Clearvlbs,'y')
    clearvars('-except',protected_variables{:})
end 