"""
Supplementary Note 1: Read length distribution

Author: Annemarie Becker

inputFile:
.map file generated by Bowtie default output.

outputFile:
read length distribution
    col0: length of footprint read
    col1: how often is this length is counted
 
"""


def readLength(inputFile, outputFile):
    
    Dict = {}

    inFile = open(inputFile, 'r')
    outFile = open(outputFile, 'w')
  
    line = inFile.readline()
    while line != '':
        fields = line.split()
        col5 = str(fields[5])       #note: if sequencing was performed without barcode reading, the column needs to be changed to 4
        length = len(col5)

        columns = len(fields)   	#check: how many columns?
        if columns > 8:
            col8 = str(fields[8])
            if col8.startswith("0"):	#check: is there a mismatch at 1st position?
                length = length - 1	#subtract wrong base at 1st position
            else:
                pass
        else:
            pass

        if length in Dict:
            Dict[length] += 1
        else:
            Dict[length] = 1

        line = inFile.readline()

    List = Dict.items()
    List.sort()
    for length in range(0,52):		#the range depends on the number of cycles that are performed in sequencing
        if length not in Dict:
            Dict[length] = 0
    List = Dict.items()
    List.sort()
    for J in List:
        outFile.write(str(J[0]) + '\t' + str(J[1]) + '\n')

        
if __name__ == '__main__':
    inputFile = ''
    outputFile = ''

    readLength(inputFile, outputFile)

