/* array.cpp
 *
 * Implements some array utility functions.  These should eventually
 * be done away with in favor of C++ alternatives.
 *
 * $Id: array.cpp,v 1.6 2007/08/04 14:26:17 post Exp $
 */

#include "array.h"
#include <cstdlib>

/* returns a newly allocated array of elements a[s]..a[t-1];
 * if s > t, then will work backword through the array,
 * returning a[s-1]..a[t] (which is a[t..s-1] reversed)
 */
WORDTYPE *splice(WORDTYPE *a, int s, int t) {
  WORDTYPE *b = new WORDTYPE[abs(t-s)+1];
  int i;
    
  for (i = 0; i < abs(t-s); i++)
    b[i] = a[(t>s) ? (s+i) : (s-i-1)];

  b[i] = 0;

  return b;
}

/* prints an array to the specified file stream */
void fprint_array(FILE *where, WORDTYPE *a) {
  WORDTYPE *b = a;
  while (*b)
    fprintf(where, "%d ", *b++);
  fprintf(where, "0");
}

/*  Returns the second-to-last word of phrase.  If the phrase
 *  has only one word, returns 0.
 */
WORDTYPE penultimate_word(WORDTYPE *ph) {
  int len = phraselen(ph);  // we can't avoid a linear pass
  return (len > 1) ? ph[len-2] : 0;
}

/* returns last word of array */

WORDTYPE last_word(WORDTYPE *ph) {
  if (*ph) while (*(ph+1)) ph++;
  return *ph;
}

/* analogous to strlen() */
int phraselen(WORDTYPE* p) {
  int len = -1;
  while (p[++len]) ;
  return len;
}


string lowercase(const string& str) {
  string str2 = str;
  for (unsigned i = 0; i < str2.size(); i++) {
    str2[i] = tolower(str2[i]);
  }
  return str2;
}

/* why can't c++ be more like perl? */
string lcfirst(const string& str) {
  string str2 = str;
  if (str2.size())
    str2[0] = tolower(str2[0]);

  return str2;
}

bool cap (const string& str) {
  if (str.size())
    return str[0] >= 'A' && str[0] <= 'Z';
  return 0;
}

bool has_num (const string& str) {
  for (unsigned i = 0; i < str.size(); i++)
    if (str[i] >= '0' && str[i] <= '9')
      return 1;
  return 0;
}

bool has(const string& str, char tok) {
  for (unsigned i = 0; i < str.size(); i++)
    if (str[i] == tok)
      return 1;
  return 0;
}

bool endswith(const string& str, string pat) {
  if (str.find_last_of(pat) == str.size() - pat.size() + 1)
    return 1;
  return 0;
}

