#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os, shutil

from lib.alignment import alignSites
from lib.reporting import storeAlignment, reportAlignment

from lib.utilites import processCommandLineArguments

if __name__ == '__main__':
    
    try:
        print '\nPre-processing the input data. Please, wait...'
        sitesList1, sitesList2, pathToOutput, maxDist = processCommandLineArguments(sys.argv)
        print 'Ready to go.\n'
        
        multi = False
        if (len(sitesList1) > 1 and len(sitesList2) > 1):
            if not os.path.exists(pathToOutput):
                os.mkdir(pathToOutput)
            multi = True
            
        root = pathToOutput
        for site1 in sitesList1:
            if multi:
                pathToOutput = os.path.join(pathToOutput, site1.name)
            
            for site2 in sitesList2:
                print 'Aligning %s with %s...' % (site1.name, site2.name)
                try:
                    p='pairwise'
                    d='database'
                    alignedSite, scoreReport = alignSites(site1, site2, maxDist, p)
                
                except Exception, e:
                    print e
                    print 'The alignment process can\'t be completed.'
                    continue
                else:
                    sitesDirRoot = storeAlignment(site1, alignedSite, pathToOutput)
                    reportAlignment(site1, alignedSite, scoreReport, sitesDirRoot, maxDist)
                    print'Done.\n'
            
            pathToOutput = root
                
        print 'Results are stored here: %s\n' % pathToOutput
    
    except SystemExit:
        pass
