// inout - demonstrate picture I/O in PGM file format
//
// Paul Heckbert	26 Oct. 1998

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

#include <arg.h>	// for arg_parse argument parser
#include <svl/SVL.h>	// simple vector/matrix library
#include "pic.h"	// picture I/O routines

int main(int argc, char **argv) {
    char *infile, *outfile;

    if (arg_parse(argc, argv,
	"%S%S", &infile, &outfile,
	    "input and output image files (PGM)",
    0) < 0)
	exit(1);

    Pic *pic = pic_read(infile, NULL);
    if (!pic) {
	fprintf(stderr, "can't read %s\n", infile);
	exit(1);
    }
    assert(pic->bpp==1);
    // check bytes per pixel (bpp); make sure file was
    // a PGM (portable gray map - grayscale - 1 byte per pixel)
    // and not a PPM (portable pix map - color - 3 bytes per pixel).
    // pic_read can handle PPM, but we can't.

    // width is pic->nx, height is pic->ny
    Mat c(pic->nx, pic->ny);		// create 2-D array of doubles

    printf("created %dx%d Mat\n", c.Rows(), c.Cols());
	// this shows another way to find out size of a "Mat"

    // copy channel 0 (the only channel) of 8-bit-per-pixel "pic"
    // to double precision array "c"
    int x, y;
    for (y=0; y<pic->ny; y++)
	for (x=0; x<pic->nx; x++)
	    c[y][x] = PIC_PIXEL(pic, x, y, 0);

    // just for fun, we'll negate the picture
    for (y=0; y<pic->ny; y++)
	for (x=0; x<pic->nx; x++)
	    c[y][x] = 255-c[y][x];

    // copy back from "c" to "pic", in preparation for file-writing
    for (y=0; y<pic->ny; y++)
	for (x=0; x<pic->nx; x++)
	    PIC_PIXEL(pic, x, y, 0) = c[y][x];

    if (!pic_write(outfile, pic, PIC_PNM_FILE)) {
	fprintf(stderr, "error writing file %s\n", outfile);
	exit(1);
    }
}

