
/* 'BM' IMAGE_COLORMASK リソースから 'IV' リソース に変換 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <windows.h>   /* 単に BYTE とか使いたいだけ */
#include <pshpack1.h>  /* 構造体をパッキングしたいので */

/* WW の 新しい resource.h が必要です */
#include "resource.h"


/* ivram.h より */


#define IV_CHARINFO_OPAQUE     0x01   /* 透明部分なし */
#define IV_CHARINFO_NORENDER   0x02   /* 完全に透明 */

/* 'IV' リソース */

#define IV_RESID_IMAGE 0x5649   /* 'IV' */

#define IV_RESFORMAT_COLOR3  0x01
#define IV_RESFORMAT_COLOR4  0x02  /* 予約 */

/* res_image_t と基本的に同じ */

typedef struct {
    res_t header;
    BYTE  width;
    BYTE  height;
    BYTE  format;       /* IV_RESFORMAT_xx */
    BYTE  reserve;
    BYTE  clrtable[4];
} iv_res_image_t;





BYTE srcbuf[16384];  /* 手抜きだね */
BYTE destbuf[16384];



void err(const char* p)
{
    puts(p);
    exit(1);
}


int main(int ac, char* av[])
{
    FILE* fp;
    res_image_t* res;
    iv_res_image_t* resiv;
    WORD* ps;
    BYTE* pcharinfo;
    WORD* pchardata;
    WORD w, mask, allmask1, allmask2;
    int i, j, charmax;
    unsigned int size;
    BYTE info;

    if (ac < 3) {
        err("usage: bm2iv bmp.fr bmp.iv");
    }

    if ((fp = fopen(av[1], "rb")) == NULL) {
        err("ファイルを開くことが出来ません");
    }
    fread(srcbuf, sizeof(srcbuf), 1, fp);
    fclose(fp);

    res = (res_image_t*)srcbuf;
    if (res->header.magic != RESID) {
        err("リソースじゃないです");
    }
    if (res->header.type != RESID_IMAGE) {
        err("'BM'リソースじゃないです");
    }
    if (res->format != IMAGE_COLORMASK) {
        err("3color+BGタイプではないです");
    }

    memcpy(destbuf, srcbuf, sizeof(res_image_t));
    resiv = (iv_res_image_t*)destbuf;
    resiv->header.type = IV_RESID_IMAGE;
    resiv->format = IV_RESFORMAT_COLOR3;
    charmax = (int)resiv->width * (int)resiv->height;

    ps = (WORD*)(srcbuf + sizeof(res_image_t));
    pcharinfo = destbuf + sizeof(iv_res_image_t);
    pchardata = (WORD*)(pcharinfo + charmax);
    for (i = 0; i < charmax; i++) {
        allmask1 = 0;
        allmask2 = 0xFFFF;
        for (j = 0; j < 8; j++) {
            w = *ps++;
            mask = ((w >> 8) | w) & 0xFF;
            mask |= (mask << 8);
            allmask1 |= mask;
            allmask2 &= mask;
            *pchardata++ = ~mask;
            *pchardata++ = w;
        }
        info = 0;
        if (allmask1 == 0) {
            info = IV_CHARINFO_NORENDER;
        } else if (allmask2 == 0xFFFF) {
            info = IV_CHARINFO_OPAQUE;
        }
        *pcharinfo++ = info;
    }

    size = sizeof(iv_res_image_t) + charmax + charmax * 32;
    size = (size + 0x0F) & 0xFFF0;
    resiv->header.size = (WORD)(size >> 4);

    if ((fp = fopen(av[2], "wb")) == NULL) {
        err("ファイルを開くことが出来ません");
    }
    fwrite(destbuf, size, 1, fp);
    fclose(fp);

    return 0;
}


