#!/usr/bin/end python

import re, string
import docPatterns

class docRoutine:

    def __init__(self, name, lines):

        type = ''
        comment = ''
        use_modules = []
        args = {}

        self.data = {
            'name': name,
            'type': '',
            'args': [],
            'use': [],
            'defs': '',
            }

        # flatten continued lines
        lines = re.sub('&\s*\n\s*&', '', lines)

        routine_flag = 0
        implicit_flag = 0
        
        for lin in lines.split('\n'):
            
            if routine_flag:
                # dive into routine

                if implicit_flag:

                    if re.match(docPatterns.comment, lin):
                        # valuable comment
                        self.data['defs'] += '\n'+lin
                    elif re.match(docPatterns.definition, lin):
                        # check that the definition relates to
                        # a routine argument
                        defs = []
                        for a in self.data['args']: 
                            if re.search(r'\b%s\b' % a.upper(), lin.upper()):
                                if not ('\n'+lin in defs):
                                    # in case two variables are defined
                                    # on the same line
                                    defs.append('\n'+lin)
                        self.data['defs'] += string.join(defs, '\n')
                    elif re.match(docPatterns.blank, lin):
                        pass
                    else:
                        # main body of routine starts here
                        routine_flag = 0
                        implicit_flag = 0
                else:

                    if re.match(docPatterns.comment, lin):
                        # valuable comment
                        self.data['defs'] += '\n'+lin
                    elif re.match(docPatterns.use, lin):
                        # use statement
                        pat = re.match(docPatterns.use, lin)
                        self.data['use'].append(pat.group('name'))
                    elif re.match(docPatterns.implicit_none, lin):
                        implicit_flag = 1
                    
            pat = re.match(docPatterns.routine, lin)
            if pat and pat.group('name')==name:
                # entering routine
                routine_flag = 1
                self.data['type'] = pat.group('type')
                args = re.sub(r'\s+', '', pat.group('args'))
                args = re.sub('^\(', '', args)
                args = re.sub('\)$', '', args)
                self.data['args'] = args.split(',')

    def out(self):

        args = reduce(lambda x,y:x+', '+y, self.data['args'])
        routine = \
            self.data['type'].upper()+' '+self.data['name']+'('+args+')'
        print '-'*len(routine)
        print routine
        print '='*len(routine)
        for m in self.data['use']:
            print '\tUSE '+m
        print self.data['defs']
        print '-'*len(routine)
        
 #.......................................................................

if __name__=='__main__':

    import sys
    if len(sys.argv) <3:
        print 'usage: ', sys.argv[0], ' <routine_name> <file.f90>'
        sys.exit(1)
      
    lines = file(sys.argv[2], 'r').read()
    d = docRoutine(sys.argv[1], lines)
    d.out()
                       
