/*

 * scanfont.c Scan Unicode font

 *

 * Function:

 *     Scan a Unicode 2 bits/pixel font and create a binary form.

 *     This routine has minimal error handling and just does a

 *     sanity check on the input.

 */

#include <stdio.h>

#include <string.h>



int main (int argc, char * * argv) {

    int  ch;

    int  mask = 0x80;

    int  out = 0xffff;

    int  uch, w, h, x, y, i, cnt;

    int  line = 0;

    int  ccount = 0;

    int  bitcnt;

    int  comment = 0;

    int  startline = 1;



    FILE * outf = fopen(argv[1], "wb");

    if (!outf) {

        printf("unable to open output file");

    }



    ch = getchar();

    while (ch > 0) {

        if (startline && ch == 'c') {

            if (out != 0xffff) {

                if (mask != 0xC0)

                    fputc(out, outf);

                if (bitcnt)

                    fprintf(stderr, "Bit error at line %d\n", line);

            }

            cnt = scanf("=%x x=%d y=%d w=%d h=%d", &uch, &x, &y, &w, &h);

            if (cnt != 5) {

                fprintf(stderr, "Error at line %d\n", line);

            }

            ccount++;

            fprintf(outf, "\x81%c%c%c%c%c%c%c",

                (uch>>16)&0xff, (uch>>8)&0xff, uch&0xff, w&0xff, h&0xff, x&0xff, y&0xff);

            out = 0;

            bitcnt = w*h;

            mask = 0xC0;

        }

        if (ch=='#') {

            comment = 1;

        }

        if (!comment && ch == '@' || ch == '*' || ch == '+' || ch == '.') {

            if (bitcnt <= 0) {

                fprintf(stderr, "Too many bits at line %d\n", line);

            } else {

                switch (ch) {

                    case '@':   out |= mask;

                        break;

                    case '*':   out |= (mask & 0xAA);

                        break;

                    case '+':   out |= (mask & 0x55);

                        break;

                }

                mask >>= 2;

                if (!mask) {

                    fputc(out, outf);

                    out = 0;

                    mask = 0xC0;

                }

                bitcnt--;

            }

        }

        if (ch == '\n') {

            line++;

            startline = 1;

            comment = 0;

        } else {

            startline = 0;

        }

        ch = getchar();

    }

    if (mask != 0xC0)

        fputc(out, outf);

    if (out != 0xffff) {

        if (bitcnt)

            fprintf(stderr, "Bit error at line %d\n", line);

    }

    fputc(0x01, outf);

    fprintf(stderr, "Character count=%d\n",ccount);

    return 0;

}

