// file: $USFS/class/image_analysis/v6.0/imaga_get_3.cc
//

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

// isip include files
//
#include "image_analysis.h"
#include "image_analysis_constants.h"

// method: get_nmods_cc
//
// arguments:
//   int_4& num_models: (output) number of model files
//   char_1**& param_files: (output) list of the parameter files
//   char_1* filenames_file: (input) file containing the list of parameter files
//
// return: a logical_1 value indicating the number of lines
//
// this method reads the name of the model files into the array param_files_a
//
logical_1 Image_analysis::get_nmods_cc(int_4& num_models_a,
				       char_1**& param_files_a,
				       char_1* filenames_file_a) {
  
  // declaring local variables
  //
  int_4 i = 0;
  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 to the temp buf");
    return ISIP_FALSE;
  }
  
  memset(buf, (int)0, ISIP_MAX_STRING_LENGTH);

  // open the file
  //
  FILE* fp = open_cc(filenames_file_a, ISIP_READ_ONLY);
  
  if (fp == (FILE*)NULL) {
    error_handler_cc((char_1*)"get_nmods_cc",
		     (char_1*)"error opening the parameter filenames");
    return ISIP_FALSE;
  }

  // count the number of lines
  //
  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)) {
      num_models_a++;
    }

    // delete memory
    //
    delete [] nonwhitespace;
  }

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

  // allocate memory for the parameter files
  //
  param_files_a = new char_1*[num_models_a];
  for (int_4 j=0; j<num_models_a; j++) {
    param_files_a[j] = new char_1[ISIP_MAX_STRING_LENGTH];
  }
  
  // rewind the file
  //
  rewind(fp);
  
  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_a[i++]);
    }

    // delete memory
    //
    delete [] nonwhitespace;
  }

  if (buf != (char_1*)NULL) {
    delete [] buf;
  }
  
  // exit gracefully
  //
  return ISIP_TRUE;
}




