/* topgm.c */
/* make a pgm file from untar-ed mtsat files */

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

#define WIDTH 2750
#define HEIGHT1 275
#define HEIGHT 2750

void
skipheader(FILE *fi) {
    int a, b;

    while (1) {
        a = fgetc(fi);
        b = fgetc(fi)*256 + fgetc(fi);
        fseek(fi, (long)(b-3), SEEK_CUR);
        if (a == 132) break;
    }
}

main(int argc, char *argv[]) {
    char foname[255];
    int fonamelen;
    long int fisize, i, j;
    char *sp;
    int a, b, x;
    FILE *fi, *fo;

    if (argc < 11) {
        fprintf(stderr, "Usage: %s file1 file2 ... file10\n", argv[0]);
        exit(1);
    }
    strcpy(foname, argv[1]);
    fonamelen = strlen(foname);
    sp = (char *)foname + fonamelen - 2;
    strcpy(sp, ".pgm");
    fo = fopen(foname, "w");
    fprintf(fo, "P5\n%d %d\n255\n", WIDTH, HEIGHT);
    fisize = WIDTH * HEIGHT1;
    for (i=1; i<=10; i++) {
        fi = fopen(argv[i], "r");
        skipheader(fi);
        for (j=0; j<fisize; j++) {
            a = fgetc(fi);
            b = fgetc(fi);
            x = ((a << 6) & 0xc0) | ((b >> 2) & 0x3f);
            fputc(x, fo);
        }
        fclose(fi);
    }
    fclose(fo);
}
