import os
import re
import sys
import shutil
import argparse
import subprocess

default_out_config = 'sorted.circos.conf'
default_out_config_path = os.path.join('<input_folder>', 'circos', default_out_config)
parser = argparse.ArgumentParser(description='A script for sorting sequences in Sibelia output.',
				formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-o', '--out_config', help='File name where sorted config is stored', 
			default=default_out_config_path)
parser.add_argument('input_folder', help='Path to folder with files generated by Sibelia/C-Sibelia')
parser.add_argument('orderchr_path', help='Path to orderchr script, including the script itself')

args = parser.parse_args()

folder = args.input_folder
circos_folder = os.path.join(folder, 'circos')
orderchr = args.orderchr_path
out_config = os.path.join(circos_folder, default_out_config) if args.out_config == default_out_config_path else args.out_config

args = ['perl', orderchr, '-links', os.path.join(circos_folder, 'circos.segdup.txt'),
	'-karyotype', os.path.join(circos_folder, 'circos.sequences.txt')]
order = ''
try:
	re_order = re.compile('chromosomes_order')
	stdout, _ = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=sys.stderr).communicate()
	order = (line for line in stdout.split('\n') if re_order.findall(line)).next()
except:
	pass

config = os.path.join(circos_folder, 'circos.conf')
shutil.copy(config, out_config)
config_handle = open(out_config, 'a')
print >> config_handle, order
config_handle.close()


