#' Interpolation of data
#'
#' @param x input vector
#' @param y input vector
#' @param xout vector at which y is calculated,  or NULL.
#' @param method = "constant" or "linear" or "natural" \cr
#' "spline" can be uses as an alias for "natural".
#' @param n # of points in (min(x), max(x)) at which y is calculated
#' when xout is NULL.
#' @param print = 1 to print the result
#' @param plot = 1 to plot the result
#' @return A matrix: cbind( xout, yout )
#'
#' @examples
#' x <- c(1,2,3,4,5,6)
#' y <- c(1,4,9,7,6,8)
#' xout <- seq(1, 7, length=10)
#' sp=interpol( x, y, xout, method="constant", plot=1 )
#' sp=interpol( x, y, xout, method="linear", plot=1 )
#' sp=interpol( x, y, xout, method="spline", plot=1 )

#' @export
#'

interpol <- function( x, y, xout=NULL, method="natural", n=3*length(x)
                    , print=0, plot=0 ){
 # interpolation by approx or spline
 # Shin-ichi Mayekawa
 # 20141216
 # error check: 20150605
 # rule option added to approx: 20160727
 #
 # Args:
 #
 #  x, y    vectors giving the coordinates of the points to be interpolated.
 #  xout    vector of new x values  where interpolation is to take place.
 #
 #  n       If xout is NULL, interpolation takes place at
 #          n equally spaced points spanning the interval [min(x), max(x)].
 #          That is, xout=seq(min(x),max(x),length=n) will be used.
 #
 #  plot    = 1 to plot the result
 #
 #
 # Values:
 #
 #  matrix of cbind( xout, yout )
 #

 # error
 if( !( is.vector(x) & is.vector(y) ) ){
  if( !( ncol(x) == 1  &  ncol(y) == 1 ) ){
   cat("\n\nerror1:(interpol) Input must be vectors.\n\n")
   return()
  }
  else{
   x=c(x); y=c(y)
  }
 }

 if( is.null(xout) ) xout=seq(min(x),max(x),length=n)
 if( method == "spline" ) method="natural"
 if( method %in% c("linear","constant") ){
  res=approx( x, y, xout=xout, method=method, rule=2 )
 }
 else{
  res=spline( x, y, xout=xout, method=method )
 }

 if( plot == 1 ){
  plot(x,y,type="p", main=method)
  if( method == "linear" )
   lines(x,y)
  else if( method == "constant" )
   lines( approx( x, y, n=100, method=method ) )
  else
   lines( spline( x, y, n=30, method=method ) )
  points( res, col=2 )
 }

 res=cbind(res$x, res$y)
 colnames(res)=c("x","y")
 if( print == 1 )
  Print(res)

 return( res )

} # end of interpol




