##################################
#                                #
# Last modified 2018/04/07       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string
import os

def run():

    if len(sys.argv) < 4:
        print 'usage: python %s bed chrFieldID leftFieldID rightFieldID ' % sys.argv[0]
        print '\tNote: the script can read .bz2, .gz, and .zip files'
        print '\tNote: the script will print to stodut by default'
        sys.exit(1)

    regions = sys.argv[1]
    chrFieldID = int(sys.argv[2])
    leftFieldID = int(sys.argv[3])
    rightFieldID = int(sys.argv[4])

    if regions.endswith('.bz2'):
        cmd = 'bzip2 -cd ' + regions
    elif regions.endswith('.gz'):
        cmd = 'gunzip -c ' + regions
    elif regions.endswith('.zip'):
        cmd = 'unzip -p ' + regions
    else:
        cmd = 'cat ' + regions
    p = os.popen(cmd, "r")
    line = 'line'
    while line != '':
        line = p.readline().strip()
        fields = line.split('\t')
        if line == '':
            break
        if line.startswith('#'):
            continue
        fields = line.strip().split('\t')
        chr = fields[chrFieldID]
        left = fields[leftFieldID]
        right = fields[rightFieldID]
        print chr + ':' + left + '-' + right
            
run()
