.packageName <- "keggorth"

getKOtags = function(str, ignore.case=TRUE) {
 if (length(str) != 1) stop("single string only please; use lapply for vector")
 data(KOgraph)
 nod = grep(str, nodes(KOgraph), ignore.case=ignore.case, value=TRUE)
 unlist(nodeData(KOgraph, nod, "tag"))
}

getKOprobes = function(str, useAcc=TRUE, plat="hgu95av2", na.action=na.omit) {
#
# this is a messy function, predicated on misunderstanding of acc
#
 tags = as.character(sapply(str, getKOtags))
#
# now that i have tags, make the graph with tags as nodes
 data(KOgraph)
 tagg = KOgraph
 nodes(tagg) = unlist(nodeData(KOgraph,nodes(KOgraph), "tag"))
# make all nodes point to themselves
 tagg = addEdge( nodes(tagg), nodes(tagg), tagg)
 if (useAcc) {
     lkacc = acc(tagg, tags) # fails for selfloop
     names(lkacc) = NULL
     tmp = unlist(lkacc)
     }
 if (length(tmp) > 0) tags = union(names(tmp), tags)
 aev = get(paste(plat, "PATH2PROBE", sep=""))
 na.action(unique(unlist(mget(tags, aev, ifnotfound=NA))))
}

indRender = function(klike, from=nodes(klike)[1], indent="  ") {
 # check for KO attributes
 ndd = names(unlist(nodeDataDefaults(klike)))
 if (!("depth" %in% ndd)) stop("must have nodeData attribute 'depth'")
 allt = nodes(klike)
 targs = unlist(lapply(acc(klike, from), names))
 #
 # bug in subgraph necessitates reconstruction of nodeData
 #
 denew = nodeData(klike, targs, "depth")
 tanew = nodeData(klike, targs, "tag")
 gg = subGraph( targs, klike )
 nodeDataDefaults(gg) = list(depth=0, tag="NONE")
 nodeData(gg, targs, "depth") = denew
 nodeData(gg, targs, "tag") = tanew
 de = unlist(nodeData(gg,,"depth"))
 # now render with cat
 allt = nodes(gg) 
 for (i in 1:length(allt)) {
  for (j in 1:de[i])  cat(indent)
  cat(allt[i], "\n")
  }
invisible(NULL)
}


keggDF2graph = function(df, root="KO.June07root") {
 dfn = names(df)
 if (!(all(c("lev1", "lev2", "term", "tag", "depth") %in% dfn))) stop(
        "data frame input must have columns lev1, lev2, term, tag, depth")
 ss = split(df, df$lev1)
 sss = lapply(ss, function(x) split(x, x$lev2))
# start graph
 KOgraph = new("graphNEL", nodes=c(root, df$term), edgemode="directed")
 lev1 = df$term[df$depth==1]
# add top level terms
 KOgraph = addEdge( root, lev1, KOgraph )
# add second and third level terms
 for (i in 1:length(sss)) {
#
   curtop = sss[[i]][[1]]$term
   for (j in 2:length(sss[[i]])) {
     tmp = sss[[i]][[j]]
     cursec = tmp[tmp$depth==2,"term"]
     KOgraph = addEdge( curtop, cursec, KOgraph )
     curth = tmp[tmp$depth==3,"term"]
     KOgraph = addEdge( cursec, curth, KOgraph )
     }
  }
 nodeDataDefaults(KOgraph, "tag") = "NONE"
 nodeData(KOgraph, df$term, "tag") <- df$tag
 nodeDataDefaults(KOgraph, "depth") = 0
 nodeData(KOgraph, df$term, "depth") <- as.numeric(df$depth)
 KOgraph
}

