#!/usr/bin/env python
import os
import sys
import glob
import getopt
import logging

from cclib.parser import ccopen

_allowedargs = ['aonames','aooverlaps','atombasis','atomcoords','atomnos',
		'ccenergies', 'charge','coreelectrons',
                'etenergies','etoscs','etrotats','etsecs','etsyms',
                'fonames','fooverlaps','fragnames','frags',
                'gbasis','geotargets','geovalues',
                'hessian','homos',
                'mocoeffs','moenergies','mosyms','mpenergies','mult',
                'natom','nbasis', 'nmo', 'nocoeffs',
                'scfenergies','scftargets','scfvalues',
                'vibdisps', 'vibfreqs','vibirs','vibramans','vibsyms']

def moreusage():
    """More detailed usage information"""
    print """Usage:  ccget <attribute> [<attribute>] <compchemlogfile> [<compchemlogfile>]
     where <attribute> is one of the attributes to be parsed by cclib
     from each of the compchemlogfiles.
For a list of attributes available in a file, type:
     ccget --list <compchemlogfile>   [or -l]"""

def usage():
    """Display usage information"""
    print """Usage:  ccget <attribute> [<attribute>] <compchemlogfile> [<compchemlogfile>]
Try     ccget --help    for more information"""


def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hl", ["help","list"])
    except getopt.GetoptError:
        # print help information and exit:
        usage()
        sys.exit(2)
    showattr = False
    for o, a in opts:
        if o in ("-h", "--help"):
            moreusage()
            sys.exit()
        if o in ("-l", "--list"):
            showattr = True
    if (not showattr and len(args)<2) or (showattr and len(args)!=1): # Need at least one attribute and the filename
        usage()
        sys.exit()

    # Figure out which are the attribute names and which are the filenames
    attrnames = []
    filenames = []
    for arg in args:
        if arg in _allowedargs:
            attrnames.append(arg)
        elif os.path.isfile(arg):
            filenames.append(arg)
        else:
            wildcardmatches = glob.glob(arg)
            # In Linux, the shell expands wild cards
            # Not so, in Windows, so it has to be done manually
            if wildcardmatches:
                filenames.extend(wildcardmatches)
            else:
                print "%s is neither a filename nor an attribute name." % arg
                usage()
                sys.exit(1)
    
    for filename in filenames:
        print "Attempting to parse %s" % filename
        log = ccopen(filename)
        if log==None:
            print "Cannot figure out what type of computation chemistry output file '%s' is.\nReport this to the cclib development team if you think this is an error." % filename
            usage()
            sys.exit()
              
        log.logger.setLevel(logging.ERROR)
        data = log.parse()
        if showattr:
            print "cclib can parse the following attributes from %s:" % filename
            for x in _allowedargs:
                if hasattr(data,x):
                    print "  %s" % x
        else:
            invalid = False
            for attr in attrnames:
                if hasattr(data,attr):
                    print "%s:\n%s" % (attr,getattr(data,attr))
                else:
                    invalid = True
            if invalid:
                print
                moreusage()

if __name__ == "__main__":
    main()
