# include <ohana.h>

#ifndef whitespace
#define whitespace(c) (((c) == ' ') || ((c) == '\t'))
#endif

/* Strip whitespace from the start and end of STRING. */
int stripwhite (char *string) {

  int i;

  if (string == (char *) NULL) return (FALSE);

  for (i = 0; whitespace (string[i]); i++);
  if (i) memmove (string, string + i, strlen(string+i)+1);
  for (i = strlen (string) - 1; (i > 0) && whitespace (string[i]); i--);
  string[++i] = 0;
  return (i);

}

/* compare two strings either as strings, or as numbers if both are
   pure numeric strings (base 10) */
int strnumcmp (char *str1, char *str2) {

  char *end1;
  char *end2;
  int num1, num2;
  int value;
 
  value = FALSE;
  num1 = strtol (str1, &end1, 10);
  num2 = strtol (str2, &end2, 10);

  if (!end1[0] && !end2[0] && (num1 == num2)) {
    value = TRUE;
  }
  if (!strcmp (str1, str2)) {
    value = TRUE;
  }
  
  return (value);
}

/* create a new string from this string */
char *strcreate (char *string) {

  char *line;

  if (string == (char *) NULL) return ((char *) NULL);
  
  ALLOCATE (line, char, MAX (1, strlen(string)) + 1);
  line = strcpy (line, string);

  return (line);
}

/* create a new string of length n from this string */
char *strncreate (char *string, int n) {

  char *line;

  if (string == (char *) NULL) return ((char *) NULL);
  
  ALLOCATE (line, char, n + 1);
  memcpy (line, string, n);
  line[n] = 0;
  return (line);
}

int scan_line (FILE *f, char *line) {

  int i, status;
  char c;
  
  status = EOF + 1;
  
  for (i = 0, c = 0; (c != '\n') && (status != EOF); i++) {
    status = fscanf (f, "%c", &c);
    line[i] = c;
  }
  line[i - 1] = 0;  /* this could make things crash! */

  if (i > 1) {
    status = EOF + 1;
  }

  return (status);
}

char *_parse_nextword (char *string) {

  if (string == (char *) NULL) return ((char *) NULL);

  for (; isspace (*string); string++);
  for (; (*string != 0) && !isspace (*string); string++);
  for (; isspace (*string); string++);
  return (string);
}

int dparse (double *X, int NX, char *line) {

  int i;
  char *word;
  char *ptr;

  word = line;
  for (i = 0; i < NX - 1; i++)
    word = _parse_nextword (word);

  *X = strtod (word, &ptr);
  if (ptr == word) return (FALSE);
  if (word[0] == '-') return (-1);
  return (1);
}

int fparse (float *X, int NX, char *line) {

  int i;
  char *word;
  char *ptr;

  word = line;
  for (i = 0; i < NX - 1; i++)
    word = _parse_nextword (word);

  *X = strtod (word, &ptr);
  if (ptr == word) return (FALSE);
  if (word[0] == '-') return (-1);
  return (1);
}

int get_argument (int argc, char **argv, char *arg) {

  int i;

  for (i = 0; i < argc; i++) {
    if (!strcmp(argv[i], arg))
      return (i);
  }
  
  return ((int)NULL);
}

int remove_argument (int N, int *argc, char **argv) {

  int i;

  if ((N != (int)NULL) && (N != 0)) {
    (*argc)--;
    for (i = N; i < *argc; i++) {
      argv[i] = argv[i+1];
    }
  }

  return (N);
}
