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



#### function to create an artifical fasta/fastq test file for star / salmon algorithms
#    out of a fasta of given target sequences which should be part of the pseudo read file
#    reads length might be variable

# 1 million is working: 14 min fasta - 18 min fastq  --> fasta 10 million  >5h stopped
# alternative: create several 1 million parts and join afterwards by bash-cat


arti.fastq <- function(fin, fout="", faq="fastq", rnum=0, stat=F){
	# generate artificial 'read' fasta or fastq file based on the input fasta
	# e.g. test file for star / salmon procedure
	# fin: fasta file with template sequences part of a reference file
	# faq: "fastq","fasta", fastq: Phred+33 Illumina: 83-95%: 'F', 1-10%:',', 0.1-2%: ':'
	# rnum: read number to generate
	# stat: T: only a stat output is given back
	
	# quality Phred+33 , 101*8
	qual <- c("FFFFFFFFFFFFFFFFFFFFFFFFF:FF:F:FFFFFFFFFFFFFFFFFF:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,FFFF
	F,FFFF:FFF,FFF:FFFFFFFFFFFFFFF:FFF,FFFFF:FFFFF,FFFFFF,FFFFFFF:FFFFF:FFF,F:FF,F:FFFFFFFFFFFFF:FF,FF:FF
	:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
	FFFFFFFFFFFFFFFFFFFFFFFFFFF:FFFFFFFFFFFFFFFF:FFFFFFFFFFFFFFFFFF:FFFFFFFFFFFFFFFFFF,FFFFFFFFFFFFFFF:FF
	FFFFFFFF:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,F,,F::F,,,:,,,,::,F,::F,:,FF,:,FF::F,:,FF,,F,F,,,F,,,FF,F,,FF
	FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
	FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:,FFFFFFFFFFFFF::FFF,F:F,,,,::FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
	FFFFFFFFFFF:FFFFFFFFFFFFFFFFFFFFFFFFFFFF:FFF:F:FFFFFFFFFFFF,FFFFF:FFFFFFFFFFFFFF::FF:FFF:FFF,F:FF,,:F")
	
	con0 <- file(fin, "r")
	ft <- readLines(con=con0)
	close(con0)
	nr <- length(ft)
	# how many entries in fasta
	n <- 0
	for(i in 1:nr){
		if(grepl(pattern=">", x=ft[i], perl=F, fixed=F)){
			n <- n+1
		}
	}
	# seq list
	idxl <- vector("character",n)
	seql <- vector("character",n)
	sli <- T
	out <- NULL
	keep <- F
	i <- 1
	j <- 1
	k <- 1
	while(sli){
		tmp1 <- grepl(pattern=">", x=ft[i], perl=F, fixed=F)
		if(tmp1){
			if(keep){
				seql[j] <- out
				out <- NULL
				j <- j+1
				keep <- F
			}
			idxl[k] <- ft[i]	# not used at the moment
			k <- k+1
			i <- i+1
		}else{
			out <- paste(out, ft[i],sep="")
			#cat("\n",out)
			keep <- T
			i <- i+1
		}
		if(i==(nr+1)){
			#cat("\n nr",nr," n",n," i",i," j",j," k",k)	# nr 6616  n 3092  i 6617  j 3092  k 3093
			seql[j] <- out
			sli <- F
		}
	}
	if(!stat){		# read file or stat
		if(file.exists(fout)){
			file.remove(fout)
			cat("\nOut file deleted")
			file.create(fout)
		}else{
			file.create(fout)
		}
		rli <- as.integer(1:n)
		k <- 1
		if(faq=="fasta"){
			rnum2 <- rnum*2
			dat <- vector("character",rnum2)
			for(i in 1:rnum){
				stmp <- sample(rli, size=1, replace=F)
				dat[k] <- paste("@E",i,sep="")
				k <- k+1
				dat[k] <- seql[stmp]
				k <- k+1
			}
		}else if(faq=="fastq"){
			rnum2 <- rnum*4
			dat <- vector("character",rnum2)
			for(i in 1:rnum){
				stmp <- sample(rli, size=1, replace=F)
				dat[k] <- paste("@E",i,sep="")
				k <- k+1
				tmp <- seql[stmp]
				dat[k] <- tmp
				k <- k+1
				dat[k] <- "+"
				k <- k+1
				tmp2 <- nchar(tmp)
				tmp3 <- substr(qual,1,tmp2)
				dat[k] <- tmp3
				k <- k+1
			}
		}
		# write out
		con1 <- file(fout, "w")
		for(i in 1:rnum2){
			writeLines(text=dat[i], con=con1, sep="\n")
		}
		close(con1)
		return()
	}else{		# only some statistics
		rli <- as.integer(1:n)
		rnum2 <- rnum*2
		dat <- vector("integer",rnum)
		for(i in 1:rnum){
			stmp <- sample(rli, size=1, replace=F)	# select index
			dat[i] <- stmp
		}
		return(list(index=c(1,n),dist.idx=dat))
	}
}

#arti.fastq(fin="/home/korschi/1/m2_miRtRNA.fasta", fout="/home/korschi/1/test_read.fasta", faq="fasta", rnum=1000)
#arti.fastq(fin="/home/korschi/1/m2_miRtRNA.fasta", fout="/home/korschi/1/test_read.fastq", faq="fastq", rnum=1000)

#a3 <- arti.fastq(fin="/home/korschi/1/m2_miRtRNA.fasta", rnum=1000, stat=T)





#### create an useful genomic fasta file
#    with collected fasta sequences
#    obviously a corresponding gtf file needs to be created too (integrated in the function)

# note: tRNAs: different names, identical sequences, different locations
#       we restrict to the unique sequences, and search with blastn for location on chr--


## better alternative for creating an  aligner file  and an  aligner index  file:
#
#   do not create a genome fasta like file (with the function below)
#
#   instead align to the miR mature fasta file (or miR+tRNA fasta file)
#   (and create a index file from that)
#   and then sort and index the bam with samtools
#   and count finally with 'samtools idxstats'
#
# 1) /on1/genome2_2711/g.trans.hu.miRtRNA.fa
# 2) STAR --runMode genomeGenerate --runThreadN 6 --genomeDir /on1/star2711joint_mt --genomeFastaFiles /on1/genome3_2711/m2_miRtRNA.fasta --limitGenomeGenerateRAM 163917594890 --genomeSAindexNbases 7
# 3) 

#   see 'miRNA-seq featureCounts problem.odt' [not found]



genome.test.structure <- function(fin, fout, gtfin, gtfout, line.width=60, sep="S", idline="", midresult=F){
	# create an useful genomic structure fasta file
	# fin: fasta file with template sequences part of a reference file
	#   with entry '>1 ' in the beginning for splitting on different chromosomes
	# fout: genome like fasta file
	# gtfin,gtfout: ens gtf file (fitting to fin) which will be adjusted to the artificial genome file
	# midresult: T: only create a one liner structure of fin and return it
	# line.width: normally 60 in the Ensembl genome fasta
	# sep: N: only 'N's as target sequence separator, S: sample separator length from 'ATGC'
	#   normal separator lines are completely filled lines
	#    plus at the end of target sequences fill up to the end of the line
	# idline: vector of (one[standard] or more) 'chromosome' id strings
	#   >2 dna:chromosome chromosome:GRCh38:2:1:242193529:1 REF
	#    id(chr)
	#      seqtype
	#                     location(type,source,chr start,end,strand)
	#                                                       comment
	
	fw <- line.width
	nbl <- 3	# separator block row number
	if(sep=="N"){
		nbr <- paste(rep("N",fw),collapse="")	# N line - no base known
	}else if(sep=="S"){
		nbr <- paste(sample(c("A","T","G","C"),size=fw,replace=T),collapse="")	# S line
	}
	#
	con0 <- file(fin, "r")
	ft <- readLines(con=con0)
	close(con0)
	nr <- length(ft)
	# how many entries in fasta
	n <- 0
	for(i in 1:nr){
		if(grepl(pattern=">", x=ft[i], perl=F, fixed=F)){
			n <- n+1
		}
	}
	newdat <- matrix("",n,4)	# overview positions
	dimnames(newdat)[[2]] <- c("chr","start","end","gene_name")
	# entries in idline
	idlen <- length(idline)
	# seq list
	idxl <- vector("character",n)
	seql <- vector("character",n)
	sli <- T
	out <- NULL
	keep <- F
	i <- 1
	j <- 1
	k <- 1
	jr <- 0		# calc number of rows, of seq given
	while(sli){
		tmp1 <- grepl(pattern=">", x=ft[i], perl=F, fixed=F)
		if(tmp1){
			if(keep){
				jr <- jr + ceiling(nchar(out)/fw)
				seql[j] <- out
				out <- NULL
				j <- j+1
				keep <- F
			}
			idxl[k] <- ft[i]
			k <- k+1
			i <- i+1
		}else{
			out <- paste(out, ft[i],sep="")
			keep <- T
			i <- i+1
		}
		if(i==(nr+1)){
			jr <- jr + ceiling(nchar(out)/fw)
			seql[j] <- out
			sli <- F
		}
	}
	if(midresult){
		mr <- cbind(idxl,seql)		# inner sep "\t" rest " "
		write.table(mr,paste(fin,".txt",sep=""),append=F,quote=F,sep=" ",row.names=F,col.names=F)	# all sep " "
		return(mr)
	}
	# split by start id
	#result <- regmatches(c(">Y2 b9 mn Y2 vv "), regexec(pattern="(?<=>)[XY0-9]{1,2}(?= )", text=c(">Y2 b9 mn Y2 vv "), perl=T))
	idxl1 <- regmatches(idxl, regexpr("(?<=>)[XY0-9]{1,2}(?= )",text=idxl, perl=T))
	# generate artificial 'read' fasta or fastq file based on the input fasta
	if(file.exists(fout)){
		file.remove(fout)
		cat("\nOut file deleted")
		file.create(fout)
	}else{
		file.create(fout)
	}
	# embed seq fragment in N blocks before and after
	# fill partly filled lines up with N
	# anum: final number of lines
	anum <- idlen + (nbl*n*2) + jr		# n entities, jr seq lines full or less filled, nbl: N block lines
	dat <- vector("character",anum)
	k <- 1	# new line counter
	ux <- unique(idxl1)		# one or more chr
	uxl <- length(ux)
	chrstartp <- vector("integer",uxl)
	chrendp <- vector("integer",uxl)
	if(uxl!=idlen){ stop(paste("idline vector length [",idlen,"] should be equal to input fasta first description id type number: '>X text' [",uxl,"]")) }
	cpos <- 0	# counter position for local/global start end
	for(i in 1:idlen){		# chr
		chrstartp[i] <- cpos+1
		dat[k] <- idline[i]
		k <- k+1
		ui <- which(idxl1 %in% ux[i])
		for(l1 in ui){			# fasta entries per chr
			newdat[l1, "chr"] <- idxl1[l1]
			newdat[l1, "gene_name"] <- unlist( strsplit(idxl[l1], split=" ", fixed=T ) )[2]
			for(l2 in 1:nbl){	# N lines
				dat[k] <- nbr
				k <- k+1
			}
			cpos <- cpos+(nbl*fw)		# present end - start seq
			newdat[l1, "start"] <- cpos+1
			
			stmp <- seql[l1]	# get seq
			inl <- nchar(stmp)
			full <- floor(inl/fw)
			rem <- inl%%fw
			if(full>0 & rem==0){
				for(l2 in 1:full){
					dat[k] <- substr(stmp, ((l2-1)*fw+1), (l2*fw) )
					k <- k+1
					cpos <- cpos+fw
				}
				newdat[l1, "end"] <- cpos	# start next
			}
			if(full>0 & rem>0){
				for(l2 in 1:full){
					dat[k] <- substr(stmp, ((l2-1)*fw+1), (l2*fw) )
					k <- k+1
					cpos <- cpos+fw
				}
				l2 <- l2+1
				dat[k] <- paste( substr(stmp, ((l2-1)*fw+1), ((l2-1)*fw+rem) ), substr(nbr, 1, (fw-rem) ), sep="")	# seq + fill
				k <- k+1
				cpos <- cpos+rem
				newdat[l1, "end"] <- cpos
				cpos <- cpos+(fw-rem)		# start next
			}
			if(full==0 & rem>0){
				dat[k] <- paste( substr(stmp, 1, rem), substr(nbr, 1, (fw-rem) ), sep="")		# seq + fill
				k <- k+1
				cpos <- cpos+rem
				newdat[l1, "end"] <- cpos
				cpos <- cpos+(fw-rem)		# start next
			}
			if(full==0 & rem==0){
				stop("empty seq elements in input fasta")
			}
			for(l2 in 1:nbl){	# last N line block
				dat[k] <- nbr
				k <- k+1
				cpos <- cpos+fw		# start next
			}
		}
		chrendp[i] <- cpos
	}
	# write custom genome
	con1 <- file(fout, "w")
	for(i in 1:anum){
		writeLines(text=dat[i], con=con1, sep="\n")
	}
	close(con1)
	cat("\n nbr ",nbr)
	cat("\n calc lines, real lines ",anum,"/",(k-1))
	cat("\n custom g fasta start  1  end ",cpos)
	# adjust gtf
	gtfout <- adjust.gtf.ens(fin=gtfin, fout=gtfout, dfin=newdat, v=F)
	return(newdat)
}


#a <- genome.test.structure(fin="/home/korschi/1/gi_miRtRNA.fasta",
#		fout="/home/korschi/1/g_miRtRNA.fasta",
#		gtfin="/home/korschi/1/mt.Homo_sapiens.miRtRNA.gtf",
#		gtfout="/home/korschi/1/g_miRtRNA.gtf",
#		idline=">1 dna:chromosome chromosome:EKOR1:1:1:end:1 REF",
#		line.width=60, sep="S")
#
# Out file deleted
# nbr  TCGTAGTCTAGCTTAGCCGTGGGGATGTATTTGTTTTGGTAGCCGTGGTCATATCACTAG
# calc lines, real lines  20701 / 20701
# custom g fasta start  1  end  1242000
# gtf gene_names:  one hit (in dfin) 2913 , more hits (check) 0 , zero hits (check) 0 / 2913 




## adjust the above used gtf file so that it fits to the custom genome
##  and save the new version by a different file name

adjust.gtf.ens <- function(fin, fout, dfin, v=F){
	# custom genome specific - adjust : chr, physical position, start, end
	#  of an ensemble based gtf file
	# fin, fout : gtf path/file
	# dfin: provide a 'newdat' table returned by genome.test.structure()
	# v: verbose: T,F
	gtf.ens <- read.table(fin, header=F, sep="\t", quote="'" )		# start end always increasing,  quote ok
	gtf.ens.l <- nrow(gtf.ens)
	dfin.l <- nrow(dfin)
	# start with gtf.ens
	coll <- NULL	# collect actions
	s1 <- 0		# one hit
	sm <- 0		# more hits
	s0 <- 0		# problems
	gel <- seq(1, gtf.ens.l, 3)		# check 3
	for(i in gel){
		# get chr,name,present positions
		g.chr <- gtf.ens[i,1]					# char
		g.pos <- unlist(gtf.ens[i,4:5])			# int
		g.n <- sub(pattern=" gene_name ","", x=unlist( strsplit(gtf.ens[i,9], split=";", fixed=T ) )[2], fixed=T)		# gtf.ens[,9] content has ""
		g.n <- gsub(pattern='[\"]','', x=g.n, perl=T)
		mat <- dfin[dfin[,4] %in% g.n, , drop=F]		# filter by name-id -- no duplicates assumed
		if(v){ cat("\n i",i," g.n",g.n," g.pos",g.pos," g.chr",g.chr,"\n"); print(mat) }
		nr <- nrow(mat)
		dimnames(mat) <- NULL
		if(nr>0){	# hit
			for(j in 1:nr){
				vec <- as.vector(mat[j,])
				gtf.ens[i, 1] <- vec[1]	# chr
				gtf.ens[(i+1), 1] <- vec[1]
				gtf.ens[(i+2), 1] <- vec[1]
				gtf.ens[i, 4:5] <- vec[2:3]	# pos
				gtf.ens[(i+1), 4:5] <- vec[2:3]
				gtf.ens[(i+2), 4:5] <- vec[2:3]
			}
			if(nr==1){
				coll <- rbind(coll, c(g.n,g.chr,g.pos,"one"))
				s1 <- s1+1
			}else{
				coll <- rbind(coll, c(g.n,g.chr,g.pos,"more"))
				sm <- sm+1
			}
		}else{	# problems (no action)
			coll <- rbind(coll, c(g.n,g.chr,g.pos,"zero"))
			s0 <- s0+1
		}
	}
	if(!is.null(coll)){ dimnames(coll)[[2]] <- c("g.n","chr_g","start_g","end_g","hits") }
	write.table(gtf.ens, paste(fout,".gtf",sep=""), append=F, quote=F, sep="\t", row.names=F, col.names=F)
	write.table(coll, paste(fout,".log",sep=""), append=F, quote=F, sep="\t", row.names=F, col.names=T)
	cat("\n gtf gene_names:  one hit (in dfin)",s1,", more hits (check)",sm,", zero hits (check)",s0,"/",length(gel),"\n")
	return()
}

#adjust.gtf.ens(fin="/home/korschi/1/mit.test.gtf", fout="/home/korschi/1/mit.test.gtf.gtf", dfin=a, v=T)

#case Homo homo




one.liner.2.fasta <- function(x, fout){
	# after unification of tRNA seq entries (all in one line),
	#  create again a fasta file with a double line structure
	xlen <- nrow(x)
	fa <- vector("character",(xlen*2))
	j <- 1
	for(i in 1:xlen){
		fa[j] <- x[i, 1]
		j <- j+1
		fa[j] <- x[i, 2]
		j <- j+1
	}
	write.table(fa, fout, append=F, quote=F, sep="\t", row.names=F, col.names=F)
	return()
}





## from a fasta file create an artificial gtf file assuming that every fasta entry is a single chromosome
##  and save the new version by a different file name
#   needed for the fasta index creation with STAR

# fasta structure:
#
# >hsa-CDH1-i2-miR3
# CGACATTGAGAGGCCTCTCCTG
# >hsa-let-7a-3p MIMAT0004481 Homo sapiens let-7a-3p
# CTATACAATCTACTGTCTTTC
# ...

# gtf structure (result):
#
# fields TAB
# a b		c		d	e	f	g	h	i
# 1	mirbase	gene	1	24	.	-	.	gene_id "ENSG00000000001"; gene_name "hsa-CDH1-i2-miR3"; gene_source "mirbase"; gene_biotype "miRNA";
# 1	mirbase	transcript	1	24	.	-	.	gene_id "ENSG00000000001"; transcript_id "ENST00000000001"; gene_name "hsa-miR-6859-5p"; gene_source "mirbase"; gene_biotype "miRNA";
# 1	mirbase	exon	1	24	.	-	.	gene_id "ENSG00000298000"; transcript_id "ENST00000720000"; exon_number "1"; gene_name "hsa-miR-6859-5p"; gene_source "mirbase"; gene_biotype "miRNA";
# 2	mirbase	gene	1	23	.	+	.	gene_id "ENSG00000299474"; gene_name "hsa-miR-5696"; gene_source "mirbase"; gene_biotype "miRNA";
# 2	mirbase	transcript	1	23	.	+	.	gene_id "ENSG00000299474"; transcript_id "ENST00000721474"; gene_name "hsa-miR-5696"; gene_source "mirbase"; gene_biotype "miRNA";
# 2	mirbase	exon	1	23	.	+	.	gene_id "ENSG00000299474"; transcript_id "ENST00000721474"; exon_number "1"; gene_name "hsa-miR-5696"; gene_source "mirbase"; gene_biotype "miRNA";

# first chr number +1 for every entry



fasta2gtf <- function(fin, fout, fmap, ens.start=1, mt=1){
	# Per fasta entry create a custom gtf entry
	# fin : fasta file where every entry is assumed to be a chr
	# fout : gtf path/file
	# fmap : path/file of the mapping file ENST ENSG HGNC
	# ens.start : where should the numbering for enst/ensg/chr start?
	# mt : 1 : miR, 2 : tRNA

	fasta <- unlist( read.table(fin, header=F, sep="\t") )	# vec of strings
	fasta.l <- length(fasta)
	fasta.desc <- regmatches(fasta, gregexpr(pattern="(?<=^>).*?(?=\\s|$)", text=fasta, perl=T))	# list
	
	# define
	mta <- switch(mt,
			'"mirbase"',
			'"GtRNAdb"'
	)
	mtb <- switch(mt,
			'"; gene_source "mirbase"; gene_biotype "miRNA";',
			'"; gene_source "GtRNAdb"; gene_biotype "tRNA";'
	)
	
	str1a <- 'gene_id "'
	# ENSG00000000001
	str1b <- '"; gene_name "'
	# hsa-miR-6859-5p
	str1c <- mtb
	
	str2a <- 'gene_id "'
	# ENSG00000000001
	str2b <- '"; transcript_id "'
	# ENST00000000001
	str2c <- '"; gene_name "'
	# hsa-miR-6859-5p
	str2d <- mtb
	
	str3a <- 'gene_id "'
	# ENSG00000000001
	str3b <- '"; transcript_id "'
	# ENST00000000001
	str3c <- '"; exon_number "1"; gene_name "'
	# hsa-miR-6859-5p
	str3d <- mtb
	
	df <- data.frame(matrix("",fasta.l,3))
	names(df) <- c("ensembl_transcript_id", "ensembl_gene_id", "hgnc_symbol")
	chr.c <- ens.start
	rec.c <- 1
	len.seq <- 0
	
	out <- NULL
	for(i in 1:fasta.l){
		if(!identical(fasta.desc[[i]], character(0))){
			tmp2 <- fasta.desc[[i]]
		}else{
			len.seq <- len.seq + nchar(fasta[i])
			cat("\na_e_len.seq",len.seq)
		}
		if(i==fasta.l){
			cat("\nf_len.seq",len.seq)
			tmp01 <- paste(chr.c, "\t", mta, "\t", "gene",       "\t", "1", "\t", len.seq, "\t.\t.\t.\t", sep="")
			tmp02 <- paste(chr.c, "\t", mta, "\t", "transcript", "\t", "1", "\t", len.seq, "\t.\t.\t.\t", sep="")
			tmp03 <- paste(chr.c, "\t", mta, "\t", "exon",       "\t", "1", "\t", len.seq, "\t.\t.\t.\t", sep="")
			
			tmp1 <- ensg.enst.n(x=chr.c, form=1)
			tmp <- paste(tmp01, str1a, tmp1, str1b, tmp2, str1c, sep="")
			out <- rbind(out, tmp)
			
			tmp1 <- ensg.enst.n(x=chr.c, form=1)
			tmp3 <- ensg.enst.n(x=chr.c, form=2)
			tmp <- paste(tmp02, str2a, tmp1, str2b, tmp3, str2c, tmp2, str2d, sep="")
			out <- rbind(out, tmp)
			
			tmp <- paste(tmp03, str3a, tmp1, str3b, tmp3, str3c, tmp2, str3d, sep="")
			out <- rbind(out, tmp)
			
			df[rec.c, ] <- c(tmp3, tmp1, tmp2)
			rec.c <- rec.c + 1
			chr.c <- chr.c + 1
			len.seq <- 0
		}else{
			if(!identical(fasta.desc[[i+1]], character(0))){
				cat("\nf_len.seq",len.seq)
				tmp01 <- paste(chr.c, "\t", mta, "\t", "gene",       "\t", "1", "\t", len.seq, "\t.\t.\t.\t", sep="")
				tmp02 <- paste(chr.c, "\t", mta, "\t", "transcript", "\t", "1", "\t", len.seq, "\t.\t.\t.\t", sep="")
				tmp03 <- paste(chr.c, "\t", mta, "\t", "exon",       "\t", "1", "\t", len.seq, "\t.\t.\t.\t", sep="")
				
				tmp1 <- ensg.enst.n(x=chr.c, form=1)
				tmp <- paste(tmp01, str1a, tmp1, str1b, tmp2, str1c, sep="")
				out <- rbind(out, tmp)
				
				tmp1 <- ensg.enst.n(x=chr.c, form=1)
				tmp3 <- ensg.enst.n(x=chr.c, form=2)
				tmp <- paste(tmp02, str2a, tmp1, str2b, tmp3, str2c, tmp2, str2d, sep="")
				out <- rbind(out, tmp)
				
				tmp <- paste(tmp03, str3a, tmp1, str3b, tmp3, str3c, tmp2, str3d, sep="")
				out <- rbind(out, tmp)
				
				df[rec.c, ] <- c(tmp3, tmp1, tmp2)
				rec.c <- rec.c + 1
				chr.c <- chr.c + 1
				len.seq <- 0
			}
		}
	}
	write.table(out, fout, append=F, quote=F, sep="", row.names=F, col.names=F)
	rec.c <- rec.c - 1		# -1 because counter too far
	cat("\n chr / entries : ",rec.c,"\n")
	df <- df[1:rec.c,]		# remove row overhead
	write.table(df, fmap, append=F, quote=F, sep="\t", row.names=F, col.names=T)
	return(df)
}

#a <- fasta2gtf(fin="a.fasta", fout="b.gtf", fmap="mapTable2.mir.trna", ens.start=11, mt=2)



#fasta2gtf.sub <- function(mt, tmp2){
#	# fasta2gtf sub-function, stitch together a text line
#	
#	return()
#}




ensg.enst.n <- function(x, form=1){
	# ENSG ENST conforming number, prefix + 11 digits at the moment
	# x: provide a number,  form: prefix
	# return a full label
	ens <- c("ENSG","ENST")
	xc <- as.character(x)
	xl <- nchar(xc)
	lz <- 11 - xl
	out <- paste(ens[form], paste(rep("0",lz), collapse=""), xc, sep="")
	return(out)
}

#ensg.enst.n(x=1, form=1)			# "ENSG00000000001"
#ensg.enst.n(x=2577, form=2)		# "ENST00000002577"




fastaWchr <- function(fin, fout, ens.start=1){
	# Per fasta entry add a number+space after '>' (chr number)
	# fin : fasta path/file
	# fout : fasta path/file
	# ens.start : where should the numbering start?
	
	fasta <- unlist( read.table(fin, header=F, sep="\t") )	# vec of strings
	fasta.l <- length(fasta)
	chr.c <- ens.start
	for(i in 1:fasta.l){
		if(grepl(pattern="^>", x=fasta[i], perl=T)){
			fasta[i] <- sub(pattern="^>", replacement=paste(">",chr.c," ",sep=""), x=fasta[i], perl=T)
			chr.c <- chr.c + 1
		}
	}
	write.table(fasta, fout, append=F, quote=F, sep="", row.names=F, col.names=F)
	chr.c <- chr.c - 1		# -1 because counter too far
	cat("\n chr / entries : ",chr.c,"\n")
	return()
}

# fastaWchr(fin="a.fasta", fout="c.fasta", ens.start=11)







