/*
 * jpeginfo.c
 * Part of jpeginfo, a small tool to show properties of jpeg images.
 */
   
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <jpeglib.h>

int main (int argc, char **argv) {
    struct jpeg_decompress_struct cinfo;
    struct jpeg_error_mgr jerr;
    int i;
    FILE *inf;
    
    /* Verify argument list */
    if (argc < 2) {
	fprintf (stderr,
"\n"		 
"This is jpeginfo V" VER ", copyright (c) Karel Kubat <karel@kubat.nl>.\n" 
"Visit http://www.kubat.nl/pages/jpeginfo for downloads and information.\n"
"Usage: jpeginfo jpegfile(s)\n"
"Shows properties of the stated file(s). Use '-' for stdin.\n"
"\n");		 
	exit (1);
    }

    /* Process all files. */
    for (i = 1; i < argc; i++) {
	cinfo.err = jpeg_std_error (&jerr);
	jpeg_create_decompress (&cinfo);

	printf ("%s: ", argv[i]);
        fflush (stdout);
	
	if (!strcmp (argv[i], "-"))
	    jpeg_stdio_src (&cinfo, stdin);
	else if (! (inf = fopen (argv[i], "r")) ) {
	    fprintf (stderr, "Cannot read %s: %s\n", argv[i], strerror(errno));
	    exit (1);
	} else
	    jpeg_stdio_src (&cinfo, inf);

	jpeg_read_header (&cinfo, TRUE);

	printf ("%u x %u / %d components / ",
		cinfo.image_width, cinfo.image_height,
		cinfo.num_components);
	switch (cinfo.jpeg_color_space) {
	case JCS_GRAYSCALE:
	    printf ("monochrome");
	    break;
	case JCS_RGB:
	    printf ("red/green/blue");
	    break;
	case JCS_YCbCr:
	    printf ("Y/Cb/Cr");
	    break;
	case JCS_CMYK:
	    printf ("C/M/Y/K");
	    break;
	case JCS_YCCK:
	    printf ("Y/Cb/Cr/K");
	    break;
	default:
	    printf ("unknown");
	}
	putchar ('\n');
	
	jpeg_destroy_decompress (&cinfo);
	if (strcmp (argv[i], "-"))
	    fclose (inf);
    }

    /* All done */
    return (0);
}
