// file: $isip/util/demo/isip_comm_server_dialog_database/web_interface.cc
// version: $Id: web_interface.cc 10086 2005-05-17 19:59:26Z elliott $
//

// standard include file
//

// local include file
//
#include "isip_comm_dialog_navigation_db.h"
#include "web_interface.h"
#include "mysql_interface.h"

// PERL_PATH and PERL_SCRIPT are defined in
// isip_comm_dialog_navigation_db_globals.cc
//
//#define PERL_PATH "$ISIP_DEVEL/util/demo/isip_comm_server_dialog_navigation_db/perl/"
//#define PERL_SCRIPT "web_access.perl"

// the two files everytime are flatmap_%i
// the two files everytime are flatmap_%i.done
// where %i is a unique number
//
#define FILE_COUNT     2

// Not used anymore. Now in global 'char clean_up_string[]'
//
/*
  #define OUTPUT_PATH "/tmp/"
  #define RM_RF_FILES_STRING "rm -rf " \
	   OUTPUT_PATH "*.done " \
	   OUTPUT_PATH "flatlocation* " \
	   OUTPUT_PATH "flat_map_* " \
	   OUTPUT_PATH "flat_*_val* " \
	   OUTPUT_PATH "flatmap_* " \
	   OUTPUT_PATH "outpage_0.html"
*/

// Only function accessible by outside files\functions is
//   int update_tables_from_web()
// prototype is in web_interface.h

// Functions private to this file
//
int read_and_insert_map_result(char *filename, MYSQL *myData);
int read_and_insert_address_result(char *filename, int flag, MYSQL *myData);
int read_and_insert_place_result(char *filename, MYSQL *myData);

int process_web_map_request(Gal_Frame frame, char *hotel, MYSQL *myData);
int process_web_address_request(Gal_Frame frame, char *hotel, MYSQL *myData);
int process_web_direction_request(Gal_Frame frame, char *hotel, MYSQL *myData);

int insert_row_into_map(char *start_name, char *start_add,
			char *start_interest, char *start_city,
			char *start_state, char *start_zip,
			char *end_name, char *end_add,
			char *end_interest, char *end_city, 
			char *end_state, char *end_zip, char *distance,
			char *time, char *directions, char *totaldistance,
			int index, MYSQL *myData);

#define SIZE_OF_FILENAME  200

//int run_command_and_wait(char *command, char **files_to_wait, int num_files,
int run_command_and_wait(char *command, char files_to_wait[][SIZE_OF_FILENAME],
			 int num_files, int time_out_sec = TIME_OUT_SECONDS);
int get_flatfile_param(char *line, char *tmp, int sizeof_tmp);
int replace_with_plus(char *line);

int process_query_for_single_entry(MYSQL *myData, char *SQLQuery,
				   MYSQL_ROW *row_zero,
				   MYSQL_RES **sql_result);

// function: update_tables_from_web
//
// arguments:
//  Gal_Frame frame: (input) frame to get properties/info from about this query
//  void *server_data: (input) the connection to the Hub for writing frames to
//                     it without having to return them.
//  MYSQL *myData_in: (input) connection to a MYSQL database
//
// return: TODO. (check process_XXX_blah) to verify
//
// This function will take a frame and extract the information out of it.
// Then depending on the type of frame it will call it to the specific
// handling function.
//
// This is the only function in this file which is visible to the outside code.
//
int update_tables_from_web(Gal_Frame frame, void *server_data,
			   MYSQL *myData_in) {
  
  // MYSQL Variables -- this is the only connection made in this file
  //
  MYSQL *myData = myData_in;
  
  char **props;
  char *drive = NULL;
  char *task = NULL;
  char *db_query = NULL;
  
  int i = 0;
  int num_keys = 0;
  int result = 0;
 
  printf("\nupdate table from web starts =:\n");
  fflush(stdout);

  //*----------- get the keys from the input frame --------------------
  
  props = Gal_GetProperties(frame, &num_keys);
  printf("\nupdate tables from web routine keys total = %i\n", num_keys);
  
  for (i = 0; i < num_keys; i++) { 
    printf("total keys[%i] this key[%i] name[%s]\n", num_keys, i, props[i]);
    
    if (strcmp(props[i],":task") == 0)
      task = Gal_GetString(frame, ":task");
    else if (strcmp(props[i],":db_query") == 0)
      db_query = Gal_GetString(frame, ":db_query");
    //    else if (strcmp(props[i],":leg1") == 0)
    //       leg1 = Gal_GetString(frame, ":leg1");
    //    else if (strcmp(props[i],":leg2") == 0)
    //       leg2 = Gal_GetString(frame, ":leg2");
    //    else if (strcmp(props[i],":leg3") == 0)
    //       leg3 = Gal_GetString(frame, ":leg3");
    //    else if (strcmp(props[i],":leg4") == 0)
    //       leg4 = Gal_GetString(frame, ":leg4");
    else if (strcmp(props[i],":Query_Address") == 0)
      drive = Gal_GetString(frame, ":Query_Address");
    else if (strcmp(props[i],":Query_List") == 0)
      drive = Gal_GetString(frame, ":Query_List");
    else if (strcmp(props[i],":Query_Direction") == 0)
      drive = Gal_GetString(frame, ":Query_Direction");
    else if (strcmp(props[i],":Query_Distance") == 0)
      drive = Gal_GetString(frame, ":Query_Distance");
    else if (strcmp(props[i],":query_params") == 0)
      drive = Gal_GetString(frame, ":query_params");
    //    else if (strcmp(props[i],":car") == 0)
    //       car = Gal_GetString(frame, ":car");
    else if (strcmp(props[i],":access_web") == 0 ||
	     strcmp(props[i],":session_id") == 0) {
      // do nothing, don't care about them, but don't want them
      // to show up down below
    }
    else {
      printf("update_tables_from_web-- looking through properties, and "
	     "found [%s] that was not examined by update_tables_from_web()\n",
	     props[i]);
    }
  }
  
  fflush(stdout);
  
  //------------ process a web request --------------
  
  result = 0;

  if (strcmp(task, "Query_Address") == 0)
    result = process_web_address_request(frame, drive, myData);

  else if (strcmp(task, "Query_List") == 0)
    result = process_web_address_request(frame, drive, myData);

  else if (strcmp(task, "drive") == 0)
    result = process_web_direction_request(frame, drive, myData);

  else 
    result = process_web_direction_request(frame, drive, myData);

  // don't close this anymore because we have only a single connection
  // if you comment this in, this galaxy server dies a crashy death
  // mysql_close(myData);

  // This is called after each call from above so having it in this one
  // place will make sure that it is cleaned up
  //
  if (remove_output_files) {
    system(clean_up_string);
  }
  
  return(result);
}

// function: get_flatfile_param
//
// arguments:
//  char *line: (input) line that contains the input line
//  char *out_str: (output) buffer to get the new data
//  int sizeof_out: (input) the size of the out_str that is safe to write
//  const VectorFloat& input: (input) input data
//
// return: -1 = something bad happened
//          1 = successful return
//
// This function will take in a line of data such as
// [name:         Walmart]
// and return 'Walmart'
//
// That data will have leading and trailing spaces removed and all
// single quotes turned into \' so that is database safe
//
// Note: This function will return from first space on. Make sure none
// of the parameter files use a space.
// GOOD[ telephone          6019174469]
// BAD [ telephone number   6019174469]
//
int get_flatfile_param(char *line, char *out_str, int sizeof_out) {
  
  if (line == NULL) {
    printf("ERROR! get_flatfile_param received null input in 'line'\n");
    fflush(stdout);
    return -1;
  }
  
  if (out_str == NULL) {
    printf("ERROR! get_flatfile_param received null input in 'line'\n");
    fflush(stdout);
    return -1;
  }
  
  int i, len;
  int x;
  char temp[60];
  
  // get length
  //
  len = (int)strlen(line);
  
  // check for newline and remove it
  //
  if (line[len-1] == '\n')
    line[len-1] = '\0';
  
  // and do it again
  //
  len = (int)strlen(line);
  
  //EXAMPLE LINE:
  //building text right here
  
  // find first white space
  // ex. between 'building' and 'text'
  for (i = 0; (i<len) && (line[i] != ' '); )
    i++;
  
  // now find next non-white space
  // ex. point to the 't' in 'text' above
  while((i<len) && (line[i] == ' '))
    i++;
  
  // See if it went over the bounds
  //
  if (i < len) {
    //copy from the current position in line
    //ex, the 't' in text
    //to the 'temp' variable
    strcpy(temp, line+i);
  }
  else{
    temp[0] = '\0';
  }
  
  // remove trailing white space
  for (x = strlen(temp) - 1; temp[x]==' ' || temp[x]=='\n'; --x);
  temp[x + 1]='\0';
  
  char *c = temp;
  for (;;) {
    // Find the next '
    //
    c = strchr(c,'\'');
    // If there isn't one, break out of loop
    //
    if (!c)
      break;
    
    // We are pointing at a ' so first make sure the buffer is
    // large enough to hold it
    if (len+1 < sizeof_out && len+1 < (int)sizeof(temp)) {
      len++;
      // c is later in memory than temp so (c-temp) is the
      // length that we are into the string
      // len - (c-temp) is the number of characters left in the
      // word
      // the "+1" is there for the final null char
      memmove(c+1, c, len-(int)(c-temp)+1);
      *c = '\\';
      // Now move past the ' or else we will have an infinite loop
      c += 2;
    }
    else {
      printf("Ran out of buffer room with text [%s]\n",temp);
      //exit(-1);
      return -1;
    }
  }
  
  // One final buffersize check
  if ((int)strlen(temp) < sizeof_out) {
    strcpy(out_str,temp);
  }
  else {
    printf("Ran out of buffer room with text [%s]\n",temp);
    //    exit -1 ;
    return -1;
  }
  
  printf("after replace ' with \\'[%s]\n", out_str);

  return 1;
}

// function: replace_with_plus
//
// arguments:
//  char *line: (input\output) string to replace spaces
//
// return: -1 = something bad happened
//          1 = successful return
//
// This function will take in a line of data such as
// [Walmart Super] and change all spaces to plus such [Walmart+Super].
// The trailing whitespace (' ','\n') is also removed.
//
// Note: This function will bomb if 'line' cannot be written to, but then again
// why would this function be called if 'line' cannot be written to?
//
int replace_with_plus(char *line) {
  
  if (line == NULL) {
    printf("ERROR! replace_with_plus received null input in 'line'\n");
    fflush(stdout);
    return -1;
  }
  
  char *c;
  int x;
  
  //printf("before replace with plus [%s]\n",line);
  
  // remove trailing white space   
  for (x = strlen(line)-1; line[x]==' ' || line[x]=='\n'; --x);
  line[x+1]='\0';
  
  // For each character, if its a space, replace with a '+'
  for (c = line; *c ; c++) {
    if (*c == ' ')
      *c = '+';
  }
  
  //printf("after replacing [%s]\n", line);

  return 1; 
}

// function: replace_with_plus
//
// arguments:
//   char *command (input) - string with command to execute "ls -l > a.1"
//   char files_to_wait[][size] (input) - two dim array of files to wait for
//   int num_files (input) - number of files in 'files_to_wait'
//   int time_out_sec (input) - number of seconds to wait (default: 60)
//
// return:  -1 = something bad happened
//         >=0 = number of files showed up successfully
//
//
// Returns how many of the files have been returned.
// Return code when no errors occur is the same as the input 'num_files'
// This function will execute a command and then wait time_out_sec seconds
// for them all to show up. It will return the total number of files
// present, or -1 if there is an error.
//
int run_command_and_wait(char *command, char files_to_wait[][SIZE_OF_FILENAME],
			 int num_files, int time_out_sec) {

  // Error check the parameters
  if (command == NULL) {
    printf("ERROR! run_command_and_wait received null input in 'command'\n");
    fflush(stdout);
    return -1;
  }
  
  if (files_to_wait == NULL) {
    printf("ERROR! run_command_and_wait received null input "
	   "in 'files_to_wait'\n");
    fflush(stdout);
    return -1;
  }
  
  if (num_files == 0) {
    printf("ERROR! run_command_and_wait received '0' as num_files\n");
    fflush(stdout);
    return -1;
  }
  
  int num_pending = num_files;
  int num_responding = 0;
  int i = 0;
  int time_out;
  struct stat stbuf;
  
  // More error checking to make sure the filenames array exists
  //
  for (i = 0; i < num_files; i++) {
    if (files_to_wait[i] == NULL) {
      printf("ERROR! run_command_and_wait received null input "
	     "in 'files_to_wait[%i]'\n", i);
      fflush(stdout);
      return -1;
    }
  }
  
  printf("---------------------------\n");
  printf("%i files are pending\n", num_files);
  printf("---------------------------\n");
  fflush(stdout);

  // Actually make the call
  //
  change_state(WAITING_FOR_WEB_RESULT, NULL);
  int sysret = system(command);
  printf("System returned [%i] on call [%s]\n", sysret, command);
  fflush(stdout);
  
  for (time_out = time_out_sec;
       (time_out > 0) && (num_pending != num_responding);
       time_out--) {
    
    //debug
    printf("time_out=[%d]\n", time_out);
    fflush(stdout);
    //debug
    
    // Set number of responding to 0
    //
    num_responding = 0;
    
    // For each file we are waiting on, see if we can get a stat on it
    // 
    for(i = 0; i < num_files; i++) {
      //debug
      printf("[%s-",files_to_wait[i]);
      
      if (stat(files_to_wait[i], &stbuf) == 0) {
	num_responding++;
	//debug
	printf("yep] \n");
      }
      else {
	//debug
	printf("nope] \n");
      }
      //debug
      fflush(stdout);
    }
    // Decrease timeout
    //
    time_out--;
    
    // If we haven't found all the files we want, sleep for a bit
    if (num_responding != num_pending)
      sleep(2);
  }

  // The web call is all done now so return self to PROCESSING_WEB_QUERY
  // state
  //
  change_state(PROCESSING_WEB_QUERY, NULL);

  sleep(2);
  return num_responding;
}

// function: read_and_insert_address_result
//
// arguments:
//  char *filename: (input) filename of source file to read
//  int flag: (input) whether or not business_name is empty
//  MYSQL *myData: (input) connection to a MYSQL database
//
// return: -1 = something bad happened
//          0 = successful return
//
// This function will read a text file and look to see if the data is
// already in the database. If it is not it will insert it.
//
// The layout of the expected file is:
//  print DATA "name           $location     
//  print DATA "specification  $business_spe 
//  print DATA "type           $business_type
//  print DATA "address        $local_address
//  print DATA "city           $cityname     
//  print DATA "state          $statename    
//  print DATA "telephone      $location     
//  print DATA "miles          $mile     
//  print DATA "refer_name     $ref_name 
//  print DATA "refer_add      $ref_add  
// and is generated from the "web_address" perl script call.
//
int read_and_insert_address_result(char *filename, int flag, MYSQL *myData) {
  
  MYSQL_RES *res = NULL;
  MYSQL_ROW row = NULL;
  char SQLQuery[2048];
  int k;
  int x;
  int exist = 0;
  unsigned int num_fields = 0;
  unsigned int i;
  MYSQL_FIELD *fields;
  
  int counter = 0;
  
  FILE *fid;
  char name[60];
  char business_spe[60];
  char business_type[60];
  char address[60];
  char city[60];
  char state[60];
  char telephone[60];
  char distance[20];
  char ref_name[60];
  char ref_add[60];
  
  int row_count;
  char line[101];

  // Error check the input
  //
  if (filename == NULL) {
    printf("ERROR! read_and_insert_address_result received null input "
	   "in 'filename'\n");
    fflush(stdout);
    return -1;
  }
  
  if (myData == NULL) {
    printf("ERROR! read_and_insert_address_result received null input "
	   "in 'myData'\n");
    fflush(stdout);
    return -1;
  }

  //debug
  printf("Entering read_and_insert_address_result() with file[%s]\n",
	 filename);
  fflush(stdout);
  //end debug
  
  row_count = 0;

  // Attempt to open the file passed in
  // 
  fid = fopen(filename,"rt");
  if (fid == NULL) {
    printf("Error opening file: %s\n", filename);
    fflush(stdout);
    return -1;
  }

  // For as many records exist, get all the expected records
  //
  while (fgets(line, 100, fid) != NULL) {
    printf("got first line as [%s]\n", line);

    if(strncmp(line,"name",4) != 0) {
      printf("read and insert address did not begin with 'name' [%s]", line);
      return -1;
    }

    get_flatfile_param(line, name, sizeof(name));
    if ((int)strlen(name) == 0)
      break;
    
    printf("name in read_insert_address***** [%s]\n", name);

    // TODO, lots more error checking here
    //
    fgets(line, 100, fid);
    get_flatfile_param(line, business_spe, sizeof(business_spe));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, business_type, sizeof(business_type));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, address, sizeof(address));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, city, sizeof(city));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, state, sizeof(state));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, telephone, sizeof(telephone));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, distance, sizeof(distance));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, ref_name, sizeof(ref_name));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, ref_add, sizeof(ref_add));
    
    counter++;

    //debug
    printf("counter=%d\n", counter);
    printf("read_and_insert_address read from file:\n");
    printf("name[%s] address[%s] city[%s] telephone[%s] distance[%s]\n",
	   name, address, city, telephone, distance);
    //end debug
    
    //--------------- insert row into SQL database -----------------
    
    // flag == 0 means that the business name != '*', so there is one in there
    // flat == 1 means the business name == '*' == "", so none present
    //
    if (flag == 1) {
      
      sprintf (SQLQuery, "select * from address where "
	       "name like \"%s\" and telephone like \"%s\" "
	       "and startname like \"%s\"  and startaddress like \"%s\" ",
	       name, telephone, ref_name, ref_add);
      
      printf("SQLQuery in read_and_insert_address #1 is [%s]\n", SQLQuery);
      
      x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
      
      // x == 0 is successful return code
      if (x == 0) {
	res = mysql_store_result(myData);
	if (res == NULL) {
	  printf("Unable to contact database in read_and_insert_address\n");
	  return -1;
	}
	row = mysql_fetch_row(res);
	if (row)
	  exist = 1;
	else
	  exist = 0;
	
	//total number of fields
	num_fields = mysql_num_fields(res);
	
	//get those fields
	fields = mysql_fetch_fields(res);
	
	//debug begin
	for (i = 0; i < num_fields; i++) {
	  printf("read_and_insert_addr #1 Field %u is %s\n",
		 i, fields[i].name);
	}
	printf("\n");
	//debug end
      }
      
      if (exist == 1) {
	do { //begin do
	  for (k = 0; k < (int)num_fields; k++) {
	    if (row[k] != NULL)
	      printf(" %s ", row[k]);
	    else
	      printf("field %d is NULL\n", k);
	  }
	  printf("\n");
	} //end do
	while ((row = mysql_fetch_row(res)));
      }   
      else {   // no data exist, insert the data
	sprintf (SQLQuery,"INSERT INTO address "
		 "(name, address, city, telephone, "
		 "distance, startname, startaddress) "
		 "VALUES('%s','%s','%s','%s','%s','%s', '%s')",
		 name, address, city, telephone,
		 distance, ref_name, ref_add);
	
	printf("Insert into using read_and_insert_address #1 [%s]\n",
	       SQLQuery);
	
	x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
	row_count++;
	
	//printf("row inserted=%d\n",row_count);
      }
    }//end flag==1
    
    // begin flag == 0
    // no business name, using type and specification
    //
    else { 
      
      sprintf (SQLQuery, "select * from address where "
	       "name like \"%s\" and telephone like \"%s\" and "
	       "specification like \"%s\"  and type like \"%s\" and "
	       "startname like \"%s\"  and startaddress like \"%s\" ",
	       name, telephone, business_spe,
	       business_type, ref_name, ref_add);
      
      printf("SQLQuery in read_and_insert_address #2 is [%s]\n", SQLQuery);
      //printf("%s\n", SQLQuery);
      
      x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
      
      // x == 0 is successful return
      if (x == 0) {
	res = mysql_store_result(myData);
	if (res == NULL) {
	  printf("Unable to contact database in read_and_insert_address\n");
	  return -1;
	}
	row = mysql_fetch_row(res);
	if (row)
	  exist = 1;
	else
	  exist = 0;
	
	//number of fields
	num_fields = mysql_num_fields(res);
	
	//get those fields
	fields = mysql_fetch_fields(res);
	
	//begin debug
	for(i = 0; i < num_fields; i++) {
	  printf("read_and_insert_addr #2 Field %u is %s\n",
		 i, fields[i].name);
	}
	printf("\n");
	//end debug
      }
      
      if (exist == 1) {
	do { //begin do
	  for (k = 0; k < (int)num_fields; k++) {
	    if (row[k] != NULL)
	      printf(" %s ", row[k]);
	    else
	      printf("field %d is NULL\n", k);
	  }
	  printf("\n");
	} //end do
	while ((row = mysql_fetch_row(res)));
      }
      
      // exist == 0
      // no data exist, insert the data*/
      else {   
	sprintf (SQLQuery,"INSERT INTO address "
		 "(name, address, city, telephone, "
		 "distance, specification, type, startname, "
		 "startaddress) VALUES('%s','%s','%s','%s',"
		 "'%s','%s', '%s','%s', '%s')",
		 name, address, city, telephone, distance,
		 business_spe, business_type, ref_name, ref_add);
	
	printf("Insert into using read_and_insert_address #2 [%s]\n",
	       SQLQuery);
	//printf("[%s]", SQLQuery);
	
	x=mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
	
	row_count++;
	printf("row inserted=%d\n",row_count);
      }
    }
  }
  
  printf("total names in the files=%d\n",counter);
  printf("total names inserted to database=%d\n", row_count);
  
  fclose(fid);
  
  return 0;
}


// function: read_and_insert_place_result
//
// arguments:
//  char *filename: (input) filename of source file to read
//  MYSQL *myData: (input) connection to a MYSQL database
//
// return: -1 = something bad happened
//          0 = successful return
//
// This function will read a text file and look to see if the data is
// already in the database. If it is not it will insert it.
//
// The layout of the expected file is:
//  name
//  address
//  city
//  telephone
//  distance
//  startaddress
//
// This function isn't even used right now.
//
/*int read_and_insert_place_result(char *filename, MYSQL *myData) {
  
  MYSQL_RES *res = NULL;
  MYSQL_ROW row = NULL;
  char SQLQuery[2048];
  int k, x;
  int exist = 0;
  unsigned int num_fields = 0;
  unsigned int i;
  MYSQL_FIELD *fields;
  
  int counter = 0;
  
  FILE *fid;
  char name[60];
  char address[60];
  char city[60];
  char telephone[60];
  char distance[20];
  char startaddress[60];
  
  int  row_count = 0;
  char line[100];
  //  char file[256];
  
  // Parameter error checking
  if (filename == NULL) {
    printf("ERROR! read_and_insert_place_result received null input "
	   "in 'filename'\n");
    fflush(stdout);
    return -1;
  }
  
  if (myData == NULL) {
    printf("ERROR! read_and_insert_place_result received null input "
	   "in 'myData'\n");
    fflush(stdout);
    return -1;
  }
  
  //strcpy(file, filename);
  
  fid = fopen(filename,"rt");
  if (fid == NULL) {
    printf("Error opening file: %s\n", filename);
    fflush(stdout);
    return -1;
  }
  
  fgets(line,100,fid);
  
  // Must begin with 
  //  if(line[0] !='n') {
  if (strncmp(line,"name",4) != 0) {
    printf("read_and_insert_place first line != 'name';value = [%s]", line);
    return -1;
  } 
  get_flatfile_param(line, name, sizeof(name));
  
  printf("****name***** [%s]\n", name);
  
  fgets(line, 100, fid);
  get_flatfile_param(line, address, sizeof(address));
  
  fgets(line, 100, fid);
  get_flatfile_param(line, city, sizeof(city));
  
  fgets(line, 100, fid);
  get_flatfile_param(line, telephone, sizeof(telephone));
  
  fgets(line, 100, fid);
  get_flatfile_param(line, distance, sizeof(distance));
  
  fgets(line, 100, fid);
  get_flatfile_param(line, startaddress, sizeof(startaddress));
  
  counter++;
  
  //debug
  printf("counter=%d\n",counter);
  printf("read_and_insert_place found in txt file:[%s] [%s] [%s] [%s] [%s]\n",
	 name, address, city, telephone, distance);
  //end debug
  
  // --------------- insert row into SQL database ----------------
  
  if((int)strlen(name) > 0) {
    
    sprintf (SQLQuery, "select * from place where name "
	     "like \"%s\" and telephone like \"%s\" and "
	     "startaddress like \"%s\" ",
	     name, telephone, startaddress);
    
    printf("read_and_insert_place sqlQuery [%s]\n", SQLQuery);
    
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
    
    // x == 0 is successful return code
    if (x == 0) {
      res = mysql_store_result(myData);
      if (res == NULL) {
	printf("Unable to contact database in read_and_insert_place\n");
	return -1;
      }
      row = mysql_fetch_row(res);
      if (row)
	exist = 1;
      else
	exist = 0;
      
      num_fields = mysql_num_fields(res);
      
      fields = mysql_fetch_fields(res);
      
      //debug begin
      for (i = 0; i < num_fields; i++) {
	printf("Field %u is %s\n", i, fields[i].name);
      }
      printf("\n");
      //end debug
    }
    
    if (exist == 1) {
      do { //begin do
	for (k = 0; k < (int)num_fields; k++) {
	  if (row[k] != NULL)
	    printf(" %s ", row[k]);
	  else
	    printf("field %d is NULL\n", k);
	}
	printf("\n");
      } //end do
      while ((row = mysql_fetch_row(res)));
    }   
    
    else {   // no data exist, insert the data
      sprintf (SQLQuery,"INSERT INTO place (name, address, city, "
	       "telephone, distance, startaddress) VALUES('%s',"
	       "'%s','%s','%s','%s','%s')",
	       name, address, city, telephone, distance, startaddress);
      
      printf("read_and_insert_place sqlQuery [%s]\n", SQLQuery);
      x=mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
      row_count++;
      
      printf("read_and_insert_place row inserted=%d\n",row_count);
    }
  }
  
  
  printf("total names in the files=%d\n",counter);
  printf("total names inserted to database=%d\n", row_count);
  
  fclose(fid);
  
  return 0;
}
*/

// function: read_and_insert_map_result
//
// arguments:
//  char *filename: (input) filename of source file to read
//  MYSQL *myData: (input) connection to a MYSQL database
//
// return: -1 = something bad happened
//          0 = successful return
//
// This function will read a text file and look to see if the data is
// already in the database. If it is not it will insert it.
//
// The layout of the expected file is:
//  start name
//  start address
//  start interest
//  start city
//  start state
//  start zip
//  end name
//  end address
//  end interest
//  end city
//  end state
//  end zip
//  total distance
//  total time
//  Number of directions
//  <SOME DIRECTIONS>
//
// This program will read the first information up to <SOME ...> and then
// will loop "Number of Directions" times reading a line and sending it
// to the function that will insert this place\direction into the specific
// leg number.
//
int read_and_insert_map_result(char *filename, MYSQL *myData) {
  
  FILE *fid;
  char start_name[60];
  char start_add[60];
  char start_interest[60];
  char start_city[60];
  char start_state[60];
  char start_zip[60];
  char end_name[60];
  char end_add[60];
  char end_interest[60];
  char end_city[60];
  char end_state[60];
  char end_zip[60];
  //  char from[60];
  //  char to[60];
  char total_distance[60];
  char distance[60];   
  char time[60];
  char direction[20];
  char line[200];
  char directions[2000];
  
  int i_direction = 0;
  int start_point;
  int leg;
  //int row_count = 0;
  
  // Parameter error checking
  if (filename == NULL) {
    printf("ERROR! read_and_insert_map_result received null input "
	   "in 'filename'\n");
    fflush(stdout);
    return -1;
  }
  
  if (myData == NULL) {
    printf("ERROR! read_and_insert_map_result received null input "
	   "in 'myData'\n");
    fflush(stdout);
    return -1;
  }

  // debug
  //system("cp /tmp/flatmap_0 /tmp/matt_backup_flat");
  //end debug
  
  fid = fopen(filename,"rt");
  if (fid == NULL) {
    printf("Error opening file in read_and_insert_map_result: %s\n",
	   filename);
    fflush(stdout);
    return -1;
  }
  
  while (fgets(line,100,fid) != NULL) {
    printf("****line========***** [%s]\n", line);
    get_flatfile_param(line, start_name, sizeof(start_name));
    
    printf("****from***** [%s]\n", start_name);
    
    fgets(line, 100, fid);
    get_flatfile_param(line, start_add, sizeof(start_add));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, start_interest, sizeof(start_interest));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, start_city, sizeof(start_city));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, start_state, sizeof(start_state));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, start_zip, sizeof(start_zip));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, end_name, sizeof(end_name));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, end_add, sizeof(end_add));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, end_interest, sizeof(end_interest));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, end_city, sizeof(end_city));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, end_state, sizeof(end_state));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, end_zip, sizeof(end_zip));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, total_distance, sizeof(total_distance));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, time, sizeof(time));
    
    fgets(line, 100, fid);
    get_flatfile_param(line, direction, sizeof(direction));
    
    // Find the number of directions following from the two places
    // Directions are pairs of lines that are 1) direction 2) miles
    //
    i_direction = atoi(direction);
    
    //debug
    printf(" number of directions [%d]\n", i_direction);
    //debug end
    
    start_point = 1;
    
    for (leg = 1; leg <= i_direction; leg++) {
      
      // Get the direction line
      fgets(line, 200, fid);
      
      // Get rid of new line
      if (line[(int)strlen(line)-1] == '\n')
	line[(int)strlen(line)-1] = 0;
      
      strcpy(directions, line);
      
      //debug
      printf(" from [%s] to [%s] leg[%i] total_distance [%s] "
	     "estimated time[%s]\n",
	     start_name, end_name, leg, total_distance, time);
      printf(" directions [%s]\n",
	     directions);
      //debug end
      
      // Get this leg's distance
      //
      fgets(line, 200, fid);
      
      if (line[(int)strlen(line)-1] == '\n')
	line[(int)strlen(line)-1] = 0;

      //debug
      printf(" distance [%s]\n", line);
      //debug end

      // Save it so that we are not abusing the 'line'
      //
      strcpy(distance, line);
      
      //--------------- insert row into SQL database -----------------
      
      insert_row_into_map(start_name, start_add, start_interest, start_city,
			  start_state, start_zip, end_name, end_add,
			  end_interest, end_city, end_state, end_zip, 
			  distance, time, directions, total_distance,
			  leg, myData);
    }
  }
  
  fclose(fid);
  
  return 0;
}

/*-----------------------------------------------------------------------*
 * Routine to extract an argument from a string delimited by colons      *
 *-----------------------------------------------------------------------*/

// function: extract_arg
//
// arguments:
//  int index (input): the number element to extract, 0-indexed
//  char *in_string (input): the string to parse and take out the index
//  char *out_string (output): the piece of the previous string
//
// return: 1 on success, 0 on fail
//
// Using a string like *:BOB:JOE:*:ONE:TWO:FOUR:*:*
// this function will walk into it such that the index number is above it
//  0   1     2    3    4     5     6    7    8
//  *: BOB : JOE : * : ONE : TWO : FOUR : * : *
// and then copy that token out and put it into out_string. in_string
// is read-only.
//
// Note: no bounds checking is done out the out_string so make sure it's
// large enough to contain the argument
//
int extract_arg(int index, char *in_string, char *out_string) {

  // Error check the input strings
  //
  if (in_string == NULL) {
    printf("ERROR! extract_arg received null input in 'in_string'\n");
    fflush(stdout);
    return 0;
  }
  
  if (out_string == NULL) {
    printf("ERROR! extract_arg received null input in 'out_string'\n");
    fflush(stdout);
    return 0;
  }
  
  int in_loc = 0;
  int out_loc = 0;
  int count = -1;
  
  // Give out_string some initial value to the output
  //
  out_string[0] = '*';
  out_string[1] = 0;
  
  // Count 'index' number of colons into the string without
  // running into a null character
  //
  for (in_loc = 0;(count < index) && (in_string[in_loc] != 0); in_loc++) {
    if (in_string[in_loc] == ':')
      count++;
  }
  // We must have ended on the index and without a null else fail!
  //
  if (count != index || in_string[in_loc] == 0)
    return 0;
  
  // Copy from the 'in_loc' to the out_loc buffer until end of array
  // or the next ':' is hit
  //
  for (out_loc = 0; (in_string[in_loc] != 0) && (in_string[in_loc] != ':');
       in_loc++) {
    out_string[out_loc++] = in_string[in_loc];
  }
  // Set final null character
  //
  out_string[out_loc] = 0;
  
  return 1;   
}


// function: process_web_map_request
//
// arguments:
//   Gal_Frame frame (input): not used, frame from the hub
//   char *map (input): The web_query map of information
//   MYSQL *myData (input): Open connection to a MYSQL database.
//
// Returns:
//      -1 = error
//      -2 (NO_RESPONSE_FROM_INTERNET) = no response from internet or db server
//       1 = successful/
//
// This function relies on a perl script named "web_location.perl" that does
// not work. Therefore this function is here only for historical purposes
// and should have major modifications done before attempting to use it.
//
// This function isn't even used right now.
//
/*int process_web_map_request(Gal_Frame frame, char *map, MYSQL *myData) {
  
  char start_add[30];
  char start_interest[30];
  char start_city[30];
  char start_state[30];
  char start_zip[30];
  char end_add[30];
  char end_interest[30];
  char end_city[30];
  char end_state[30];
  char end_zip[30];
  char web_query[1000];
  
  //   int num_pending;
  //   int num_responding;
  
  //   int time_out;
  //int i = 0;
  int ret;
  //struct stat stbuf;
  
  //input parameters check
  //
  if (map == NULL) {
    printf("ERROR! process_web_map_request receieved null input in map!\n");
    fflush(stdout);
    return -1;
  }
  if (myData == NULL) {
    printf("ERROR! process_web_map_request receieved null input in "
	   "myData!\n");
    fflush(stdout);
    return -1;
  }
  
  char *filenames[10]; // Create space for the filenames and clear it
  memset(filenames,0,sizeof(filenames));
  char single_file[100];
  
  printf("\nprocess web map request starts =: map has value of [%s]\n", map);
  fflush(stdout);
  
  //---- strip the map request info from colon delimited string  -----
  
  // TODO, why does this have 4 different start_interests?!?
  //
  extract_arg(0, map, start_interest);
  extract_arg(1, map, start_interest);
  extract_arg(2, map, start_add);
  extract_arg(3, map, start_interest);
  extract_arg(4, map, start_interest);
  
  extract_arg(5, map, start_city);
  extract_arg(6, map, start_state);
  extract_arg(7, map, start_zip);
  extract_arg(8, map, end_interest);
  extract_arg(9, map, end_add);
  
  if (start_add[0] == '*') {
    strcpy(start_add, "");
  }
  
  if (start_interest[0] == '*') {
    strcpy(start_interest, "");
  }
  
  if (start_city[0] == '*') {
    strcpy(start_city, "Starkville");
  }
  
  if (start_state[0] == '*') {
    strcpy(start_state, "MS");
  }
  
  if (start_zip[0] == '*') {
    strcpy(start_zip, "39759");
  }
  
  if (end_add[0] == '*') {
    strcpy(end_add, "");
  }
  
  if (end_interest[0] == '*') {
    strcpy(end_interest, "");
  }
  
  if (end_city[0] == '*') {
    strcpy(end_city, "Starkville");
  }
  
  if (end_state[0] == '*') {
    strcpy(end_state, "MS");
  }
  
  if (end_zip[0] == '*') {
    strcpy(end_zip, "");
  }
  
  
  //------ this builds the final string and goes to the web  ---------
  
  sprintf(web_query, RM_RF_FILES_STRING);
  system(web_query);
  
//
//  sprintf(web_query, "web_map.perl %s %s %s %s %s %s %s %s %s %s %d > outpage_%d
//  .html &",
//  "\"\" ", "\"\" ", "\"\" ", "\"\" ", "39759",   
//  "\"\"", "\"\"", "Jackson", "MS", "\"\"", 0, 0
//  );
    
// printf("hotel query = [%s]\n", web_query);
//   system(web_query);
//  sleep(10);
  
  printf("Warning! Using \"web_location.perl\" script and it doesnt work!\n");
  fprintf(stderr,
	 "Warning! Using \"web_location.perl\" script and it doesnt work!\n");
  sprintf(web_query, PERL_PATH PERL_SCRIPT " \"1\" " //"web_location.perl "
	  "\"%s\" \"%s\" \"%s\" "
	  "\"%s\" \"%s\" %d \"%s\"> "
	  OUTPUT_PATH "outpage_%d.html &",
	  start_add, end_add, start_city,
	  start_state, start_zip, 0, OUTPUT_PATH, 0);

  // Note, filenames[x] usage has changed and not reflected here
  //
  filenames[0] = OUTPUT_PATH "flatmap_0";
  filenames[1] = OUTPUT_PATH "flatmap_0.done";
  
  printf("map query = [%s]\n", web_query);
  ret = run_command_and_wait(web_query, filenames, FILE_COUNT);
  if (ret != FILE_COUNT) {
    printf("Not all the files were returned from run and wait call #1\n");
    printf("Going to continue but may fail when opening a file...\n");
  }
  
  if (ret != FILE_COUNT) {
    printf("ERROR: No response from the internet\n");
    fflush(stdout);
    return(NO_RESPONSE_FROM_INTERNET);
  }
  
  sprintf(single_file, OUTPUT_PATH "flatmap_0");
  read_and_insert_map_result(single_file, myData);
  
  if (remove_output_files) {
    sprintf(web_query, RM_RF_FILES_STRING);
    system(web_query);
    
    printf("rm files\n");
    fflush(stdout);
  }
  
  fflush(stdout);
  
  return(1);
}
*/

/*-----------------------------------------------------------------------*
 * Routine which gets address information from the WWW			 *
 *-----------------------------------------------------------------------*/

// function: process_web_address_request
//
// arguments:
//   Gal_Frame frame (input): not used, frame from the hub
//   char *map (input): The web_query map of information
//   MYSQL *myData (input): Open connection to a MYSQL database.
//
// Returns:
//      -1 = error
//      -2 (NO_RESPONSE_FROM_INTERNET) = no response from internet or db server
//       1 = successful/
//
// This function accepts a web_query map and extracts the necessary info
// and performs an address query. It uses the 'web_location_1.perl' script
// to find out a location from a name.
//
// It creates a file and then passes that file to
// 'read_and_insert_address_result' for insertion into the database.
//
int process_web_address_request(Gal_Frame frame, char *map, MYSQL *myData) {
  char business_name[60];
  char business_spe[30];
  char business_type[30];
  char start_city[30];
  char start_state[30];
  char start_zip[30];
  char ref_name[30];
  char ref_add[30];
  char start_name[30];
  char end_name[30];
  char web_query[1000];
  char line[200];
  char name[30];

  // Create space for the filenames and clear it
  //
  char filenames[10][SIZE_OF_FILENAME];
  memset(filenames, 0, sizeof(filenames));
  char single_file[SIZE_OF_FILENAME];
  
  int flag = 0;  // flag indicator what type of query
  int ret;
  
  //struct stat stbuf;
  FILE *fid;
  
  printf("\nprocess web address request starts =:\n");
  fflush(stdout);
  
  //input parameters check
  //
  if (map == NULL) {
    printf("ERROR! process_web_map_request receieved null input in map!\n");
    fflush(stdout);
    return -1;
  }
  if (myData == NULL) {
    printf("ERROR! process_web_map_request receieved null input in "
	   "myData!\n");
    fflush(stdout);
    return -1;
  }
  
  /*---- strip the map request info from colon delimited string  -----*/

  // example of this is
  //   :query_params ":*:*:*:*:GAS STATIONS:*:*:*:*:*"
  extract_arg(0, map, start_name);
  extract_arg(1, map, end_name);
  extract_arg(2, map, business_name);
  extract_arg(3, map, business_spe);
  extract_arg(4, map, business_type);
  
  extract_arg(5, map, start_city);
  extract_arg(6, map, start_state);
  extract_arg(7, map, start_zip);

  // These two are the [Arrive_Near] informations
  //
  extract_arg(8, map, ref_name); 
  extract_arg(9, map, ref_add);
  
  if (business_name[0] == '*') {
    strcpy(business_name, "");
    flag = 1;
  }
  
  if (business_spe[0] == '*') {
    strcpy(business_spe, "");
  }
  
  if (business_type[0] == '*') {
    strcpy(business_type, "");
  }
  
  if (start_city[0] == '*') {
    strcpy(start_city, "Starkville");
  }
  
  if (start_state[0] == '*') {
    strcpy(start_state, "MS");
  }
  
  if (start_zip[0] == '*') {
    strcpy(start_zip, "39759");
  }
  
  // not commented out by mwe
  //   if (ref_add[0] == '*') {
  // strcpy(ref_add, "\"\"");
  // }
  
  
  //------ this builds the final string and goes to the web  ---------
  
  
  // Remove these files
  //
  //sprintf(web_query, RM_RF_FILES_STRING);
  //system(web_query);
  system(clean_up_string);
  /*
    sprintf(web_query, "web_map.perl %s %s %s %s %s %s %s %s %s %s %d > outpage_%d
    .html &",
    "\"\" ", "\"\" ", "\"\" ", "\"\" ", "39759",   
    "\"\"", "\"\"", "Jackson", "MS", "\"\"", 0, 0
    );
    
    printf("hotel query = [%s]\n", web_query);
    system(web_query);
    sleep(10);
  */
  
  
  // get refer address if it is unknown
  //
  
  if(ref_add[0] =='*' && ref_name[0] =='*') {
    strcpy(ref_add, "");
    strcpy(ref_name, "");
  }
  //else if(ref_add[0] != '*' && ref_name[0] == '*') {
  else if(ref_name[0] == '*') {
    strcpy(ref_name, "");
  }
  
  //else if(ref_add[0] == '*' && ref_name[0] != '*') {
  else if(ref_add[0] == '*') {
    
    //debug begin
    printf("About to go into web_location_1.perl call and the following\n");
    printf("is the data: ref_name[%s] business_name[%s] business_spe[%s]\n",
	   ref_name, business_name, business_spe);
    printf("business_type[%s]\n",
	   business_type);
    //debug end
    
    // web_location_1.perl creates flatmap_%i with the number given
    // in the argv[1]. Fill in the "waiting for files" array with
    // the 2 files that will be created
    //
    sprintf(web_query, "\"%s\" \"2\" " //"web_location_1.perl "
	    "\"%s\" \"%s\" \"%s\" "
	    "\"%s\" \"%s\" \"%d\" \"%s\"> "
	    "\"%soutpage_%d.html\" &",
	    perlscript, 
	    //TODO- Check and see if this should be ref_name, or one of the
	    //business_* variables
	    ref_name, "", start_city,
	    //start_state, start_zip, 0, output_path, output_path, 0);
	    start_state, start_zip, unique_output_number,
	    output_path, output_path, unique_output_number);


    //OUTPUT_PATH "flatmap_0";
    //OUTPUT_PATH "flatmap_0.done";
    sprintf(filenames[0], "%sflatmap_%i", output_path, unique_output_number);
    sprintf(filenames[1], "%sflatmap_%i.done",
	    output_path, unique_output_number);
    
    printf("ref_add[%s] ref_name[%s] "
	   "process_web_address_request query = [%s]\n",
	   ref_add, ref_name, web_query);
    
    // Run the command
    //
    ret = run_command_and_wait(web_query, filenames, FILE_COUNT);
    if (ret != FILE_COUNT) {
      printf("Not all the files were returned from run and wait call #1\n");
      printf("Going to continue but may fail when opening a file...\n");
    }
    
    // get the address information from a file
    //
    // Open the file
    sprintf(single_file, "%sflatmap_%i", output_path, unique_output_number);
    printf("Opening output file [%s]\n", single_file);
    fid = fopen(single_file, "rt");
    if (fid == NULL) {
      printf("Error opening file: %s\n", single_file);
      fflush(stdout);
      return -1;
    }
    
    // TODO- I'm guessing there will be only one record?
    // This looks for "name" and "ref_add"
    //
    // Why does this even do this? We don't even USE this information
    // in this function?
    // ANSWER: this gets "ref_add". We don't use name but use ref_add
    // down below in the next web_call.
    //
    if (fgets(line,100,fid) != NULL) {
      if(strncmp(line,"name",4) != 0) {
	printf("Line 1 is not 'name' in file %s\n", single_file);
	return -1; //exit(1);
      } 
      
      get_flatfile_param(line, name, sizeof(name));
      
      //debug
      printf("****name***** [%s]\n", name);
      //debug
      
      fgets(line, 100, fid);
      get_flatfile_param(line, ref_add, sizeof(ref_add));
      
      //debug
      printf("****ref_add***** [%s]\n", ref_add);
      //debug

      fclose(fid);
    }
    else {
      printf("Unable to open up a file after going a query. Major error!\n");
      return -1;
    }
  }
  
  //sprintf(web_query, RM_RF_FILES_STRING);
  //system(web_query);
  system(clean_up_string);
  
  sprintf(web_query, "\"%s\" \"3\" " //"web_address.perl "
	  "\"%s\" \"%s\" \"%s\" \"%s\" \"%s\" "
	  "\"%s\" \"%s\" \"%s\" \"%d\" \"%s\" > "
	  "\"%soutpage_%d.html\" &",
	  perlscript, business_name, business_spe, business_type,
	  start_city, start_state, start_zip,
	  //ref_name, ref_add, 0, output_path, output_path, 0);
	  ref_name, ref_add, unique_output_number,
	  output_path, output_path, unique_output_number);

	  
  //OUTPUT_PATH "flatmap_0";
  //OUTPUT_PATH "flatmap_0.done";
  sprintf(filenames[0], "%sflatmap_%i", output_path, unique_output_number);
  sprintf(filenames[1], "%sflatmap_%i.done",
	  output_path, unique_output_number);
    
  //debug
  printf("address query = [%s]\n", web_query);
  
  ret = run_command_and_wait(web_query, filenames, FILE_COUNT);
  if (ret != FILE_COUNT) {
    printf("Not all the files were returned from run and wait call #2\n");
    printf("Going to continue but may fail when opening a file...\n");
  }
  
  // How many of the two files were created
  // "2" is because of the two files given above
  //
  if (ret != FILE_COUNT) {
    printf("ERROR: No response from the internet\n");
    fflush(stdout);
    return NO_RESPONSE_FROM_INTERNET;
  }
  
  //sprintf(single_file, OUTPUT_PATH "flatmap_0");
  sprintf(single_file, "%sflatmap_%i", output_path, unique_output_number);
  read_and_insert_address_result(single_file, flag, myData);
  
  if (remove_output_files) {
    //sprintf(web_query, RM_RF_FILES_STRING);     
    //system(web_query);
    system(clean_up_string);
    printf("rm'd files\n");
  }

  printf("\nprocess web address request ends =:\n");  

  fflush(stdout);
  
  return(1);
}

// function: process_web_address_request
//
// arguments:
//   MYSQL *myData (input): an open MySQL connection
//   char *SQLQuery (input): the query to perform
//   MYSQL_ROW *row_zero (output): if any data is returned, the first row
//                    is placed here for retrieval out of the function
//   MYSQL_RES **sql_result (output): A pointer to a MYSQL_RES pointer. The
//                    result of the query is placed here./
// Returns:
//    -2 = bad parameters
//    -1 = unsuccessful query
//     0 = successful query with row result (eg, returned values)
//     1 = successful query with no row result (eg, no returned values)
//
// This function will execute the query and then attempt to save the result.
// Just because the result is null does not mean the query failed. It may
// be a delete or a update which does not return any results.
//
// When using should check for both 0 and 1 (probably different cases) and then
// less than 0 for errors.
//
int process_query_for_single_entry(MYSQL *myData, char *SQLQuery,
				   MYSQL_ROW *row_zero,
				   MYSQL_RES **sql_result) {

  // Error check parameters
  //
  if (myData == NULL) {
    printf("web_interface: process_query_for_single_entry(): null MYSQL\n");
    return -2;
  }

  if (SQLQuery == NULL) {
    printf("web_interface: process_query_for_single_entry(): null SQLQuery\n");
    return -2;
  }

  if (sql_result == NULL) {
    printf("web_interface: process_query_for_single_entry(): "
	   "null result sql_result ptr\n");
    return -2;
  }

  printf("process_single_query: [%s]\n", SQLQuery);
  fflush(stdout);
  
  int ret_int = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
  // 0 is successful return code so if not zero, there is an error
  //
  if (ret_int != 0) {
    return -1;
  }

  // so here we know it was a successful query so get the result
  //
  *sql_result = mysql_store_result(myData);
  if (*sql_result == NULL) {
    // so there was no response. if mysql_fetch_row == 0 then there
    // wasn't suppose to be any response.
    //
    if (mysql_field_count(myData) == 0) {
      // it's all good so return 1
      return 1;
    }
    // there was suppose to be some response so now return error!
    //
    else {
      printf("web_interface: process_query_for_single_entry(): "
	     "Query returned but without expected results\n");
      return -1;
    }
  }

  // so here we know that it has a successful result so determine if
  // records were returned or not and save to *row_zero
  //
  *row_zero = mysql_fetch_row(*sql_result);

  // found no records
  if (*row_zero == NULL) {
    return 1;
  }

  // found records
  return 0;
}

/*-----------------------------------------------------------------------*
 * Routine which gets direction guide information from the WWW     	 *
 *-----------------------------------------------------------------------*/

// function: process_web_direction_request
//
// arguments:
//   Gal_Frame frame (input): not used, frame from the hub
//   char *map (input): The web_query map of information
//   MYSQL *myData (input): Open connection to a MYSQL database.
//
// Returns:
//      -1 = error
//      -2 (NO_RESPONSE_FROM_INTERNET) = no response from internet or db server
//       1 = successful/
//
// Given a map (web_query) this function will extract the info and then
// attempt to look up missing info using the database and the web. The
// web is then "hit" looking for the directions from the place. The output
// of this function is a file that is passed to 'read_and_insert_map_result'
//
// Other ramble:
// There are only a few pieces of data actually REQUIRED for the directions.
// The actual perl script only really uses:
//    start_add, start_city, start_state, start_zip
//    end_add, end_city, end_state, end_zip
// Considering that we do not store or get the zip from anywhere, the
// zip is assumed to be 39762 (see TODO list somewhere about how to find out
// the zip if need be)
//
// The data is stored in the database with sid\did (source\destination) id's
// which are the same as the id's of this place in the 'place' table
//
// So these values of *_campus, *_building, *_service, *_ref_name, *_ref_add
// start_interest are really just there to help out finding the name
// and address and some aren't even used!
//
// So, we need really about 4 items
//    1- name of source
//    2- address of source
//    3- name of destin
//    4- address of destin
// 
int process_web_direction_request(Gal_Frame frame, char *map, MYSQL *myData) {
  
  MYSQL_RES *res;
  MYSQL_ROW row;
  char SQLQuery[2048];
  //int x;
  
  char start_campus[120],    end_campus[120];
  char start_building[120],  end_building[120];
  char start_service[120],   end_service[120];
  char start_name[120],      end_name[120];
  char start_add[120],       end_add[120];
  char start_interest[120],  end_interest[120];
  char start_city[120],      end_city[120];
  char start_state[120],     end_state[120];
  char start_zip[120],       end_zip[120];
  char start_ref_name[120],  end_ref_name[120];
  char start_ref_add[120],   end_ref_add[120];

  // These are no longer used as they are not very clear
  //
  //char start_place[120],    end_place[120];
  //start_place[0] = 0;
  //end_place[0] = 0;
  
  char name[120];
  char web_query[1000];
  char line[200];
  
  //input parameters check
  //
  // map is the *:*:*:*:WALMART:*:*:* string
  if (map == NULL) {
    printf("ERROR! process_web_direction_request receieved null "
	   "input in map!\n");
    fflush(stdout);
    return -1;
  }
  if (myData == NULL) {
    printf("ERROR! process_web_direction_request receieved null "
	   "intput in myData!\n");
    fflush(stdout);
    return -1;
  }
  
  //   int  num_pending;
  //   int num_responding;
  //   int time_out;
  //int i;
  int ret;

  // Create space for the filenames and clear it
  //
  char filenames[10][SIZE_OF_FILENAME];
  memset(filenames,0,sizeof(filenames));
  char single_file[SIZE_OF_FILENAME];
  
  //struct stat stbuf;
  FILE *fid;
  
  printf("\nprocess web direction request starts =:\n");
  fflush(stdout);
  
  //---- strip the map request info from colon delimited string  -----

  //"how do i get from china garden to walmart ?"
  //                0 1 2   3          4 5     6      7 8 9 0 1 2 3  14     5 6
  //:query_params ":*:*:*:CHINA GARDEN:*:*:STARKVILLE:*:*:*:*:*:*:*:WALMART:*:*:*:*:*:*:*"  
  extract_arg(0, map, start_campus);
  extract_arg(1, map, start_building);
  extract_arg(2, map, start_service);
  extract_arg(3, map, start_name);
  extract_arg(4, map, start_add);
  extract_arg(5, map, start_interest);
  extract_arg(6, map, start_city);
  extract_arg(7, map, start_state);
  extract_arg(8, map, start_zip);
  extract_arg(9, map, start_ref_name);
  extract_arg(10, map, start_ref_add);
  
  extract_arg(11, map, end_campus);
  extract_arg(12, map, end_building);
  extract_arg(13, map, end_service);
  extract_arg(14, map, end_name);
  extract_arg(15, map, end_add);
  extract_arg(16, map, end_interest);
  extract_arg(17, map, end_city);
  extract_arg(18, map, end_state);
  extract_arg(19, map, end_zip);
  extract_arg(20, map, end_ref_name);
  extract_arg(21, map, end_ref_add);

  // Change from * to ""
  //
  if (start_campus[0] == '*') {
    strcpy(start_campus, "");
  }
  
  if (start_building[0] == '*') {
    strcpy(start_building, "");
  }
  
  if (start_service[0] == '*') {
    strcpy(start_service, "");
  }
  
  if (start_name[0] == '*') {
    strcpy(start_name, "");
  }
  
  if (start_add[0] == '*') {
    strcpy(start_add, "");
  }
  
  if (start_interest[0] == '*') {
    strcpy(start_interest, "");
  }
  
  if (start_city[0] == '*') {
    strcpy(start_city, "Starkville");
  }
  
  if (start_state[0] == '*') {
    strcpy(start_state, "MS");
  }
  
  if (start_zip[0] == '*') {
    strcpy(start_zip, "39759");
  }
  
  if (start_ref_name[0] == '*') {
    strcpy(start_ref_name, "");
  }
  
  if (start_ref_add[0] == '*') {
    strcpy(start_ref_add, "");
  }
  
  if (end_campus[0] == '*') {
    strcpy(end_campus, "");
  }
  
  if (end_building[0] == '*') {
    strcpy(end_building, "");
  }
  
  if (end_service[0] == '*') {
    strcpy(end_service, "");
  }
  
  if (end_name[0] == '*') {
    strcpy(end_name, "");
  }
  
  if (end_add[0] == '*') {
    strcpy(end_add, "");
  }
  
  if (end_interest[0] == '*') {
    strcpy(end_interest, "");
  }
  
  if (end_city[0] == '*') {
    strcpy(end_city, "Starkville");
  }
  
  if (end_state[0] == '*') {
    strcpy(end_state, "MS");
  }
  
  if (end_zip[0] == '*') {
    strcpy(end_zip, "39759");
  }
  
  if (end_ref_name[0] == '*') {
    strcpy(end_ref_name, "");
  }
  
  if (end_ref_add[0] == '*') {
    strcpy(end_ref_add, "");
  }
  
  // --- get the starting campus address if necessary --

  printf("DEBUG BEGIN: entering web direction with following data\n");
  printf("s_campus[%s] s_building[%s] s_service[%s] s_name[%s] s_add[%s]\n",
	 start_campus, start_building, start_service, start_name,
	 start_add);
  printf("s_interest[%s] s_city[%s] s_state[%s] s_zip[%s] s_ref_name[%s]"
	 "s_ref_add[%s]\n",
	 start_interest, start_city, start_state, start_zip, start_ref_name,
	 start_ref_add);
  printf("e_campus[%s] e_building[%s] e_service[%s] e_name[%s] e_add[%s]\n",
	 end_campus, end_building, end_service, end_name,
	 end_add);
  printf("e_interest[%s] e_city[%s] e_state[%s] e_zip[%s] e_ref_name[%s]"
	 "e_ref_add[%s]\n",
	 end_interest, end_city, end_state, end_zip, end_ref_name,
	 end_ref_add);
  printf("DEBUG END\n");

  /*
    BEGIN TODO for rewrite
    need only a single name + single address for each one
    right now it doesnt do that
    1) find out if any campus\building\service\name contain name AND
    add contains address.
    2) starting in order of name\building\campus\service query
    for the address in the database
    3) when any of them hit, copy the current one to name and
    save add in address
    END
  */
  // First check to see if we were given an address
  // If so, where we given a name to go along with it? Copy the name to
  // name
  //
  if (start_add[0] != 0) {
    // Check to see if 'name' contains the name
    //
    if (start_name[0] != 0) {
      // name already holds it, so don't do anything
    }
    else if (start_building[0] != 0) {
      strcpy(start_name, start_building);
    }
    else if (start_campus[0] != 0) {
      strcpy(start_name, start_campus);
    }
    else if (start_service[0] != 0) {
      strcpy(start_name, start_service);
    }
    else {
      // we have an address but no name. This is a problem....
      // do we have a perl script to handle this?
      //
      printf("TODO! NEED TO FIX THIS -- HAVE AN ADDRESS WITH NO NAME\n");
      fprintf(stderr,"TODO! NEED TO FIX THIS -- HAVE AN ADDRESS WITH "
	      "NO NAME\n");
    }
  }

  // This means we were not given an address so, make sure we were given
  // one of the name\building\campus\service cause if not, we cannot do
  // anything
  //
  else {
    if (start_name[0] == 0 && start_building[0] == 0 &&
	start_campus[0] == 0 && start_service[0] == 0) {
      // nope, we werent given anything so just exit bad
      return -1;
    }
    
    // So if we are here, we were given a name in one of these fields
    // so now just go through them until we find something

    // using 'start_name' in "place->name" table
    //
    if (start_name[0] != 0 && start_add[0] == 0) {
      printf("Entered start_name[0]/start_add[0] looking in place->name\n");

      // Make the query
      //
      sprintf (SQLQuery,"select address from place "
	       "where name like \"%%%s%%\"",
	       start_name);

      // Clean up files before making a call
      system(clean_up_string);
      
      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(start_add, row[0]);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return -1;
      }
    }

    // using 'start_name' in "address->name" table
    //
    if (start_name[0] != 0 && start_add[0] == 0) {
      printf("Entered start_name[0]/start_add[0] looking in address->name\n");
      
      // Make the query
      //
      sprintf (SQLQuery,"select address from address "
	       "where name like \"%%%s%%\"",
	       start_name);

      // Clean up files before making a call
      system(clean_up_string);

      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(start_add, row[0]);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return -1;
      }
    }

    // using 'start_building' in "campusname->name" table
    //   
    if (start_building[0] != 0 && start_add[0] == 0) {
      printf("Entered start_building[0]/start_add[0] looking in "
	     "campusname->name\n");

      // Make the query -- 'refname' contains an address
      //
      sprintf (SQLQuery,"select refname from campusname "
	       "where name like \"%%%s%%\"",
	       start_building);

      // Clean up files before making a call
      system(clean_up_string);

      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(start_add, row[0]);
	strcpy(start_name, start_building);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return -1;
      }
    }

    // using 'start_building' in "address->name" table
    //   
    if (start_building[0] != 0 && start_add[0] == 0) {
      printf("Entered start_building[0]/start_add[0] looking in "
	     "address->name\n");

      // Make the query -- 'refname' contains an address
      //
      sprintf (SQLQuery,"select address from address "
	       "where name like \"%%%s%%\"",
	       start_building);

      // Clean up files before making a call
      system(clean_up_string);

      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(start_add, row[0]);
	strcpy(start_name, start_building);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return -1;
      }
    }
    
    // using 'start_campus' in "campusname->name" table
    //   
    if (start_campus[0] != 0 && start_add[0] == 0) {
      printf("Entered start_campus[0]/start_add[0] looking in "
	     "campusname->name\n");

      // Make the query -- 'refname' contains an address
      //
      sprintf (SQLQuery,"select refname from campusname "
	       "where name like \"%%%s%%\"",
	       start_campus);

      // Clean up files before making a call
      system(clean_up_string);

      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(start_add, row[0]);
	strcpy(start_name, start_campus);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return 1;
      }     
    }//end campus

    if (start_service[0] != 0 && start_add[0] == 0) {
      printf("Entered start_service[0]/start_add[0] looking in "
	     "campusname->name\n");

      // Make the query -- 'refname' contains an address
      //
      sprintf (SQLQuery,"select refname from campusname "
	       "where name like \"%%%s%%\"",
	       start_service);

      // Clean up files before making a call
      system(clean_up_string);

      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(start_add, row[0]);
	strcpy(start_name, start_service);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return 1;
      }     
    }
	
  }//end else for given name but no address
	
  /*printf("start_campus is [%s]\n", start_campus);
  if (strcmp(start_campus, "") != 0) {
    
    // Query for 'refname' -- inside 'start_campus'
    //
    sprintf (SQLQuery,"select refname from campusname "
	     "where name like \"%%%s%%\"",
	     start_campus);
    
    //debug
    printf("entered start_campus, query[%s]\n", SQLQuery);
    //end debug
    
    // Do query, a successful return code is 0
    //
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
    if (x == 0) {
      res = mysql_store_result(myData);
      if (res == NULL) {
	printf("Unable to contact database in process_web_direct\n");
	return -1;
      }      
      row = mysql_fetch_row(res);
      if (row) {
	strcpy(start_add, row[0]);
	
	//debug
	printf("stored to 'start_add' as [%s]\n", start_add);
	//debug
      }
    }
  }//end start_campus
  

  printf("start_name is [%s]\n", start_name);  
  if (strcmp(start_name, "") != 0) {
    // Query for 'building' -- inside 'start_campus'
    //
    sprintf (SQLQuery, "select building from campusname "
	     "where name like \"%%%s%%\"",
	     start_name);
    
    printf("entered start_name, query [%s]\n", SQLQuery);
    
    // Do query, a successful return code is 0
    //
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
    if (x == 0) {
      res = mysql_store_result(myData);
      if (res == NULL) {
	printf("Unable to contact database in process_web_direct\n");
	return -1;
      }      
      row = mysql_fetch_row(res);
      if (row) {
	strcpy(start_name, row[0]);
	
	//debug
	printf("start_name is returned as [%s]\n", start_name);
	//debug
      }
    }
  }   

  printf("start_building is [%s]\n", start_building);    
  if (strcmp(start_building, "") != 0) {
    
    sprintf (SQLQuery,"select refname from campusname "
	     "where building like \"%%%s%%\"",
	     start_building);
    
    printf("entered start_building, query [%s]\n", SQLQuery);
    
    // Do query, a successful return code is 0
    //
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
    if (x == 0) {
      res = mysql_store_result(myData);
      if (res == NULL) {
	printf("Unable to contact database in process_web_direct\n");
	return -1;
      }      
      row = mysql_fetch_row(res);
      if (row) {
	strcpy(start_building, row[0]);
	strcpy(start_name, start_building);
	
	//debug
	printf("found refname from campus as: %s\n", start_building);
	//debug
      }
    } 
  }

  printf("start_service is [%s]\n", start_service);
  if (strcmp(start_service, "") != 0) {
    
    sprintf (SQLQuery,"select refname from campusname "
	     "where building like \"%%%s%%\"",
	     start_service);
    
    printf("entered start_service, query [%s]\n", SQLQuery);
    
    // Do query, a successful return code is 0
    //
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
    if (x == 0) {
      res = mysql_store_result(myData);
      if (res == NULL) {
	printf("Unable to contact database in process_web_direct\n");
	return -1;
      }      
      row = mysql_fetch_row(res);
      if (row) {
	strcpy(start_service, row[0]);
	strcpy(start_name, start_service);
	
	//debug
	printf("found 'refname' from 'start_service' as: %s\n", start_name);
	//debug
      }
      
    }    
  }
  else {
    printf("%s\n", start_service);
  }
  */

  //=== BEGIN
  if (end_add[0] != 0) {
    // Check to see if 'name' contains the name
    //
    if (end_name[0] != 0) {
      // name already holds it, so don't do anything
    }
    else if (end_building[0] != 0) {
      strcpy(end_name, end_building);
    }
    else if (end_campus[0] != 0) {
      strcpy(end_name, end_campus);
    }
    else if (end_service[0] != 0) {
      strcpy(end_name, end_service);
    }
    else {
      // we have an address but no name. This is a problem....
      // do we have a perl script to handle this?
      //
      printf("TODO! NEED TO FIX THIS -- HAVE AN ADDRESS WITH NO NAME\n");
      fprintf(stderr,"TODO! NEED TO FIX THIS -- HAVE AN ADDRESS WITH "
	      "NO NAME\n");
    }
  }

  // This means we were not given an address so, make sure we were given
  // one of the name\building\campus\service cause if not, we cannot do
  // anything
  //
  else {
    if (end_name[0] == 0 && end_building[0] == 0 &&
	end_campus[0] == 0 && end_service[0] == 0) {
      // nope, we werent given anything so just exit bad
      return -1;
    }
    
    // So if we are here, we were given a name in one of these fields
    // so now just go through them until we find something

    // using 'end_name' in "place->name" table
    //
    if (end_name[0] != 0 && end_add[0] == 0) {
      printf("Entered end_name[0]/end_add[0] looking in place->name\n");

      // Make the query
      //
      sprintf (SQLQuery,"select address from place "
	       "where name like \"%%%s%%\"",
	       end_name);

      // Clean up files before making a call
      system(clean_up_string);

      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(end_add, row[0]);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return -1;
      }
    }

    // using 'end_name' in "address->name" table
    //
    if (end_name[0] != 0 && end_add[0] == 0) {
      printf("Entered end_name[0]/end_add[0] looking in address->name\n");
      
      // Make the query
      //
      sprintf (SQLQuery,"select address from address "
	       "where name like \"%%%s%%\"",
	       end_name);

      // Clean up files before making a call
      system(clean_up_string);

      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(end_add, row[0]);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return -1;
      }
    }

    // using 'end_building' in "campusname->name" table
    //   
    if (end_building[0] != 0 && end_add[0] == 0) {
      printf("Entered end_building[0]/end_add[0] looking in "
	     "campusname->name\n");

      // Make the query -- 'refname' contains an address
      //
      sprintf (SQLQuery,"select refname from campusname "
	       "where name like \"%%%s%%\"",
	       end_building);

      // Clean up files before making a call
      system(clean_up_string);

      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(end_add, row[0]);
	strcpy(end_name, end_building);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return -1;
      }
    }

    // using 'end_building' in "address->name" table
    //   
    if (end_building[0] != 0 && end_add[0] == 0) {
      printf("Entered end_building[0]/end_add[0] looking in "
	     "address->name\n");

      // Make the query -- 'refname' contains an address
      //
      sprintf (SQLQuery,"select address from address "
	       "where name like \"%%%s%%\"",
	       end_building);

      // Clean up files before making a call
      system(clean_up_string);

      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(end_add, row[0]);
	strcpy(end_name, end_building);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return -1;
      }
    }
    
    // using 'end_campus' in "campusname->name" table
    //   
    if (end_campus[0] != 0 && end_add[0] == 0) {
      printf("Entered end_campus[0]/end_add[0] looking in "
	     "campusname->name\n");

      // Make the query -- 'refname' contains an address
      //
      sprintf (SQLQuery,"select refname from campusname "
	       "where name like \"%%%s%%\"",
	       end_campus);

      // Clean up files before making a call
      system(clean_up_string);

      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(end_add, row[0]);
	strcpy(end_name, end_campus);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return 1;
      }     
    }//end campus

    if (end_service[0] != 0 && end_add[0] == 0) {
      printf("Entered end_service[0]/end_add[0] looking in "
	     "campusname->name\n");

      // Make the query -- 'refname' contains an address
      //
      sprintf (SQLQuery,"select refname from campusname "
	       "where name like \"%%%s%%\"",
	       end_service);

      // Clean up files before making a call
      system(clean_up_string);

      ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      if (ret == 0) {
	// if 0, then found data and got data in row
	strcpy(end_add, row[0]);
	strcpy(end_name, end_service);
      }
      else if (ret == 1) {
	//successful, but no data returned so no-op
      }
      else {
	printf("process_web_direction: Returned error code from "
	   "process_query_for_single_entry!\n");
	return 1;
      }     
    }
	
  }//end else for given name but no address

  // END

  /*
  // --- get the end campus address if necessary -- //
  printf("end_campus is [%s]\n", end_campus);  
  if (strcmp(end_campus, "") != 0) {
    
    // Query for 'refname' -- inside 'end_campus'
    //
    sprintf (SQLQuery,"select refname from campusname "
	     "where name like \"%%%s%%\"",
	     end_campus);
    
    printf("entered end_campus, query[%s]\n", SQLQuery);
    
    // Do query, a successful return code is 0
    //
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
    if (x == 0) {
      res = mysql_store_result(myData);
      if (res == NULL) {
	printf("Unable to contact database in process_web_direct\n");
	return -1;
      }      
      row = mysql_fetch_row(res);
      if (row) {
	strcpy(end_add, row[0]);
	
	//debug
	printf("found refname in 'end_campus' as: %s\n", end_add);
	//debug
      }       
    }
    
    // Query for 'building' -- inside 'end_campus'
    //
    sprintf (SQLQuery,"select building from campusname "
	     "where name like \"%%%s%%\"",
	     end_campus);
    
    printf("end_campus #2, query[%s]\n", SQLQuery);
    
    // Do query, a successful return code is 0
    //
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
    if (x == 0) {
      res = mysql_store_result(myData);
      if (res == NULL) {
	printf("Unable to contact database in process_web_direct\n");
	return -1;
      }      
      row = mysql_fetch_row(res);
      if (row) {
	strcpy(end_name, row[0]);
	
	//debug
	printf("found 'building' in 'end_campus' as: %s\n", end_name);
	//debug
      }
    }// end x==0
  } // end end_campus
  
  // Original line in the code was
  //       if(!strcmp(end_building, "\"\"") == 0) {
  // So I'm not sure if which they meant...
  // I'm going to assume they meant "!= 0"
  //
  if(strcmp(end_building, "") != 0) {
    sprintf (SQLQuery,"select refname from campusname where "
	     "building like \"%%%s%%\"",
	     end_building);
    
    printf("entered end_building, query [%s]\n", SQLQuery);
    
    // Do query, a successful return code is 0
    //
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
    if (x == 0) {
      res = mysql_store_result(myData);
      if (res == NULL) {
	printf("Unable to contact database in process_web_direct\n");
	return -1;
      }      
      row = mysql_fetch_row(res);
      if (row) {
	strcpy(end_building, row[0]);
	strcpy(end_name, end_building);
	
	//debug
	printf("end_building: %s\n", end_building);
	//debug
      }
    }       
  }
  
  if(strcmp(end_service, "") != 0) {
    
    sprintf (SQLQuery,"select refname from campusname "
	     "where building like \"%%%s%%\"",
	     end_service);
    
    printf("entered end_service, query [%s]\n", SQLQuery);
    
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
    if (x == 0) {
      res = mysql_store_result(myData);
      if (res == NULL) {
	printf("Unable to contact database in process_web_direct\n");
	return -1;
      }      
      row = mysql_fetch_row(res);
      if (row) {
	strcpy(end_service, row[0]);
	strcpy(end_name, row[0]);
	
	//debug
	printf("end_service\\end_name is now [%s]\n", end_name);
	//debug	 
      }
    }
  }
  */
  
  /* --- get the start reference address if necessary -- */
  
  /*
  //THIS SECION NOT COMMENTED OUT BY MWE
  //see below for re-write by someone else
  if(strcmp(start_ref_add, "\"\"") == 0) {
  
  // get the start address from starting business name
  // 
  sprintf(web_query, "web_location_1.perl \"%s\" %d \"%s\" \"%s\" \"%s\"> outpage_%d.html &",
  start_ref_name, num_pending, start_city, start_state, start_zip, num_pending);
  
  printf("direction query = [%s]\n", web_query);
  system(web_query);
  num_pending++;
  fflush(stdout);
  
  printf("---------------------------\n"); fflush(stdout);
  printf("%d web queries are pending\n", num_pending); fflush(stdout);
  printf("---------------------------\n"); fflush(stdout);
  
  while((time_out > 0) && (num_pending != num_responding)){
  printf("time_out=[%d]\n", time_out);
  fflush(stdout);
  num_responding = 0;
  for(i=0;i<num_pending;i++){
  sprintf(web_query, "flatmap_%d",i);
  if (stat(web_query, &stbuf) == 0)
  num_responding++;
  }
  time_out--;
  if (num_responding != num_pending) sleep(1);
  }
  }
  
  if(strcmp(start_ref_add, "\"\"") == 0) {
  // get the starting address from a file previous store by web
  // perl script
  //
  sprintf(web_query, "flatmap_0");
  if (stat(web_query, &stbuf) == 0){
  
  fid = fopen("flatmap_0","rt");
  if (fid==NULL){
  printf("Error opening file: flatmap_0\n"); fflush(stdout);
  }
  
  if (fgets(line,100,fid) != NULL) {
  if(line[0] !='n') {printf("%s", line); exit(1);} 
  get_flatfile_1_param(line, name);
  //       if (strlen(name) == 0) break;
  printf("****name***** [%s]\n", name);
  fgets(line, 100, fid);    get_flatfile_1_param(line, start_place);
  fgets(line, 100, fid);    get_flatfile_1_param(line, start_city);
  fgets(line, 100, fid);    get_flatfile_1_param(line, start_state);
  }       
  
  fclose(fid);
  }
  }
  
  if ((time_out == 0) && (num_responding <= 1)){
  printf("ERROR: No response from the internet\n"); fflush(stdout);
  return(NO_RESPONSE_FROM_INTERNET);
  }

  END NON-COMMENT BY MWE
  */
  
  //------ this builds the final string and goes to the web  --------- //
  
  //sprintf(web_query, RM_RF_FILES_STRING);
  //system(web_query);
  system(clean_up_string);
  
  //printf("the length of start add is %i[%s]\n",strlen(start_add), start_add);
  printf("start_add=[%s], end_add=[%s]\n", start_add, end_add);
  fflush(stdout);

  // We need the addresses of the start and ending places, so the next two
  // sections will use "web_location_1.perl" in order to find an address
  // to correspond to the name of the place if it hasn't already been filled
  //

  // Find address of start place using the web because i couldnt find in the
  // database at all
  //
  if(start_add[0] == 0) {
    
    // get the start address from starting business name
    // 
    sprintf(web_query, "\"%s\" \"2\" " //"web_location_1.perl "
	    "\"%s\" \"%s\" \"%s\" "
	    "\"%s\" \"%s\" \"%d\" \"%s\" > "
	    "\"%soutpage_%d.html\" &",
	    perlscript, start_name, "", start_city,
	    //start_state, start_zip, 0, output_path, output_path, 0);
	    start_state, start_zip, unique_output_number,
	    output_path, output_path, unique_output_number);
    
    printf("direction query = [%s]\n", web_query);

    //OUTPUT_PATH "flatmap_0";
    //OUTPUT_PATH "flatmap_0.done";
    sprintf(filenames[0], "%sflatmap_%i", output_path, unique_output_number);
    sprintf(filenames[1], "%sflatmap_%i.done",
	    output_path, unique_output_number);
    
    ret = run_command_and_wait(web_query, filenames, FILE_COUNT);
    if (ret != FILE_COUNT) {
      printf("Not all the files were returned from run and wait call #3\n");
      printf("Going to continue but may fail when opening a file...\n");
    }
    
    // If the two files we want didn't show up, then we have a problem!
    //
    if (ret != FILE_COUNT) {
      printf("ERROR: No response from the internet\n");
      fflush(stdout);
      return(NO_RESPONSE_FROM_INTERNET);
    }

    // get the starting address from a file previous store by web
    // perl script
    //
    //sprintf(single_file, OUTPUT_PATH "flatmap_0");
    sprintf(single_file, "%sflatmap_%i", output_path, unique_output_number);
    
    fid = fopen(single_file,"rt");
    if (fid == NULL) {
      printf("Error opening file: %s\n", single_file);
      fflush(stdout);
      return -1;
    }
    
    if (fgets(line,100,fid) != NULL) {
      if(strncmp(line,"name",4) != 0) {
	printf("Line 1 is not 'name' in file %s\n", single_file);
	return -1;
      } 
      get_flatfile_param(line, name, sizeof(name));
      
      printf("****name***** [%s]\n", name);
      
      fgets(line, 100, fid);
      get_flatfile_param(line, start_add, sizeof(start_add));
      
      fgets(line, 100, fid);
      get_flatfile_param(line, start_city, sizeof(start_city));
      
      fgets(line, 100, fid);
      get_flatfile_param(line, start_state, sizeof(start_state));
      
      //NOTE: There are an additional two parameters that web_location_1
      //returns but since this is not a for\while loop, it doesn't matter.
      //
      //additional two properties are 'telephone' and 'miles'
    }
    
    fclose(fid);
  }//end start_add == ""
  
  //sprintf(web_query, RM_RF_FILES_STRING);
  //system(web_query);
  system(clean_up_string);
  
  //printf("the length of start add is %d\n", strlen(start_add));
  printf("start_add=[%s], end_add=[%s]\n", start_add, end_add);
  fflush(stdout);


  // Find address of the ending place
  //
  if(end_add[0] == 0) {
    
    // get the destination address from destination business name
    // 
    sprintf(web_query, "\"%s\" \"2\" " //"web_location_1.perl "
	    "\"%s\" \"%s\" \"%s\" "
	    "\"%s\" \"%s\" \"%d\" \"%s\" > "
	    "\"%soutpage_%d.html\" &",
	    perlscript, end_name, "", end_city,	  
	    //end_state, end_zip, 0, output_path, output_path, 0);
	    end_state, end_zip, unique_output_number,
	    output_path, output_path, unique_output_number);
    
    printf("end_name direction query = [%s]\n", web_query);

    //OUTPUT_PATH "flatmap_0";
    //OUTPUT_PATH "flatmap_0.done";
    sprintf(filenames[0], "%sflatmap_%i", output_path, unique_output_number);
    sprintf(filenames[1], "%sflatmap_%i.done",
	    output_path, unique_output_number);
    
    ret = run_command_and_wait(web_query, filenames, FILE_COUNT);
    if (ret != FILE_COUNT) {
      printf("Not all the files were returned from run and wait call #5\n");
      printf("Going to continue but may fail when opening a file...\n");
    }
    
    // If the two files we want didn't show up, then we have a problem!
    //
    if (ret != FILE_COUNT) {
      printf("ERROR: No response from the internet\n");
      fflush(stdout);
      return(NO_RESPONSE_FROM_INTERNET);
    }
    
    // get the end address from a file previous store by web
    // perl script
    //
    //sprintf(single_file, OUTPUT_PATH "flatmap_0");
    sprintf(single_file, "%sflatmap_%i", output_path, unique_output_number);
    fid = fopen(single_file,"rt");
    if (fid == NULL) {
      printf("Error opening file: %s\n", single_file);
      fflush(stdout);
      return -1;
    }
    
    if (fgets(line,100,fid) != NULL) {
      if(strncmp(line,"name",4) != 0) {
	printf("Line 1 is not 'name' in file %s\n", single_file);
	return -1;
      } 
      get_flatfile_param(line, name, sizeof(name));
      
      //if (strlen(name) == 0) break;
      printf("****name***** [%s]\n", name);
      
      fgets(line, 100, fid);
      get_flatfile_param(line, end_add, sizeof(end_add));
      
      fgets(line, 100, fid);
      get_flatfile_param(line, end_city, sizeof(end_city));
      
      fgets(line, 100, fid);
      get_flatfile_param(line, end_state, sizeof(end_state));
    }
    
    fclose(fid);
  } //end end_add == ""

  // if we get here and either start_add\end_add are null then that's an error
  // so error!
  if (start_add[0] == 0 || end_add[0] == 0) {
    printf("Error: start_add[%s] end_add[%s] -- one of these is null and "
	   "we can't have that!\n", start_add, end_add);
    return -1;
  }  
  
  // We don't want blank names so if we get here and somehow we still have
  // blank names, just return
  //
  if (start_name[0] == 0 || end_name[0] == 0) {
    printf("Error: start_name[%s] end_name[%s] -- one of these is null and "
	   "we can't have that!\n", start_name, end_name);
    return -1;
  }

  // When we get to here we are guarantee-ing that we have
  // start_add and end_add populated. If they weren't then we would
  // have had some sort of error when accessing the web and would have
  // returned.
  //
  
  //sprintf(web_query, RM_RF_FILES_STRING);
  //system(web_query);
  
  printf("start_add=[%s], end_add=[%s]\n", start_add, end_add);
  fflush(stdout);
  
  /*
  // TODO, check to make sure this logic is right. do we want to copy over
  // place if address is not null? and since address is always not null here
  // (i am pretty sure) we shouldn't have these be if's
  //
  if (strcmp(start_add, "") != 0) 
    strcpy(start_place, start_add);
  
  if (strcmp(end_add, "") != 0) 
    strcpy(end_place, end_add);
  
  // Do this in perl script now
  //   replace_with_plus(start_place);
  //   replace_with_plus(end_place);
  
  if (strcmp(start_name, "") ==0)
    strcpy(start_name, start_place);
  
  if (strcmp(end_name, "") ==0)
    strcpy(end_name, end_place);
  */
  
  // get the direction from starting business name to end name
  // 
  sprintf(web_query, "\"%s\" \"4\" " //"web_map.perl "
	  "\"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" "
	  "\"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%d\" \"%s\" > "
	  "\"%soutpage_%d.html\" &",
	  perlscript, start_name, start_add, start_interest,
	  start_city, start_state, start_zip,   
	  end_name, end_add, end_interest,
	  //end_city, end_state, end_zip, 0, output_path, output_path, 0);
	  end_city, end_state, end_zip, unique_output_number,
	  output_path, output_path, unique_output_number);
  
  printf("web_map query = [%s]\n", web_query);

  //OUTPUT_PATH "flatmap_0";
  //OUTPUT_PATH "flatmap_0.done";
  sprintf(filenames[0], "%sflatmap_%i", output_path, unique_output_number);
  sprintf(filenames[1], "%sflatmap_%i.done",
	  output_path, unique_output_number);
  
  ret = run_command_and_wait(web_query, filenames, FILE_COUNT);
  if (ret != FILE_COUNT) {
    printf("Not all the files were returned from run and wait call #4\n");
    printf("Going to continue but may fail when opening a file...\n");
  }
  
  //sprintf(single_file, OUTPUT_PATH "flatmap_0");
  sprintf(single_file, "%sflatmap_%i", output_path, unique_output_number);
  printf("calling 'read_and_insert_map_result' with [%s]\n", single_file);
  read_and_insert_map_result(single_file, myData);
  
  sleep(2);
  
  if (remove_output_files) {
    //sprintf(web_query, RM_RF_FILES_STRING);
    //system(web_query);
    system(clean_up_string);
    
    printf("rm'd files\n");
  }
  
  printf("\nprocess web direction request ends =:\n");
  fflush(stdout);
  
  return 1;
}

// function: insert_row_into_map
//
// Inputs:
//    *_name         - the name of the start\end places
//    *_add          - the address of the start\end places
//    *_interest     - not used, perhaps for later expansion?
//    *_city         - the city of the start\end places
//    *_state        - the state of the start\end places
//    *_zip          - the zip of the start\end places
//    distance       - the distance of this one leg
//    time           - the total time for the trip from start to end
//    directions     - this leg's directions
//    total_distance - the total distance between start and end
//    index          - 1-based index of which leg this is
//    myData         - an open mySQL connection to the database
//
// Returns 1 on success
// Returns -1 on fail
//
// This function takes all of this information and then does the following
// 1) Checks to make sure that 'start' is a location in 'place'
// 2) Checks to make sure that 'end' is a location in 'place'
// 3) Retrives the 'sid' and 'did' of the start\end locations
// 4) Checks to see if there is already a entry for this start\end directions
// 5) If there is not, insert the direction for this index
//
// In a nutshell this takes 2 places and a single leg of the direction
// and inserts the leg into the 'route' table using the sid\did (source\destin)
//
int insert_row_into_map(char *start_name, char *start_add, 
			char *start_interest, char *start_city, 
			char *start_state, char *start_zip, 
			char *end_name, char *end_add,
			char *end_interest, char *end_city, 
			char *end_state, char *end_zip,

                        char *distance, char *time,
			char *directions, char *total_distance,
			int index, MYSQL *myData) {
  
  //int x = 0;
  int ret = 0;
  int exist = 0;
  int starting = 0, ending = 0;
  //int k = 0;
  //unsigned int i;
  
  //unsigned row_count = 0;
  MYSQL_RES *res = NULL;
  MYSQL_ROW row = NULL;
  char SQLQuery[2048];
  //unsigned int num_fields = 0;
  //MYSQL_FIELD *fields;
  
  // Parameter checking
  //
  if (!start_name || !start_add || !start_city || !start_state ||
      !start_zip || !end_name || !end_add || !end_city ||
      !end_state || !end_zip || !distance || !time ||
      !directions || !total_distance) {
    printf("ERROR! insert_row_into_map received null input in one of "
	   "the start\\end parameters\n");
    fflush(stdout);
    return -1;
  }
  if (myData == NULL) {
    printf("ERROR! insert_row_into_map received null input in myData\n");
    fflush(stdout);
    return -1;
  }
  
  // First check to make sure this STARTING place exists
  // 
  sprintf (SQLQuery, "select * from place where name like \"%s\" "
	   "and city like \"%s\" and state like \"%s\" and zip like \"%s\" ",
	   start_name, start_city, start_state, start_zip);
  
  printf("insert_row_into_map query [%s]\n", SQLQuery);

  // BEGIN LONGER WAY
  //
  /*x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
  
  // x = 0 is successful return code
  if (x == 0) {
    res = mysql_store_result(myData);
    if (res == NULL) {
      printf("Unable to contact database in insert_row_into_map\n");
      return -1;
    }
    row = mysql_fetch_row(res);
    if (row)
      exist = 1;
    else
      exist = 0;
    
    num_fields = mysql_num_fields(res);
    fields = mysql_fetch_fields(res);
    
    //debug
    for (i = 0; i < num_fields; i++) {
      printf("Field %u is %s\n", i, fields[i].name);
    }
    printf("\n");
    //debug end
  }
  
  if (exist == 1) {     
    do { //begin do
      for (k = 0; k < (int)num_fields; k++) {
	if (row[k] != NULL)
	  printf(" %s ", row[k]);
	else
	  printf("field %d is NULL\n", k);
      }
      printf("\n");
    } //end do
    while ((row = mysql_fetch_row(res)));
  }
  
  // no data exist, insert the data
  // This says that the starting address was not found so add it
  //
  else {
    sprintf (SQLQuery,"INSERT INTO place "
	     "(name, address, city, state, zip) "
	     "VALUES(\"%s\",\"%s\", \"%s\",\"%s\", \"%s\") ",
	     start_name, start_add, start_city, start_state, start_zip);
    
    printf("insert_row_map [%s]", SQLQuery);
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
    row_count++;
    printf("row inserted=%d\n", row_count);
  }
  */
  // END LONGER WAY
  //

  // BEGIN SHORTER WAY
  // Clean up files before making a call
  system(clean_up_string);

  ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);

  // if successful and rows returned, then just print out some debug
  if (ret == 0) {
    printf("Found data in database!\n");
  }
  // if successful and no rows returned, we need to insert it
  else if (ret == 1) {
    printf("Found not data in database...inserting it now!\n");
    sprintf (SQLQuery,"INSERT INTO place "
	     "(name, address, city, state, zip) "
	     "VALUES(\"%s\",\"%s\", \"%s\",\"%s\", \"%s\") ",
	     start_name, start_add, start_city, start_state, start_zip);
    printf("insert_row_into_map: insertion [%s] ", SQLQuery);
    ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
    if (ret < 0) {
      printf("\ninsert_row_into_map: Error inserting into database\n");
    }
    else {
      printf("successful!\n");
    }
  }
  // these are the two error codes
  else {
    printf("insert_row_into_map: Returned error code from "
	   "process_query_for_single_entry!\n");
    return -1;
  } 
  // END SHORTER WAY
  
  // Now to check whether the ending address is found in the place table
  //
  sprintf (SQLQuery, "select * from place where name like \"%s\" "
	   "and city like \"%s\" and state like \"%s\" and zip like \"%s\" ",
	   end_name, end_city, end_state, end_zip);
  
  printf("insert_row_into_map query [%s]\n", SQLQuery);
  
  /*
    BEGIN LONGER WAY
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
  
  if (x == 0) {
    res = mysql_store_result(myData);
    if (res == NULL) {
      printf("Unable to contact database in insert_row_into_map\n");
      return -1;
    }
    row = mysql_fetch_row(res);
    if (row)
      exist = 1;
    else
      exist = 0;
    
    num_fields = mysql_num_fields(res);
    fields = mysql_fetch_fields(res);
    
    //debug begin
    for (i = 0; i < num_fields; i++) {
      printf("Field %u is %s\n", i, fields[i].name);
    }
    printf("\n");
    //debug end
  }
  
  if (exist == 1) {     
    do { //begin do
      for (k = 0; k < (int)num_fields; k++) {
	if (row[k] != NULL)
	  printf(" %s ", row[k]);
	else
	  printf("field %d is NULL\n", k);
      }
      printf("\n");
    } //end do
    while ((row = mysql_fetch_row(res)));
  }
  else {   // no data exist, insert the data
    sprintf (SQLQuery,"INSERT INTO place "
	     "(name, address, city, state, zip) "
	     "VALUES(\"%s\",\"%s\",\"%s\", \"%s\", \"%s\") ",
	     end_name, end_add, end_city, end_state, end_zip);
    
    printf("insert_row_map [%s]", SQLQuery);
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
    row_count++;
    printf("row inserted=%d\n", row_count);
  }
  END LONGER WAY
  */
  // BEGIN SHORTER WAY
  // Clean up files before making a call
  system(clean_up_string);
  
  ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);

  // if successful and rows returned, then just print out some debug
  if (ret == 0) {
    printf("Found data in database!\n");
  }
  // if successful and no rows returned, we need to insert it
  else if (ret == 1) {
    printf("Found not data in database...inserting it now!\n");
    sprintf (SQLQuery,"INSERT INTO place "
	     "(name, address, city, state, zip) "
	     "VALUES(\"%s\",\"%s\",\"%s\", \"%s\", \"%s\") ",
	     end_name, end_add, end_city, end_state, end_zip);
    printf("insert_row_into_map: insertion [%s]", SQLQuery);
    ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
    if (ret < 0) {
      printf("\ninsert_row_into_map: Error inserting into database\n");
    }
  }
  // these are the two error codes
  else {
    printf("insert_row_into_map: Returned error code from "
	   "process_query_for_single_entry!\n");
    return -1;
  } 
  // END SHORTER WAY

  
  // get the starting place id just inserted or already existing in the table
  //
  sprintf (SQLQuery, "select id from place where "
	   "name like \"%s\" and city like \"%s\" and "
	   "state like \"%s\" and zip like \"%s\" ",
	   start_name, start_city, start_state, start_zip);
  
  printf("insert_row_into_map id-query [%s]\n",SQLQuery);

  // BEGIN SHORTER WAY
  // Clean up files before making a call
  system(clean_up_string);

  ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);

  // if successful and rows returned, then just print out some debug
  if (ret == 0) {
    printf("Found data in database!\n");
    starting = atoi(row[0]);
  }
  // if successful and no rows returned, we need to insert it
  else if (ret == 1) {
    printf("insert_row_into_map: Did not find an ID for the start place "
	   "and the start place was just inserted! Big error!\n");
    return -1;
  }
  // these are the two error codes
  else {
    printf("insert_row_into_map: Returned error code from "
	   "process_query_for_single_entry!\n");
    return -1;
  } 
  // END SHORTER WAY
 
  /*
  BEGIN LONGER WAY
  x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
  
  if (x == 0) {
    res = mysql_store_result(myData);
    if (res == NULL) {
      printf("Unable to contact database in insert_row_into_map\n");
      return -1;
    }
    row = mysql_fetch_row(res);
    if (row) {
      starting = atoi(row[0]);
    }
    else {
      printf("insert_row_into_map: Did not find an ID for the start place "
	     "and the start place was just inserted! Big error!\n");
      return -1;
    }
    
    //debug
    printf("starting place id[%d]\n", starting);
    //debug end
  }
  END LONGER WAY
  */

   
  // get the end place id just inserted or already existing in the table
  //
  sprintf (SQLQuery, "select id from place where "
	   "name like \"%s\" and city like \"%s\" and "
	   "state like \"%s\" and zip like \"%s\" ",
	   end_name, end_city, end_state, end_zip);
  
  printf("insert_row_into_map id-query [%s]\n",SQLQuery);

  /*
    BEGIN LONGER WAY
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
  
  if (x == 0) {
    res = mysql_store_result(myData);
    if (res == NULL) {
      printf("Unable to contact database in insert_row_into_map\n");
      return -1;
    }
    row = mysql_fetch_row(res);
    if (row) {
      ending = atoi(row[0]);
    }
    else {
      printf("insert_row_into_map: Did not find an ID for the end place "
	     "and the start place was just inserted! Big error!\n");
      return -1;
    }
    
    printf("end place id[%d]\n", ending);
  }
  END LONGER WAY
  */

  // BEGIN SHORTER WAY
  // Clean up files before making a call
  system(clean_up_string);
  
  ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);

  // if successful and rows returned, then just print out some debug
  if (ret == 0) {
    printf("Found data in database!\n");
    ending = atoi(row[0]);
  }
  // if successful and no rows returned, we need to insert it
  else if (ret == 1) {
    printf("insert_row_into_map: Did not find an ID for the end place "
	   "and the start place was just inserted! Big error!\n");
    return -1;
  }
  // these are the two error codes
  else {
    printf("insert_row_into_map: Returned error code from "
	   "process_query_for_single_entry!\n");
    return -1;
  } 
  // END SHORTER WAY

  
  // test if the route already exists in the table
  //
  sprintf (SQLQuery,"select * from route where "
	   "sid = '%d' and did = '%d' and routeindex = '%d'",
	   starting, ending, index);
  
  printf("sid|did = startID|DestinationID--testing if route exists[%s]\n",
	 SQLQuery);
  
  /*BEGIN LONGER WAY
    x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
  
  if (x == 0) {
    res = mysql_store_result(myData);
    if (res == NULL) {
      printf("Unable to contact database in insert_row_into_map\n");
      return -1;
    }
    row = mysql_fetch_row(res);
    if (row) {
      exist = 1;
    }
    //no data exist, insert the data
    else { 
      sprintf (SQLQuery, "INSERT INTO route "
	       "(sid, did, routeindex, distance, totaldistance, "
	       "time, directions) VALUES('%d', '%d', '%d', "
	       "'%s', '%s', '%s', '%s')",
	       starting, ending, index, distance,
	       total_distance, time, directions);
      
      x = mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
      row_count++;
      printf("row inserted=%d\n", row_count);
    }
  }
  END LONGER WAY
  */

   // BEGIN SHORTER WAY
  // Clean up files before making a call
  system(clean_up_string);
  
  ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
      
  // if successful and rows returned, then just print out some debug
  if (ret == 0) {
    printf("Found data in database!\n");
    exist = 1; //basically no-op cause not used anywhere else
  }
  // if successful and no rows returned, we need to insert it
  else if (ret == 1) {
    printf("Found not data in database...inserting it now!\n");
    sprintf (SQLQuery, "INSERT INTO route "
	     "(sid, did, routeindex, distance, totaldistance, "
	     "time, directions) VALUES('%d', '%d', '%d', "
	     "'%s', '%s', '%s', '%s')",
	     starting, ending, index, distance,
	     total_distance, time, directions);
    printf("insert_row_into_map: insertion [%s]\n", SQLQuery);
    ret = process_query_for_single_entry(myData, SQLQuery, &row, &res);
    if (ret < 0) {
      printf("insert_row_into_map: Error inserting into database\n");
    }    
  }
  // these are the two error codes
  else {
    printf("insert_row_into_map: Returned error code from "
	   "process_query_for_single_entry!\n");
    return -1;
  } 
  // END SHORTER WAY
  
  fflush(stdout);
  return 1;
}
