#!/usr/bin/env python
import os
import sys
import uuid
import numpy as np
import pandas as pd

#args
if(len(sys.argv)!=4):
	print("USAGE: python mtable2bedgraph.py [mtable_in_file] [hg19 or hg38] [outFile]")
	sys.exit()
in_file = sys.argv[1]
assembly = sys.argv[2]
outFile = sys.argv[3]
if assembly == 'hg19':
	chr_file = os.environ['HG19CHROMRANGES']
elif assembly == 'hg38':
	chr_file = os.environ['HG38CHROMRANGES']

#hash chrom sizes
chr_tbl = pd.read_csv(chr_file,sep='\t',header=None,names=['chr','start','end'])

#new temp bed file (unsorted)
fin = open(in_file,'r')
fin.readline() #discard header
hash_str = str(uuid.uuid4())
temp_file = hash_str + '.bed'
fout = open(temp_file,'w')
for line in fin:
	line_parts = [a.strip() for a in line.split('\t')]
	chrs = line_parts[0]
	start = int(line_parts[1])
	end = int(line_parts[2])
	if(start < chr_tbl.start[chr_tbl.chr==chrs] or end > chr_tbl.end[chr_tbl.chr==chrs]):
		continue
	val = float(line_parts[3])
	fout.write('\t'.join(line_parts[0:3]) + '\t' + str(val)+'\n')
fin.close()
fout.close()

#sort the bed file
os.system('sortBed2 '+temp_file+' > '+temp_file+'1.bed')

#create bedgraph file out of sorted bed
fin = open(temp_file+'1.bed','r')
fout = open(out_file,'w')
fout.write('track type=bedGraph name=\''+in_file+'\' description=\''+in_file+'\'\n')
for line in fin:
	fout.write(line.strip()+'\n')
fout.close()

#remove temp files
os.system('rm '+temp_file+' '+temp_file+'1.bed')