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



#### replacement for the text() function in the graphics package
#    if the output is a lot of text
#    works well in a setting like
#	pmai <- par()$mai
#	par(mai=c(0.2,0.2,0.2,0.2))
#	plot.new()
#	...
#	txt.wrap()
#   ...
#   par(mai=pmai)
#    see e.g.  test.disp01()  in  ../proxyRela2/test_norm.R


txt.wrap <- function(str, wrapAt=1, element="", x=.1, y=.85, delta=0.05, adj=c(0,0.5), cex=0.7){
	# instead of using standard text() function in plot area
	# str: one (long) char string
	# wrapAt: wrap after
	# element: if not "", not after character postions instead after number of elements
	f1 <- function(){#char postions
		nch <- nchar(str)
		f.nch <- nch/wrapAt
		f.nch.f <- floor(f.nch)
		f.nch.r <- nch %% wrapAt # no is 0
		res <- vector("list",f.nch.f)
		for(i in 1:f.nch){
			res[[i]] <- substr(str, 1, wrapAt)
			str <- substr(str, (wrapAt+1), nchar(str))
			if(i==f.nch & f.nch.r!=0){ res[[(i+1)]] <- str }	# rest
		}
		return(res)
	}
	f2 <- function(){#element postions
		strlen <- nchar(str)
		epos <- unlist(gregexpr(pattern=element,text=str,perl=T))
		elen <- length(epos)
		epos <- epos[seq(0,elen,wrapAt)]
		elen <- length(epos)
		f.ne <- elen/wrapAt
		f.ne.f <- floor(f.ne)
		f.ne.r <- elen %% wrapAt # no is 0
		res <- vector("list",f.ne.f)
		ep <- c(0,epos)
		elen <- length(ep)
		for(i in 1:(elen-1)){
			res[[i]] <- substr(str, (ep[i]+1), ep[i+1])
			if(i==(elen-1) & (ep[i+1]+1)<=strlen){ res[[(i+1)]] <- substr(str, (ep[i+1]+1), strlen) }	# rest
		}
		return(res)
	}
	if(length(str)>1){ stop("str needs to be one string") }
	if(nchar(str)==0){ stop("str is empty") }
	
	if(element==""){
		res <- f1()
	}else{
		res <- f2()
	}
	rlen <- length(res)
	y1 <- y
	k <- 1
	for(i in 1:rlen){
		if(k==58){ plot.new(); k <- 1; y1 <- y }	# for pdf pages...
		text(x=x, y=y1, labels=res[[i]], adj=adj, cex=cex, family="mono")
		y1 <- y1-delta
		k <- k+1
	}
	return()
}



par()$font


#plot.new()
#txt.wrap(str="aa,bb, cc, dd, ee,ff, gg,hh,aa,bb, cc, dd, ee,ff, gg,hh,ii",
#		wrapAt=8, element=",", x=.1, y=.85, delta=0.05, adj=c(0,0.5), cex=0.7)
#
#plot.new()
#txt.wrap(str="aa,bb, cc, dd, ee,ff, gg,hh,ii",
#		wrapAt=5, element="", x=.1, y=.85, delta=0.05, adj=c(0,0.5), cex=0.7)
#
#plot.new()
#a9 <- paste((colSums(a$peaks)),collapse=",")
#txt.wrap(str=a9, wrapAt=10, element=",", x=.1, y=.85, delta=0.05, adj=c(0,0.5), cex=0.7)	



