function [U,V,t]=readJplUV(netcdfDir,tLineIn,xyzdim)
%[U,V,t]=readJplUV(netcdfDir,tLineIn,xyzdim)
%reads U and V velocities from the database of JPL ROMS files
%IN/OUT
% netcdfDir 	-- [string] directory with netcdf files
% tLineIn 	-- [nt,1] in matlab time array of times to be read. 
%	the timestep should be no less than an hour
% xyzdim  	-- [3,1] dimension of a single timestep of u cariable (e.g. [131,171,24])
% U 		-- [xyzdim,length(tLineIn)] array of U velocities
% V		-- [xyzdim,length(tLineIn)] array of V velocities
%
% Sergey Frlov, Feb 2012
%



if min(diff(tLineIn))<0.9/24
  error('Timestep in tLineIn should be at least 1 hour long');
end

%retreave inventory of files on disk
fnames=dir(fullfile(netcdfDir,['mb_fcst_*.nc']));
ncFilesTstart=[];
for i=1:length(fnames)
  ncFilesTstart(i,1)=datenum(fnames(i).name(9:end-3),'yyyymmddHH');
end

U=nan([xyzdim length(tLineIn)],'single');
V=nan([xyzdim length(tLineIn)],'single');
t=nan([length(tLineIn) 1],'single');

for i=1:length(tLineIn)

  idxFile=find((tLineIn(i)-ncFilesTstart)>=0,1,'last');
  if isempty(idxFile)|(tLineIn(i)-ncFilesTstart(idxFile))>2
    error(['Gaps in JPL forecast are too big at: ' datestr(tLineIn(i))]);
  end
  fname_=fullfile(netcdfDir,fnames(idxFile).name);  

  t_=ncread(fname_,'time')/24+ncFilesTstart(idxFile)-1/24;
  [gapLength idxHour]=min(abs(t_-tLineIn(i)));
  if gapLength>2/24
    error(['Read ' fnames(idxFile).name ' but the closest data is more than 2 hours away from ' ...
	datestr(tLineIn(i))]);
  end

  U(:,:,:,i)=ncread(fname_,'u',[1 1 1 idxHour],[inf inf inf 1]);
  V(:,:,:,i)=ncread(fname_,'v',[1 1 1 idxHour],[inf inf inf 1]);
  t(i,1)=tLineIn(i);

end


