function [u,v,x,y,time]=webReadHFradar(hfType,t0,tWindow,debug)
%[u,v,x,y,time]=readHFradar(hfType,t0,tWindow)
% reads HF currents from the MBARI/CENCOOS repository
%IN
% hfType -- either 'oma' or 'totals'
% t0 -- start time (matlab time)
% tWindow -- [tstart tend] reads hf radara currents for the window t0+tWindow
% 
%OUT
% u	- [npoints,1] u currents
% v	- [npoints,1] v curents
% x	- [npoints,1] longitude
% y	- [npoints,1] latitude
% time	- [ntimes,1] timestamps
%
% SF 2010

u=[];
v=[];
x=[];
y=[];
time=[];

if nargin < 4
  debug =0;
end
if strcmp(hfType,'totals')
  rDir='http://cencalcurrents.org/DataRealTime/Totals/MNTY/';
  prefix='tuv_';
elseif strcmp(hfType,'oma')
  rDir='http://cencalcurrents.org/DataRealTime/Oma/MNTY/';
  prefix='oma_';
else
  error(['Unknown type of HFradar data'])
end
if length(tWindow) > 1,
  times=[t0+tWindow(1):1/24:t0+tWindow(2)];
else
  times = t0+tWindow;
end
times = round(times*24)/24;
for i=1:length(times),
  %disp(['read ' datestr(times(i),31)]);
  dv=datevec(times(i));
  fpath=sprintf('%d_%02d',dv(1:2));
  fname=sprintf('%sMNTY_%d_%02d_%02d_%02d00.mat',prefix,dv(1:4));
  url=[rDir fpath '/' fname];
  apath=fullfile('archive',fpath);
  aname=fullfile(apath,fname);
  if ~exist(apath,'dir')
    mkdir(pwd,apath);
  end
  status=exist(aname,'file');
  if status,
    dirinfo = dir(aname);
    status = dirinfo.bytes > 0;
  end
  if ~status,
    if debug, disp(['get ' url]);end
    [data, status]=urlwrite(url,aname);
  end
  if status,
    dirinfo = dir(aname);
    status = dirinfo.bytes > 0;
  end
  if status
    % Turn warnings off
    warns = warning('query');
    warning('off');
    tmp=load(aname,'TUV');
    % Turn warnings back on
    for iwarn = 1:numel(warns)
    	warning(warns(iwarn).state,warns(iwarn).identifier);
    end
    u(:,i)=tmp.TUV.U;
    v(:,i)=tmp.TUV.V;
    x(:,i)=tmp.TUV.LonLat(:,1);
    y(:,i)=tmp.TUV.LonLat(:,2);
    time(:,i)=tmp.TUV.TimeStamp;
  else
    disp(['Cant read: ' fname])
  end
end
if length(x)>0
  x=x(:,1);
  y=y(:,1);
end


