// file: $USFS/class/ppm/v1.0/ppm_read_0.cc
//

// isip include files
//
#include "ppm.h"

#include <integral_constants.h>
#include "ppm_constants.h"

// method: read_header_cc
//
// arguments: none
//
// return:
//  a logical_1 value indicating the status
//
// this method loads the following information appearing at the
// beginning of the ppm file:
//
//  magic number
//  width height (width and height of image)
//  max_colors (number of colors)
//
// it also checks the magic number and returns ISIP_FALSE if the
// image is not of the format P6.
//
// ppm headers must have three lines containing the above information,
// and can have an arbitrary number of comments consisting of lines beginning
// with "#"
//
logical_1 Ppm::read_header_cc() {

  // declare some scratch space large enough to hold all possible
  // strings encountered in the header
  //
  char_1* tmp_string = new char_1[ISIP_MAX_STRING_LENGTH];

  // loop until done
  //
  int_4 num_lines_needed = PPM_HEADER_NUM_LINES;
  int_4 num_lines = 0;

  while(num_lines < num_lines_needed) {

    // read a line
    //
    fgets((char*)tmp_string, ISIP_MAX_STRING_LENGTH-1, fp_d);

    // check for a comment field
    //
    if (tmp_string[0] != PPM_HEADER_COMMENT_CHAR) {

      // check for the magic number
      //
      if (num_lines == (int_4)0) {
	magic_number_d = new char_1[strlen((char*)tmp_string) + 1];
	sscanf((char*)tmp_string, (char*)PPM_HEADER_R0, magic_number_d);

	// check the magic number
	//
	if (strcmp((char*)magic_number_d, (char*)PPM_MAGIC_NUMBER) != (int)0) {
	  return ISIP_FALSE;
	}
      }

      // check for the image sizes
      //
      else if (num_lines == (int_4)1) {
	sscanf((char*)tmp_string, (char*)PPM_HEADER_R1, &width_d, &height_d);
	if ((width_d < (int_4)0) || (height_d < (int_4)0)) {
	  return ISIP_FALSE;
	}
      }

      // read max_colors 
      //
      else if (num_lines == (int_4)2) {
	sscanf((char*)tmp_string, (char*)PPM_HEADER_R2, &max_colors_d);
	if (max_colors_d < (int_4)0) {
	  return ISIP_FALSE;  
	}
      }

      // we appear to have found a valid line
      //
      num_lines++;
    }
  }

  // set the file position
  //
  beg_d = ftell(fp_d);

  // release memory
  //
  delete [] tmp_string;

  // exit gracefully
  //
  return ISIP_TRUE;
}
