#' trim leading and trailing blanks
#'
#' @param x string vector or matrix
#' @param leading = 1 to remove the leading blanks
#' @param trailing = 1 to remove the trailing blanks
#' @param middle = 1 to replace consecutive blanks by one (compress)
#' @param all = 1 to remove the leading and trailing blanks and compress\cr
#' = 2 to remove all the blanks
#' @param blank = a character to define the blank
#'
#' @return trimed string vector
#'
#' @examples
#' testc="   c a  p r i    ci  ous   "
#' trim( testc )
#' trim( testc, leading=1, trailing=0 )
#' trim( testc, middle=1, trailing=0 )
#' trim( trim( testc, middle=1 ), leading=1 )
#' trim( testc , all=1 ) # same as above.
#' trim( testc, all=2 )
#' A=demomat(3,3,root="a"); A[1,1]="  a1 1"; A[2,2]="   a2 2 "
#' trim(A,all=1)
#' trim(A,all=2)
#'
#' @export
#'

trim <- function( x, leading=FALSE, trailing=TRUE, middle=FALSE, all=FALSE
                 , blank=" " ){
 # trim leading and trailing blanks
 # Shin-ichi Mayekawa
 # 20111127,1202
 # zenkaku: 120323
 # data frame warning: 120323
 # zen -> blank: 20150604dnc
 # matrix input: 20150803
 # names: 20150809cot
 # all=2: 20171010dnc
 # bugfix for middle: 20220816cop
 #
 # Args:
 #  leading   = 1 to remove the leading blanks
 #  trailing  = 1 to remove the trailing blanks
 #  middle    = 1 to replace consecutive blanks by one (compress)
 #   excluding leanding and trailing blanks
 #  all       = 1 to remove the leading and trailing blanks and compress
 #  blank     = a blank character to be used instead of " ".
 #
 #

 if( is.data.frame(x) ){
  cat("warning:(trim)  Use sapply(data.frame, trim, options...).\n")
  return(NULL)
 }


 if( all == 1 ){
  leading=1; trailing=1; middle=1
 }

 ismat=is.matrix(x)
 if( ismat ){
  nr=nrow(x); nc=ncol(x)
 }
 islist=is.list(x)
 len=length(x)

 c1=paste("^",blank,"+",sep="")
 c2=paste(blank,"+$",sep="")
 # c32=paste(blank,"+([^",blank,"]+)",sep="") # excluding tail
 # c33=paste("(.)",blank,"+",sep="") # excluding head
 c3=paste("([^",blank,"]+)",blank,"{2,}([^",blank,"]+)",sep="")
 y=x

 if( all == 2 ) y=gsub(blank, "", y)
 else{
  if( leading == 1 )  y=sub(c1, "", y)
  if( trailing == 1 ) y=sub(c2, "", y)
  if( middle == 1 ){
   y=gsub(c3, paste("\\1",blank,"\\2",sep=""), 
          gsub( c3, paste("\\1",blank,"\\2",sep=""), y ) )
  }
 }

 if( ismat ){
  y=matrix(y,nr,nc)
  dimnames(y)=dimnames(x)
 }
 if( islist ){
  y=as.list(y)
  names(y)=names(x)
 }

 return( y )

} # end of trim


