//-------------------------------------------------------------------//
// Synopsis:    Linear piecwise interpolation.

// Syntax:      y = lintrp2 ( X, XD, YD )

// Description:

//      This function performs piecewise linear interpolation through
//      data defined by vectors xd,yd. The components of xd are
//      presumed to be in nondecreasing order. Any point where
//      xd(i)==xd(i+1) generates a jump discontinuity. For points
//      outside the data range, the interpolation gives yd(1) for x <
//      xd(1), and gives yd(nd) for x > x(nd), where nd=length(xd).
//
//      This function is a faster version of lintrp.
//

//      Tzong-Shuoh Yang  (yang@isec.com) 4/21/96

//-------------------------------------------------------------------//

lintrp2 = function ( x, xd, yd )
{
  local (x, xd, yd)	

  y = zeros(size (x)); 
  nd = length (xd);

  ind = sort(x).ind;

  j    = sum(x <  xd[1]);
  jmax = x.n - sum(x >= xd[nd]) + 1;

  for (i in 1:j)
  {
     y[ind[i]] = yd[1];
  }
  j = j + 1;
  if (j > x.n) { return y;}

  for (i in jmax:x.n)
  {
     y[ind[i]] = yd[nd];
  }

  for (i in 1:nd-1)
  {
    xlft = xd[i]; 
    ylft = yd[i]; 
    xrht = xd[i+1]; 
    yrht = yd[i+1];
    dx = xrht - xlft;
    if (dx != 0)
    {
      s = (yrht - ylft)/dx;
      while( x[ind[j]] >= xlft && x[ind[j]] < xrht)
      {
         y[ind[j]] = ylft + s*(x[ind[j]] - xlft);
         j = j + 1;
         if (j >= jmax) { break; }
      }
    }
    if (j >= jmax) { break; }
  }

  return y;
};
