#!/usr/bin/env python

from __future__ import print_function
import sys
#import socket
#hostname = socket.gethostname()
#if hostname.startswith('bs-mbp115'):
#   print('I am on', hostname, file=sys.stderr)
#   #for v in sys.path: print(v)
#else:
#    sys.path.insert('/home/ozagordi/pysam-0.4.1/pysam')
#    print('I am on', hostname, file=sys.stderr)
import pysam
assert pysam.__version__ == '0.4.1'

def main():
    import sys
    import os.path
    import subprocess
    file_in = sys.argv[1]
    if not os.path.exists(file_in):
        sys.exit('file %s not found' % file_in)
    #ref_file = sys.argv[2]
    file_stem = os.path.split(file_in)[1].split('.')[0]
    samfile = pysam.Samfile(file_in, "r" )
    #SAM -> BAM if not there
    if not os.path.exists(file_stem+'.bam'):
        print('SAM -> BAM', file=sys.stderr)
        cml = 'samtools view -b -S -o %s %s' % (file_stem+'.bam', file_in)
        print(cml, file=sys.stderr)
        subprocess.call(cml, shell='/bin/bash')
    else:
        print('BAM file was there, using it', file=sys.stderr)
        
    #sort BAM file
    if not os.path.exists(file_stem+'_sorted.bam'):
        print('Sorting', file=sys.stderr)
        pysam.sort(file_stem+'.bam', file_stem+'_sorted')
    else:
        print('BAM file already sorted, using it', file=sys.stderr)
        
    #index the sorted bam in any case    
    pysam.index(file_stem+'_sorted.bam')
    
    sorted_bam = pysam.Samfile(file_stem+'_sorted.bam', 'rb')
    #fastafile = pysam.Fastafile(ref_file)
    for i in range(1, 30):
        ref_name = sorted_bam.header['SQ'][i]['SN']
        iter = sorted_bam.pileup( ref_name, 15, 200 )
        reads = len(list(iter))
        print(ref_name, reads)
#        for x in iter:
#        print(dir(x))
#        print(x.n)
#        print(x.pos)
#        print(dir(x.pileups))
#        sys.exit()
    
    
    
#    print(len(list(sorted_bam.fetch())))
#    print(len(list(sorted_bam.fetch("PR_20_unambiguous", 100, 125))))
#    print(len(list(sorted_bam.fetch(region="PR_20_unambiguous"))))
#    pileup_iter = sorted_bam.pileup(stepper = "all", fastafile = fastafile)
#    snpcall_iter = pysam.IteratorSNPCalls(pileup_iter)
#    for call in snpcall_iter:
#        print(str(call))
        
if __name__ == '__main__':
    main()
