.packageName <- "AffyExpress"

AffyInteraction<-function(object, method, main.var, strata.var,compare1, 
    compare2, covariates=NULL, p.int=0.05, m.int=0, adj.int="none",
	p.value=0.05, m.value=0, adj="none", filename1="result", 
      filename2="inter_result"){
	
    target<-pData(object)
    cdf.name <-annotation(object)
    result<-list()		
    if (length(covariates)==0) {
        design.int<-make.design(target, c(main.var, strata.var), int=c(1,2))
	  design.all<-make.design(target, main.var)
    }
    else{
	  design.int<-make.design(target, c(main.var, strata.var, covariates), 
	      int=c(1,2))
	  design.all<-make.design(target, c(main.var,covariates))
    }
    contrast.int<-make.contrast(design.int, interaction=TRUE)
    contrast.all<-make.contrast(design.all, compare1, compare2)
    result.int<-regress(object, design.int, contrast.int, method, adj.int)
    print ("For interaction test:")
    result[[1]]<-select.sig.gene(result.int, p.int, m.int)
    names(result)[1]<-"Interaction Test"	
    sig.ID<-result[[1]]$ID[result[[1]]$significant==TRUE]
    sig.index<-match(sig.ID, rownames(exprs(object)))
    result.no.int<-regress(object[-sig.index,], design.all, contrast.all, 
	    method, adj)
    print ("------------------------------------------------------")
    print ("For genes without interaction effect:")
    result[[2]]<-select.sig.gene(result.no.int, p.value, m.value)
    names(result)[2]<-"Genes Without Interaction Effect"
    print ("------------------------------------------------------")
    print ("For genes with interaction effect:")
    str.table<-post.interaction(strata.var, compare1, compare2, 
        design.int, object[sig.index,], method, adj, p.value, m.value)
    for (j in 1:length(str.table)){
	    result[[2+j]]<-str.table[[j]]
	    names(result)[2+j]<-names(str.table)[j]
    }
    result2html(cdf.name, result[[2]], filename1)
    interaction.result2html(cdf.name, str.table, result[[1]], filename2)
    result
}



AffyQA<-function (parameters, raw, Output = "AffyQA.html") 
{
    require("R2HTML")
	require("affyPLM")
    require("simpleaffy")
    targets_old <- pData(raw)
    dum <- rep(c("yellow", "red", "turquoise", "brown", "darkviolet", 
        "steelblue", "springgreen", "sienna", "darkslategray", 
        "salmon", "purple", "olivedrab", "orange", "wheat", "hotpink", 
        "black", "orchid"), 10)
   

    print("Retrieving grouping parameters")
    num <- match(parameters, colnames(targets_old))
    if (length(num) < 1 | sum(is.na(num)) > 0) {
        stop("Please check your parameter names, which must match the \n  colnames of phenotype files.")
    }
    target_sort <- SortMat(targets_old, Sort = num)
    target_sort <- as.matrix(target_sort)
    size <- nrow(target_sort)
    targets <- c()
    for (i in 1:size) {
        targets[i] <- target_sort[i, num[1]]
        if (length(num) > 1) {
            for (j in 2:length(num)) {
                targets[i] <- paste(targets[i], target_sort[i, 
                  num[j]], sep = ".")
            }
        }
    }
    singular <- unique(as.character(targets))
    counter <- array(0, length(singular))
    for (x in 1:length(singular)) {
        count = 0
        for (k in 1:length(targets)) {
            if (targets[k] == singular[x]) {
                count <- count + 1
            }
        }
        counter[x] = count
    }
    for (x in 1:length(singular)) {
        if (counter[x] > 1) {
            index <- which(targets == singular[x])
            targets[index] <- paste(targets[index], c(1:counter[x]), 
                sep = ".")
        }
    }
    target_sort <- cbind(target_sort, targets)

    colnames(target_sort)[length(colnames(target_sort))]<-"Sample ID"

    raw <- raw[, match(rownames(target_sort), rownames(pData(raw)))]
    genome <- cdfName(raw)
    testchip <- grep("^Test3", genome)
    if (length(testchip) > 0) {
        genome <- "test3"
        raw@cdfName <- "test3"
    }
    genome <- cleancdfname(cdfName(raw))

    ##included <-getAlpha1(genome)
	setQCEnvironment(genome)
    included <- qc.get.alpha1()


    HTMLStart(filename = Output)
    HTML("<a name= \"top\"></a>", file = Output)
    titl <- as.title("<p align=center>Affymetrix Quality Assessment</p>")
    HTML(titl, file = Output, append = FALSE)
	
    ##targetDisplay <- xtable(target_sort)
    ##HTML(targetDisplay, file = Output)
	HTML(target_sort, file = Output)
    HTML(paste("The samples are grouped by:", paste(parameters, 
        collapse = " and ")), file = Output)
    HTML("<hr><dl><li> Figure 1 -<a href= #fig1> Affy Recommended Quality \n\t    Assessment </a>", 
        file = Output)
    HTML("<li> Figure 2 -<a href = #fig2> RNA Quality Assessment</a>", 
        file = Output)
    HTML("<li> Figure 3 -<a href = #fig3> Sample Quality Assessment </a>", 
        file = Output)
    HTML("<li> Figure 4 - Quality Diagnostic using PLM", file = Output)
    HTML("<dd>Figure 4a - <a href = #fig4>Pseudo-chip Images </a>", 
        file = Output)
    HTML("<dd>Figure 4b -<a href = #fig5> NUSE and RLE plots</a>", 
        file = Output)
    HTML("<li> <font size=4 color=red> I need <a href=\n\t    http://informatics.coh.org/microarray/quality_control.asp> \n\t\thelp</a> to interpret these plots. </font></dl>", 
        file = Output)
    if (is.na(included)) {
        figure1 <- "Figure1.png"
        png(file = figure1)
	      plot(1,1, col="white", yaxt="n", xaxt="n", xlab="", ylab="", bty="n")
	      text(1,1,label="Your Chip is not supported by simplyaffy", col="red")
	      HTML("<hr><a name= \"fig1\"></a>", file = Output)
        HTMLInsertGraph(figure1, file = Output, Caption = "Figure 1: Affymetrix \n\t\t    recommended Quality Assessment", 
            GraphBorder = 1, Align = "center", append = TRUE)
        dev.off()

    }
    else {
        data_mas5 <- call.exprs(raw, sc = 500, "mas5")
	      qc <- qc(raw, data_mas5)
        figure1 <- "Figure1.png"
        png(file = figure1, height = 960)
        layout(matrix(c(1, 3, 5, 7, 2, 4, 6, 7), nr = 4, ncol = 2), 
            TRUE)
        par(mar = c(2, 2, 2, 1))
        description(raw)@title <- "Raw Intensity"
        boxplot(raw, cex.main = 0.9, cex.axis = 0.7, col = dum[1:size], 
            names = rep("", size))
        barplot(avbg(qc), names = " ", cex.axis = 0.7, col = dum[1:size], 
            cex.main = 0.9, font.main = 3, main = "Average background", 
            font.main = 1)
        barplot(percent.present(qc), names = " ", cex.axis = 0.7, 
            col = dum[1:size], cex.main = 0.9, font.main = 3, 
            main = "Percentage Present", font.main = 1)
        barplot(sfs(qc), main = "Scaling Factor", cex.axis = 0.7, 
            names = " ", cex.main = 0.9, font.main = 3, col = dum[1:size], 
            font.main = 1)
        boxplot(data.frame(spikeInProbes(qc)), col = dum, cex.axis = 0.7, 
            cex.main = 0.9, main = "Hybridization Controls", 
            names = c(" ", " ", " ", " "))
        legend("topleft", col = dum[1:4], cex = 0.8, lty = 1, 
            legend = c("BioB", "BioC", "BioD", "Cre"))
        boxplot(data.frame(2^ratios(qc)), col = dum, cex.axis = 0.7, 
            cex.main = 0.9, main = "Housekeeping Controls", names = c(" ", 
                " ", " ", " "))
        legend("topright", col = dum[1:4], cex = 0.8, lty = 1, 
            legend = c("ACTIN 3'/5'", "GAPDH 3'/5'", "ACTIN 3'/M", 
                "GAPDH 3'/M"))
        ##barplot(0.1, cex.axis = 0.01, yaxt = "n", xaxt = "n", 
        ##    col = "white")
        plot(1,1, col="white", yaxt="n", xaxt="n", xlab="", ylab="", bty="n")
        legend("center", col = dum[1:size], lty = 1, cex = 0.9, 
            legend = targets)
        HTML("<hr><a name= \"fig1\"></a>", file = Output)
        HTMLInsertGraph(figure1, file = Output, Caption = "Figure 1: Affymetrix \n\t\t    recommended Quality Assessment", 
            GraphBorder = 1, Align = "center", append = TRUE)
        dev.off()
    }
    print("Generating RNA digestion plot...")
    figure2 <- "Figure2.png"
    png(file = figure2)
    deg <- AffyRNAdeg(raw)
    summaryAffyRNAdeg(deg)
    flag <- FALSE
    for (i in 1:dim(deg$means.by.number)[1]) {
        for (j in 1:dim(deg$means.by.number)[2]) {
            if (deg$means.by.number[i, j] < 0) {
                deg$means.by.number[i, j] <- NA
                flag <- TRUE
            }
        }
    }
    if (flag == TRUE) {
        for (i in 1:dim(deg$means.by.number)[1]) {
            for (j in 1:dim(deg$means.by.number)[2]) {
                if (is.na(deg$means.by.number[i, j])) {
                  deg$means.by.number[i, j] <- mean(deg$means.by.number[i, 
                    ], na.rm = TRUE)
                  deg$ses[i, j] <- mean(deg$ses[i, ], na.rm = TRUE)
                }
            }
        }
    }
    plotAffyRNAdeg(deg, col = dum[1:size])
    legend("topleft", col = dum[1:size], lty = 1, cex = 0.7, 
        legend = targets)
    dev.off()
    HTML("<hr><a name= \"fig2\"></a>", file = Output)
    HTMLInsertGraph(figure2, file = Output, Caption = "Figure 2: RNA Quality \n\t    Assessment", 
        GraphBorder = 2, Align = "center", append = TRUE)
    data <- rma(raw)
    r <- cor(exprs(data))
    d <- 1 - r
    hc <- hclust(as.dist(d), method = "average")
    print("Generating sample hierarchical clustering plot...")
    figure3 <- "Figure3.png"
    png(file = figure3)
    plot(hc, main = "Hierarchical Clustering of Samples", xlab = " ", 
        sub = " ", labels = targets)
    dev.off()
    HTML("<hr><a name= \"fig3\"></a>", file = Output)
    HTMLInsertGraph(figure3, file = Output, Caption = "Figure 3: Sample Quality \n\t    Assessment", 
        GraphBorder = 2, Align = "center", append = TRUE)
    row <- round(sqrt(size))
    for (x in row:size) {
        if (((row * x) - size) >= 0) {
            col <- x
            break
        }
    }
    print("Generating pseudo-chip images...")
    figure4 <- "Figure4.png"
    png(file = figure4)
    sampleNames(raw) <- targets
    data_PLM <- fitPLM(raw, output.param = list(varcov = "none"))
    par(mar = c(1, 1, 2, 1), mfrow = c(row, col))
    for (i in 1:size) {
        image(data_PLM, which = i)
    }
    dev.off()
    HTML("<hr><a name= \"fig4\"></a>", file = Output)
    HTMLInsertGraph(figure4, file = Output, Caption = "Figure 4a: Pseudo-chip \n\t    Images", 
        GraphBorder = 2, Align = "center", append = TRUE)
    figure5 <- "Figure5.png"
    png(file = figure5)
    par(mfrow = c(1, 2), las = 2, mar = c(3, 2, 2, 1))
    boxplot(data_PLM, main = "NUSE Plot", cex.axis = 0.7, names = targets, 
        col = dum[1:size])
    Mbox(data_PLM, main = "LPE Plot", names = targets, cex.axis = 0.7, 
        col = dum[1:size])
    dev.off()
    HTML("<a name= \"fig5\"></a>", file = Output)
    HTMLInsertGraph(figure5, file = Output, Caption = "Figure 4b: Normalized \n\t    Unscaled Standard Error Plot and Relative Log Expression Plot", 
        GraphBorder = 2, Align = "center", append = TRUE)
    HTML("<hr>This report was generated by ", file = Output)
    HTML(paste("<li>", "affy Version", package.version("affy"), 
        "(by Rafael A. Irizarry, Laurent Gautier and Benjamin Bolstad),"), 
        file = Output)
    HTML(paste("<li>", "affyPLM Version", package.version("affyPLM"), 
        "(by Benjamin Bolstad),"), file = Output)
    HTML(paste("<li>", "limma Version", package.version("limma"), 
        "(by Gordon Smyth),"), file = Output)
    HTML(paste("<li>", "R2HTML Version", package.version("R2HTML"), 
        "(by Eric Lecoutre),"), file = Output)
    HTML(paste("<li>", "simpleaffy Version", package.version("simpleaffy"), 
        "(by Crispin J. Miller), and"), file = Output)
    ##HTML(paste("<li>", "xtable Version", package.version("xtable"), 
    ##    "(by David Dahl)"), file = Output)
    HTML(paste("<hr>Generated on: ", date()), file = Output)
    HTMLStop()
}


AffyRegress<-function(normal.data, cov, compare1, compare2, method, 
    int=NULL, level=NULL, adj="none", p.value=0.05, m.value=0, 
	filename="result")
{    
    cdf.name<-annotation(normal.data)
    target<-pData(normal.data)
    design<-make.design(target, cov, int)
    contrast<-make.contrast(design, compare1, compare2, level)
    result<-regress(normal.data, design, contrast, method, adj=adj)
    select<-select.sig.gene(result, p.value=p.value, m.value=m.value)
    result2html(cdf.name, select, filename)
    select
}

Filter<-function(object, numChip=1, bg=0, range=0, iqrPct=0)
{
    require("genefilter")
    ## method 1:  filtering based on minimum # of chip > bg
    if (bg > 0){
        maxChip<-dim(exprs(object))[2]
        if (numChip > maxChip){
            stop (paste("numChip must <= ", maxChip,sep=""))
        } 
        f<-kOverA(numChip, bg) 		
	fun<-filterfun(f)
	good1<-genefilter(object, fun)
    }
    else {
        good1<-rep(TRUE, dim(exprs(object))[1])
    }
    ## method 2: max-min > range
    if (range >0) {
        max<-apply(exprs(object), 1, max)
	min<-apply(exprs(object), 1, min)
	data_ratio<-max-min
	if (range > max(data_ratio)){
            stop (paste("range must < ", max(data_ratio),sep=""))
        }
	good2 <- data_ratio >=range
    }
    else {
        good2<-rep(TRUE, dim(exprs(object))[1])
    }
    ## method 3: IQR > iqrPct 
    if (iqrPct>0) {
        iqr<- apply(exprs(object), 1, IQR)
	good3 <-iqr >= quantile(iqr, iqrPct)
    }
    else {
        good3<-rep(TRUE, dim(exprs(object))[1])
    }
    good <-good1 & good2 & good3
    print(paste("After Filtering, N = ", sum(good), sep=""))
    filtered<-object[good]
    filtered
}

SortMat <- function(Mat, Sort) {
    if (dim(Mat)[2] == 1){
        temp<-rep(NA, dim(Mat)[1])
        Mat_temp0<-cbind(Mat, temp)
        m <- do.call("order", as.data.frame(Mat_temp0[,Sort]))
        result0<-Mat_temp0[m,]
        result <-data.frame(result0[,1])
        rownames(result)<-rownames(result0)
        colnames(result)<-colnames(result0)[1]
    }
    else{
        m <- do.call("order", as.data.frame(Mat[,Sort]))
        result<-Mat[m,]
    }
    result
}

cal.eq<-function(compare, var1, var2, level.var){
    value1 <-0
    value2 <-0
    v1<-unlist(strsplit(var1, "\\/"))[2]
    v2<-unlist(strsplit(var2, "\\/"))[2]
    if (compare == v1 | level.var == v1) value1 <-1
    if (compare == v2 | level.var == v2) value2 <-1
    value <- value1*value2
    value
}

f.test<-function(fit){
    fit$t <- fit$coef / fit$stdev.unscaled / fit$sigma
    F.stat <- classifyTestsF(fit, fstat.only = TRUE, df=fit$df.residual)
    fit$F <- as.vector(F.stat)
    df1 <- attr(F.stat, "df1")
    df2 <- attr(F.stat, "df2")
    fit$F.p.value <- pf(fit$F, df1, df2, lower.tail = FALSE)
    fit
}

find.col.index<-function(filename, parameter){

    index = which(colnames(filename) ==parameter)
    num <- c()
    if (length(index) >0){
	num <- c(num, index)
    }
    else stop (paste(parameter," is not found",sep=""))
    num
}

get.f<-function(fit){
    fit$t <- fit$coef / fit$stdev.unscaled / fit$sigma
    F.stat <- classifyTestsF(fit, fstat.only = TRUE, df=fit$df.residual)
    fit$F <- as.vector(F.stat)
    fit
}
import.data<-function(phenotype.file, path=getwd(), ...){
    phenoD<-read.AnnotatedDataFrame(phenotype.file, path=path, ...)
    raw<-ReadAffy(filenames=rownames(pData(phenoD)), phenoData=phenoD, celfile.path=path)
    raw
}


interaction.result2html<-function(cdf.name, result, inter.result, filename="inter_result")
{

    library(cdf.name,character.only =TRUE) 
	require("annaffy")
    fullresult<-list()
    name.index<-list()
    g<-list()
    for (j in 1:length(result)){
        fullresult[[j]]<-cbind(result[[j]]$ID, result[[j]]$Log2Ratio.1, 
	    result[[j]]$adj.P.Val)
	name.index[[j]]<-(unlist(strsplit(names(result)[j], "\\.")))[1]
	colnames(fullresult[[j]])<-c("ID", "M", "adj.P.Val")
	colnames(fullresult[[j]])[2]<-paste(name.index[[j]], ":Log2Ratio", 
	    sep="")
	colnames(fullresult[[j]])[3]<-paste(name.index[[j]],":Adj.P",sep="")
	g[[j]]<-result[[j]]$significant
    }
    result.table<-merge(fullresult[[1]], fullresult[[2]])
    good <-g[[1]]|g[[2]]
    if (length(result)>2){
        for (i in 3:length(result)){
	    result.table<-merge(result.table, fullresult[[i]])
	    good<-good|g[[i]]
	}
    }
    if (sum(good)==0) print ("No significant result is generated for the 
        interaction model")
    else {
	gN <- as.character(result[[1]]$ID)
	aaf.handler()
	anncols <- aaf.handler()[c(1:3, 7, 8)]
	probeid <- gN[good]
	anntable <- aafTableAnn(probeid, cdf.name, anncols)
	t.table<-list()
	for (h in 1:length(result)){
	    t.table[[h]]<-aafTable(result.table[,(h*2)][good], 
	        result.table[,(h*2+1)][good], 
		colnames=colnames(result.table)[(h*2):(h*2+1)])
	}
	testtable<-merge(t.table[[1]], t.table[[2]])
	if (length(result)>2){
	    for (i in 3:length(result)){
		testtable<-merge(testtable, t.table[[i]])
	    }
	}
	table<-merge(anntable, testtable)
	inter.sig<-cbind(inter.result$ID, inter.result$adj.P.Val)
	match.index<-match(result.table$ID[good], inter.sig[,1])
	inter.sig1<- aafTable("Interaction.P"=inter.sig[,2][match.index])
	table1<-merge(table, inter.sig1)
	saveHTML(table1, paste(filename,"html", sep="."), title="Interaction Table")
    }
}


make.contrast<-function(design.matrix, compare1=NULL, compare2=NULL, 
    level=NULL, interaction=FALSE){
	
	param<-colnames(design.matrix)
	if (interaction== TRUE) {
		inter.eq<-array(rep(0,length(param)*length(param)), 
		    dim=c(length(param),length(param)))
		inter.index<-rep(FALSE,length(param))
		for (j in 2:length(param)){
			if (length(grep(":",param[j]))!=0) {
				inter.eq[j,j]<-1
				inter.index[j]<-TRUE
			}
		}
		eq<-cbind(inter.eq[,inter.index])
	}
	else {
		eq1<-rep(0, length(param))
		eq1[1]<-1
		eq2<-eq1
		for (i in 2:length(param)){
			if (length(grep(":",param[i]))==0) {
				value<-unlist(strsplit(param[i], "\\/"))[2]
                        if (compare1 == value) eq1[i] <- 1
				if (compare2 == value) eq2[i] <- 1
			}
			else {
				var.1<-unlist(strsplit(param[i], "\\:"))[1]
				var.2<-unlist(strsplit(param[i], "\\:"))[2]
				eq1[i]<-cal.eq(compare1, var.1, var.2, level)
				eq2[i]<-cal.eq(compare2, var.1, var.2, level)
			}
		}
	eq<- cbind(eq1 - eq2)
	}
	eq
}


make.design<-function (target, cov, int = NULL) 
{    
    target<-data.frame(as.matrix(target))
    attach(target, warn.conflicts = FALSE)
    formula1 <- make.formula(target, cov, int = int)
    design <- model.matrix(as.formula(formula1))
    detach(target)
    newcolnames<-colnames(design)
    for (i in 1:length(cov)){
        newcolnames<-sub(cov[i], paste(cov[i],"/",sep=""), newcolnames)
    }
    colnames(design)<-newcolnames
    design
}

make.formula<-function (target, cov, int=NULL){

	factor.list<-list()
	index.cov<-c()
	formula.cov<-c()
	c.name<-colnames(target)
	
	if (length(int)>0) {

		if (length(int) !=2) stop ("You can only have two numbers")
		index.int1 = find.col.index(target, cov[int[1]])
		index.int2 = find.col.index(target, cov[int[2]])
		formula.int<-paste(as.name(c.name[index.int1]),as.name(c.name[index.int2]),sep="*")
		a<-(cov==cov[int[1]])
		b<-(cov==cov[int[2]])
		c<-a|b
		cov.not.int<-cov[!c]
		if (length(cov.not.int) !=0) {
		
			for (j in 1:length(cov.not.int)) {
				index.cov[j]<-find.col.index(target, cov.not.int[j])
				formula.int<-paste(formula.int,as.name(c.name[index.cov[j]]),sep="+")
			}

		}
		formula<-paste("~", formula.int, sep="")
	}
	else {
		index.cov[1]<-find.col.index(target, cov[1])
		formula.cov<-paste("~",as.name(c.name[index.cov[1]]),sep="")
		
		if (length(cov)>1) {
			for (j in 2:length(cov)) {
				index.cov[j]<-find.col.index(target, cov[j])
				formula.cov<-paste(formula.cov,as.name(c.name[index.cov[j]]),sep='+')
			}
		}	
		formula<-formula.cov
	}
	formula
}




permute.1<-function(object, design, contrast, fstat){
    shuffle<-as.integer(sample(rownames(design)))
    design.p<-design[shuffle,]
    fit <- lmFit(object, design.p)
    fit2 <- contrasts.fit(fit, contrast)
    f<-get.f(fit2)
    flag<-rep(0,length(f))
    for (i in 1:length(f)){
        if (f[i,1]$F>fstat[i,1]$F)  
            flag[i]<-1
    }
    flag
}
post.interaction<-function(strata.var, compare1, compare2, design.int, 
    object, method, adj="none", p.value=0.05, m.value=0)
{
    target<-pData(object)
    result<-list()
    contrast.sep<-list()
    r.full.temp<-list()
    col.index.1<-find.col.index (target, strata.var)
    u.1<-unique(target[col.index.1])
    for (j in 1: dim(u.1)[1]){
        contrast.sep[[j]]<-make.contrast(design.int, compare1, compare2, 
	    level=t(u.1)[1,j])
	r.full.temp[[j]]<-regress(object, design.int, contrast.sep[[j]], 
	    method=method, adj=adj)

	tempname<-paste("Level",t(u.1)[1,j],sep="-")  
	print (paste ("At ",  tempname, ":", sep=""))
	result[[j]]<-select.sig.gene(r.full.temp[[j]],p.value=p.value, 
	    m.value=m.value) 
      names(result)[j]<-tempname
    }
    result
}

pre.process<-function(method, raw, plot=FALSE, output=FALSE)
{
    if (method == "gcrma") {
		require("gcrma")
 	    normaldata <- gcrma(raw)
    }
    else if (method == "rma") {
        normaldata  <- rma(raw)
    }
    else stop ("Only rma or gcrma are supported")
    if (plot == TRUE) {
        size<-dim(exprs(normaldata))[2]
        row <- round(sqrt(size))
	    for(x in row:size) {
	        if(((row*x)-size) >= 0) {
	            col <- x; break
	        } 
        }
        par(mar=c(1,1,2,1),mfrow=c(row,col))
        for (i in 1:size) {
            hist(exprs(normaldata)[,i],200)
        }
	}
    if (output == TRUE) {
        write.table(exprs(normaldata),file="normal.csv", sep = ",", 
		        col.names = NA)
    }
    normaldata
}
regress<-function(object, design, contrast, method, adj="none", 
    permute.time=1000) 
{
	fit <- lmFit(object, design)
	fit2 <- contrasts.fit(fit, contrast)
	if (method == "F") {
		fit2 <- f.test(fit2)
	}
	else if (method == "L"){
		fit2 <- eBayes(fit2)
	}
	else if (method == "P"){
		fit2 <- f.test(fit2)
	 	f<-get.f(fit2)
		p<-matrix(NA, nrow=length(f), ncol=(permute.time-1))
		for (i in 1:(permute.time-1)){
    	      p[,i]<-permute.1(object, design, contrast, f)
		}
		p.1<-rep(1,length(f))
		p<-cbind(p, p.1)
		count<-apply(p,1,sum)
		fit2$F.p.value<-count/permute.time
	}
	adj.P.Value <- p.adjust(fit2$F.p.value, method = adj)
	diff<-cbind(fit2$genes, as.data.frame(fit2$coefficients), 
	    as.data.frame(fit2$F), as.data.frame(fit2$F.p.value), 
		as.data.frame(adj.P.Value)) 
	Log2Ratio.name<-c()
	for (i in 1:(dim(contrast)[2])){
		Log2Ratio.name<-c(Log2Ratio.name, paste("Log2Ratio",i,sep="."))
	}
	names(diff)<-c("ID", Log2Ratio.name, "F", "P.Value","adj.P.Val")
	diff_sort <- SortMat(diff, Sort=1)
	diff_sort
}
result2html<-function(cdf.name, result, filename="result"){
    
    library(cdf.name,character.only =TRUE)
	require("annaffy")
    good <-result$significant
    if (sum(good)==0) print("No significant result is generated")
    else{
        fullresult<-cbind(result$ID, result$Log2Ratio.1, result$adj.P.Val)
        gN <- as.character(result$ID)
        aaf.handler()
        anncols <- aaf.handler()[c(1:3, 7, 8)]
        probeid <- gN[good]
        anntable <- aafTableAnn(probeid, cdf.name, anncols)
        testtable <- aafTable( "Log2 ratio"=fullresult[,2][good],
        "P.Value"=fullresult[,3][good])
        table<-merge(anntable, testtable)
        saveHTML(table, paste(filename,"html", sep="."), title="Target Genes")
    }
}
select.sig.gene<-function(top.table, p.value =0.05, m.value =0)  
{
	good.p<-top.table$adj.P.Val <p.value
	index<-grep("Log2Ratio", names(top.table))
	good.matrix<-matrix(0,nrow=dim(top.table), ncol=length(index))
	for (i in 1:length(index)){
		good.matrix[,i]<-abs(top.table[,index[i]]) >= m.value 
	}
	good.m<-(apply(good.matrix, 1, sum)>0)
	significant<-good.p & good.m
	result<-cbind(top.table, significant)
	print(paste("There are ", sum(significant), " differentially expressed genes",sep=""))
	print("based on your selection criteria.")
	result
}
