#' Find the Location of the Quote to the Right or Left of the One at loc.
#'
#' @param exp A string.
#' @param loc The location of a quote.
#' @param right = 0 to find the one to the left.
#'
#' @details
#' If exp contains double quotes, exp must be defined by using single quotes
#' or must be escaped by the use of \.
#'
#' @return
#' The location of the quote found.
#'
#' @examples
#' exp='regexp("a", "12""a56")'
#' loc=regexpr('"',exp)
#' locn=locbalq(exp, loc)
#' Print(substr(exp,loc,locn))
#' loc=13
#' locn=locbalq(exp, loc)
#' Print(substr(exp,loc,locn))
#'
#' # location of the non-matching quote
#' loc=10
#' locn=locbalq(exp, loc)
#' Print(substr(exp,loc,locn))
#'
#' exp="regexp('a', '12''a56')"
#' locbalq(exp, regexpr("'",exp))
#' loc=16
#' locn=locbalq(exp, loc, right=0)
#' Print(substr(exp,locn,loc))
#'
#' @export
#'

locbalq <- function( exp, loc, right=1 ){
 # location of matching quote
 # Shin-ichi Mayekawa
 # 20171115,16
 #

 # error check
 nch=nchar(exp)
 if( loc > nch  |  loc <= 0 ){
  cat("\n\nerror1(locbalq)"
      , "loc must be positive and less than nchar(exp).\n\n")
  return(0)
 }

 # remove attributes from loc by regexpr
 attributes(loc)$match.length=NULL
 attributes(loc)$useBytes=NULL

 # quote
 q=substr(exp,loc,loc)

 # matching paren
 qqDS=c("'",'"')
 if( q %in% qqDS ){
  q2=q
  rev=0
  exp1=substr(exp,loc,nch)
 }
 else{
  cat("\n\nwarning1(locbalq) substr(exp,loc,loc) is not a quote.\n\n")
  return(0)
 }

 # DQ=rawToChar(as.raw(2))
 # SQ=rawToChar(as.raw(1))
 # e=exp
 # e=gsub("\"\"",DQ,e,fixed=1)
 # e=gsub("\'\'",SQ,e,fixed=1)
 # Print(e)

  e=strsplit( exp, "" )[[1]]

  locq=which(e==q)
  llq=length(locq)
  locqq=which(locq == loc)
  if( right ){
   if( locqq < llq ) locn=locq[locqq+1]
   else{
    cat("\nerror1:(locbalq) No matching quote in the right direction.\n")
    stop()
   }
  }
  else{
   if( 1 < locqq ) locn=locq[locqq-1]
   else{
    cat("\nerror1:(locbalq) No matching quote in the backward direction.\n")
    stop()
   }
  }

  return( locn )

} # end of locbalq



