#!/usr/bin/python
#Script to clean up superfluous tags from OO documents
#Author: Carsten Agger, agger@modspil.dk
#Feel free to do anything you like with this script, 
#including improving it to make it more suitable
#for cleaning up HTML generated by the OpenOffice.org/LibreOffice suite.
#No warranty whatsoever is supplied, use at own risk.
#
#BUGS: This will only work with entire HTML files, not with snippets. The
#      reason is the encoding. In order for this to work correctly across
#      unicode/ASCII, the correct charset MUST be specified in the header. 

import sys
import lxml.html.clean as clean

def clean_html(input_stream, output_stream):
    if len(input_stream) > 0:   
        infile = open(input_stream, "r")
    else:
        infile = sys.stdin
    h = infile.read()
    infile.close()
    C = clean.Cleaner(style = True, page_structure = True, remove_tags =
                      ['font'])
    clean_h = C.clean_html(h)

    if len(output_stream) > 0:
        outfile = open(output_stream, "w")
    else:
        outfile = sys.stdout
    outfile.write(clean_h)
    outfile.close()

def print_usage():
    print "Usage: cleanhtml <input_file> <output_file>"


if __name__ == '__main__':

    in_stream = out_stream = ''
    #TODO: Use getopt to parse options, this will do for now
    if 1 <= len(sys.argv) <= 3:
        if (len(sys.argv) > 1) and ((sys.argv[1] == '-h') 
                                    or (sys.argv[1] == '--help')):
            print_usage()
            sys.exit()
        else:
            if len(sys.argv) >= 2:
                in_stream = sys.argv[1]
            if len(sys.argv) == 3:
                out_stream = sys.argv[2]
        clean_html(in_stream, out_stream)
    else:
        print_usage()

    

