# TODO: Add comment
# 
# Author: E.Korsching 10.9.2009
###############################################################################



shapiro.wilk.test <- function(x, Shapiro.W.alpha, ncx, ncy){
    # Shapiro-Wilk test : test on deviation from normal distribution
    # get data.frame with the two groups
    # calculate test on each row (gene etc.) for each group
	# w: small : deviation from normal distribution  (p<=alpha) , w->1: normal distribution (p>alpha)
    
    #
    f1 <- function(x, Shapiro.W.alpha, ncx, ncy){
		
        sw.g1 <- shapiro.test(jitter(x[1:ncx]))			#Error in shapiro.test(c(1, 1, 1)) : all 'x' values are identical -->> jitter()
		sw.g2 <- shapiro.test(jitter(x[(ncx+1):(ncx+ncy)]))
		# it might be possible to generate NA p values while W=1
        if(is.na(sw.g1$p.value)){ sw.n1 <- NA }else{ sw.n1 <- if(sw.g1$p.value>Shapiro.W.alpha){ T }else{ F } }
		if(is.na(sw.g2$p.value)){ sw.n2 <- NA }else{ sw.n2 <- if(sw.g2$p.value>Shapiro.W.alpha){ T }else{ F } }
        #
        sw.w.ratio <-  sw.g1$statistic / sw.g2$statistic

        return(c(sw.n1, sw.n2, sw.w.ratio))
    }
    #
    result1 <- data.frame(t(apply(x, 1, f1, Shapiro.W.alpha, ncx=ncx, ncy=ncy)))
    names(result1) <- c("sw.n1", "sw.n2", "sw.w.ratio")
    #
    return(result1)
}



