# TODO: Add comment
# 
# Author: E.Korsching Apr 16, 2014
###############################################################################



trim.distribution <- function(x, fraction=NULL, where="both"){
	# trim a vector (tuple idea) by distribution extremes but
	#   preserve as much as possible from the original tuple order
	# fraction of trimming: 0..1
	# where: "both": trim upper and lower end of distribution
	#  (means fraction/2 on upper and fraction/2 for lower end)
	#  "upper": trim fraction of upper end, "lower": trim fraction of lower end
	if(is.null(fraction)){
		cat("\n trim.values: fraction 0..1 is missing")
		return()
	}
	x.len <- length(x)
	x.order <- order(x)		# order for trim
	p.order <- seq(1,x.len,1)[x.order]	# apply order to seq of positions -> positions after trim will form the final set
	
	if(where=="both"){
		trim <- floor(x.len * fraction/2)		# trim will only start if 'floor' is >= 1
	}else{
		trim <- floor(x.len * fraction)
	}
	if(where=="both"){
		lo <- trim + 1
		hi <- x.len - trim
	}
	if(where=="upper"){
		lo <- 1
		hi <- x.len - trim
	}
	if(where=="lower"){
		lo <- trim + 1
		hi <- x.len
	}
	
	p.order.trim <- p.order[lo:hi]
	p.order.trim <- sort(p.order.trim)		# preserve remaining order
	y <- x[p.order.trim]	# keep remaining positions 
	return(y)
}



#trim.distribution(x=c(1,3,5,6,6,4,8,9,2,5,1,3,5,6,6,4,8,9,2,5), fraction=0.1, where="lower")
#trim.distribution(x=c(1,3,5,6,6,4,8,9,2,5,1,3,5,6,6,4,8,9,2,5), fraction=0.1, where="upper")
#trim.distribution(x=c(1,3,5,6,6,4,8,9,2,5,1,3,5,6,6,4,8,9,2,5), fraction=0.1, where="both")

# 1,3,5,6,6,4,8,9,2,5,1,3,5,6,6,4,8,9,2,5		"lower"
#   3 5 6 6 4 8 9 2 5   3 5 6 6 4 8 9 2 5
# 1,3,5,6,6,4,8,9,2,5,1,3,5,6,6,4,8,9,2,5		"upper"
# 1 3 5 6 6 4 8   2 5 1 3 5 6 6 4 8   2 5
# 1,3,5,6,6,4,8,9,2,5,1,3,5,6,6,4,8,9,2,5		"both"
#   3 5 6 6 4 8 9 2 5 1 3 5 6 6 4 8   2 5


