#! /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')
            just_found_end_of_header, found_end_of_header = False, False
            header_lines, module_lines = [ ], [ ]
            for i, line in enumerate(fp):
               if not found_end_of_header:
                  if i == 0 and not line.startswith('from') and not line.startswith('import'):
                     just_found_end_of_header = True
                  elif line.startswith('from') or line.startswith('import'):
                     header_lines.append(line)
                  elif line == '\n' or line.startswith('py.test'):
                     just_found_end_of_header = True
                  else:
                     raise Exception(full_file_name)
               if found_end_of_header:
                  module_lines.append(line)
               elif just_found_end_of_header:
                  found_end_of_header = True
                  if header_lines:
                     sorted_header_lines = list(sorted(header_lines))
                     if header_lines != sorted_header_lines:
                        total_nonalphabetized_module_headers += 1
                     module_lines.extend(sorted_header_lines)
                     header_lines = [ ]
                  module_lines.append(line)
                  just_found_end_of_header = False
            if header_lines:
               assert not module_lines
               module_lines.extend(header_lines)
            fp.close( )
            fp = file(full_file_name, 'w')
            fp.write(''.join(module_lines))
            fp.close( )
   print 'Total nonalphabetized headers fixed: %s' % total_nonalphabetized_module_headers
   print ''


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