// file: lton_file_0.cc
//

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

// isip include files
//
#include "lat_to_nbest.h"
#include "lat_to_nbest_constants.h"

// method: open_file_cc
//
// arguments:
//  FILE*& fp : (output) file pointer
//  char_1* file_name : (input) file name
//  char_1* mode : (input) mode to open the file in
//
// return: a logical_1 flag indicating success
//
// this method opens a file and returns the file pointer -- mainly used
// to allow for polling the disk several times when a file is not found
//
logical_1 open_file_cc(FILE*& fp_a, char_1* file_name_a, char_1* mode_a) {

  // define local variables
  //
  int_4 retry = LTON_WAIT_ITER;
  int_4 delay = LTON_WAIT_TIME;

  // if file does not exist iterate through a sleep loop
  //
  for (int_4 j = 0; j < retry; j++) {

    // open file
    //
    fp_a = fopen((char*)file_name_a, (char*)mode_a);

    // sleep if file not found
    //    
    if (fp_a == (FILE*)NULL) {
      sleep(delay);
    }
    else {
      break;
    }
    
  }

  // error and exit if cannot open file after delay
  //
  if (fp_a == (FILE*)NULL) {
    fprintf(stdout, "Cannot open file %s\n", file_name_a);
    exit(ISIP_PROTO_ERROR);
  }
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
