# TODO: Add comment
# 
# Author: Korsching 18.11.2011
###############################################################################



normSpikeInRegression <- function(x, y, ref.col=1, subfolder.filename=NULL){
	# normalize according to spike in controls via x-y-regression (Bablok)
	# x: data to be normalized - cols: experiments, rows: genes / exons ... (data.frame)
	# y: normalization data set (corresponding col order to x!, data.frame)
	# ref.col: column which remains to be unchanged
	#  average to be used as a normalization factor
	# subfolder.filename: path + name for results
	
	#ini
	nrx <- nrow(x)
	ncx <- ncol(x)
	nry <- nrow(y)
	if(ncx<2){ cat("\n minimum of 2 columns in x"); break }
	
	#work
	#calculate transformation factors for each col pair
	# and apply normalisation
	cat("\n correct by slope only \n")
	ab <- list(ncx-1)
	j <- 1
	for(i in c(1:ncx)[-ref.col]){
#		ab[[j]] <- linfit.ab(x=y[,ref.col], y=y[,i])		#get: list(intercept, slope)
		tmp <- bablok.passing(x=y[,ref.col], y=y[,i])[1:2,1]		#get: matrix: intercept(1,1), slope(2,1)
		ab[[j]] <- list(tmp[1],tmp[2])
		cat("\n column ",i," intercept ",ab[[j]][[1]]," slope ",ab[[j]][[2]])
		#correct by: col.i=a+b*col.ref -> ignore intercept -> col.i/b=col.i.corrected
		x[,i] <- x[,i]/ab[[j]][[2]]
		j <- j+1
	}
	
	#check for NaN (0/0) or NA (0/NA)
	#erg.factor[is.na(erg.factor)] <- 0
	#check for Inf (1/0)
	#erg.factor[is.infinite(erg.factor)] <- 0
	
	#plot regression
	#
	if(!is.null(subfolder.filename)){
		png(filename = paste(getwd(),subfolder.filename,".",format(Sys.time(), "%Y%m%d%H%M"),".png", sep=""),
				width = 800, height = 800, units = "px", pointsize = 12, bg = "white")
	}
	
	if( (ncx/2)<=1 ){ par(mfrow=c(1,2)) } else { par( mfrow=c(ceiling(ncx/2),2) ) }
	j <- 1
	for(i in c(1:ncx)[-ref.col]){
		plot(y[,ref.col], y[,i], xlab=paste( "column",ref.col,names(y[ref.col]) ), ylab=paste( "column",i,names(y[i]) ))
		abline(ab[[j]][[1]],ab[[j]][[2]])
		mtext( paste("intercept",round(ab[[j]][[1]],2),"slope",round(ab[[j]][[2]],4) ) )
		j <- j+1
	}
	
	if(!is.null(subfolder.filename)){ dev.off() }
	
	#
	return( round(x,digits=2) )
}




