#!/usr/bin/end python

import re
import docPatterns

class docModule:

    def __init__(self, name, lines):

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

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

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

        module_flag = 0
        contains_flag = 0
        
        for lin in lines.split('\n'):

            pat_m = re.match(docPatterns.module, lin)
            if module_flag:
                # dive into module

                if contains_flag:
                    if re.match(docPatterns.routine, lin):
                        # routine detected
                        pat = re.match(docPatterns.routine, lin)
                        statement = pat.group('type').upper() + ' ' + \
                                 pat.group('name') + pat.group('args')
                        self.data['contains'].append(statement)                            
                else:
                    # we are still in the module header
                    self.data['defs'] += '\n'+lin

                if re.match(docPatterns.contains, lin):
                    contains_flag = 1

                if re.match(docPatterns.end_module, lin):
                    module_flag = 0
                    contains_flag = 0

            elif pat_m and re.search(r'\b%s\b'%name, lin):
                module_flag = 1
            

    def out(self):

        module = 'MODULE '+self.data['name']
        print '-'*len(module)
        print module
        print '='*len(module)
        print self.data['defs']
        for c in self.data['contains']:
            print '\t' + c
        
 #.......................................................................

if __name__=='__main__':

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