import bisect


class MeshCleaner:
    def __init__(self, i, o, out_color=None):
        self.input = open(i, 'r')
        self.out = o
        self.v = []
        self.v_min = None
        self.v_max = None
        self.f = []
        self.ind = []
        self.color = out_color

    def clean(self):
        line = self.input.readline()
        while line[0] != 'v':
            line = self.input.readline()

        while line[0] == 'v':
            words = line.split()
            self.v.append([float(words[1]), float(words[2]), float(words[3])])
            line = self.input.readline()

        while line[0] != 'f':
            line = self.input.readline()

        tmp = []
        while line[0] == 'f':
            words = line.split()
            bisect.insort(tmp, int(words[1]) - 1)
            bisect.insort(tmp, int(words[2]) - 1)
            bisect.insort(tmp, int(words[3]) - 1)
            bisect.insort(self.f, [int(words[1]) - 1,
                                   int(words[2]) - 1,
                                   int(words[3]) - 1])
            line = self.input.readline()

        self.input.close()

        i = 0
        out = open(self.out, 'w')
        mapper = {}
        count = 1
        while i < len(tmp):
            index = tmp[i]
            out.write('v {0} {1} {2} '.format(*self.v[index]))
            if self.color is not None:
                out.write(self.color)
            out.write('\n')
            self.ind.append(index)
            mapper[index] = count
            count += 1
            n = i + 1
            while n < len(tmp) and tmp[n] == index:
                n += 1
            i = n

        i = 0
        while i < len(self.f):
            f = self.f[i]
            out.write('f {0} {1} {2}\n'.format(mapper[f[0]],
                                               mapper[f[1]],
                                               mapper[f[2]]))
            n = i + 1
            while n < len(self.f) and self.f[n] == f:
                n += 1
            i = n

        out.write('\n')
        out.close()
