#!/usr/bin/python3
'''
Collect sequence lengths.
Pipeline usage: STATS
'''
from __future__ import print_function

import sys
import argparse

def read_data( inpfile ):
    fh = open(inpfile)
    label=None
    seqlen=None
    nbad=0
    nok=0
    for line in fh.readlines():
        line = line.strip().rstrip('\n')
        if len(line)==0 or line[0] in '#': continue
        if line[0]=='>':
            if seqlen is not None:
                if label is None:
                    nbad=nbad+1
                    print(line)
                else:
                    print('%s %d %.2f'%(label,seqlen,float(seqlen-nxlen)/float(seqlen)))
                    nok=nok+1

            seqlen=None
            nxlen=0
            label=line[1:]
        else:
            if seqlen is None:
                seqlen = 0
                nxlen  = 0
            seqlen += len(line)
            nxlen  += line.count('X')
    rval=0
    if seqlen is not None and label is not None:
        print('%s %d %.2f'%(label,seqlen,float(seqlen-nxlen)/float(seqlen)))
        nok=nok+1
    if nbad>0:
        print('# error: found %d bad lines - sequences with no label associated - is this really a fasta file?'%nbad,file=sys.stderr)
        rval=255
    if nok==0:
        print('#NO DATA')
    return rval


parser = argparse.ArgumentParser(description='get sequence lengths and output one per line: <label> <length>')

parser.add_argument("-f", "--file", dest="filename",
                    help="input fasta file", metavar="FILE", required=True)


options = parser.parse_args()

##########################################################################


rval=read_data(options.filename)
sys.exit(rval)
