# TODO: Add comment
# 
# Author: E.Korsching Sep 11, 2013
###############################################################################


counts.start.in.window <- function(x, window.x){
	# counts all reads which are -starting- in a given physical position window
	# extracts from a simple  scanBam() object  one list  with  pos and qwidth  and  optional score  object
	# note: depending on the read length there might be boundary effects
	# window.x: c(min,max), the view is downstream
	
	# check x
#	if(length(x)==2){ flag <- 0 }
#	if(length(x)==3){ flag <- 1 }
	
	# extract pos and qwidth objects
	pos <- x[["pos"]]
#	qwidth <- x[["qwidth"]]
#	if(flag==1){ score <- x[["score"]] }
	# to be sure order
	pos.o <- order(pos)
	pos <- pos[pos.o]
#	qwidth <- qwidth[pos.o]
#	if(flag==1){ score <- score[pos.o] }
	# how many positions 
	lpos <- length(pos)		# greater 28000 might be wrong (read length 35)
#	lqwidth <- length(qwidth)
#	if(lpos!=lqwidth){ cat("\n length of pos and qwidth differ"); return(matrix(0,1,2)) }	###
	# control qwidth
	#  look for most prominent read length and get index - take only this read length
#	freq.qwidth <- summary(as.factor(qwidth))
#	most.promi <- as.numeric( names(freq.qwidth)[which(freq.qwidth==max(freq.qwidth))] )
#	tmp.logi <- qwidth==most.promi
#	qwidth <- qwidth[tmp.logi]		# RLE
#	pos <- pos[tmp.logi]
#	if(flag==1){ score <- score[tmp.logi] }
	# control pos deviations / clip
	tmp.logi <- pos>window.x[1] & pos<window.x[2]
	pos <- pos[tmp.logi]
#	qwidth <- qwidth[tmp.logi]
#	if(flag==1){ score <- score[tmp.logi] }
	# count
	erg <- matrix(0,1,1)
	erg[1,1] <- length(pos)
#	if(flag==1){ erg[1,2] <- median(score[tmp.logi]) }		# median
	
	return(erg)
}


#ac <- counts.start.in.window( list( pos=as.integer(c(18,25,25,25,38)), qwidth=as.integer(c(10,10,10,10,10)) ) , c(20,50) )
#ac <- counts.start.in.window( list( pos=as.integer(c(21,25,25,25,46)), qwidth=as.integer(c(10,10,10,10,10)) ) , c(20,50) )



