%
% Function INTPOLOT interpolates the time varying matrix 
% X at the given independent variable TP
%
function Y = intpolot(X,tp)

   [xd,rp,t] = vunpck(X);
   np = size(t,1);
   t0 = t(1);
   tf = t(np);
   
   if tp < t0
      disp(['TP: ',num2str(tp),' is less than the first independent variable.'])
      Y = X;
      return
   end
   if tp > tf
      disp(['TP: ',num2str(tp),' is greater than the last independent variable.'])
      Y = X;
      return
   end
   
   if ~isempty(find(t==tp))
%      disp(['The point to interpolate at, TP: ',num2str(tp),', is already in the data.']);
      Y = X;
      return
   end
   
   ilt = find(t<tp); tl = t(ilt(max(size(ilt))));
   igt = find(t>tp); tg = t(igt(1));
   Xl = vunpck(xtract(X,tl));
   Xg = vunpck(xtract(X,tg));
   Xlt = xtract(X,t0,tl);
   Xgt = xtract(X,tg,tf);
   Xn = Xl + (Xg - Xl)*(tp-tl)/(tg-tl);
   Y = vpck( [vunpck(Xlt);Xn;vunpck(Xgt)],[t(ilt); tp; t(igt)]);
   
end
