close all
clear all

import_netcdf;  %Required for Octave.

load('JuneJulMeanWinds.mat');

GRIB_path = 'GribFiles/';

while(1)  %Repeat forever, checks for new grib files every 10 seconds.

files = dir([GRIB_path '2*GFS*.grb']);

for i = 1:length(files)
    %Convert new grib files to netcdf.
    nc_filenm = [files(i).name(1:end-4) '.nc'];
    if(~exist([GRIB_path nc_filenm]))
        disp([nc_filenm ' does not exist, converting']);
        
        cmd = ['cdo -f nc copy ' GRIB_path files(i).name ' ' GRIB_path nc_filenm];
        disp(['Running ' cmd]);
        system(cmd);
        
    end
    
    blended_nc_filenm = ['blended_' files(i).name(1:end-4) '.nc'];
    
    if(~exist([GRIB_path blended_nc_filenm]))
        
        cmd = ['cp ' GRIB_path nc_filenm  ' ' GRIB_path blended_nc_filenm]
        system(cmd);
        
        [GRIB_path blended_nc_filenm]
                        
        ncid = netcdf.open([GRIB_path blended_nc_filenm],'WRITE');
        
        lon_id = netcdf.inqVarID(ncid,'lon');
        lon = netcdf.getVar(ncid,lon_id);
        lat_id = netcdf.inqVarID(ncid,'lat');
        lat = netcdf.getVar(ncid,lat_id);
        u_id = netcdf.inqVarID(ncid,'var33');
        u = netcdf.getVar(ncid,u_id);
        v_id = netcdf.inqVarID(ncid,'var34');
        v = netcdf.getVar(ncid,v_id);
        time_id = netcdf.inqVarID(ncid,'time');
        time = netcdf.getVar(ncid,time_id);  %This reports time in days from some unknown time.
        
        time_shift = datenum(55143,2,5)-datenum(2014,6,3);  %This adjusts to matlab datenums.  Appropriate shift was found empirically.
        time = time - time_shift;
        
        n_times = length(time);
        delta_t = 24*diff(time(end-1:end));  %Delta time in hours
               
        
        %Modify template variables.
        [XX,YY] = meshgrid(longitude,latitude);
        [X,Y] = meshgrid(lon,lat);
        u_interp = interp2(XX,YY,u_mean',X,Y);
        v_interp = interp2(XX,YY,v_mean',X,Y);
        
        
        
        for n = 1:n_times
          %Linear Blend over length of grib file.  
            %m = (n-1)/(n_times-1);  %0->1
            %f = 1-m;                %1->0
          %Linear Blend over last 2 thirds of the length of grib file.  
          n_blend_start = floor(n_times/3);
          if(n < n_blend_start)
              m = 0; f = 1;
          else
            m = (n-n_blend_start)/(n_times-n_blend_start);  %0->1
            f = 1-m;                %1->0
          end
          
          u(:,:,1,n) = f*u(:,:,1,n) + m*u_interp';
          v(:,:,1,n) = f*v(:,:,1,n) + m*v_interp';
        end
        
        %Write new values to file
        netcdf.putVar(ncid,u_id,u);
        netcdf.putVar(ncid,v_id,v);
                
        netcdf.close(ncid);
        
        cmd = ['cdo -f grb copy ' GRIB_path blended_nc_filenm ' ' GRIB_path 'blended_' files(i).name];
        disp(['Running ' cmd]);
        system(cmd);
        
    end
    
end

pause(10);

end