function queueOutgoing( target, hourAdjustment )

%hf radar prediction
%SF, February 2, 2012

addpath code

if nargin < 1,
    error('Must specify a target')
end
if nargin < 2,
    hourAdjustment = 0;
end

%-----------------------
% get current UTC time
%-----------------------

if exist('javaMethod'),
    epochSecs = 0.001 * javaMethod('currentTimeMillis','java.lang.System');
    gmtNow = datenum(1970,1,1,0,0,epochSecs);
elseif exist('java_invoke'),
    epochSecs = 0.001 * java_invoke('java.lang.System','currentTimeMillis').doubleValue;
    gmtNow = datenum(1970,1,1,0,0,epochSecs);
elseif exist( 'java' ),
    epochSecs = 0.001 * java.lang.System.currentTimeMillis;
    gmtNow = datenum(1970,1,1,0,0,epochSecs);
else 
    gmtNow = datenum(strftime('%Y-%m-%dT%H:%M:%S',gmtime(time())),'yyyy-mm-ddTHH:MM:SS'); % a bit silly to do all those string ops to make sure the time is in GMT...
end

gmtNow = gmtNow - hourAdjustment/24;

%-----------------------
%-- set parameters
%-----------------------

startDate=floor(gmtNow*24)/24;
for startDate=startDate:-1/24:startDate-1;
  u = [];
  [u,v,x,y,timehf] = webReadHFradar('oma',startDate,0,1);
  if numel(u) > 0,
    break;
  end
end
clear u v x y timehf

pHorizon=1/24; 	%prediction horizon in days, for test_trim1, anything > 1hr is equivalent
netFile='data/net_savefile.mat';	%surrgoate file 

%-----------------------
%-- read and truncate model
%----------------------- 
%load model 
load(netFile,'net');

%trim the model
net=ms2sngPrec(net);

%the following constants are used as shortcuts 
xlags = net.inputDataHistory;
ulags = net.forcingsHistory;
ylags = net.predHorizon;

maxPastIdx=min([xlags ulags]);
maxFutureIdx=max([ulags ylags]);
zeroIdx = abs(maxPastIdx)+1;
deltaT=net.deltaT;

%-----------------------
%-- read IC
%-----------------------
tLine=round([startDate+maxPastIdx*deltaT:deltaT:startDate+pHorizon]'*24)/24;

%load EOF data and EOF mappings
em = fort_readColumns('../../Resources/HFRadarModel/1.ens_mean.mtx',1,'single');	%mean state
U = fort_readColumns('../../Resources/HFRadarModel/1.U.mtx',1:50,'single')';		%EOF matrix
load('data/1.stateInfo.mat','stateInfo');	%mapping between full state and EOF state
load('data/gr.mat','gr');	%grid data

%load HF-Radar data from MBARI shared disk 
%in this first cut, we are working with past data, so we are reading data through the end of the prediction interval
%[u,v,x,y,timehf]=webReadHFradar('oma',startDate,[maxPastIdx*deltaT pHorizon]);
[u,v,x,y,timehf]=webReadHFradar('oma',startDate,[maxPastIdx*deltaT 0],1);

%project HF-Radar data into EOF space (date compression)
data=nan(size(U,1),length(timehf),'single');
for i=1:length(timehf)

  %make input to ens_map_vars2stVect
  tmpIn=[];
  tmpIn.u=u(:,i);
  tmpIn.v=v(:,i);	

  %assemble normalized state vector 
  st=ens_map_vars2stVect(tmpIn,stateInfo,1);

  %if there are any gaps in data (in space)
  %fill them with the value of the mean state
  st(isnan(st))=em(isnan(st));

  %map full space vector into EOF sub-space
  st=st-em;
  data(:,i)=U*st;
end

%deal with possible short gaps in HF radar data. Gaps shorter than 3.01*deltaT are interpolated over
idxnnan=~(timehf==0);
[data tLine_] = filter_time(data(:,idxnnan)', timehf(idxnnan),tLine(1),tLine(end), deltaT, 1,3.01*deltaT);
data=data';tLine_=tLine_';%transpose for consistency
data = data(:,1:zeroIdx); % trim away fluff
%---forcings
%for this specific surrogate, the forcing input is trivial 
forcings=zeros(1,length(tLine)+net.utaps,'single');

try 
  load( fullfile('outgoing',[target '.mat']))
catch lasterr;
  disp(lasterr);
  outgoingMap = [];
end

if isfield(outgoingMap,'time'),
  outgoingMap([outgoingMap.time] < min(tLine)) = [];
end

for i=1:size(data,2),
  fsumOk = 0;
  outgoingMapIndex = length(outgoingMap) + 1;
  fsum = fchecksum(data(:,i));
  for j=1:length(outgoingMap),
    if abs(tLine(i) - outgoingMap(j).time) < 0.01,
      outgoingMapIndex = j;
      allowableDifference = 1e-6;
      if( i < 6 )
        allowableDifference = 10^(-i);
      end
      fsumOk = abs((fsum - outgoingMap(j).fsum)/fsum) < allowableDifference;
    end
  end
  if ~fsumOk,
    outgoingMap(outgoingMapIndex).time = tLine(i);
    outgoingMap(outgoingMapIndex).fsum = fsum;
    path = 'outgoing';
    mkdir( path );
    path = fullfile(path,target);
    mkdir( path );
    path = fullfile(path,datestr(tLine(i),'yyyymmddHH'));
    disp(['saving ' path ] );
    fort_write(path,data(:,i));
  end
end

save( fullfile('outgoing',[target '.mat']), 'outgoingMap');

fort_write('../../Resources/HFRadarModel/gr.hgrid.X.mtx',gr.hgrid.X);
fort_write('../../Resources/HFRadarModel/gr.hgrid.Y.mtx',gr.hgrid.Y);
fort_write('../../Resources/HFRadarModel/gr.hgrid.idx_x2X.mtx',gr.hgrid.idx_x2X);
fort_write('../../Resources/HFRadarModel/net.inputDataHistory.mtx',net.inputDataHistory);
fort_write('../../Resources/HFRadarModel/net.forcingsHistory.mtx',net.forcingsHistory);
fort_write('../../Resources/HFRadarModel/net.inpMean.mtx',net.inpMean);
fort_write('../../Resources/HFRadarModel/net.Tpca.mtx',net.Tpca);
fort_write('../../Resources/HFRadarModel/net.w1.mtx',net.w1);
fort_write('../../Resources/HFRadarModel/net.b1.mtx',net.b1);
fort_write('../../Resources/HFRadarModel/net.TpcaY.mtx',net.TpcaY);
fort_write('../../Resources/HFRadarModel/stateInfo.std.all.mtx',stateInfo.std.all);
