#! /usr/bin/env python

from abjad.tools import iotools
import os


def _remove_source_file_terminal_blank_lines():
   total_source_files_with_blank_lines = 0
   total_blank_lines = 0
   for path, subdirectories, files in os.walk('.'):
      for f in files:
         found_import_as_statement = False
         if f.endswith(('.py', '.ly', '.raw', '.rst')):
            full_file_name = os.path.join(path, f)
            file_pointer = file(full_file_name, 'r')
            lines = file_pointer.readlines()
            file_pointer.close()
            if lines:
                if lines[-1] == '\n':
                    total_source_files_with_blank_lines += 1
                    for line in reversed(lines[:]):
                        if line == '\n':
                            total_blank_lines += 1
                            lines.pop(-1)
                        else:
                            break
                    file_pointer = file(full_file_name, 'w')
                    file_pointer.write(''.join(lines))
   print 'Total source files with terminal blank lines: %s' % total_source_files_with_blank_lines
   print 'Total source file-terminal blank lines:       %s' % total_blank_lines
   print ''


if __name__ == '__main__':
   iotools.clear_terminal()
   print 'Removing source file-terminal blank lines ...'
   print ''
   _remove_source_file_terminal_blank_lines()
