#!/usr/bin/python
#Last-modified: 31 Jan 2013 11:01:07 AM

""" Module/Scripts Description

Copyright (c) 2008 Yunfei Wang <tszn1984@gmail.com>

This code is free software; you can redistribute it and/or modify it
under the terms of the BSD License (see the file COPYING included with
the distribution).

@status:  experimental
@version: 1.0.0
@author:  Yunfei Wang
@contact: tszn1984@gmail.com
"""

# ------------------------------------
# python modules
# ------------------------------------

import os,sys
import string
import argparse
from ngslib.wBed import Bed,Utils,IO
from random import randint

# ------------------------------------
# constants
# ------------------------------------

USERHOME=os.path.expanduser('~')

# ------------------------------------
# Misc functions
# ------------------------------------

def argParser():
    ''' Parse arguments. '''
    p=argparse.ArgumentParser(description="Generate random Bed regions from specified genome.")
    p._optionals.title = "Options"
    p.add_argument("-l","--length",dest='length',type=int,metavar="Length",required=True,help="Bed length.")
    p.add_argument("-n","--number",dest="number",type=int,metavar="Number",required=True,help="Number of Beds.")
    p.add_argument("-g","--genome",dest="genome",type=str,metavar="Genome",default=USERHOME+"/Data/hg19/hg19.sizes",help="Genome size file generated by faSize.")
    if len(sys.argv)==1:
        sys.exit(p.print_help())
    args = p.parse_args()
    return args

# ------------------------------------
# Classes
# ------------------------------------

# ------------------------------------
# Main
# ------------------------------------

if __name__=="__main__":
    # Get parameters
    args=argParser()
    #genome={}
    #for line in IO.ColumnReader(args.genome):
    #    genome[line[0]]=int(line[1])
    genome=Utils.genomeSize(args.genome)
    counts={}
    gsize=float(sum(genome.values()))
    # number of Beds in each chrom
    for chrom in genome:
        counts[chrom]=int(genome[chrom]/gsize*args.number+0.5)
    # check number
    diff=sum(counts.values())-args.number
    chroms=counts.keys()
    chroms.sort()
    if diff !=0:
        for i in diff>0 and range(diff) or range(diff,0):
            j=randint(1,len(counts))
            counts[chroms[j-1]]+= diff>0 and -1 or 1
    # generate Beds
    cnt=1
    for chrom in chroms:
        for i in xrange(counts[chrom]):
            pos=randint(0,genome[chrom]-args.length)
            print Bed([chrom,pos,pos+args.length,"bed_"+str(cnt)])
            cnt+=1


