#' Creates html files from the help files of an R package
#'
#' @param pkgname  Package name
#' @param outdir The name of the directory to which the html files 
#' are written.
#' @param debug = 1 to print details.
#'
#' @examples
#' #  res1=package_info("lazy.tools",      "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.mat",        "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.symbolic",   "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.stat",       "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.sasef",      "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.mdpref",     "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.procrustes", "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.irt",        "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.fa",         "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.cluster",    "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.mirt",       "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.mds",        "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.accel",      "d:/Rpgm/packages/HTML_help")
#' #  res1=package_info("lazy.Bayes",      "d:/Rpgm/packages/HTML_help")
#' cat("none\n")
#'
#' @references
#'   Part of the code is from http://m884.hateblo.jp/entry/20100214/1266135349 by
#'   masaha03 (id:phosphor_m).
#'
#' @export
#'

package_info <- function( pkgname
                        , outdir="d:/Rpgm/packages/HTML_help", debug=0 ){
 # display info on package and create local html help files
 # Shin-ichi Mayekawa
 # 20150618
 # read 00Index: 20150618DNC
 # top: 20150822
 # / in the filename: 20150924,25
 # < added: 20151008
 # default outdir: 20161121
 # roxgen2: 20171007
 #

 # Args:
 #
 #  pcgname   a package name
 #  outdir    name of the directory in which the html files will be written,
 #            or NULL to skip html creation.
 #
 # Note
 #  All the information is contained in head and funclist.
 #  It is not neccesary to read 00Inde.html but it makes it much easier
 #  to construct index.html.
 #

 # execulte help(package="packagename")
 code=paste( 'pkg=help( package="', pkgname,'", help_type="text"'
             , ', try.all.packages=TRUE )', sep="" )
 eval(parse(text=code))

 # pick up the part which defines a list of functions in the package.
 # pkg below contains a string "list( c( xxxx ), c(xxxx), ...)"
 pkg=as.character(pkg)[3]

 #cat("\n***************\n")
 #pkg2=gsub('\"',"'",pkg,fixed=TRUE)
 #print(pkg2)
 #cat("\n***************\n")

 # assign the list to pkg_info
 code=paste("pkg_info=",pkg,sep="")
 eval(parse(text=code))

 # last element is NULL
 pkg_info=pkg_info[-3]

 # Here, funclist contains all package info.
 # The first element is the description, the 2nd, function list
 head=pkg_info[[1]]
 funclist=pkg_info[[2]]

 # function names
 from=which( substr(funclist,1,1) != " " )
 nfunc=length(from)
 to=from[-1]-1; to[nfunc]=length(funclist)
 funcnames=sapply( strsplit( funclist[from], " " ), "[[", 1 )

 # get path info by giving one function name.
 file=as.character( help( funcnames[1], (pkgname), help_type="text"
                          , try.all.packages=FALSE ) )
 path <- dirname(file)
 dirpath <- dirname(path)


 cat("\nInformation on package:", pkgname,"\n")
 cat("\n Stored in ", dirpath,". \n\n")
 cat("Description\n")
 print(head, quote=0)
 cat("\n\nList of Functions\n")
 Print(from,to,funcnames)

 # copy 00Index.html from R library directory
 Index=paste(dirpath,"/html/00Index.html", sep="")
 pkg_index=readLines(Index)

 # modify link to DISCRIPTION (in the same directory)
 pkg_index=gsub("../DESCRIPTION","DESCRIPTION",pkg_index)

 # modify UP link
 pkg_index=gsub("../../../doc/html/packages.html","../packages.html",pkg_index)

 # modify TOP link
 pkg_index=gsub("../../../doc/html/index.html"
                , paste(pkgname,".html",sep=""),pkg_index)


 # R.css
 Rcss=readLines(paste(dirpath,"/html/R.css", sep=""))


 if( !is.null(outdir) ){

  # output directory
  outdir=paste( outdir,"/", pkgname, sep="" )
  if( !dir.exists(outdir) ){
   dir.create(outdir, recursive=TRUE)
  }

  # Rcss
  outdirfile=paste(outdir,"/R.css",sep="")
  writeLines(Rcss, outdirfile)

  # index file
  outdirfile=paste(outdir,"/index.html",sep="")
  writeLines(pkg_index, outdirfile)

  # description
  outdirfile=paste(outdir,"/DESCRIPTION",sep="")
  writeLines(head, outdirfile)

  # each function files
  cat("\n processing .")
  for( i in seq_along(funcnames) ){
   fname=funcnames[i]
   if( regexpr("[*/<]",fname)[[1]] > 0 ) next
   outdirfile=paste(outdir,"/",fname,".html",sep="")
   if( debug ) Print(outdirfile)
   res=extract_help( fname, pkgname=pkgname, print=0, debug=debug )
   # modify the last-1st line, where, usually, we find a link to package index.
   ll=res[length(res)-1]
   ll=gsub("]",' <a href="index.html">Index</a>]',ll)
   res[length(res)-1]=ll
   writeLines( res, outdirfile )
   cat(".")
  }
  cat(" done!\n")

 } # end of html creation

 return(funclist)

} # end of package_info


extract_help <- function( funcname, pkgname=NULL, print=1, debug=0 ){
 # extract help file of func in package
 # part of the code is from http://m884.hateblo.jp/entry/20100214/1266135349
 # Shin-ichi Mayekawa
 # 20150618

 # Args:
 #
 #  funcname   function name
 #  pkgname    package name or NULL
 #  print      = 1 to print ugly result
 #  debug      = 1 to print intermediate result
 #

 if( is.null(pkgname) )
  file=as.character( help( funcname, help_type="text", try.all.packages=TRUE ) )
 else
  file=as.character( help( funcname, (pkgname), help_type="text"
                           , try.all.packages=FALSE ) )
 path <- dirname(file)
 dirpath <- dirname(path)
 pkgname2 <- basename(dirpath)
 RdDB <- file.path(path, pkgname2)
 if( debug ){
  Print(funcname,pkgname)
  Print(path,dirpath,pkgname2)
  Print(RdDB)
 }
 if (file.exists(paste(RdDB, "rdx", sep = "."))) {
  temp <- tools::Rd2HTML(tools:::fetchRdDB(RdDB, basename(file)),
                         out = tempfile("Rtxt"), package = pkgname2,
                         outputEncoding=localeToCharset()[1], no_links=TRUE)

  temp2 <- readLines(temp)
  temp2 <- gsub("(&lsquo;)|(&rsquo;)|(&ndash;)","", temp2)
  if( print == 1 ){
   cat("\n\n\n*** top of ", funcname," in ", pkgname, "\n")
   print(temp2)
   cat("********************** end temp2 ***********************\n")
  }

  return( temp2 )
 }
} # end of extract_help


