static void bg_dopalette() {
        int offs;
        int color, code, i;
        int[] colmask = new int[32];
        int pal_base;

        pal_base = Machine.drv.gfxdecodeinfo[0].color_codes_start;

        for (color = 0; color < 32; color++) {
            colmask[color] = 0;
        }

        for (offs = aerofgt_bg1videoram_size[0] - 2; offs >= 0; offs -= 2) {
            code = aerofgt_bg1videoram.READ_WORD(offs);
            color = ((code & 0xe000) >> 13) + 8 * charpalettebank;
            code = (code & 0x07ff) + (gfxbank.read(0 + ((code & 0x1800) >> 11)) << 11);
            colmask[color] |= Machine.gfx[0].pen_usage[code];
        }

        for (offs = aerofgt_bg2videoram_size[0] - 2; offs >= 0; offs -= 2) {
            code = aerofgt_bg2videoram.READ_WORD(offs);
            color = ((code & 0xe000) >> 13) + 16;
            code = bg2_chardisplacement + (code & 0x07ff) + (gfxbank.read(4 + ((code & 0x1800) >> 11)) << 11);
            colmask[color] |= Machine.gfx[0].pen_usage[code];
        }

        for (color = 0; color < 32; color++) {
            for (i = 0; i < 16; i++) {
                if ((colmask[color] & (1 << i)) != 0) {
                    palette_used_colors.write(pal_base + 16 * color + i, PALETTE_COLOR_USED);
                }
            }
            /* bg1 uses colors 0-7 and is not transparent */
            /* bg2 uses colors 16-23 and is transparent */
            if (color >= 16 && (colmask[color] & (1 << 15)) != 0) {
                palette_used_colors.write(pal_base + 16 * color + 15, PALETTE_COLOR_TRANSPARENT);
            }
        }
    }