#!/usr/bin/env python3
"""
maxalign.py - Python wrapper script to run maxalign.pl from BioLegato.

 Synopsis:
   
        maxalign.py infile [options]
   

@modified: July 3 2023
@author: Brian Fristensky
@contact: brian.fristensky@umanitoba.ca
"""

import argparse
import os
import shutil
import subprocess
import sys


PROGRAM = "maxalign.py: "
USAGE = "\n\t USAGE: maxalign.py [options] infile "

DEBUG = True

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Wrapper class for command line parameters"
class Parameters:

    def __init__(self):
        """
                Initializes arguments:
                Then calls read_args() to fill in their values from command line
                """

        self.IFN = "" 
        self.ALLGAPCOLS = False
        self.read_args()

    def read_args(self):
        """
                Read command line arguments into a Paramters object
                """
        parser = argparse.ArgumentParser()
        parser.add_argument("infile", action="store", default="", help="input file")
        parser.add_argument("-a", action="store_true", default=False, help="")

        try:
            args = parser.parse_args()           
            self.IFN = args.infile
            self.ALLGAPCOLS = args.a
        except ValueError:
            print(USAGE)

        if DEBUG :
            print("IFN: " + self.IFN)
            print("ALLGAPCOLS: " + str(self.ALLGAPCOLS))

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Run maxalign"
def Runmaxalign(P):

        COMMAND=["maxalign.pl"]
        if P.ALLGAPCOLS :
            COMMAND.append("-a")
        COMMAND.append(P.IFN)
        print(COMMAND)
        p = subprocess.Popen(COMMAND)
        p.wait()

#======================== MAIN PROCEDURE ==========================
def main():
    """
        Called when not in documentation mode.
        """

    P = Parameters ()

    # Make a temporary directory in which to run the program
    STARTDIR = os.getcwd()
    TEMPDIR  = 'maxalign.' + str(os.getpid())
    os.mkdir(TEMPDIR)
    shutil.copyfile(P.IFN, os.path.join(TEMPDIR, P.IFN))
    # From here on, everything is done in TEMPDIR
    os.chdir(TEMPDIR)

    Runmaxalign(P)  
    shutil.copyfile("heuristic.fsa", os.path.join(STARTDIR, P.IFN + ".fsa")) 
    shutil.copyfile("heuristic_exclude_headers.txt", os.path.join(STARTDIR, P.IFN + ".excluded.txt")) 
    shutil.copyfile("heuristic_include_headers.txt", os.path.join(STARTDIR, P.IFN + ".retained.txt")) 
    shutil.copyfile("report.txt", os.path.join(STARTDIR, P.IFN + ".report.txt"))       

    os.chdir(STARTDIR)
    shutil.rmtree(TEMPDIR)

if ("-test" in sys.argv):
    pass
else:
    main()
