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

// system include files
//
#include <string.h>

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

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

// method: write_header_cc
//
// arguments:
//    int_4 width_a (output): the image width in pixels
//    int_4 height_a (output): the image height in pixels
//    int_4 max_colors_a (output): the largest color in the image
//
// return: a logical_1 to indicate status
//
// this method writes the following information at the
// beginning of the ppm file:
//
//  magic number
//  width height (width in pixels x height in pixels)
//  max_colors (number of colors)
//
//
logical_1 Ppm::write_header_cc(int_4 width_a, int_4 height_a,
			       int_4 max_colors_a) {

  // check for the range of max color
  //
  if (max_colors_a < (int_4)0 || max_colors_a > PPM_MAX_COLOR) {
    return ISIP_FALSE;
  }
    
  // save these values
  //
  if (magic_number_d != (char_1*)NULL) {
    delete [] magic_number_d;
    magic_number_d = (char_1*)NULL;
  }

  magic_number_d = new char_1[strlen((char*)PPM_MAGIC_NUMBER) + 1];
  strcpy((char*)magic_number_d, (char*)PPM_MAGIC_NUMBER);

  width_d = width_a;
  height_d = height_a;
  max_colors_d = max_colors_a;

  // write the header consisting of magic_number in one line, width and height
  // in one line and the max_color in the other line
  //
  fprintf(fp_d, (char*)PPM_HEADER_W, (char*)magic_number_d,
	  width_d, height_d, max_colors_d);

  // read and set the beginning of the image data
  //
  beg_d = ftell(fp_d);
  
  // create a buffer of zeros
  //
  int_4 num_bytes = width_a*height_a*PPM_NBYTES_PER_PIXEL;
  uint_1 zeros[num_bytes];
  memset(zeros, (int)0, num_bytes*sizeof(uint_1));

  // write the file with zeros so that incremental reads and writes
  // can be performed
  //
  if (fwrite(zeros, sizeof(uint_1), num_bytes, fp_d) != (size_t)num_bytes) {
    return ISIP_FALSE;
  }

  // seek to the beginning of the file
  //
  fseek(fp_d, beg_d, SEEK_SET);

  // exit gracefully
  //
  return ISIP_TRUE;
}



