#!/usr/bin/env python
import re, os, sys, shutil
from math import *   
from string import *
from optparse import OptionParser
import operator
import bisect


import BED
import UCSC
import GenomeData;

grep = "/bin/grep";
cat = "/bin/cat";

plus = re.compile("\+");
minus = re.compile("\-");
Dir = os.getcwd();

def fileExists(f):
	try:
		file = open(f)
	except IOError:
		exists = 0
	else:
		exists = 1
	return exists

def is_sorted(list):
        """
        Check if sorted in ascending order.
        input is a list of BED with chrom, start, end and value.
        output: sorted =1 or 0
        """
	sorted = 1;
	for index in range(0, len(list)-1):
		if list[index].start > list[index+1].start:
			sorted = 0;
	return sorted;
	
def rescale_a_column(input_file, c, rescale_factor, output_file):
	"""
	c is the 0-based column number 
	Return a list of names
	
	"""
	infile = open(input_file,'r')
	outfile = open(output_file, 'w')
	for line in infile:
		if not re.match("#", line):
			line = line.strip()
			sline = line.split()
			if (len(sline)>0):
				new_value = atof(sline[c]) * rescale_factor;
				sline[c] = str(new_value);
				outfile.write('\t'.join(sline)+'\n')
	infile.close()
	outfile.close()
	
def normalize_a_column(input_file, c, output_file):
	"""
	c is the 0-based column number 
	Return a list of names
	
	"""
	line_number = 0;
	infile = open(input_file,'r')
	outfile = open(output_file, 'w')
	for line in infile:
		if not re.match("#", line):
			line = line.strip()
			sline = line.split()
			if (len(sline)>0):
				if (line_number == 0): 
					rescale_factor = atof(sline[c])
				new_value = atof(sline[c]) / rescale_factor;
				sline[c] = str(new_value);
				outfile.write('\t'.join(sline)+'\n')
				line_number += 1;
	infile.close()
	outfile.close()

	