#include <stdio.h>
#include <unistd.h>

/*
 * This program extracts JPEG files from another file.
 * The JPEG files are written as 001.jpg etc to the current directory.
 * The input file should be given on the command line.
 */
int
main(int argc, char** argv) {
    char name[100];
    int n = 1;
    int x, y, last;
    int size, zeros;
    FILE* in;
    FILE* out;

    if (argc == 1) {
        fprintf(stderr, "Usage: %s inputfile\n", argv[0]);
        return 1;
    }

    in = fopen(argv[1], "r");
    if (in == NULL) return 1;

    zeros = size = last = 0;
    out = 0;
    while (1) {
        while ((y = fread(&x, 4, 1, in)) == 1 && x != 0xe0ffd8ff
                && x != 0xe1ffd8ff) {
            if (out && fwrite(&x, 4, 1, out) != 1) {
                fprintf(stderr, "could not write %s\n", name);
                return 1;
            }
            if (x == 0) {
                zeros += 4;
            } else {
                last = x;
                zeros = 0;
            }
            size += 4;
        }
        if (y != 1) break;
        if (out) {
            if (fclose(out)) {
                fprintf(stderr, "could not close %s\n", name);
                return 1;
            }
            if (last == 0x000000d9) {
                zeros += 3;
            } else if (last == 0x0000d9ff) {
                zeros += 2;
            } else if ((last & 0xffd9ff00) == 0x00d9ff00) {
                zeros += 1;
            }
            if (truncate(name, size-zeros)) return 1;
        }
        
        sprintf(name, "%.3i.jpg", n++);
        fprintf(stderr, "%s\n", name);
        out = fopen(name, "w");
        if (out == NULL) {
            fprintf(stderr, "could not open %s\n", name);
            return 1;
        }
        size = 4;
        zeros = 0;
        if (fwrite(&x, 4, 1, out) != 1) {
            fprintf(stderr, "could not write %s\n", name);
            return 1;
        }
    }

    fclose(in);

    return 0;
}
