#! /usr/bin/env python

# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Footrpints Detector v1.0
# Copyright (c) 2008 by Xiaoyu Chen and William Noble
# All rights reserved.
# Redistribution is not permitted without the permission of the authors.
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

# This program reads:
# 1) DHS bed file
# 2) footprints file generated by rank_footprints.m

# It generates the bed file for the footprints.


import sys

DHSBedFile = sys.argv[1]
ftprtFile = sys.argv[2]

fpDHS = open(DHSBedFile, 'r')
DHSBed = []
for line in fpDHS:
    item = line.split()
    DHSBed.append({'CHR':item[0], 'START':int(item[1])}) 
fpDHS.close()

fpFtprt = open(ftprtFile, 'r')
sys.stdout.write('chr\tstart\tstop\tscore\tq-value\n')
for line in fpFtprt:
    item = line.split()
    DHSid = int(item[0])-1
    ftprtStart = int(item[1])
    ftprtStop = int(item[2])

    chr = DHSBed[DHSid]['CHR']
    start = ftprtStart + DHSBed[DHSid]['START'] -1
    # Bed format, stop+1
    stop = ftprtStop + DHSBed[DHSid]['START']
    sys.stdout.write(chr+'\t'+str(start)+'\t'+str(stop)+ \
                     '\t'+item[3]+'\t'+item[4]+'\n')
