#' Check If the Objects Listed Exist in the Parent Frame
#'
#' @param varname A string vector containing object names
#' @param ntogoback n for \code{parent.frame}
#' @param mode A string vector containing what to look for.
#' @param get = 1 to retrieve the value of those objects.
#' @param debug = 1 to print intermediate results
#'
#' @return
#'  If \code{get=0}: \cr
#'   \code{ex} A vector indicating the existence of each object. \cr
#'  If \code{get=1}: \cr
#'   A list of \code{ex} and a list, \code{value}, which contains
#'   the values of the objects found.
#'
#' @examples
#' a=0; b=0; c=0; d=0; e=0
#' rm(a,b,c,d,e)
#'
#' a="A0"
#' b="B0"
#' d=function(a){print(a)}
#' Exists( varname=c("a","b","c","d","e") )
#' Exists( varname=c("a","b","c","d","e"), get=1 )
#' Exists( varname=c("a","b","c","d","e"), get=1, mode="function" )
#'
#' func1 <- function(){
#'  a="A1"
#'  b="B1"
#'  res=Exists( varname=c("a","b"), get=1 )
#'  Print(res)
#'  res=Exists( varname=c("a","b"), get=1, ntogoback=2 )
#'  Print(res)
#' }
#' func1()
#'
#'
#' @export
#'

Exists <- function( varname, ntogoback=1
                  , mode=c("numeric", "character","logical")
                  , get=0, debug=0 ){
 # get varname from the calling directory
 # Shin-ichi
 # old test_parent2: 20170920,20221112cot
 # modified as Exists: 20230509dnc
 #

 # nvar
 nvar=length(varname)

 if( debug ){
  # parent (calling, not enclosing) env
  sysparent=sys.parent(n=ntogoback)
  parentframe=parent.frame(n=ntogoback)

  Print(sysparent)
  cat("parent environment given by parent.frame(n=",ntogoback,") is "
      , sep="")
  print(parentframe)
  Print(varname,nvar)
 }

 value=vector("list",length=nvar)
 names(value)=varname
 ex=numeric(nvar)
 names(ex)=varname
 for( i in 1:nvar ){

  temp=varname[i]
  exi=exists( temp, where=parent.frame(n=ntogoback) )
  if( exi ){
   temp2=get(temp,pos=parent.frame(n=ntogoback))
   if( mode(temp2) %in% mode ){
    if( get == 1 ) value[[i]]=temp2
    ex[i]=TRUE
   }
   else{
    ex[i]=FALSE
   }
   rm(temp2)
  } # end of exists

 } # end of variable name loop

 if( debug ){
  Print(ex)
  Print(value)
 }

 if( get != 1 ) return( ex )
 else return( named_list(ex,value) )

} # end of Exists


