.packageName <- "biocViews"
bcv2html <- function (x, file = NULL, css = "../../../R.css", packageURL = "../Descriptions/", 
    reposname = "CRAN") 
{
    if (is.character(x)) 
        x <- read.ctv(x)
    if (is.null(file)) 
        file <- paste(x$name, ".html", sep = "")
    ampersSub <- function(x) gsub("&", "&amp;", x)
    zpaste <- function(..., sep = "", collapse = NULL) paste(..., 
        sep = sep, collapse = collapse)
    htm1 <- c("<html>", "<head>", zpaste("  <title>", reposname, 
        " Task View: ", ampersSub(x$topic), "</title>"), zpaste("  <link rel=stylesheet type=\"text/css\" href=\"", 
        css, "\">"), "</head>", "", "<body>", zpaste("  <h2>", 
        reposname, " Task View: ", ampersSub(x$topic), "</h2>"), 
        zpaste("  <h3>Maintainer: ", ampersSub(x$maintainer), 
            "</h3>"))
    htm2 <- ampersSub(x$info)
    titles <- sapply(x$packagelist[, 1], packageDescription, 
        field = "Title")
    titles <- paste("[", titles, "]", sep = "")
    pkg2html <- function(a, b, tt) zpaste("    <li><a href=\"", 
        packageURL, a, ".html\">", a, "</a>", " ", tt, if (b) 
            " (core)"
        else "", "</li>")
    htm3 <- c(zpaste("  <h3>", reposname, " packages:</h3>"), 
        "  <ul>", sapply(1:NROW(x$packagelist), function(i) pkg2html(x$packagelist[i, 
            1], x$packagelist[i, 2], titles[i])), "  </ul>")
    htm4 <- c("  <h3>Related links:</h3>", "  <ul>", sapply(x$links, 
        function(x) paste("    <li>", ampersSub(x), "</li>", 
            sep = "")), "  </ul>")
    htm <- c(htm1, "", htm2, "", htm3, "", htm4, "", "</body>", 
        "</html>")
    writeLines(htm, con = file)
    invisible(htm)
}
getBcViews <- function(packnames, vocab, root="vocRoot", interp=TRUE) {
 allv <- sapply(packnames, packageDescription, field="biocViews")
#
# in sept 05, packageDescription could introduce a newline
#
 allv <- gsub("\\\n", " ", allv)
#
# if they use biocViews: x,y,z
#  this particular approach will work -- thanks seth
 allv <- strsplit(allv, ",[ \t]*")
 knownTerms <- nodes(vocab)
 knownTermsLower <- tolower(knownTerms)
 allv <- lapply(allv, function(x) {
     idx <- match(tolower(x), knownTermsLower)
     unknown <- is.na(idx)
     if (any(unknown)) {
         warning("Dropping unknown biocViews terms:\n",
                 paste(x[unknown], collapse=", "))
         idx <- idx[!is.na(idx)]
     }
     knownTerms[idx]
 })
 lens <- sapply(allv, length)
 repp <- rep(packnames, lens)
 ans <- split( repp, unlist(allv) )
 if (interp) pump(ans, vocab, root)
 else ans
}
getCTVs <- function (vpal, vocab) 
{
    vn <- names(vpal)
    nv <- length(vn)
    out <- list()
    for (i in 1:length(vn)) {
        tmp <- makeCTV(vn[i], vn[i], "None", vpal[[i]], "None", 
            vocab)
        tf <- tempfile()
        saveXML(tmp, file = tf)
        out[[vn[i]]] <- read.ctv(tf)
        unlink(tf)
    }
    out
}

getPackNames <- function (rpackDir, majv = 1) #, dest = tempfile()) 
{
#
# searches a given source directory for packages with major version > majv
#
    curd <- getwd()
    on.exit(setwd(curd))
    setwd(rpackDir)
    cands <- dir(patt = "DESCRIPTION", recurs = TRUE)
    lkdep <- strsplit(cands, "/")
    el2 <- sapply(lkdep, function(x) x[2])
    ok <- el2 == "DESCRIPTION"
    cands <- cands[ok]
    allde <- lapply(cands, readLines)
    sallde <- lapply(allde, function(x) {
        tmp <- strsplit(x, ": ")
        nms <- sapply(tmp, function(x) x[1])
        names(tmp) <- nms
        tmp
    })
    pt <- sapply(sallde, function(x) x$Title[2])
    pn <- sapply(sallde, function(x) x$Package[2])
    pv <- sapply(sallde, function(x) x$Version[2])
    ppv <- strsplit(pv, "\\.")
    mv <- sapply(ppv, function(x) as.numeric(x[1]))
    packNms <- pn[mv >= majv]
    packNms
#    packTits <- pt[mv >= majv]
#    writeLines(paste(packNms, packTits, sep = "+"), dest)
#    cat("package names+titles written to", dest)
#    invisible(dest)
}

packAssoc2viewlist <- function (pael) 
{
    allconc <- sapply(pael, function(x) na.omit(c(x$top, x$second, 
        x$third)))
    ns <- sapply(allconc, length)
    pks <- rep(names(allconc), ns)
    split(pks, unlist(allconc))
}
#setClass("annotatedPackageRef",
#	representation(
#		packagename="character",
#		title="character",
#		maintainer="character",
#		vocEnv="environment",
#		terms="character")) 
		
.BADpackAssoc <- function(packlist, vocGraph, root="vocRoot") {
 topl <- adj(vocGraph, root)[[1]]
 out <- list()
 for (i in packlist) {
   cat("top level concept for", i, "\n")
   out[[i]] <- list()
   out[[i]]$top <- topl[ menu(topl, graphics=TRUE, title=paste("Package", i,"-> vocabulary associations")) ]
   sec <- adj( vocGraph, out[[i]]$top )[[1]]
   if (length(sec) > 0) {
       cat("second level concept for", i, "\n")
       out[[i]]$second <- sec[ menu(sec, graphics=TRUE) ]
       }
   else out[[i]]$second <- NA
   if (!is.na(out[[i]]$second)) thir <- adj( vocGraph, out[[i]]$second )[[1]]
   else thir <- NULL
   if (length(thir) > 0) {
       cat("third level concept for", i, "\n")
       out[[i]]$third <- thir[ menu(thir, graphics=TRUE) ]
       }
   else out[[i]]$third <- NA
   pdstuff <- packageDescription( i, fields=c("Package", "Title", "Maintainer", "Description") )
   out[[i]]$maintainer <- pdstuff$Maintainer
   out[[i]]$packagename <- pdstuff$Package
   killnl <- function(x) gsub("\\\n", " ", x)
   out[[i]]$desc <- killnl(pdstuff$Description)
   out[[i]]$title <- pdstuff$Title
 }
 out
}

#
# what we need to do here: build an xhtml document component on the
# subtopics of each topic, embed the `info' narrative component if any
# and build the package/links list
#

tellSuperTop <- function( topic, vocab, root="vocRoot" ) {
# returns vector of supertopics
 if (length(topic)>1) stop("must have length 1 topic")
 require(RBGL)
 path <- sp.between.scalar( vocab, root, topic )$path
 path[-c(1, length(path))]
}
tellSubTop <- function( topic, vocab ) {
 if (length(topic)>1) stop("must have length 1 topic")
# returns vector of subtopics
 desc <- acc( vocab, topic )[[1]]
 names(desc)[desc==1]
}


###################################################
### chunk number 12: makeVocInfo
###################################################
makeVocInfo <- function(topic, vocab, root="vocRoot") {
 list(supertopics=tellSuperTop(topic,vocab, root),
   subtopics=tellSubTop(topic,vocab))
}

 
makeCTV <- function( viewname, topic, viewmaintainer, packs, links, vocab, root="vocRoot" ) {
 require(XML)
 tr <- xmlOutputDOM("a")
 tr$addTag("CRANTaskView", close=FALSE)
  tr$addTag("name", viewname)
  tr$addTag("topic", topic)
  tr$addTag("maintainer", viewmaintainer)
  vocInf <- makeVocInfo( viewname, vocab, root )
  if (length(sut <- vocInf$supertopics)>0 | length(sbt <- vocInf$subtopics)>0) { 
       tr$addTag("info", close=FALSE)
       if (length(sut)>0) 
	{
	tr$addNode(xmlTextNode("<p>Subview of:</p>"))
	tr$addTag("ul", close=FALSE)
        for (i in 1:length(sut)) {
		tr$addTag("li", close=FALSE)
		tr$addTag("view", sut[i])
		tr$closeTag() # li
		}
	tr$closeTag() # ul
        }
       if (length(sbt)>0) 
	{
	tr$addNode(xmlTextNode("<p>Has subviews:</p>"))
	tr$addTag("ul", close=FALSE)
        for (i in 1:length(sbt)) {
		tr$addTag("li", close=FALSE)
		tr$addTag("view", sbt[i])
		tr$closeTag() # li
		}
	tr$closeTag() # ul
        }
       tr$closeTag() #info
   } else # done doing  vocab info
  tr$addTag("info", "none")
  tr$addTag("packagelist", close=FALSE)
  if (length(packs)>0) {
    for (i in 1:length(packs)) 
 	tr$addTag("pkg", packs[i])
    }
  tr$closeTag()
  tr$addTag("links", links)
  tr$closeTag()
  xmlChildren(tr$value())[[1]] # return node
}

#packAssoc2vlist <- function(pael) {
# allconc <- unique(sapply(pael, function(x) c(x$top, x$second, x$third)))
# tall <- t(allconc)
# pks <- rep(rownames(tall),3) # assumes 3 level hierarchy
# split(pks, as.character(tall))
#}

#getctv <- function(vl) {
# n <- length(vl)
# nms <- names(vl)
# out <- list()
# for (i in 1:n) {
##makeCTV <- function( viewname, topic, viewmaintainer, info, packs, links ) {
#  out[[i]] <- makeCTV( nms[i], nms[i], vl[[i]]$maintainer , "no", vl[[i]], "no" )
# }
# out
#}


#<CRANTaskView>
#
#  <name>MachineLearning</name>
#  <topic>Machine Learning &amp; Statistical Learning</topic>
#  <maintainer>Torsten Hothorn</maintainer>
#  
#  <info>
#    Several add-on packages implement ideas and methods developed at the
#    borderline between computer science and statistics - this field of research
#    is usually referred to as machine learning. 
#
#    The packages can be roughly structured into the following topics:
#    <ul>
#      <li><i>Neural Networks</i>: Single-hidden-layer neural network are 
#             implemented in package <tt>nnet</tt> as part of the <pkg>VR</pkg>
#             bundle (shipped with base R). </li>
#      <li><i>Recursive Partitioning</i>: Tree-structured models for
#             regression, classification and survival analysis, following the
#	     ideas in the CART book, are
#             implemented in <pkg>rpart</pkg> (shipped with base R) and <pkg>tree</pkg>.
#             An adaptation of <pkg>rpart</pkg> for multivariate responses
#             is available in package <pkg>mvpart</pkg>. The validity of
#             trees can be investigated via permutation approaches with package 
#             <pkg>rpart.permutation</pkg> and a tree algorithm fitting 
#             nearest neighbors in each node is implemented in package 
#             <pkg>knnTree</pkg>. For problems with binary input variables
#             the package <pkg>LogicReg</pkg> implements logic regression.
#             Graphical tools for the visualization of
#             trees are available in packages <pkg>maptree</pkg> and 
#             <pkg>pinktoe</pkg>.</li>
#      <li><i>Regularized and Shrinkage Methods</i>: Regression models with some
#             constraint on the parameter estimates can be fitted with the
#             <pkg>lasso2</pkg> and <pkg>lars</pkg> packages. The shrunken
#             centroids classifier and utilities for gene expression analyses are
#             implemented in package <pkg>pamr</pkg>.</li>
#      <li><i>Random Forests</i>: The reference implementation of the random
#             forest algorithm for regression and classification is available in 
#             package <pkg>randomForest</pkg>. Package <pkg>ipred</pkg> has bagging
#             for regression, classification and survival analysis as well as
#             bundling, a combination of multiple models via
#             ensemble learning.</li>
#      <li><i>Boosting</i>: Various forms of gradient boosting are
#             implemented in packages <pkg>gbm</pkg> and <pkg>boost</pkg>.</li>
#      <li><i>Support Vector Machines</i>: The function <tt>svm()</tt> from 
#             <pkg>e1071</pkg> offers an interface to the LIBSVM library and
#             package <pkg>kernlab</pkg> implements a flexible framework 
#             for kernel learning (including SVMs, RVMs and other kernel
#	     learning algorithms). An interface to the SVMlight implementation
#	     (only for one-against-all classification) is provided in package
#	     <pkg>klaR</pkg>.</li>
#      <li><i>Model selection and validation</i>: Package <pkg>e1071</pkg>
#             has function <tt>tune()</tt> for hyper parameter tuning and 
#             function <tt>errorest()</tt> (<pkg>ipred</pkg>) can be used for
#             error rate estimation. The cost parameter C for support vector
#             machines can be chosen utilizing the functionality of package
#             <pkg>svmpath</pkg>.</li>
#    </ul>
#  </info>
#
#  <packagelist>
#    <pkg>boost</pkg>
#    <pkg priority="core">e1071</pkg>
#    <pkg priority="core">gbm</pkg>
#    <pkg>ipred</pkg>
#    <pkg priority="core">kernlab</pkg>
#    <pkg>klaR</pkg>
#    <pkg>lars</pkg>
#    <pkg>lasso2</pkg>
#    <pkg>mvpart</pkg>
#    <pkg>pamr</pkg>
#    <pkg>rpart.permutation</pkg>
#    <pkg priority="core">randomForest</pkg>
#    <pkg priority="core">rpart</pkg>
#    <pkg>svmpath</pkg>
#    <pkg>tree</pkg>
#    <pkg priority="core">VR</pkg>
#  </packagelist>
#
#  <links>
#    <a href="http://www.boosting.org/">Boosting Research Site</a>
#  </links>
#
#</CRANTaskView>

#setClass("annotatedPackageRef",
#	representation(
#		packagename="character",
#		title="character",
#		maintainer="character",
#		vocEnv="environment",
#		terms="character")) 
		
packAssoc <- function(packlist, vocGraph, root="vocRoot") {
 topl <- adj(vocGraph, root)[[1]]
 out <- list()
 for (i in packlist) {
   cat("top level concept for", i, "\n")
   out[[i]] <- list()
   while (length(out[[i]]$top) == 0)  {
       out[[i]]$top <- pickItems( topl )
       if (length(out[[i]]$top) == 0) warning("you must pick one top level term")
       }
   sec <- unlist ( adj( vocGraph, out[[i]]$top ) )
   if (length(sec) > 0) {
       cat("second level concept for", i, "\n")
       out[[i]]$second <- pickItems( as.character(unlist(sec)) ) #sec[ menu(sec, graphics=TRUE) ]
       }
   else out[[i]]$second <- NA
   if (!any(is.na(out[[i]]$second))) thir <- unlist( adj( vocGraph, out[[i]]$second ) )
   else thir <- NULL
   if (length(thir) > 0) {
       cat("third level concept for", i, "\n")
       out[[i]]$third <- pickItems( as.character(unlist(thir)) ) #thir[ menu( athir, graphics=TRUE) ]
       }
   else out[[i]]$third <- NA
   pdstuff <- packageDescription( i, fields=c("Package", "Title", "Maintainer", "Description") )
   out[[i]]$maintainer <- pdstuff$Maintainer
   out[[i]]$packagename <- pdstuff$Package
   killnl <- function(x) gsub("\\\n", " ", x)
   out[[i]]$desc <- killnl(pdstuff$Description)
   out[[i]]$title <- pdstuff$Title
   cat("Continue? Type 1 if yes, 0 otherwise:")
   xx <- scan(n=1)
   if (xx != 1) return(out)
 }
 out
}

pump <- function(viewlist, vocab, root="vocRoot") {
 # make packages annotated to hypernyms of their
 # direct annotations
 vs <- names(viewlist)
 for (v in vs) {
   st <- tellSuperTop( v, vocab, root )
   if (length(st) > 0) {
     for (sti in st)
       viewlist[[sti]] <- union(viewlist[[sti]], viewlist[[v]])
   }
 }
 viewlist
}
 
.topwrap.OLD <- function (gra) 
{
    topt <- adj(gra, "vocRoot")[[1]]
    sapply(topt, function(x) paste("<li><a href=",x, ".html>", x, "</a>\n", sep = ""))
}

topwrap <- function (gra) 
{
    topt <- adj(gra, "vocRoot")[[1]]
      ostr <- list()
    j <- 0
    for (i in 1:length(topt)) {
      j <- j+1
      ostr[[j]] <- paste("<li><a href=",topt[i], ".html>", topt[i], "</a>\n", sep = "")
      nn <- adj(gra, topt[i])[[1]]
      if (length(nn) > 0) {
         j <- j+1
ostr[[j]] <- paste("<ul><li> subviews:", paste("<a href=", nn, ".html>", nn, "</a>", sep="", collapse=", "), "</ul>\n")
         }
    }
    unlist(ostr)
}
