.packageName <- "Resourcerer"
# Downloads the zip file (e. g. Agilent_Human1_cDNA.zip) defined by
# "which" from TIGR's RESOURCERER and then reads the data into R as a
# matrix
# which - a character string for the name of the zip file to be
#         downloaded from TIGR Resourcerer.
# AnnBuilder is required
#
# Copyright 2004, J. Zhang. All rights reserved
#

getResourcerer <- function(which, organism = c("human", "mouse", "rat"),
                destDir = file.path(.path.package("Resourcerer"), "temp"),
                baseUrl = "ftp://ftp.tigr.org/pub/data/tgi/Resourcerer",
                clean = TRUE, exten = "zip"){

    # destDir is not used untile the functions are included in a package
    fileName <- loadResourcerer(which, organism, destDir, baseUrl)
    resData <- as.matrix(read.table(fileName, skip = 1, sep = "\t",
                       header = FALSE, quote = "", comment.char = "",
                       colClasses = "character", strip.white = TRUE))
    resColName <- resData[1,]
    resData <- resData[2:nrow(resData), ]
    resData[resData == ""] <- NA
    colnames(resData) <- resColName
    if(clean){
        unlink(fileName)
    }

    return(resData)
}

# Downloads the zip file (e. g. Agilent_Human1_cDNA.zip) defined by
# "which" from TIGR's RESOURCERER and then returns the name of the
# expanded file.
# which - a character string for the name of the zip file to be
#         downloaded from TIGR.
#
# AnnBuilder is required
loadResourcerer <- function(which, organism = c("human", "mouse", "rat"),
                 destDir = file.path(.path.package("Resourcerer"), "temp"),
                 baseUrl = "ftp://ftp.tigr.org/pub/data/tgi/Resourcerer",
                           exten = "zip"){
    organism <- match.arg(organism)
    switch(organism,
           human = url <- paste(baseUrl, "Human", which, sep = "/"),
           mouse = url <- paste(baseUrl, "Mouse", which, sep = "/"),
           rat = url <- paste(baseUrl, "Rat", which, sep = "/"),
           stop("Unknown organism name"))
    # destDir is not used untile the functions are included in a package
    temp <- loadFromUrl(url, destDir)
    unlink(temp)

    return(file.path(destDir, gsub(paste("\\.", exten, sep = ""), "", which)))
}

# Takes the name for an expanded TIGR cDNA file stored locally and
# returns a matrix mapping TIGE cDNA probe ids to either GenBank,
# LocusLink, or UniGene ids as defined by "which".
# tigrFile - a character string for an expanded TIGR Resourcerer
# annotation file (e. g. Agilent_Human1_cDNA).
# This function is intended to be used to get a base file ready for
# AnnBuilder to use to build an annotation package
#

getProbe2ID <- function(tigrFile, baseMapType = c("gb", "ll", "ug")){
    which <- match.arg(baseMapType)
    switch(which,
           gb = map <- 3,
           ll = map <- 5,
           ug = map <- 4)
    tigr <- as.matrix(read.table(tigrFile, skip = 2, sep = "\t",
                       header = FALSE, quote = "", comment.char = "",
                       colClasses = "character", strip.white = TRUE))
    tigr <- tigr[, c(1, map)]
    tigr[tigr == ""] <- "NA"
    colnames(tigr) <- c("Probe", which)

    return(tigr)
}

resourcerer2BioC <- function(which, organism = c("human", "mouse", "rat"),
               destDir =  file.path(.path.package("Resourcerer"), "temp"),
               pkgName, pkgPath, srcUrls = getSrcUrl("all", organism),
               otherSrc = NULL, baseMapType = c("gb", "ug", "ll"),
               version = "1.1.0", makeXML = TRUE, fromWeb = TRUE,
               baseUrl = "ftp://ftp.tigr.org/pub/data/tgi/Resourcerer",
               check = FALSE, author = list(author = "Anonymous",
                              maintainer = "anonymous@email.com"),
                             exten = "zip"){
    organism <- match.arg(organism)
    baseMapType = match.arg(baseMapType)

    if(missing(pkgName)){
        pkgName <- gsub(paste("\\.", exten, sep = ""), which)
    }
    if(missing(pkgPath)){
        pkgPath <- file.path(.path.package("Resourcerer"), "temp")
    }

    baseFile <- tempfile()
    unziped <- loadResourcerer(which, organism, destDir, baseUrl, exten)
    base <- getProbe2ID(unziped, baseMapType)
    write.table(base, baseFile, quote = FALSE, sep = "\t",
                col.names = FALSE, row.names = FALSE)
    if(baseMapType != "ll"){
        tempSrc <-  getProbe2ID(unziped, "ll")
        tempOther <- tempfile()
        names(tempOther) <- "Resourcerer"
        write.table(tempSrc, tempOther, quote = FALSE, sep = "\t",
                col.names = FALSE, row.names = FALSE)
        otherSrc <- c(otherSrc, tempOther)
    }
    options(show.error.messages = FALSE)
    tryMe <- try(ABPkgBuilder(baseFile, srcUrls, baseMapType,
                         otherSrc, pkgName, pkgPath,
                         organism, version, makeXML, author, fromWeb))
    options(show.error.messages = TRUE)
    if(inherits(tryMe, "try-error")){
        return("Unsuccessful")
    }
    if(check && baseMapType != "ll"){
        checkMapping(pkgName, tempOther, file.path(pkgPath, pkgName, "data",
                      paste(pkgName, "LOCUSID.rda", sep = "")))
    }
    unlink(c(unziped, tempOther))
    return("Successful")
}

# map2LL - a character string to a tab separated file with the first
# column for probe id and second column for LL id
# llRda - a character string for the name of an rda file for an
# environment with keys being probe ids and values for matching LL
# ids.

checkMapping <- function(pkgName, map2LL, llRda, outFile =
    file.path(.path.package("Resourcerer"), "temp", "checkMapping.out")){

    output <- NULL
    load(llRda)
    bioC <- as.list(get(gsub("\\.rda", "", basename(llRda))))
    bioC <- cbind(names(bioC), unlist(bioC))
    tigr <- read.table(map2LL, header = FALSE, sep = "\t", as.is = TRUE,
                       strip.white = TRUE, colClasses = "character")
    combined <- as.matrix(merge(bioC, tigr, by.x = "V1", by.y = "V1",
                                all.x = TRUE))
    combined[is.na(combined)] <- "NA"
    diff <- combined[, 2] == combined[,3]
    output <- c(output, paste(pkgName, paste("Total =", nrow(combined)),
                paste("Match =", length(diff[diff])),
                paste("Mismatch =", length(diff[!diff])), sep = "\t"))
    write(output, outFile, append = TRUE)
}

.First.lib <- function(libname, pkgname, where) {

    if(.Platform$OS.type == "windows" && require(Biobase) && interactive()
        && .Platform$GUI ==  "Rgui"){
        addVigs2WinMenu("Resourcerer")
    }
    require("AnnBuilder")
}
