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

def process( options ):
    '''
    Reads clusters from input file.
    '''
    nfiles=0
    lastSpecies=None
    outfh = None
    allSpec = set()
    if options.input=='-' or options.input is None:
        fh = sys.stdin
    else:
        fh = open( options.input, mode='r' )

    # loop over input
    for line in fh:
        # remove empty/commented lines, ascii(#) = 35
        line = line.strip()
        if len(line)==0 or line[0]=='#':
            continue
        elems = line.split(options.taxsep)
        species = elems[0]
        if lastSpecies is None or species != lastSpecies:
            if not outfh is None:
                outfh.close()
            mode = 'w'
            if species in allSpec:
                mode = 'a'

            output = os.path.join(options.outdir,'{}_{}.txt'.format(options.label,species))
            allSpec.add(species)
            outfh = open(output,mode)
            nfiles += 1
            print('{},{}'.format(species,output))
            lastSpecies = species

        outfh.write(line+'\n')
            

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Simple plot tool')

    parser.add_argument('-f', '--file', dest='input',
                        help='input file with genes', metavar='FILE', default = '-' )
    parser.add_argument('-s', '--sep', dest='taxsep',
                        help='species separator', default = ':' )
    parser.add_argument('-d', '--dir', dest='outdir',
                        help='output directory', default = '' )
    parser.add_argument('-l', '--label', dest='label',
                        help='output label', default = 'genes' )

    
    options = parser.parse_args()
    process( options )
