##################################
#                                #
# Last modified 02/07/2009       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

try:
    import psyco
    psyco.full()
except:
    pass

from commoncode import *
import sys

if len(sys.argv) < 2:
    print 'usage: python %s rdsfile outputfile [-withmulti] [-cache pages]' % sys.argv[0]
    sys.exit(1)

rdsfile = sys.argv[1]
outfilename = sys.argv[2]

withUniqs = True
withMulti = False
withFlag = ''
if '-withmulti' in sys.argv:
    withMulti = True
useFlagLike = False
if '-flagLike' in sys.argv:
    useFlagLike = True


doSplices = False

doCache = False
cachePages = 100000
if '-cache' in sys.argv:
    doCache = True
    cachePages =  int(sys.argv[sys.argv.index('-cache') + 1])

print '\nsample:' 
RDS = readDataset(rdsfile, verbose = True, cache=doCache)

#check that this is better than the dataset's default cache size
if cachePages > RDS.getDefaultCacheSize():
    RDS.setDBcache(cachePages)

readlen = RDS.getReadSize()

if withUniqs:
    chromList = RDS.getChromosomes()
elif withMulti:
    chromList = RDS.getChromosomes(table = 'multi')
chromList.sort()

outfile = open(outfilename, 'w')

def singleReadWrite(chrom, pos, sense, weight, readID):
    start = pos
    if sense == '+':
        outfile.write('%s\t%d\t%s\n' % (chrom, start))
    if sense == '-':
        outfile.write('%s\t%d\t%s\n' % (chrom, start))
    
for achrom in chromList:
    index = 0
    if achrom == 'chrM':
        continue
    print 'chromosome %s' % (achrom)
    # first handle uniqs and multireads
    hitDict = RDS.getReadsDict(fullChrom=True, chrom=achrom, flag=withFlag, withWeight=True, withID=True, doUniqs=withUniqs, doMulti=withMulti, readIDDict=False)
    for (pos, sense, weight, readID) in hitDict[achrom]:
        if sense == '+':
            shiftedpos=pos+shift 
        if sense == '-':
            shiftedpos=pos-shift 
        singleReadWrite(achrom, shiftedpos, sense, weight, readID)
        index += 1
    print index

outfile.close()


    