1#########################################################################
2#                                                                       #
3#                                                                       #
4#   copyright 2002 Paul Henry Tremblay                                  #
5#                                                                       #
6#   This program is distributed in the hope that it will be useful,     #
7#   but WITHOUT ANY WARRANTY; without even the implied warranty of      #
8#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU    #
9#   General Public License for more details.                            #
10#                                                                       #
11#                                                                       #
12#########################################################################
13import os
14
15from calibre.ebooks.rtf2xml import copy
16from calibre.utils.cleantext import clean_ascii_chars
17from calibre.ptempfile import better_mktemp
18from . import open_for_read, open_for_write
19
20
21class ReplaceIllegals:
22    """
23    reaplace illegal lower ascii characters
24    """
25
26    def __init__(self,
27            in_file,
28            copy=None,
29            run_level=1,
30            ):
31        self.__file = in_file
32        self.__copy = copy
33        self.__run_level = run_level
34        self.__write_to = better_mktemp()
35
36    def replace_illegals(self):
37        """
38        """
39        with open_for_read(self.__file) as read_obj:
40            with open_for_write(self.__write_to) as write_obj:
41                for line in read_obj:
42                    write_obj.write(clean_ascii_chars(line))
43        copy_obj = copy.Copy()
44        if self.__copy:
45            copy_obj.copy_file(self.__write_to, "replace_illegals.data")
46        copy_obj.rename(self.__write_to, self.__file)
47        os.remove(self.__write_to)
48