function [ReadNCEPwkData] = ReadNCEPwkData(prefix, last_jdate, file_nc_in, file_ascii_out)
%  function [ReadNCEPwkData] = ReadNCEPwkData(prefix, file_nc_in, file_ascii_out)
%
%         prefix: ="sst" for SST or "err" for Error
%     last_jdate: We only need the data when timej > last_jdate
%     file_nc_in: Original file with NCEP weekly data in netCDF format (input)
% file_ascii_out: Output data file in ascii format: time[jd], lon, lat, sst or err [oC]
% time is the Julian date from 1992-01-01
%
% This function use the netCDF toolbox
%
% Francis Bringas, 2008Sep08

% Reading data in netCDF format:
nc = netcdf(file_nc_in,'nowrite');
times = nc{'time'}(:);                                % time in seconds since 1800-01-01 00:00:00
timej = int16( times - 70125 );                       % time in Julian Days since 1992-01-01 00:00:00
lon = nc{'lon'}(:);                                   % longitude
lat = nc{'lat'}(:);                                   % latitude
var = nc{prefix}(:);                                  % sea surface temperature or error
var_mv = nc{prefix}.missing_value(:);                 % sea surface temperature or error Missing Values (NaN)
var_ao = nc{prefix}.add_offset(:);                    % sea surface temperature or error Add Offset
var_sf = nc{prefix}.scale_factor(:);                  % sea surface temperature or error Scale Factor

% let's select the time values we need (only those between kmin and kmax)
kmin = 1e20;
kmax = -1e20;
for i = 1 : length(times)
    if ( timej(i) > last_jdate )
       if ( i < kmin )
          kmin = i;
       end
       if ( i > kmax )
          kmax = i;
       end
    end
end

% Printing the data in ascii format:
fsal = fopen(file_ascii_out,'w');
for k = kmin : kmax
   for i = 1 : length(lon)
      for j = 1 : length(lat)
         if ( var(k,j,i) == var_mv )
            fprintf(fsal,'%.6g,%.6g,%.6g,%.3s\n', timej(k), lon(i), lat(j), 'NaN');
         else
            var_uv = var_ao + ( var(k,j,i) * var_sf );   % sea surface temperature or error unpacked value
            fprintf(fsal,'%.6g,%.6g,%.6g,%.8g\n', timej(k), lon(i), lat(j), var_uv);
         end
      end
   end
end
fclose(fsal);

ReadJA2nc = 0;

%---------- end of code ----------------

%---------- end of file ----------------