.packageName <- "RMAPPER"
setOldClass("data.frame")

setClass("mapperHits", representation( 
	query="character", hits="data.frame"))

setGeneric("query", function(x)standardGeneric("query"))
setMethod("query", "mapperHits", function(x) {
 x@query
})
setGeneric("hits", function(x)standardGeneric("hits"))
setMethod("hits", "mapperHits", function(x) {
 x@hits
})

setMethod("show", "mapperHits", function(object) {
 cat("MAPPER.CHIP.ORG hits collection on query:\n", query(object), "\n")
 cat("There were ", nh <- nrow(hits(object)), "hits.\n")
 if (nh > 5) {
	cat("First 5 hits:\n")
	print(hits(object)[1:5,])
	}
 else print(hits(object))
})
reshapeMapper <- function(df) {
#
# assumes the file structure returned as of 29 Jan 06
# the rectangular component has three records per hit
# first record is full and last column is binding model, 
#   second is empty except for last column, which encodes match
#   third is empty except for last column which gives sequence
#
 nh <- nrow(df)/3
 kp <- df[seq(1,nh*3,3),]
 mat <- df[seq(2,nh*3,3),ncol(df)]
 sq <- df[seq(3,nh*3,3),ncol(df)]
 names(kp)[ncol(df)] <- "AlignModel"
 data.frame(kp, Match=mat, Seq=sq)
}

readMapper <- function(infile=NULL, mapperPW=NULL,
	stub="http://mapper.chip.org/mapper/db-rpc?", models=NULL, ...) {
#
# this function will either read from a downloaded file (generated by db-rpc)
# or issue a query direct to MAPPER.  your credentials, typically in the
# form of x@y.z.w:mypwd, must be supplied; as the MAPPER site says, these
# credentials are sent in the clear
#
		if (!is.null(infile)) {
			tmp <- read.delim(infile,skip=1,h=TRUE,sep="\t")
			qtext <- "[FROM FILE]"
		}
	else {
		require(RCurl)
		if (is.null(mapperPW)) stop("you must supply your MAPPER usern:pwd")
		h <- getCurlHandle(userpwd=mapperPW)
		plist <- list(...)
		kw <- names(plist)
		if (is.null(models)) {  # be sure there is a models entry
			kw = c(kw,"models")
			plist[["models"]] = "M1"
		}
		parmvals <- as.character(unlist(plist))
		arglist <- paste(kw,parmvals,sep="=",collapse="&")
		qtext = arglist
		URLstring <- paste(stub,arglist,sep="")
		tmp <- try(getURL(URLstring, curl=h))
		if (inherits(tmp, "try-error")) stop("curl operations threw error.  sorry.\n")
		tc <- textConnection(tmp)
                tmp <- read.delim(tc,sep="\t", skip=1, h=TRUE) 
		close(tc)
	}
	new("mapperHits", query=qtext, hits=reshapeMapper(tmp))
}

