Copy filename to a tempfile, write pages to filename except the teared one.

    ..note ::

        Adapted from sciunto's code, https://github.com/sciunto/tear-pages

    :param filename: PDF filepath
    :param teared_pages: Numbers of the pages to tear. Default to first page \
            only.

def tearpage_backend(filename, teared_pages=None):
    """
    Copy filename to a tempfile, write pages to filename except the teared one.

    ..note ::

        Adapted from sciunto's code, https://github.com/sciunto/tear-pages

    :param filename: PDF filepath
    :param teared_pages: Numbers of the pages to tear. Default to first page \
            only.
    """
    # Handle default argument
    if teared_pages is None:
        teared_pages = [0]

    # Copy the pdf to a tmp file
    with tempfile.NamedTemporaryFile() as tmp:
        # Copy the input file to tmp
        shutil.copy(filename, tmp.name)

        # Read the copied pdf
        # TODO: Use with syntax
        try:
            input_file = PdfFileReader(open(tmp.name, 'rb'))
        except PdfReadError:
            fix_pdf(filename, tmp.name)
            input_file = PdfFileReader(open(tmp.name, 'rb'))
        # Seek for the number of pages
        num_pages = input_file.getNumPages()

        # Write pages excepted the first one
        output_file = PdfFileWriter()
        for i in range(num_pages):
            if i in teared_pages:
                continue
            output_file.addPage(input_file.getPage(i))

        tmp.close()
        outputStream = open(filename, "wb")
        output_file.write(outputStream)