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


rev.complement <-function(x, p=NULL, ver=F){
	# transform a nucleotid sequence: reverse, complement
	# x: sequence with no space, possible coding: A,T(U),G,C,N,.- (gap)
	# p: single procedure or sequence of prcedures: r: reverse, c: complement,
	#    tr: translate: T->U: "tu", U->T: "ut"
	#    examples:  "r"; c("r","c") [reverse and complement]; c("ut","r","c")
	# ver: verbose
	fr <- function(){
		r <- seq(xlen,1)
		for(i in 1:xlen){
			x2[r[i]] <- x1[i]
		}
		return(x2)
	}
	fc <- function(x){
		if(x){
			map <- matrix(0,13,2)
			map[,1] <- c("A","U","G","C","a","u","g","c","N","n",".","-"," ")
			map[,2] <- c("U","A","C","G","u","a","c","g","N","n",".","-"," ")
		}else{
			map <- matrix(0,13,2)
			map[,1] <- c("A","T","G","C","a","t","g","c","N","n",".","-"," ")
			map[,2] <- c("T","A","C","G","t","a","c","g","N","n",".","-"," ")
		}
		for(i in 1:xlen){
			x2[i] <- map[which(map[,1] %in% x1[i], arr.ind=F), 2]
		}
		return(x2)
	}
	ftu <- function(){
		map <- matrix(0,13,2)
		map[,1] <- c("A","T","G","C","a","t","g","c","N","n",".","-"," ")
		map[,2] <- c("A","U","G","C","a","u","g","c","N","n",".","-"," ")
		for(i in 1:xlen){
			x2[i] <- map[which(map[,1] %in% x1[i], arr.ind=F), 2]
		}
		return(x2)
	}
	fut <- function(){
		map <- matrix(0,13,2)
		map[,1] <- c("A","U","G","C","a","u","g","c","N","n",".","-"," ")
		map[,2] <- c("A","T","G","C","a","t","g","c","N","n",".","-"," ")
		for(i in 1:xlen){
			a <- map[which(map[,1] %in% x1[i], arr.ind=F), 2]
			x2[i] <- a
		}
		return(x2)
	}
	
	if(is.null(p)){ stop("parameter p NULL") }
	xlen <- nchar(x)
	if(ver){ cat("\nbases",xlen) }
	x1 <- unlist(strsplit(x, split = ""))
	x1len <- length(x1)
	if(xlen!=x1len){ stop("problem with the string") }
	x2 <- vector("character",xlen)
	u1 <- "U" %in% x1 | "u" %in% x1
	t1 <- "T" %in% x1 | "t" %in% x1
	if(u1&t1){ stop("Both, U and T are in the sequence") }
	plen <- length(p)
	if(ver){ cat("\n>",x1) }
	for(i in 1:plen){
		tmp <- p[i]
		if(tmp=="r"){
			x1 <- fr()
		}else if(tmp=="c"){
			x1 <- fc(u1)
		}else if(tmp=="tu"){
			x1 <- ftu()
			u1 <- T
		}else if(tmp=="ut"){
			x1 <- fut()
			u1 <- F
		}else{ stop("strange input") }
	}
	if(ver){ cat("\n>",x1,"\n") }
	return( paste(x1, sep="", collapse="") )
}


#rev.complement(x="AATTCGC.ccnA CT-CT", p="r", ver=T)
#rev.complement(x="AATTCGC.ccnA CT-CT", p="c", ver=T)
#rev.complement(x="AATTCGC.ccnA CT-CT", p=c("r","c"), ver=T)
#rev.complement(x="AATUCGC.CCNA CT-CT", p=c("r","c"), ver=T)
#rev.complement(x="AAUUCGC.CCNA CU-CU", p=c("ut","r","c"), ver=T)




