// file: $USFS/util/analyze_image/v6.0/ai_gfs_0.cc
//

// isip include files
//
#include "analyze_image.h"
#include "analyze_image_constants.h"

// method: get_next_filename_cc
//
// arguments:
//   char_1*& fname: (output) next file name
//   int_4 argc: (input) number of arguments
//   char_1** argv: (input) arguments 
//   int_4& pos: (input/output) current position in the argv stream
//
// return: a logical_1 value indicating the number of lines
//
// this method returns a file name one at a time
//
logical_1 get_next_filename_cc(char_1*& fname_a, int_4 argc_a,
			       char_1** argv_a, int_4& pos_a) {
  
  // define global variables
  //
  static FILE* fp;
  static logical_1 flag = ISIP_FALSE;

  // declare a dummy object
  //
  Ppm ppm;
  
  // declare local variables
  //
  char_1* temp_buf = new char_1[ISIP_MAX_STRING_LENGTH];
  int_4 m = 1;
  
  // check if pos is less than the number of arguments
  //
  if (pos_a < argc_a) {
    
    // expanding the filename
    //
    if (ppm.expand_cc(temp_buf, argv_a[pos_a]) == ISIP_FALSE) {
      fprintf(stdout, "%s: error in expanding the filename\n", argv_a[pos_a]);
    }
    
    // check if file is ppm
    //
    if (ppm.is_ppm_cc(temp_buf) == ISIP_TRUE) {
      strcpy((char*)fname_a, (char*)temp_buf);
      m = 0;
      pos_a++;
    }
    
    // if not ppm check if it is a file containing list of ppm files
    //
    else {
      
      // check the flag to open the file for the first time
      //
      if (flag == ISIP_FALSE) { 
	fp = fopen((char*)temp_buf, "r");
      }
      
      // check for the end of the file
      //
      if (fgets((char*)temp_buf, ISIP_MAX_STRING_LENGTH, fp) != (char*)NULL) {
	
	// cut off the newline char
	//
	temp_buf[strlen((char*)temp_buf)-1] = ISIP_NULL;
	
	// check for a comment line and/or blank line
	//
	char_1* nonwhitespace = new char_1[2];
	
	if ((temp_buf[0] != ISIP_POUND) &&
	    (sscanf((char*)temp_buf, "%1s", nonwhitespace) > (int)0)) {

	  char_1* file_name = new char_1[ISIP_MAX_STRING_LENGTH];
	  
	  if (ppm.expand_cc(file_name, temp_buf) == ISIP_FALSE) {
	    fprintf(stdout, "%s: error in expanding the file name\n",
		    temp_buf);
	  }
	  strcpy((char*)fname_a, (char*)file_name);
	  flag = ISIP_TRUE;

	  // delete memory
	  //
	  delete [] file_name;
	}

	// delete memory
	//
	delete [] nonwhitespace;
	
      }
      
      // if end of the line close the file and increment the argument
      //
      else {
	flag = ISIP_FALSE;
	fclose(fp);
	pos_a++;
      }
    }
  }
  
  // to return ISIP_FALSE after reading the arguments
  //
  if ((pos_a == argc_a) && (m == (int)1)) {
    pos_a++;
  }

  // delete memory
  //
  delete [] temp_buf;
  
  // return status
  //
  if (pos_a > argc_a) {
    return ISIP_FALSE;
  }
  else {
    return ISIP_TRUE;
  }
}
