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

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

// isip include files
//
#include "ppm.h"
#include <integral_constants.h>

// method: open_cc
//
// arguments: 
//  char_1* fname_d : (input) image file to be opened
//  int_4 mode : (input) the desired access mode
//
// return: none
//     
// this method openes the image in the given mode and exits
//

logical_1 Ppm::open_cc(char_1* filename_a, int_4 mode_a) {
  
  // check if there is already an open pointer
  //
  if (fp_d != (FILE*)NULL) {
    error_handler_cc((char_1*)"open_cc",
		     (char_1*)"file has not been closed");
  }

  // expand the filename
  //
  char_1 expand_name[ISIP_MAX_STRING_LENGTH];

  if (expand_cc(expand_name, filename_a) == ISIP_FALSE) {
    error_handler_cc((char_1*)"open_cc", (char_1*)"error expanding name");
  }
  
  // mode: readonly
  //
  if (mode_a  == ISIP_READ_ONLY) {
    fp_d = fopen((char*)expand_name, "r");
  }
  
  // mode: write only
  //
  else if (mode_a  == ISIP_WRITE_ONLY) {
    fp_d = fopen((char*)expand_name, "w");
  }
    
  // mode: read plus writing
  //
  else if (mode_a  == ISIP_READ_PLUS) {
    fp_d = fopen((char*)expand_name, "r+");
  }
    
  // mode: write plus read
  //
  else if (mode_a  == ISIP_WRITE_PLUS) {
    fp_d = fopen((char*)expand_name, "w+");
  }
    
  // check if there is an error in opening this file
  //
  if (fp_d == (FILE*)NULL) {
    error_handler_cc((char_1*)"open_cc",
		     (char_1*)"cannot open file");
  }
    
  // save the filename
  //
  if (fname_d != (char_1*)NULL) {
    error_handler_cc((char_1*)fname_d, (char_1*)"fname_d not NULL");
  }
    
  fname_d = new char_1[ISIP_MAX_STRING_LENGTH];
  memset(fname_d,(int)0, ISIP_MAX_STRING_LENGTH);
  strcpy((char*)fname_d, (char*)expand_name);
    
  // load the ppm header for read modes
  //
  if ((mode_a == ISIP_READ_ONLY) || (mode_a == ISIP_READ_PLUS)) {
    if (read_header_cc() == ISIP_FALSE) {
      error_handler_cc((char_1*)"open_cc",
		       (char_1*)"error loading the ppm header");
      return ISIP_FALSE;
    }
  }
  
  // exit gracefully
  //
  return ISIP_TRUE;
}




