#include <string.h>
#include <stdlib.h>
#include <stdio.h>

void get_flatfile_param(char *line, char *tmp, int sizeof_tmp) {

   int i, len;
   int x;
   char temp[120];

   // 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
   //
   for (i = 0; (i<len) && (line[i] != ' '); )
     i++;

   // now find next non-white space
   // ie, point to the 't' in 'text' above
   while((i<len) && (line[i] == ' '))
     i++;
   
   // See if it went over the bounds
   if (i<len) {
      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';

   //printf("[%s]\n", temp);

   // replace ' with \'
   len = strlen(temp);

   //printf("len=%d\n",len);

   /* Original implementation, could be problematic,
      re-written below
   for(i=0; i<len; i++) {
     if(temp[i] == '\'') {
       tmp[j++]='\\';
       tmp[j++]=temp[i];
     }
     else {
       tmp[j++]=temp[i];
     }
   }
   tmp[j++]='\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_tmp && 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
       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);
     }
   }
   
   // One final buffersize check
   if ((int)strlen(temp) < sizeof_tmp) {
     strcpy(tmp,temp);
   }
   else {
     printf("Ran out of buffer room with text [%s]\n",temp);
     exit(-1);
   }
  
   printf("after replace ' with \\'[%s]\n", tmp);
}
