#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

//
// Raw to RLE (run length encoded) converter
//

typedef unsigned char byte;

int Encode(byte *pix, byte *rle) {
    int nbytes = 0;
    byte curbyte = *pix;
    int howmany = 0;
    byte *dest = rle;
    byte *src = pix;

    for (;;) {
        if (pix - src == 320*200) {
            *dest++ = howmany;
            *dest++ = curbyte;
            *dest++ = 0;
            *dest++ = 0;
            return dest - rle;
        }
        if (howmany == 255) {
            *dest++ = howmany;
            *dest++ = curbyte;
            howmany = 0;
            curbyte = *pix;
            continue;
        }

        if (*pix != curbyte) {
            *dest++ = howmany;
            *dest++ = curbyte;
            howmany = 0;
            curbyte = *pix;
            continue;
        } else {
            howmany++;
            pix++;
        }
    }
}


main(int argc, char *argv[]) {
    FILE *fdin, *fdout;
    byte *buf;
    byte *buf2;
    int size;

    if (argc != 3) {
        printf("CONVERT <pixfile> <outfile>\n");
        return 1;
    }
    fdin = fopen(argv[1], "rb");
    if (!fdin) {
        printf("Cannot openread\n");
        return 1;
    }
    fdout = fopen(argv[2], "wb");
    if (!fdout) {
        printf("Cannot create\n");
        return 1;
    }
    buf = malloc(320*200);
    buf2 = malloc(100000);
    if (!buf || !buf2) {
        printf("outamem\n");
        return 1;
    }
    if (fread(buf, 320, 200, fdin) != 200) {
        printf("Cannot read\n");
        return 1;
    }
    fclose(fdin);

    size = Encode(buf, buf2);
    fwrite(buf2, 1, size, fdout);
    fclose(fdout);
    printf("ok");
    return 0;
}

