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


void substitute_d_by_e(char *string);
char *get_parvalue(char *name_variable);

int sfetch(char *name_variable, char *string)
{
  int i_line=-1;
  char *p;

  i_line=get_parline(name_variable);
  if (i_line ==  -1) 
    return 0;
  else 
    {
      strcpy(string,parvalue[i_line]);

      /* Deal with strings beginning with quotes 
         such as string_name = "my_string" */

      if (string[0] == '"')
	{
	  int len,i;
	  len = strlen(string);

	  for (i=0;i<len-1;i++)
	    string[i] = string[i+1];
	  string[len-1] = '\0';

	  /* Suppose the last character was also a ", zap it */

	  if((p = strchr(string,'"')) != NULL) *p = '\0';
	}
      return 1;
    }
}

int dfetch(char *name_variable, double *dd) 
{
  int i_line=-1;

  i_line=get_parline(name_variable);
  if (i_line == -1) 
    return 0;
  else
    {
      double val;
      substitute_d_by_e(parvalue[i_line]);
      /* *dd = (double) atof(parvalue[i_line]);  */
      sscanf(parvalue[i_line],"%le",&val);
      *dd = (double) val; 
      return 1;
    }
}

int ffetch(char *name_variable, float *rr)
{
  int i_line=-1;

  i_line=get_parline(name_variable);
  if (i_line == -1) 
    return 0;
  else 
    {
      substitute_d_by_e(parvalue[i_line]);
      sscanf(parvalue[i_line],"%e",rr);
      return 1;
    }
}
   
int ifetch(char *name_variable, int *ii)
{
  int i_line;

  i_line=get_parline(name_variable);
  if (i_line == -1)
    return 0;
  else 
    {
      *ii= atoi(parvalue[i_line]);
      return 1;
    }
}

int get_parline(char *name_variable)
{
  int i_line=-1,line_index=0,flag;
  
  flag = GP_opened();
  if(flag == 0)
       {
	 fprintf(stderr,"Getpar: Read %d lines of input\n",
			    GP_read_parfile());
       }
  while(parname[line_index] != NULL)
    {
      if(strcmp(parname[line_index],name_variable) == 0)
	i_line = line_index;
      line_index++;
    }
  return i_line;
}
  
void substitute_d_by_e(char *string) 
{
  int index;

  index =0;
  while ((*string != '\0') && (index < MAX_STRING_LENGTH) ) 
    {
      if((*string == 'd' ) || (*string == 'D' )) *string = 'e';
      string++;
      index++;
    }
}