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

import re

def map_line(line):
    # strip layer polarity statement at start of header
    if line == '%LPD*%':
        return ''

    # Replace end of aperture list comment with empty line and layer polarity statement
    if line == 'G04 APERTURE END LIST*':
        return '\n%LPD*%\n' # this is the last newline in this file

    # strip comments
    if line.startswith('G04'):
        return ''

    # add G54 prefix to aperture selection statements
    if re.fullmatch(r'D[1-9][0-9]\*', line):
        return f'G54{line}'

    # make flash statements more complicated
    if (m := re.fullmatch(r'(.*)D03\*', line)):
        return f'{m[1]}D02*G55D03*'

    # replace M02 EOF with M00 EOF, and insert X0Y0D02
    if line == 'M02*':
        return 'X0Y0D02*M00*'

    # Merge G01/02/03 with following coordinate
    if line in ('G01*', 'G02*', 'G03*'):
        return line[:-1]

    # Preserve line endings for header lines
    if any(line.startswith(cmd) for cmd in ('%FS', '%MO', '%AD')):
        return f'{line}\n'

    return line

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

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