#!/usr/bin/python3
import sys
import argparse
import io

"""
The program outputs the nr of clusters with facc < max (--facc).
It finds at most nmax (--nmax) clusters.
The input spcov file is generated by statclus (from BRHCLUS) and sorted wrt to facc.
"""

def process( options ):
    '''
    process the input spcov file
    '''
    N=None
    with open( options.spcov, mode='r' ) as fh:
        N=0
        for line in fh:
            
            line = line.strip().rstrip('\n')
            # remove empty/commented lines
            if len(line)==0 or line[0]=='#':
                continue
            elems = line.split()
            if len(elems)<9:
                continue
            
            if not elems[1].isnumeric():
                continue

            facc = float(elems[8])
            if facc < options.facc:
                N = N+1
            else:
                break
            
            # we have reached max N
            if N == options.nmax:
                break

    # nothing found - return 0
    if N is None:
        return 0
    
    # min N is 2
    if N<2:
        N=2
    return N
                

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Get Nmax for subsampling')

    parser.add_argument('-c', '--spcov', dest='spcov',
                        help='cluster coverage file', metavar='FILE', required=True )
    parser.add_argument('-m', '--nmax', dest='nmax',
                        help='max N', type = int, default=8 )
    parser.add_argument('-f', '--facc', dest='facc',
                        help='max accumulated cluster coverage', type = float, default = 0.9 )
    
    options = parser.parse_args()
    N = process( options )
    print(N)
