#!/usr/bin/env python

"""
Copyright (c) 2015 Kwangbom Choi, The Jackson Laboratory
This software was developed by Kwangbom "KB" Choi in Gary Churchill's Lab.
This 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.
This software 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 this software. If not, see <http://www.gnu.org/licenses/>.
"""

import sys
import getopt
import numpy as np
from emase.AlignmentPropertyMatrix import AlignmentPropertyMatrix as APM


help_message = '''
Usage:
    get-common-alignments -i <h5_file_list> -o <out_file>

Input:
    -i <h5_file_list> : comma(,) separated list of emase format (PyTables) files
    -o <out_file>     : output file name
'''


class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg


def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hi:c:o:", ["help"])
        except getopt.error, msg:
            raise Usage(msg)

        # Default values of vars
        flist = None
        outfile = 'alignments.common.h5'
        complib = 'zlib'

        # option processing (change this later with optparse)
        for option, value in opts:
            if option in ("-h", "--help"):
                raise Usage(help_message)
            if option == "-i":
                flist = value.split(',')
            if option == "-c":  # hidden option (Specify the compression mode for writing PyTables)
                complib = value
            if option == "-o":
                outfile = value

        # Check if the required options are given
        if flist is None or len(flist) < 2:
            raise Usage(help_message)

        #
        # Main body
        #

        alnmat = APM(h5file=flist[0])
        for f in flist[1:]:
            alnmat_next = APM(h5file=f)
            if np.all(alnmat.rname == alnmat_next.rname):
                alnmat = alnmat * alnmat_next
            else:
                print >> sys.stderr, "[FATAL ERROR] The read ID's are not compatible."
                return 2

        alnmat.save(h5file=outfile, complib=complib)

        #
        # End of main body
        #

    except Usage, err:
        print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
        return 2


if __name__ == "__main__":
    sys.exit(main())
