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

// Syntax:      y = lintrp ( 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).

//      Original by: H.B.W, Spring 1990

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

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

  y = zeros(size (x)); 
  nd = length (xd);
  y = y + yd[1]*(x < xd[1]) + yd[nd]*(x >= xd[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;
      y = y + (x >= xlft).*(x < xrht).*(ylft + s*(x - xlft));
    }
  }

  return y;
};
