#' inspect the contents of RDS file
#'
#' This function inspects the contents of an RDS file.
#'
#' @param RDS The name of .RDS file
#' @param func The function to apply to the contents of the .RDS file
#' such as \code{str} or \code{print},
#' @param max.level the max.level option for str when func=str.
#' @param return = 1 to return the the result of func.
#' @param ... additional parameters to func
#'
#' @details
#' Note that \code{saveRDS(object,filename.RDS)} saves a single object in
#' an external file and that
#' \code{save(object1,object2,...,file="filename.RData")}
#' saves the multiple objects in an external file.
#'
#' @examples
#' a <- 1;  b <- 2;  C <- matrix(1:6,3,2);  E <- letters[1:5]
#' ds <- data.frame(a,b,C);  ds2 <- list(C,ds)
#' Big <- list(a=a, b=b,C=C,E=E,ds=ds,ds2=ds2)
#' saveRDS(Big, file="testRDS.RDS")
#' inspect_RDS("testRDS.RDS")
#' inspect_RDS("testRDS.RDS", func=print)
#'
#' # retrieve the contents from .RDS file
#' # loadRDS( RDSfilename )
#'
#'@export
#'

inspect_RDS <- function( RDname, func=str, max.level=1, return=0, ... ){
 # inspect .rds saved by saveRDS function
 # Shin-ichi Mayekawa
 # 20240122,20260219
 # load -->  readRDS: 20260411
 # comments: 20260516
 #

 funcname=deparse(substitute(func))

 tempEnv=new.env()
 RDS=readRDS( RDname )
 if( funcname == "str" ){
  if( !return ) str(RDS, max.level=max.level, ...)
  else{
   res=capture.output( str(RDS, max.level=max.level, ...) )
   print(res)
  }
 }
 else{
  res=func(RDS, ...)
  print(res)
 }
 rm(RDS)
 if( return ) return( res )

} # inspect_RData




#' inspect the contents of RData file
#'
#' This function inspects the contents of an RData file.
#'
#' @param RData The name of .RData file
#' @param str = 1 to apply str to each object
#' @param max.level the max.level option for str
#'
#' @details
#' Note that \code{saveRDS(object,filename.RDS)} saves a single object in
#' an external file and that
#' \code{save(object1,object2,..., file="filename.RData")}
#' saves the multiple objects in an external file.
#'
#' @examples
#' a <- 1;  b <- 2;  C <- matrix(1:6,3,2);  E <- letters[1:5]
#' ds <- data.frame(a,b,C);  ds2 <- list(C,ds)
#' save(a,b,C,ds,ds2,E, file="testRData.RData")
#' inspect_RData("testRData.RData")
#'
#' # retrieve the contents from .RData file
#' # loadRDS( RDatafilename )
#'
#' @export
#'

inspect_RData <- function( RData, str=0, max.level=0 ){
 # inspect .RData saved by save function
 # Shin-ichi Mayekawa
 # 20260219
 # new func: 20260415
 # new method: 20260416
 # inspect_RD renamed as inspect_RData: 20260516
 #

 tempEnv=new.env()
 load(RData, envir=tempEnv)
 olist=ls(envir=tempEnv)
 cat("\nObjects in",RData,"\n  ")
 olist2=paste(1:length(olist),olist,sep=":")
 cat(olist2, sep=", "); cat("\n")

 if( str ){
  temp=capture.output(
   for( i in 1:length(olist) ){
    cat(olist[i],": ")
    str(tempEnv[[olist[i]]], max.level=max.level)
   }
  )
  str=gsub("\t"," ", temp, fixed=TRUE)
  printm(str, .lj.=1)
 }

} # end of inspect_RData


