#' Replace Characters by New Ones
#'
#' @param from A character string to be replaced by "to".
#' By default, there are no need to escape special characters.
#' @param to A character string to replace "from".
#' @param char A character vector where replacement occur.
#' @param n # of times to replace
#' @param start The location from which the replacement starts.
#' @param fixed A parameter to be passed to gregexpr and gsub.
#' @param ... Additional parameters to gregexpr and gsub.
#'
#' @details Do not use regular expressions in from such as [a-b] etc. \cr
#' When from does not contain regular expression, \cr
#' fixed=0 and ignoe.case=1 \cr
#' should work.
#'
#' @return A string with replacement.
#'
#' @examples
#' char <- paste( paste(letters,collapse=""),"0123456789",'"'
#'           , "'`!#$%&'()[]{}<>*+-,.;:/^~=_|", sep="", collapse="" )
#' lchar <- nchar(char)
#' char <- paste(char,char,char,sep=" ",collapse="")
#'
#'
#' # one to one
#' replacec( "b", "B", char )
#' replacec( "b", "B", char, 2 )
#' replacec( "b", "B", char, 1, 135)
#'
#' # many to one
#' replacec( "bc", "B", char )
#' replacec( "bc", "B", char, 2 )
#' replacec( "bc", "B", char, 1, 135 )
#'
#' # one to many
#' replacec( "b", "BC", char )
#' replacec( "b", "BC", char, 2 )
#' replacec( "b", "BC", char, 1, 135 )
#'
#' # to null string
#' replacec( "b", "", char, 99 )
#'
#' # special characters
#' replacec( "(", "[paren]", char )
#' replacec( "^", "[hat]", char )
#' replacec( "!#$", "[esd]", char )
#'
#' # ignore.case
#' replacec("B","[B]",char, fixed=0, ignore.case=1 )
#'
#' @export
#'

replacec <- function( from, to, char, n=1, start=1, fixed=1, ... ){
 #  Replace the occurence of "from" in "char" by "to".
 #  Search starts at column "start" and ends when "n" replacements
 #  have accomplished.
 # Shin-ichi Mayekawa
 # original SAS macro/iml version: 930623-040622
 # 20150620,21
 #

 lchar=nchar(char)

 # error check
 if( start < 0  |  lchar < start ){
  cat("\n\nerror1:(replace) start out out range.\n")
  Print(lchar, start)
  return()
 }
 if( n <= 0 ){
  cat("\n\nerror1:(replace) n out of range.\n")
  Print(lchar, n)
  return()
 }
 if( nchar(from) <= 0 ){
  cat("\n\nerror1:(replace) from must contain at least one chracter.\n")
  Print(nchar(from), from)
  return()
 }

 loc=gregexpr( from, char, fixed=fixed, ... )[[1]]
 loc=loc[loc >= start]
 if( length(loc) == 0 ) return(char)
 if( length(loc) > n ) loc=loc[1:n]
 lloc=length(loc)
 mid=substr(char,loc[1],loc[lloc]+nchar(from)-1)
 # Print(loc,lloc,mid, nchar(from))
 mid=gsub( from, to, mid, fixed=fixed, ... )
 top=NULL; tail=NULL
 if( loc[1] > 1 ) top=substr(char,1,loc[1]-1)
 if( loc[lloc] < lchar ) tail=substr(char,loc[lloc]+nchar(from),lchar)
 res=paste(top,mid,tail, sep="", collapse="" )

 return( res )

} # end of replacec


