// file: $USFS/util/ppm_print/v1.0/ppm_print.cc
//
// a program that reads a region of an image and prints it to stdout.
//

// isip include files
//
#include "ppm_print.h"
#include <ppm.h>
#include <ppm_constants.h>

// main program
//
int main(int argc, char** argv) {

  // declare command line arguments
  //
  int_4 width = PPM_DEFAULT_W;
  int_4 height = PPM_DEFAULT_H;
  int_4 woff = PPM_DEFAULT_WOFF;
  int_4 hoff = PPM_DEFAULT_HOFF;
  char_1 file[ISIP_MAX_FNAME_SIZE];

  // declare an object
  //
  Ppm ppm;

  // parse the command line
  //
  if (get_parameters_cc(argc, argv,
			width, height, woff, hoff, file) == ISIP_FALSE) {
    fprintf(stdout, "%s: error in command line arguments\n", argv[0]);
    return ISIP_ERROR;
  }

  // open the file
  //
  if (ppm.open_cc(file, ISIP_READ_ONLY) == ISIP_FALSE) {
    return ISIP_ERROR;
  }

  // get information about the image
  //
  if (width < (int_4)0) {
    width = ppm.get_width_cc();
  }
  if (height < (int_4)0) {
    height = ppm.get_height_cc();
  }

  // define a block size and associated buffers
  //
  int_4 bsize = width * height;
  uint_1 b_red[bsize];
  uint_1 b_green[bsize];
  uint_1 b_blue[bsize];  

  // get a sub-image
  //
  if (ppm.read_cc(b_red, b_green, b_blue,
		  woff, hoff, width, height) == ISIP_FALSE) {
    fprintf(stdout, "%s: error reading the image\n", argv[0]);
  }

  // dump the values to standard out
  //
  int_4 m = (int_4)0;

  fprintf(stdout, "width offset = %ld pixels\n", woff);
  fprintf(stdout, "height offset = %ld pixels\n", hoff);
  fprintf(stdout, "\n");

  for (int_4 k=0; k<height; k++) {
    for (int_4 l=0; l<width; l++) {
      fprintf(stdout,
	      "(%5.5ld %5.5ld) r:%3.3u g:%3.3u b:%3.3u\n",
	      hoff+k, woff+l, b_red[m], b_green[m], b_blue[m]);
      m++;
    }
  }

  // close the file
  //
  ppm.close_cc();

  // exit gracefully
  //
  fprintf(stdout, "\n<end of program %s>\n", argv[0]);

  return ISIP_NO_ERROR;
}

