#!/usr/bin/python
#
# Shawn Driscoll
# 20160926
#
# rnaseqc-from-table.py
#
#
# Run RNA-SeQC on BAM alignments indexed in the samples_qc.tsv file
#

#==============================================================================
# imports
#==============================================================================

import sys, argparse, os, re
from os.path import isfile, expanduser

#==============================================================================
# globals
#==============================================================================

HOME = expanduser("~")
RNASEQC_PATH = "{}/opt/rnaseqc".format(HOME)
RNASEQC_JAR = "RNA-SeQC_v1.1.8.jar"
BWA_PATH = HOME + "/opt/bwa-0.6.2/bwa"
BWA_RRNA_INDEX = HOME + "/alind/ucsc/mm10_rRna/bwa/mm10_rRna.fa"
GTF_ANNOT = HOME + "/genomes/ucsc/mm10/mm10_merged.gtf"
#GC_REF = HOME + "/alind/ucsc/mm10_t/mm10_t.gc.tsv"
GENOME_REF = HOME + "/alind/ucsc/mm10/mm10.fa"

#==============================================================================
# main
#==============================================================================

def main():

	#
	# build command and run it
	#

	cmd = get_rnaseqc_cmd(args.outpath, args.tsv, args.single_end)
	rres = runcmd(cmd)
		
	return 0


#==============================================================================
# defs
#==============================================================================

#
# run a system level command.
def runcmd(cmd):
	sys.stderr.write("CMD: {}\n".format(cmd))
	rres = os.system(cmd)
	return rres

#
# return string for the complete rna-seqc command
def get_rnaseqc_cmd(outpath, sample_file, se):
	#
	# build command
	cmd = "java -jar " + RNASEQC_PATH + "/" + RNASEQC_JAR
	dparts = {}
	dparts["-o"] = outpath
	dparts["-r"] = GENOME_REF
	dparts["-s"] = sample_file
	dparts["-bwa"] = BWA_PATH
	dparts["-BWArRNA"] = BWA_RRNA_INDEX
	dparts["-t"] = GTF_ANNOT
#	dparts["-gc"] = GC_REF
#	dparts["-strat"] = "gc"
	dparts["-rRNAdSampleTarget"] = "1000000"
	if se:
		dparts['-singleEnd'] = ""

	for opt in dparts.keys():
		cmd = cmd + " " + opt + " " + dparts[opt]

	return cmd

#==============================================================================
# entry point
#==============================================================================


parser = argparse.ArgumentParser(description="Run RNA-SeQC on aligned bam files from align-fastq-table.py.")
parser.add_argument('tsv', type=str, help="Tab-delim table, with header, generated by align-fastq-table.py")
parser.add_argument('outpath', type=str, 
	help="Name for output folder")
parser.add_argument('--single-end', action="store_const", const=True, default=False, 
	help="Alignments are single-end [False]")

args = parser.parse_args()

if __name__ == "__main__":

	try:
		#sys.exit(main(args))
		sys.exit(main())
	except KeyboardInterrupt:
		sys.stderr.write("\n\nUser killed execution...\n\n")
