#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copy coordinates from a template, based on an annotated sequence alignment.
#
# Author: Sebastian Kelm
# Created: 10/09/2009
#
# Revisions:
#



import sys, os.path
#import re
from array import array

if __name__ == "__main__":
  # Make sure we can import stuff from this file's directory
  sys.path.append(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), "..", "lib-python"))
  sys.path.append(os.path.abspath(os.path.dirname(sys.argv[0])))

from prosci.common import *
from prosci.util.ali import Ali
from prosci.util.gaps import *


def basename_noext(fname):
  return ".".join(os.path.basename(fname).split(".")[:-1])


if __name__ == "__main__":
    # We are running on the command line
    #
   
    import prosci.shell
    
    ################################
    # Command line option handling #
    ################################
    
    params = prosci.shell.Params(allowed=("help", "onlymain"), helpoption="help", usage="""
  Adds any number of entries to an existing tem file and prints everything to STDOUT.

  Entries must have the same sequence length as those in the tem file (not counting gaps).

  USAGE:
    $0 [OPTIONS] <main_tem_file> [tem_file_to_add...]""", help="""
  OPTIONS:
      --help
          print this message and exit
      --onlymain
          keep only entrygroups already present in the main tem file
        \n""")
    
    if (not params.args):
      params.writeHelp()
      sys.exit(1)
    
    main_tem_file    = params.args[0]
    tem_files_to_add = params.args[1:]
    
    if main_tem_file == "-":
      main_tem = Ali(sys.stdin, ignore_duplicates=True)
    else:
      try:
        f = open(main_tem_file)
        main_tem = Ali(f, ignore_duplicates=True)
      finally:
        f.close()
    main_codes = [eg.getCode() for eg in main_tem]
    
    aggregate = Ali([])
    aggregate.add(main_tem, merge_duplicates=True)
    
    for fname in tem_files_to_add:
      if fname == "-":
        add_tem = Ali(sys.stdin)
      else:
        try:
          f = open(fname)
          add_tem = Ali(f, ignore_duplicates=True)
        finally:
          f.close()
      if params.isOpt("onlymain"):
        for eg in add_tem:
          if eg.getCode() in main_codes:
            aggregate.add(eg, merge_duplicates=True)
      else:
        aggregate.add(add_tem, merge_duplicates=True)
    
    #aggregate.gappify()
    
    print aggregate
    
