// file: $USFS/class/image_segmentation/v1.0/imags_get_0.cc
//

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

// isip include files
//
#include "image_segmentation.h"
#include "image_segmentation_constants.h"

// method: get_nmods_cc
//
// arguments:
//   char_1* param_filelist: (input)the parameter file list
//   
// return:
//   a logical_1 value indicating status
//
// this method reads the parameter file list, getting the number of
// models and the model file names
//
logical_1 Image_segmentation::get_nmods_cc(char_1* param_filelist_a) {

  // declaring local variables
  //
  char_1* buf = new char_1[ISIP_MAX_STRING_LENGTH];

  if (buf == (char_1*)NULL) {
    error_handler_cc((char_1*)"get_nmods_cc",
		     (char_1*)"error allocating memory for the temp buf");
    return ISIP_FALSE;
  }  
  memset(buf, (int)0, ISIP_MAX_STRING_LENGTH);

  // open the file list
  //
  FILE* fp = fopen((char*)param_filelist_a, "r");
  
  if (fp == (FILE*)NULL) {
    error_handler_cc((char_1*)"get_nmods_cc",
		     (char_1*)"error opening the parameter file list");
    return ISIP_FALSE;
  }

  // count the number of lines
  //
  while(fgets((char*)buf, ISIP_MAX_STRING_LENGTH, fp) != (char*)NULL) {
    
    // check for comment lines and blank lines
    //
    char_1* nonwhitespace = new char_1[2]; 
    
    if ((buf[0] != ISIP_POUND) &&
	(sscanf((char*)buf, "%1s", nonwhitespace) > (int)0)) {
      num_models_d++;
    }

    // delete memory
    //
    if (nonwhitespace != (char_1*)NULL) {
      delete [] nonwhitespace;
    }
  }

  // delete memory if necessary
  //
  if (param_files_d != (char_1**)NULL) {
    for (int_4 j=0; j<num_models_d; j++) {
      if (param_files_d[j] != (char_1*)NULL) {
	delete [] param_files_d[j];
      }
    }
    delete [] param_files_d;
  }

  // allocate memory for the parameter files
  //
  param_files_d = new char_1*[num_models_d];
  for (int_4 j=0; j<num_models_d; j++) {
    param_files_d[j] = new char_1[ISIP_MAX_STRING_LENGTH];
  }
  
  // rewind the file
  //
  rewind(fp);
  
  int_4 i = 0;

  while(fgets((char*)buf, ISIP_MAX_STRING_LENGTH, fp) != (char*)NULL) {
    
    // checking for a comment line and/or/ a blank line
    //
    char_1* nonwhitespace = new char_1[2];
    
    if ((buf[0] != ISIP_POUND) &&
	(sscanf((char*)buf, "%1s", nonwhitespace) > (int)0)) {
      
      // parse the line
      //
      sscanf((char*)buf, "%s", param_files_d[i++]);
    }

    // delete memory
    //
    if (nonwhitespace != (char_1*)NULL) {
      delete [] nonwhitespace;
    }
  }

  if (buf != (char_1*)NULL) {
    delete [] buf;
  }

  // exit gracefully
  //
  return ISIP_TRUE;
}
