#!/usr/bin/env python
"""

f2py2e - Fortran to Python C/API generator. 2nd Edition.
         See __usage__ below.

Copyright 1999--2005 Pearu Peterson all rights reserved,
Pearu Peterson <pearu@cens.ioc.ee>
Permission to use, modify, and distribute this software is given under the
terms of the NumPy License.

NO WARRANTY IS EXPRESSED OR IMPLIED.  USE AT YOUR OWN RISK.
$Date: 2005/05/06 08:31:19 $
Pearu Peterson
"""
__version__ = "$Revision: 1.90 $"[10:-1]

import __version__
f2py_version = __version__.version

import sys
import os
import pprint
import types
import re
errmess=sys.stderr.write
#outmess=sys.stdout.write
show=pprint.pprint

import crackfortran
import rules
import cb_rules
import auxfuncs
import cfuncs
import f90mod_rules

outmess = auxfuncs.outmess

try:
    from numpy import __version__ as numpy_version
except ImportError:
    numpy_version = 'N/A'

__usage__ = """\
Usage:

1) To construct extension module sources:

      f2py [<options>] <fortran files> [[[only:]||[skip:]] \\
                                        <fortran functions> ] \\
                                       [: <fortran files> ...]

2) To compile fortran files and build extension modules:

      f2py -c [<options>, <build_flib options>, <extra options>] <fortran files>

3) To generate signature files:

      f2py -h <filename.pyf> ...< same options as in (1) >

Description: This program generates a Python C/API file (<modulename>module.c)
             that contains wrappers for given fortran functions so that they
             can be called from Python. With the -c option the corresponding
             extension modules are built.

Options:

  --2d-numpy       Use numpy.f2py tool with NumPy support. [DEFAULT]
  --2d-numeric     Use f2py2e tool with Numeric support.
  --2d-numarray    Use f2py2e tool with Numarray support.
  --g3-numpy       Use 3rd generation f2py from the separate f2py package.
                   [NOT AVAILABLE YET]

  -h <filename>    Write signatures of the fortran routines to file <filename>
                   and exit. You can then edit <filename> and use it instead
                   of <fortran files>. If <filename>==stdout then the
                   signatures are printed to stdout.
  <fortran functions>  Names of fortran routines for which Python C/API
                   functions will be generated. Default is all that are found
                   in <fortran files>.
  <fortran files>  Paths to fortran/signature files that will be scanned for
                   <fortran functions> in order to determine their signatures.
  skip:            Ignore fortran functions that follow until `:'.
  only:            Use only fortran functions that follow until `:'.
  :                Get back to <fortran files> mode.

  -m <modulename>  Name of the module; f2py generates a Python/C API
                   file <modulename>module.c or extension module <modulename>.
                   Default is 'untitled'.

  --[no-]lower     Do [not] lower the cases in <fortran files>. By default,
                   --lower is assumed with -h key, and --no-lower without -h key.

  --build-dir <dirname>  All f2py generated files are created in <dirname>.
                   Default is tempfile.mktemp().

  --overwrite-signature  Overwrite existing signature file.

  --[no-]latex-doc Create (or not) <modulename>module.tex.
                   Default is --no-latex-doc.
  --short-latex    Create 'incomplete' LaTeX document (without commands
                   \\documentclass, \\tableofcontents, and \\begin{document},
                   \\end{document}).

  --[no-]rest-doc Create (or not) <modulename>module.rst.
                   Default is --no-rest-doc.

  --debug-capi     Create C/API code that reports the state of the wrappers
                   during runtime. Useful for debugging.

  --[no-]wrap-functions    Create Fortran subroutine wrappers to Fortran 77
                   functions. --wrap-functions is default because it ensures
                   maximum portability/compiler independence.

  --include_paths <path1>:<path2>:...   Search include files from the given
                   directories.

  --help-link [..] List system resources found by system_info.py. See also
                   --link-<resource> switch below. [..] is optional list
                   of resources names. E.g. try 'f2py --help-link lapack_opt'.

  --quiet          Run quietly.
  --verbose        Run with extra verbosity.
  -v               Print f2py version ID and exit.


numpy.distutils options (only effective with -c):

  --fcompiler=         Specify Fortran compiler type by vendor
  --compiler=          Specify C compiler type (as defined by distutils)

  --help-fcompiler     List available Fortran compilers and exit
  --f77exec=           Specify the path to F77 compiler
  --f90exec=           Specify the path to F90 compiler
  --f77flags=          Specify F77 compiler flags
  --f90flags=          Specify F90 compiler flags
  --opt=               Specify optimization flags
  --arch=              Specify architecture specific optimization flags
  --noopt              Compile without optimization
  --noarch             Compile without arch-dependent optimization
  --debug              Compile with debugging information

Extra options (only effective with -c):

  --link-<resource>    Link extension module with <resource> as defined
                       by numpy.distutils/system_info.py. E.g. to link
                       with optimized LAPACK libraries (vecLib on MacOSX,
                       ATLAS elsewhere), use --link-lapack_opt.
                       See also --help-link switch.

  -L/path/to/lib/ -l<libname>
  -D<define> -U<name>
  -I/path/to/include/
  <filename>.o <filename>.so <filename>.a

  Using the following macros may be required with non-gcc Fortran
  compilers:
    -DPREPEND_FORTRAN -DNO_APPEND_FORTRAN -DUPPERCASE_FORTRAN
    -DUNDERSCORE_G77

  When using -DF2PY_REPORT_ATEXIT, a performance report of F2PY
  interface is printed out at exit (platforms: Linux).

  When using -DF2PY_REPORT_ON_ARRAY_COPY=<int>, a message is
  sent to stderr whenever F2PY interface makes a copy of an
  array. Integer <int> sets the threshold for array sizes when
  a message should be shown.

Version:     %s
numpy Version: %s
Requires:    Python 2.3 or higher.
License:     NumPy license (see LICENSE.txt in the NumPy source code)
Copyright 1999 - 2005 Pearu Peterson all rights reserved.
http://cens.ioc.ee/projects/f2py2e/"""%(f2py_version, numpy_version)


def scaninputline(inputline):
    files,funcs,skipfuncs,onlyfuncs,debug=[],[],[],[],[]
    f,f2,f3,f4,f5,f6,f7=1,0,0,0,0,0,0
    verbose = 1
    dolc=-1
    dolatexdoc = 0
    dorestdoc = 0
    wrapfuncs = 1
    buildpath = '.'
    include_paths = []
    signsfile,modulename=None,None
    options = {'buildpath':buildpath}
    for l in inputline:
        if l=='': pass
        elif l=='only:': f=0
        elif l=='skip:': f=-1
        elif l==':': f=1;f4=0
        elif l[:8]=='--debug-': debug.append(l[8:])
        elif l=='--lower': dolc=1
        elif l=='--build-dir': f6=1
        elif l=='--no-lower': dolc=0
        elif l=='--quiet': verbose = 0
        elif l=='--verbose': verbose += 1
        elif l=='--latex-doc': dolatexdoc=1
        elif l=='--no-latex-doc': dolatexdoc=0
        elif l=='--rest-doc': dorestdoc=1
        elif l=='--no-rest-doc': dorestdoc=0
        elif l=='--wrap-functions': wrapfuncs=1
        elif l=='--no-wrap-functions': wrapfuncs=0
        elif l=='--short-latex': options['shortlatex']=1
        elif l=='--overwrite-signature': options['h-overwrite']=1
        elif l=='-h': f2=1
        elif l=='-m': f3=1
        elif l[:2]=='-v':
            print f2py_version
            sys.exit()
        elif l=='--show-compilers':
            f5=1
        elif l[:8]=='-include':
            cfuncs.outneeds['userincludes'].append(l[9:-1])
            cfuncs.userincludes[l[9:-1]]='#include '+l[8:]
        elif l[:15]=='--include_paths':
            f7=1
        elif l[0]=='-':
            errmess('Unknown option %s\n'%`l`)
            sys.exit()
        elif f2: f2=0;signsfile=l
        elif f3: f3=0;modulename=l
        elif f6: f6=0;buildpath=l
        elif f7: f7=0;include_paths.extend(l.split(os.pathsep))
        elif f==1:
            try:
                open(l).close()
                files.append(l)
            except IOError,detail:
                errmess('IOError: %s. Skipping file "%s".\n'%(str(detail),l))
        elif f==-1: skipfuncs.append(l)
        elif f==0: onlyfuncs.append(l)
    if not f5 and not files and not modulename:
        print __usage__
        sys.exit()
    if not os.path.isdir(buildpath):
        if not verbose:
            outmess('Creating build directory %s'%(buildpath))
        os.mkdir(buildpath)
    if signsfile:
        signsfile = os.path.join(buildpath,signsfile)
    if signsfile and os.path.isfile(signsfile) and 'h-overwrite' not in options:
        errmess('Signature file "%s" exists!!! Use --overwrite-signature to overwrite.\n'%(signsfile))
        sys.exit()

    options['debug']=debug
    options['verbose']=verbose
    if dolc==-1 and not signsfile: options['do-lower']=0
    else: options['do-lower']=dolc
    if modulename: options['module']=modulename
    if signsfile: options['signsfile']=signsfile
    if onlyfuncs: options['onlyfuncs']=onlyfuncs
    if skipfuncs: options['skipfuncs']=skipfuncs
    options['dolatexdoc'] = dolatexdoc
    options['dorestdoc'] = dorestdoc
    options['wrapfuncs'] = wrapfuncs
    options['buildpath']=buildpath
    options['include_paths']=include_paths
    return files,options

def callcrackfortran(files,options):
    rules.options=options
    funcs=[]
    crackfortran.debug=options['debug']
    crackfortran.verbose=options['verbose']
    if 'module' in options:
        crackfortran.f77modulename=options['module']
    if 'skipfuncs' in options:
        crackfortran.skipfuncs=options['skipfuncs']
    if 'onlyfuncs' in options:
        crackfortran.onlyfuncs=options['onlyfuncs']
    crackfortran.include_paths[:]=options['include_paths']
    crackfortran.dolowercase=options['do-lower']
    postlist=crackfortran.crackfortran(files)
    if 'signsfile' in options:
        outmess('Saving signatures to file "%s"\n'%(options['signsfile']))
        pyf=crackfortran.crack2fortran(postlist)
        if options['signsfile'][-6:]=='stdout':
            sys.stdout.write(pyf)
        else:
            f=open(options['signsfile'],'w')
            f.write(pyf)
            f.close()
    return postlist

def buildmodules(lst):
    cfuncs.buildcfuncs()
    outmess('Building modules...\n')
    modules,mnames,isusedby=[],[],{}
    for i in range(len(lst)):
        if '__user__' in lst[i]['name']:
            cb_rules.buildcallbacks(lst[i])
        else:
            if 'use' in lst[i]:
                for u in lst[i]['use'].keys():
                    if u not in isusedby:
                        isusedby[u]=[]
                    isusedby[u].append(lst[i]['name'])
            modules.append(lst[i])
            mnames.append(lst[i]['name'])
    ret = {}
    for i in range(len(mnames)):
        if mnames[i] in isusedby:
            outmess('\tSkipping module "%s" which is used by %s.\n'%(mnames[i],','.join(map(lambda s:'"%s"'%s,isusedby[mnames[i]]))))
        else:
            um=[]
            if 'use' in modules[i]:
                for u in modules[i]['use'].keys():
                    if u in isusedby and u in mnames:
                        um.append(modules[mnames.index(u)])
                    else:
                        outmess('\tModule "%s" uses nonexisting "%s" which will be ignored.\n'%(mnames[i],u))
            ret[mnames[i]] = {}
            dict_append(ret[mnames[i]],rules.buildmodule(modules[i],um))
    return ret

def dict_append(d_out,d_in):
    for (k,v) in d_in.items():
        if k not in d_out:
            d_out[k] = []
        if type(v) is types.ListType:
            d_out[k] = d_out[k] + v
        else:
            d_out[k].append(v)

def run_main(comline_list):
    """Run f2py as if string.join(comline_list,' ') is used as a command line.
    In case of using -h flag, return None.
    """
    if sys.version_info[0] >= 3:
        import imp
        imp.reload(crackfortran)
    else:
        reload(crackfortran)
    f2pydir=os.path.dirname(os.path.abspath(cfuncs.__file__))
    fobjhsrc = os.path.join(f2pydir,'src','fortranobject.h')
    fobjcsrc = os.path.join(f2pydir,'src','fortranobject.c')