# TODO: Add comment
# 
# Author: E.Korsching Oct 14, 2014
###############################################################################


color.mix <- function(x){
	# mix RGB colors by converting to CMYK, adding all divided by number and converting back
	#  subtractive mixing (natural like)
	# get a vector of RGB values in hex notation (at least two values) and returns a hex value
	# if only -one- or -non- hex value is given those values will be returned
	
	#ini
	x.len <- length(x)
	if(x.len<2){ return(x) }
	
	require(colorspace)
	
	toCYMK <- function(r, g, b){						# 0..1 not 0..255
		cmyk <- vector(mode="numeric",length=4)
		
		k <- min( 1-r, min(1-g, 1-b) )					# 1 : replace by 255 if those values are used
		c <- 1*(1-r-k)/(1-k) 
		m <- 1*(1-g-k)/(1-k) 
		y <- 1*(1-b-k)/(1-k) 
		
		cmyk[1] <- c
		cmyk[2] <- m
		cmyk[3] <- y
		cmyk[4] <- k
		
		return(cmyk)
	}
	
	toRGB <- function(c, m, y, k){						# 0..1
		rgb <- vector(mode="numeric",length=3)
		
		r <- -(c * (1-k) / 1 + k - 1)
		g <- -(m * (1-k) / 1 + k - 1)
		b <- -(y * (1-k) / 1 + k - 1)
		
		rgb[1] <- r
		rgb[2] <- g
		rgb[3] <- b
		
		return(rgb)
	}
	
	# convert to RGB
	x2 <- hex2RGB(x, gamma=F)@coords		# S4, sRGB class
	
	# convert to CYMK
	x3 <- matrix(0,x.len,4)
	for(i in 1:x.len){
		x3[i,] <- toCYMK(r=x2[i,1], g=x2[i,2], b=x2[i,3])
	}
	
	# col sums / number of rows
	x4 <- colSums(x3)/x.len
	
	# convert to RGB and hex
	x5 <- toRGB(c=x4[1], m=x4[2], y=x4[3], k=x4[4])
	x6 <- hex( RGB(R=x5[1], G=x5[2], B=x5[3]), fixup=F )		# return hex value
	
	return(x6)
}

#color.mix(c("#0000FF","#2900D5"))

#plot(1,1,cex=4,pch=19,col="#0000FF",xlim=c(0,6),ylim=c(0.5,1.5))			# red  - red blue gradient
#points(x=2,y=1,cex=4,pch=19,col=color.mix(c("#0000FF","#FF0000")))	# mix red-blue
#points(x=3,y=1,cex=4,pch=19,col="#FF0000")							# blue
#points(x=4,y=1,cex=4,pch=19,col="#7E0080")		# mid of gradient 125/250
#points(x=5,y=1,cex=4,pch=19,col="#80007E")		# mid of gradient 126/250
#a.pal <- colorRampPalette(c("blue", "red"),space = "rgb")
#aa <- a.pal(250)
#for(i in 1:250){
#	segments(x0=0.5+i/50,y0=0.5,x1=0.5+i/50,y1=0.8,lwd=2,col=aa[i])
#	if(i==125 | i==126 | i==140 | i==141) segments(x0=0.5+i/50,y0=1.2,x1=0.5+i/50,y1=1.5,lwd=2,col=aa[i])
#}


