#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from optparse import OptionParser, OptionGroup
import sys
import os

__author__ = "Tobias Marschall"

usage = """%prog [options]

Reads deletion list from stdin and outputs regions of interest (ROIs) to be realigned by LASER. 
Regions might overlap. (Use bedtools sort/merge to cure that.)"""

def main():
	parser = OptionParser(usage=usage)
	parser.add_option("-d", action="store", dest="distance", default=750, type=int,
			help='Distance from deletion breakpoints to be included (default: 750).')
	parser.add_option("-m", action="store", dest="max_length", default=None, type=int,
			help='Maximum deletion length to be considered (default: none).')

	(options, args) = parser.parse_args()
	if (len(args) != 0) or os.isatty(0):
		parser.print_help()
		sys.exit(1)

	n = 0
	for line in (s.strip() for s in sys.stdin):
		n += 1
		fields = line.split()
		if len(fields) < 3:
			print('Invalid input on line', n, file=sys.stderr)
			return 1
		chromosome = fields[0]
		coord1 = int(fields[1])
		coord2 = int(fields[2]) + 1
		assert coord1 < coord2
		svlen = coord2 - coord1
		if (options.max_length != None) and (svlen > options.max_length):
			continue
		if svlen > 4*options.distance:
			center = (coord1 + coord2) // 2
			print(chromosome, max(0, coord1-options.distance), coord1+options.distance, sep='\t')
			print(chromosome, max(0, center-options.distance), center+options.distance, sep='\t')
			print(chromosome, max(0, coord2-options.distance), coord2+options.distance, sep='\t')
		else:
			print(chromosome, max(0, coord1-options.distance), coord2+options.distance, sep='\t')

if __name__ == '__main__':
	sys.exit(main())
