/* File: vstart.c
   
   A function that returns the first word
   in a string that starts with a vowel.
*/

#include <stdio.h>
#include <ctype.h>
#include "genlib.h"
#include "simpio.h"
#include "strlib.h"


/* Function Prototype */
string vstart(string) ;
bool isvowel(char) ;
int vposition(string) ;


main() {
   string str ;

   printf("This program finds the first word ") ;
   printf("starts with a vowel\n") ;
   printf("End the program by entering a blank line.\n") ;
   while (TRUE) {
      printf("String: ") ;
      str = GetLine() ;
      if ( StringEqual(str, "") ) break ;
      printf("The word is: %s.\n", vstart(str)) ;
   }
}


/* Return true if the given character is a vowel */
bool isvowel (char c) {
  char uc ;

  uc = toupper(c) ;
  if ( (uc == 'A') || uc == 'E' || uc == 'I' ||
     (uc == 'O') || uc == 'U') {
     return(TRUE) ;
  } else {
     return(FALSE) ;
  }
}

/* Find the position of first word that starts 
   with a vowel */
int vposition(string str) {
   char c ;
   int i, n ;
   bool first_letter;

   first_letter = TRUE ;
   n = StringLength(str) ;
   for (i = 0 ; i < n ; i++) {
      c = IthChar(str, i) ;
      if ( first_letter && !isspace(c) ) {
         first_letter = FALSE ;
	 if ( isvowel(c) ) return(i) ;
      } else if ( !first_letter && isspace(c) ) {
	 first_letter = TRUE ; 
      }
   } /* end for loop */
   return(n) ;
}


/* Return the first word that starts with a vowel */
string vstart(string str) {
   char c ;
   int start, stop, n ;
   string result ;

   n = StringLength(str) ;
   start = vposition(str) ;

   /* Find the end of the word */
   stop = start + 1 ;
   while ( stop < n ) {
      c = IthChar(str, stop) ;
      if (isspace(c)) break ;
      stop++ ; 
   }
  
   /* return the result */
   result = SubString(str, start, stop - 1) ;
   return(result) ; 
}


