##################################################
# Function: apply.position
# Overview: Like sapply, but applies a function that depends on 
#   each vector value and its position.
#   For example, apply.position(c(100:105), function(x, pos) { x + pos }
#   returns the vector
#   100 + 1, 101 + 2, 102 + 3, 103 + 4, 104 + 5, 105 + 6
#   or
#   101 103 105 109 111
# Arguments:
#   v: vector to apply function to
#   fun: function taking two arguments. The first
#    argument is the value, the second is the position
##################################################
apply.position <- function(v, fun)
{
  if(!is.vector(v))
    stop("this function only works on vectors")

  pos <- 0
  sapply(v, function(x) {
    pos <<- pos + 1;
    fun(x, pos)
  })
}

##################################################
# Function: apply.position.matrix
# Overview: Calls apply.position on each row
#   of a matrix.
# Arguments:
#   m: matrtix to which function will be applied
#   fun: function taking two arguments. The first
#    argument is the value, the second is the position
#   column.only: if TRUE, position for each value is
#     its column in the matrix. if FALSE, position
#     is the absolute position in the matrix.
##################################################
apply.position.matrix <- function(m, fun, column.only=TRUE)
{
  if(!is.matrix(m))
    stop("this function only works on matrices")

  for(row in 1:nrow(m))
  {
    m[row,] <- apply.position(m[row,], fun)
  }
  m
}

#############################################################
# This dataset has 30 genes, 10 arrays (two classes of five)
# Arrays 16-30 are differentially expressed
# in a time course analysis.
#############################################################
gen.dataset1 <- function(file=NA, covfile=NA)
{
  set.seed(99)

  class1.top <- matrix(rnorm(75, mean=1, sd=0.2), ncol=5)
  class2.top <- class1.top
  class1.bot <- matrix(rnorm(75, mean=1, sd=0.2), ncol=5)
  class2.bot <- apply.position.matrix(class1.bot, function(x, pos) x + pos*2)

  class1 <- matrix(c(t(class1.top), t(class1.bot)), ncol=5, byrow=TRUE)
  class2 <- matrix(c(t(class2.top), t(class2.bot)), ncol=5, byrow=TRUE)

  m <- matrix(c(class1, class2), ncol=10)

  dimnames(m) <- list(c(paste("Not Sig", 1:15), paste("Sig", c(16:30))), c(paste("Array", 1:10)))

  if(!is.na(file))
    write.table(m, file, sep="\t", quote=FALSE, col.names=NA)

  # Covariate names
  cov1 <- c("Array", c(paste("Array", 1:10)))
  cov2 <- c("Experiment Class", rep("control", 5), rep("experiment", 5))
  cov3 <- c("Time Point", c(1:5), c(1:5))
  cov <- matrix(c(cov1,cov2,cov3), nrow=3, byrow=TRUE)

  if(!is.na(covfile))
    write.table(cov, covfile, sep="\t", col.names=FALSE, row.names=FALSE, quote=FALSE)

  list(data=m, cov=cov)
}
