#! /usr/bin/env python

from abjad.cfg.cfg import ABJADPATH
from abjad.tools import iotools
import os


def _main( ):
   total_nonalphabetized_module_headers = 0
   for path, subdirectories, files in os.walk(ABJADPATH):
      for f in files:
         if f.endswith('.py'):
            full_file_name = os.path.join(path, f)
            fp = file(full_file_name, 'r')
            header_lines = [ ]
            for i, line in enumerate(fp):
               if i == 0 and \
                  not line.startswith('from') and not line.startswith('import'):
                  break
               elif line.startswith('from') or line.startswith('import'):
                  header_lines.append(line)
               elif line == '\n' or line.startswith('py.test'):
                  break
               else:
                  print ''
                  print total_module_headers
                  print ''
                  print full_file_name
                  print header_lines
                  print line
                  raise Exception
            if header_lines:
               sorted_header_lines = list(sorted(header_lines))
               if header_lines != sorted_header_lines:
                  total_nonalphabetized_module_headers += 1
                  print '#### NONALPHABETIZED HEADER #######\n'
                  print ''.join(header_lines)
                  print ''.join(sorted_header_lines)
   print 'Total nonalphabetized headers: %s' % total_nonalphabetized_module_headers
   print ''


if __name__ == '__main__':
   iotools.clear_terminal( )
   print 'Finding nonalphabetized module headers ...'
   print ''
   _main( )
