"""
Script to fix <BriefDescription> newlines
"""

import os
import re
import sys
from lxml import etree


if __name__ == '__main__':
  #print sys.argv
  if len(sys.argv) < 2:
    app = os.path.basename(sys.argv[0])
    print
    print 'Script to prune whitespace from xml text'
    print 'Usage: python %s filename' % app
    print
    sys.exit(-1)

  filename = sys.argv[1]
  dom = etree.parse(filename)
  root = dom.getroot()
  #print root.tag

  mods = 0  # count the modified elements
  for element in root.iter(tag="BriefDescription"):
    #print element.text
    text = element.text
    # Check for any newline-followed-by-whitespace
    if re.match(r"\n\s", text):
      # Remove all newline-followed-by-whitespace
      split_list = re.split(r"\n\s*", text)
      # Prune out any empty strings
      content_list = [item for item in split_list if item != '']
      new_string = '\n'.join(content_list)

      # print 'new_string:'
      # print new_string
      # print

      element.text = new_string
      mods += 1

  if mods:
    dom.write(filename)
    print 'Wrote %d text-element updates to %s' % (mods, filename)
  else:
    print 'No text-element updates to %s' % filename

  #print 'Finis'
