"process.CSN" <-
function(csns.names=NULL,eg.names=NULL,probesetNames=NULL,entrez.func=function(probe){probe},platform="HG-U133_Plus_2",protocol="gcrma",tries=2,quiet=FALSE,verbose=TRUE)

# This code uses the Bioconductor interface to download SN data sets
# from the Celsius database and map the row IDs to Entrez Gene IDs.
# The results are written to a file

# Modified by daigle 2/1/08

{
  eg.names <- as.character(eg.names)
  
  # Load Bioconductor libraries
  require(celsius,quietly=TRUE)
  celsius <- new("celsiusServer",celsiusUrl="http://celsius.genomics.ctrl.ucla.edu",platform=platform)
  celsius@protocol <- protocol
  celsius@verbose <- verbose

  # Get/process CSNs
  if(!quiet) cat("Processing CSNs...")
  for(try in 1:tries) {
    if(is.null(tryCatch(csn <- my.getSampleData(celsius,id=csns.names,probesetNames=probesetNames),error=function(e) NULL))) {
      cat("Get failed! Trying again...\n")
      Sys.sleep(30)
    }
    else break
  }
  if(try == tries) stop("Couldn't get csns!")
  if(!quiet) cat("Done!\n")
 
  csn.names <- rownames(csn)
  csn.values <- csn

  # Convert ids
  if(!quiet) cat("Converting ids...")
  entrez.ids <- as.character(unlist(sapply(csn.names,function(x) entrez.func(x))))
  csn.values <- csn.values[!is.na(entrez.ids),]
  entrez.ids <- entrez.ids[!is.na(entrez.ids)]
  if(!quiet) cat("Done!\n")

  # Average duplicates
  if(!quiet) cat("Averaging duplicates...")
  to.remove <- c()
  for(id in 1:length(entrez.ids)) {
    if(id %in% to.remove) next
    which <- which(entrez.ids == entrez.ids[id])
    if(length(which) > 1) {
      csn.values[which[1],] <- colMeans(csn.values[which,],na.rm=TRUE)
      to.remove <- c(to.remove,which[2:length(which)])
    }
  }
  if(length(to.remove)) {
    csn.values <- csn.values[-to.remove,]
    entrez.ids <- entrez.ids[-to.remove]
  }
  if(!quiet) cat("Done!\n")

  # Add to output matrix
  if(!quiet) cat("Adding to output matrix...")
  exp.mat <- matrix(as.numeric(NA),nrow=length(eg.names),ncol=ncol(csn.values))
  rownames(exp.mat) <- eg.names
  colnames(exp.mat) <- colnames(csn.values)
  exp.mat[entrez.ids[entrez.ids %in% eg.names],] <- csn.values[entrez.ids %in% eg.names,]
  if(!quiet) cat("Done!\n")

  return(exp.mat)
}