# TODO: Add comment
# 
# Author: E.Korsching  2016
###############################################################################



regression.difference <- function(z, mat=T){
	# significance test each col versus each col if the regression slope is different
	#  follows the doc: "How to calculate the difference of two slopes.pdf"
	# z: get list element with first: correlation coefficients matrix  and  second: order
	#  e.g. list(rk.Rmale.2.d.1h[[3]][1:9,,drop=F], rk.Rmale.2.d.1h[[1]][1,2:10])
	# mat: T: return result as matrix
	# erg: collect results: slope difference test p values
	
	# ini
	if(anyNA(z[[1]])){ stop("NA values in input") }
	
	f1 <- function(){
		# customize
		data.g1 <- cbind(y=x[,i], xo=c(1:nr), g=rep(1, nr))
		data.g2 <- cbind(y=x[,j], xo=c(1:nr), g=rep(2, nr))
		data.g <- data.frame( rbind(data.g1, data.g2), row.names=c(1:(nr*2)) )
		# test
		m.b <- lm(y ~ xo * g, data=data.g)
		m.null <- lm(y ~ xo + g, data=data.g)
		p.val <- anova(m.null, m.b)$'Pr(>F)'[2]		# def: p>0.05 : equal slopes; p<=0.05 : different slopes
		#
		return(p.val)
	}
	
	x <- z[[1]][ z[[2]], ]		# create ordered matrix
	
	nr <- nrow(x)
	nc <- ncol(x)
	
	if(mat){
		x.names <- dimnames(x)[[2]]
		erg <- data.frame(matrix(0,nrow=nc,ncol=nc))	# matrix, lower triangle filled
		dimnames(erg)[[1]] <- x.names
		dimnames(erg)[[2]] <- x.names
		for(i in 1:(nc-1)){ #x
			for(j in (i+1):nc){ #y
				erg[j,i] <- f1()
			}
		}
	}else{
		erg <- vector("numeric",length=(nc^2-nc)/2)		# vector without diagonal values, order col wise top down, lower triangle
		k <- 1
		for(i in 1:(nc-1)){ #x
			for(j in (i+1):nc){ #y
				erg[k] <- f1()
				k <- k+1
			}
		}
	}
	cat("\n rows: ",nr," - columns: ",nc,"\n\n")
	return(erg)
}


#aa <- regression.difference(z=list(rk.Rmale.2.d.1h[[3]][1:9,,drop=F], rk.Rmale.2.d.1h[[1]][1,2:10]), mat=T)



