#!/usr/bin/python
#==============================================================================
# rnaseqc-table-from-bams.py
#
# Shawn Driscoll
# 20170510
#
# Gene Expression Laboratory, Pfaff
# Salk Institute for Biological Studies
#
# Build an rnaseqc table from bams. if the bams were generated by the 
# parse-run pipeline then all of the info parts will be included in the 
# table info.
#==============================================================================

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

# from igraph import *
# from subprocess import Popen
# from random import gauss, random, sample
# from scipy.stats import norm
# import numpy as np
# import numpy.random as npr

# R support
# import rpy2.robjects as robjects
# r = robjects.r

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

HOME = expanduser("~")

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

def main(args):

	# variables
	fparts = []
	sample_parts = []
	stub = ""
	tmp = None

	outlines = []
	sample_line = []

	for f in args.bamlist:
		# take the file name apart
		fparts = f.split("/")
		tmp = fparts[-1].split(".")

		stub = tmp[0]
		# check if this is a 'parse-run' file
		fparts = stub.split("_")
		if len(fparts)==7:

			sample_name = "|".join(fparts[0:3])
			file_name = f
			comment = "|".join(fparts[3:len(fparts)])
		else:
			sample_name = stub
			file_name = f
			comment = "None"

		outlines.append([sample_name, file_name, comment])


	print "Sample ID\tBam File\tNotes"
	for l in outlines:
		print "\t".join(l)

	

	return 0



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


parser = argparse.ArgumentParser(description="Use this to build a table of BAM files for the RNA-SeqC program. Then use 'ranseqc-from-table.py' to run the program on this table.")
parser.add_argument('bamlist', type=str, metavar='bamlist', nargs="+", help="BAM files to include in table.")

args = parser.parse_args()

if __name__ == "__main__":

	try:
		sys.exit(main(args))
	except KeyboardInterrupt:
		sys.stderr.write("\nkilled it\n")

