#!/usr/bin/python3

# orthologer - Pipeline for deducing orthology from fasta files.
# Copyright (C) 2005-2023 E. Zdobnov lab: F. Tegenfeldt
# <fredrik.tegenfeldt@unige.ch> based on code by E. Kriventseva
#
# This file is part of orthologer.
#
# orthologer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# orthologer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with orthologer.  If not, see <http://www.gnu.org/licenses/>.

'''
This searches for cd-hit cases where masked out regions have been aligned.
Pipeline usage: MASKER
'''

from __future__ import print_function

import sys
import argparse
import fasta_tools as FT
import orthologer_tools as OT

def process_fasta(inpfile,fmaskedmax, minlen, stype):
    try:
        inpf = open(inpfile,"r")
    except IOError:
        OT.print_error('file open failed for %s' % (inpfile))
        sys.exit(-1)

    # make sure data type is valid
    stype=FT.makeType(stype)
    masked=FT.getMasked(stype)

    done=False

    # loop over fasta files
    while not done:
        # get next fasta
        (eof,label,descr,sequence)=FT.getNext(inpf)
        if eof:
            done=True
        elif label is None:
            done=True
            continue

        # get fasta type if not established
        if stype is None:
            found,stype=FT.getType(sequence,False)
            masked=FT.getMasked(stype)

        if masked is not None:
            # replace all lower case characters with upper case masked char
            sequence = FT.replaceLowerCaseMasked(sequence,masked)
            # count all masked
            nmasked = FT.statCharSequence(sequence,masked)

            f = float(nmasked)/float(len(sequence))
            oklen=FT.longestSequence(sequence,masked,minlen)
            if oklen<minlen:
                print(('#MASKED longest unmasked region is too short (%d < %d) ; f(masked)=%6.2f: %s')%(oklen,minlen,f,label))
                print(('#MASKED %s')%(sequence))
                continue

            if f<fmaskedmax:
                # fraction masked is small enough - print sequence
                if descr is None: descr=''
                else: descr=' '+descr
                print(('>%s%s')%(label,descr))
                print(sequence)
            else:
                print(('#MASKED with f(masked)=%6.2f: %s')%(f,label))
                print(('#MASKED %s')%(sequence))

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

parser = argparse.ArgumentParser(description='Check fasta files')

parser.add_argument('-f', '--fasta', dest='filename', help='fasta file', metavar='FILE', required=True)
parser.add_argument('--maxf', dest='maxf', help='maximum fraction masked bases allowed', type=float, default=0.6)

parser.add_argument('--minlen', dest='minlen', help='minimum length allowed', type=int, default=30)
parser.add_argument('--type', dest='stype', help='data type (prot or nucl)', default=None)

options = parser.parse_args()

# process fasta file
process_fasta(options.filename,options.maxf,options.minlen, options.stype)
