%
%  This script reads in the raw tracks files, runs "utrans" to determine
%  translation speed, adds a given fraction of the translation speed to the
%  circular wind speed, orders the tracks by maximum lifetime wind and also
%  by maximum wind at a point of interest, and stores the results. K.
%  Emanuel, November, 2008
%  Copyright 2009 WindRiskTech L.L.C.
%  Last modified January, 2011
%
%------------------------------------------------------------------------
reduction=0.7;  % Specified fraction of translation speed to add to 
                % circular wind speed.
unzip_utility='unzip';  % Local unzip utility command name   
direc='matlab_binaries/';
%------------------------------------------------------------------------
datea=input('Input date (e.g. 2010091712) or file name','s');
if datea(1) == '2'
    storm=input('Input storm name (e.g. AL11)','s');
else
    storm=[];
end    
comm=['del poly.in'];
[status, result]=system(comm);
fs=[unzip_utility ' -o ',direc,datea,storm,'.zip'];
[status, result]=system(fs);
if status ~= 0
    disp('File does not exist')
    return
end    
file=[datea storm '.mat'];
comm=['del temp.mat'];
[status, result]=system(comm);
clear comm
comm=['del sorted.mat'];
[status, result]=system(comm);
clear comm
comm=['rename ' file ' temp.mat'];
[status, result]=system(comm);
shape='circ';
load('temp.mat')
%
%  Use the following two lines to specify latitude and longitude of a point
%  of interest, if other than that provided in the master binary file.
%
% clat=42.0;
% clong= -72.0;
%
[nn,m]=size(vstore);
vloc=zeros(1,nn);
%
[ut,vt,jmax] = utrans(latstore,longstore);
%
if char(shape) == char('poly')
    fs3=['poly.in'];
    a=load(fs3);
    xa=a(:,1);
    ya=a(:,2);
    xb=a(:,3);
    yb=a(:,4);  
    [nseg,dum1]=size(a);
    for i=1:nseg,
        if xa(i) < 0
            xa(i)=xa(i)+360;
        end
        if xb(i) < 0
        xb(i)=xb(i)+360;
        end
    end    
    %  
    [nint,xint,yint,jint,kint] = boxm(longstore,latstore,xa,ya,xb,yb);
    %
    for i=1:nn,
        if kint(i) > 0
            vloc(i)=vstore(i,kint(i))+reduction.*sqrt(ut(i,kint(i)).^2+ ...
                vt(i,kint(i)).^2);
        end    
    end    
    vloc=transpose(vloc);
else
[vs, dir, dayk] = pointseries(latstore,longstore,vstore,rmstore, ...
         monthstore,daystore,hourstore,ut,vt,jmax,clat,clong);
vloc=max(vs,[],2);
end
%
vmax=vstore+reduction.*sqrt(ut.^2+vt.^2);
dum=max(vmax,[],2);
[vsort,nsort]=sortrows(dum,-1);
%
clear dum
[vsortp,nsortp]=sortrows(vloc,-1);
%
file=['sorted'];
%
if char(shape) == char('circ')
save(file,'vs','dir','dayk','vsort','nsort','vsortp','nsortp','freq',...
    'storm','datea')
else
    save(file,'vsort','nsort','vsortp','nsortp','freq',...
    'storm','datea')
end