#!/usr/bin/env python3
#
# Mess up an Excellon file to look like it was generated by Zuken CR-8000.
# Only meant to work with KiCAD Excellon files.
#

import re

class Mapper:
    def __init__(self):
        self.g05_found = False

    def map_line(self, line):
        # Remove comments
        if line[0] == ';':
            return ''

        # Drop G90
        if line == 'G90':
            return ''

        # Drop first G05
        if line == 'G05' and not self.g05_found:
            self.g05_found = True
            return ''

        # Strip FMAT line (we need to put it in further down)
        if line == 'FMAT,2':
            return ''

        # Replace unit line with new header
        if line in ('METRIC', 'INCH'):
            return f'{line},LZ\nICI,OFF\nVER,1\nFMAT,2\nDETECT,ON\nATC,ON\n'
        
        # Add non-functional M06 to all tool uses after T01 with 
        if re.fullmatch(r'T[0-9]*', line):

            # Pad tool indices to two digits
            if len(line) == 2:
                line = f'{line[0]}0{line[1]}'

            return f'M06\n{line}\n'

        # Remove trailing non-functional T0
        if line == 'T0':
            return ''

        # Replace M30 EOF with M00 EOF
        if line == 'M30':
            return 'M00\n'

        # Convert coordinates into fixed-width 4.4 format
        if (m := re.fullmatch(r'X([-0-9.]*)Y([-0-9.]*)', line)):
            x, y = float(m[1]), float(m[2])
            # sign, four digits, point, four digits = 10 digits
            x, y = f'{x: 010.4f}', f'{y: 010.4f}'
            x, y = x.strip().replace('.', ''), y.strip().replace('.', '')
            return f'X{x}Y{y}\n'

        return f'{line}\n'

def zukenka(data):
    m = Mapper()
    return ''.join(m.map_line(line) for line in data.splitlines())

if __name__ == '__main__':
    import sys
    print(zukenka(sys.stdin.read()))
