import numpy as np
import PIL.Image
import sys

X_FLIP = 0x4000
Y_FLIP = 0x8000
PAL = 0x1000

im = PIL.Image.open(sys.argv[1])
tiles = np.array(np.split(np.array(np.split(np.array(im), 28, 0)), 32, 2))
tilemapRaw = bytearray(32 * 28 * 2)
tilemap = np.ndarray(shape=(28, 32), dtype='<u2', buffer=tilemapRaw)
tiledata = [[0] * 64]

for tid in np.mgrid[:32, :28].reshape(2, -1).T:
    tile = tiles[tuple(tid)]
    tid = tuple(np.flip(tid))
    data = list(tile.flatten())
    try:
        index = tiledata.index(data)
        tilemap[tid] = index | PAL
        continue
    except:
        pass

    data = list(np.flip(tile, 0).flatten())
    try:
        index = tiledata.index(data)
        tilemap[tid] = index | PAL | Y_FLIP
        continue
    except:
        pass

    data = list(np.flip(tile, 1).flatten())
    try:
        index = tiledata.index(data)
        tilemap[tid] = index | PAL | X_FLIP
        continue
    except:
        pass

    data = list(np.flip(np.flip(tile, 0), 1).flatten())
    try:
        index = tiledata.index(data)
        tilemap[tid] = index | PAL | X_FLIP | Y_FLIP
        continue
    except:
        pass

    data = list(tile.flatten())
    index = len(tiledata)
    tilemap[tid] = index | PAL
    tiledata.append(data)

chardataRaw = bytearray(len(tiledata) * 32)

for i, tile in enumerate(tiledata):
    for y in range(8):
        tileData = [0] * 4
        for x in range(8):
            t = tile[y * 8 + x]
            tileData[0] |= ((t & 1) >> 0) << (7 - x)
            tileData[1] |= ((t & 2) >> 1) << (7 - x)
            tileData[2] |= ((t & 4) >> 2) << (7 - x)
            tileData[3] |= ((t & 8) >> 3) << (7 - x)
        tileBase = i * 32 + y * 2
        print(tileBase)
        chardataRaw[tileBase + 0x00] = tileData[0]
        chardataRaw[tileBase + 0x01] = tileData[1]
        chardataRaw[tileBase + 0x10] = tileData[2]
        chardataRaw[tileBase + 0x11] = tileData[3]

def printMem(mem):
    for i in range(len(mem) // 16):
        line = mem[i * 16:(i + 1) * 16]
        print(', '.join([f'0x{b:02X}' for b in line]) + ',')

@@ -1299,16 +1299,161 @@
  * 32)%0A%0A
+palette = np.array(im.getpalette(), np.uint16).reshape(-1, 3)%0Apalette %3E%3E= 3%0Apalette = palette%5B:,0%5D %7C (palette%5B:,1%5D %3C%3C 5) %7C (palette%5B:,2%5D %3C%3C 10)%0A%0A
 for i, t
@@ -1839,32 +1839,8 @@
 * 2%0A
-        print(tileBase)%0A
     
@@ -2149,16 +2149,23 @@
   print(
+'%5Ct' + 
 ', '.joi
@@ -2203,8 +2203,258 @@
  + ',')%0A
+%0Aprint('uint16_t palette%5B%5D = %7B');%0Afor rgb in palette%5B:16%5D:%0A    print(f'%5Ct0x%7Brgb:04X%7D,')%0Aprint('%7D;')%0Aprint()%0A%0Aprint('uint8_t tilemap%5B%5D = %7B');%0AprintMem(tilemapRaw)%0Aprint('%7D;')%0Aprint()%0A%0Aprint('uint8_t chardata%5B%5D = %7B');%0AprintMem(chardataRaw)%0Aprint('%7D;')%0A

Clean up snes-tile script