#include <stdio.h>

char *get_punctuation(char *line, int *pos);
void get_word (char *line, int *pos, char *word);
int is_letter (char c);
int is_consonant (char c);
void latinize (char *word, char *latin);

int main (int argc, char *argv[]) {
  FILE *in, *out;
  char line[500];
  char *punctuation;
  int position;
  char word[100];
  char latin[100]; /* move up */

  /* error checking */
  if (argc != 3) {
    printf ("Must provide two filenames"
            " as arguments.\n");
    exit (1);
  }

/* open files for input and output */
  in = fopen (argv[1], "r");
  out = fopen (argv[2], "w");

  while (1) {

  /* attempt to read in a line */
    if (fgets (line, 500, in)) {

      position = 0;
      while (1) {

      /* get punctuation before word or eol */
        punctuation =
          get_punctuation (line, &position);
        fprintf (out, "%s", punctuation);
      /* if saw eol, break */
        if (line[position] == '\0') {
          break;
        }
      /* get word from line; different approach */
        get_word (line, &position, word);

      /* convert word to Pig Latin; */
        latinize (word, latin);

      /* write out converted word; */
        fprintf (out, "%s", latin);
      } /* while */
    } /* if */
    else break;
  }
/* close files; */
  fclose (in);
  fclose (out);
}

char *get_punctuation(char line[], int *pos) {
  int start = *pos;
  char *punc;
  int i;

  /* Find end of punctuation (letter or eol) */
  while (line[*pos] != 0 &&
         !is_letter (line[*pos]))
    (*pos)++;
  if (*pos == start) {
    return ""; 
  }
  /* Allocate space for punctuation and copy it */
  punc = (char *) malloc (*pos - start + 1);
  for (i = 0; i < *pos - start; i++) {
    *(punc + i) = line[start + i];
  }
  *(punc + i) = '\0';
  return punc;
}

void get_word (char *line, int *pos, char *word) {
  while (is_letter (line[*pos])) {
    *word = line[*pos];
    word++;
    (*pos)++;
  }
  *word = '\0';
}

int is_letter (char c) {
  if (c >= 'a' && c <= 'z') return 1;
  if (c >= 'A' && c <= 'z') return 1;
  if (c == '\'' || c == '-') return 1;
  return 0;
}

void latinize (char *word, char *latin) {
  int count = 0;
  int dest = 0;
  int i;

  /* Count consonants at beginning */
  while (is_consonant (word[count])) count++;

  /* Copy subsequent letters (if any) to latin */
  for (i = count; word[i] != '\0'; i++)
    latin[dest++] = word[i];

  /* If # consonants > 0, copy them to latin */
  if (count > 0)
    for (i = 0; i < count; i++)
      latin[dest++] = word[i];
  else /* move 'h' to latin */
    latin[dest++] = 'h';

  /* move "ay\0" to latin */
  latin[dest++] = 'a';
  latin[dest++] = 'y';
  latin[dest] = '\0';
}

int is_consonant (char c) {
  if (!is_letter (c)) return 0;
  if (strchr ("aeiouAEIOU", c)) return 0;
  return 1;
}

