function X2 = Synchronize(T1,X1,T2,flag,method,MaxShift);
% function X2 = Synchronize(T1,X1,T2,flag,method,MaxShift);
% interpolates data in matrix X1 taken at times T1 to times T2
% Time is assumed to progress down rows, so T1 and T2 should be column vectors
% and X1 should be a matrix where each column is a set of measurements
% taken at times T1. The output X2 is the columns of X1 interpolated to times T2.
% flag tells the Synchronize what value should be treated as a flag (or nan)
% method is one of:
%      'nearest' - nearest neighbor interpolation
%      'linear'  - linear interpolation
%      'spline'  - cubic spline interpolation
%      'cubic'   - cubic interpolation
%      (see helps for interp1)
% MaxShift is the maximum allowed time shift in the interpolation,
%    or the maximum allowed data gap in T1 that can be interpolated across 

if nargin < 6,
   help Synchronize;
   return;
end


if ~isnan(flag),
   % convert flags to nans
   X1(X1 == flag) = nan;
   T1(T1 == flag) = nan;
end

[T1u,iu] = unique(T1); % sort T1 & remove repeats
% keep track of changes with iu 

cols = size(X1,2);
X2 = repmat(nan,length(T2),cols);

for c = 1:cols,
   f = find(isfinite(T1u+X1(iu,c)));
   if length(f) >= 2,
      X2(:,c) = interp1(T1u(f),X1(iu(f),c),T2,method);
   end   
   
   if isfinite(MaxShift),
      % convert data gaps to nans
      t2 = interp1(T1u(f),T1u(f),T2,'nearest');
      f = find(abs(t2-T2) > MaxShift);
      X2(f,c) = 1.0e+25;
   end
end

if ~isnan(flag),
   % convert nans to flags
   X2(isnan(X2)) = flag;
end
