#' Running Average Smooth
#'
#' @param x a univariate time series.
#' @param bandwid # of the neighbouring elements to be averaged.
#' Must be a positive odd number.
#' @param maxiter # of repetitions.
#'
#' @details The following code will be repeated maxiter times: \cr
#'    \code{filter(x,rep(1/bandwid,bandwid), sides=2)} \cr
#' x[1:m] and x[(length(x)-m+1):length(x)] will remain unchanged.
#' where \code{m=(bandwid-1)/2}.
#'
#' @return a vector of the same length as x.
#'
#' @examples
#' x <- c(4, 1, 3, 6, 6, 4, 1, 6, 2, 4, 2)
#' y <- smoothra( x, bandwid=3, 2 )
#' Print(x,y)
#'
#' @export
#'

smoothra <- function( x, bandwid=3, maxiter=1 ){
 # running average smooth
 # Shin-ichi Mayekawa
 # 20160718
 #

 # error
 if( bandwid %% 2 == 0 ){
  cat("\nerror1(smoothra): bandwid must be a positive odd number.\n")
  stop()
 }
 lenx=length(x)
 if( bandwid >= lenx ){
  cat("\nerror1(smoothra): bandwid must be less than length(x).\n")
  stop()
 }

 m=(bandwid-1)/2
 left=x[1:m]; right=x[(lenx-m+1):lenx]
 for( i in 1:maxiter ){
  x=filter(x,rep(1/bandwid,bandwid), sides=2)
  x[1:m]=left; x[(lenx-m+1):lenx]=right
 }
 attributes(x)=NULL
 return( x )
} # smoothra


