%Script for writing best track data to netcdf 
%
%Load best track data matlab binary
%
filen=input('Enter file name (e.g. attracks)','s');
filein=strcat(filen,'.mat');
load(filein) 
%[st1 st2]=size(stname);
%if st1 > st2
%   stname=transpose(stname);
%end
%
clear filedes
if filen == 'attracks'
 filedes='Atlantic tracks';
elseif filen == 'wptracks'
 filedes='Western North Pacific tracks';
elseif filen == 'eptracks'
 filedes='Eastern North Pacific tracks';
elseif filen == 'iotracks'
 filedes='North Indian Ocean tracks';
elseif filen == 'shtracks'
 filedes='Southern Hemisphere tracks';
elseif filen == 'gbtracks'
 filedes='Global tracks';
end
%
%Netcdf output file
file = strcat(filen,'.nc');
%remove old netcdf file if exists
system(['rm -f ',file]);
%create netcdf file
ncid=netcdf.create(file,'clobber');
%
%add dimensions
nsize=max(size(yeari));
[~,stsize]=size(char(stname));
[~,bsize]=size(basini);
[~,tsize]=size(latm);
[~,msize]=size(monthm);
if msize < tsize
   monthm(:,msize+1:tsize)=0;
   daym(:,msize+1:tsize)=0;
   hourm(:,msize+1:tsize)=0;
end
nsizeid=netcdf.defDim(ncid,'ns',nsize);
bsizeid=netcdf.defDim(ncid,'bs',bsize);
ntimeid=netcdf.defDim(ncid,'time',tsize);
nchrid=netcdf.defDim(ncid,'chr',stsize);

%add and write variables
%
yearid=netcdf.defVar(ncid,'yearic','double',nsizeid);
%
if bsize > 1
     basinid=netcdf.defVar(ncid,'basinic','double',[nsizeid,bsizeid]);
else
     basinid=netcdf.defVar(ncid,'basinic','double',nsizeid);
end
%
nsid=netcdf.defVar(ncid,'nsic','double',nsizeid);
%
stnameid=netcdf.defVar(ncid,'stnamec','char',[nsizeid,nchrid]);
%
monthid=netcdf.defVar(ncid,'monthmc','double',[nsizeid,ntimeid]);
%
dayid=netcdf.defVar(ncid,'daymc','double',[nsizeid,ntimeid]);
%
hourid=netcdf.defVar(ncid,'hourmc','double',[nsizeid,ntimeid]);
%
latid=netcdf.defVar(ncid,'latmc','double',[nsizeid,ntimeid]);
%
longid=netcdf.defVar(ncid,'longmc','double',[nsizeid,ntimeid]);
%
vsid=netcdf.defVar(ncid,'vsmc','double',[nsizeid,ntimeid]);
%
pcid=netcdf.defVar(ncid,'pcmc','double',[nsizeid,ntimeid]);
%
netcdf.endDef(ncid);
%
netcdf.putVar(ncid,yearid,yeari)
netcdf.putVar(ncid,basinid,basini)
netcdf.putVar(ncid,nsid,nsi);
netcdf.putVar(ncid,stnameid,char(stname));
netcdf.putVar(ncid,monthid,monthm);
netcdf.putVar(ncid,dayid,daym);
netcdf.putVar(ncid,hourid,hourm);
netcdf.putVar(ncid,latid,latm);
netcdf.putVar(ncid,longid,longm);
netcdf.putVar(ncid,vsid,vsm);
netcdf.putVar(ncid,pcid,pcm);

%
netcdf.close(ncid);
