#include <windows.h>
#include <sapi.h>
#ifndef USE_WIN_STREAM
#include <iostream>
#endif
#include <vector>
#include <string>
#include "st.h"

using namespace std;

class tts {
   bool read_line(string & line) {
      bool rc = false;
      line = "";
      char ch;
      ch = cin.get();
      while(cin) {
         rc = true;
         if(ch == '\n') {
            break;
         }
         line += ch;
         ch = cin.get();
      }
      return rc;
   }
   wchar_t * GetWC(const char *c) {
      const size_t cSize = strlen(c)+1;
      wchar_t *wc = new wchar_t[cSize];
      mbstowcs (wc, c, cSize);
      return wc;
   }
public:
   int run(const vector< string > & args) {
      ISpVoice * pVoice = NULL;

      ::CoInitialize(NULL);

      HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
      string line0;
      wchar_t * line;
      if(args.size() == 0) {
         cout << "Windows text to speach prompt.." << endl;
         cout << "Build Date: " << __DATE__ << " " << __TIME__ << endl;
         cout << "Author: Matt Coan" << endl;
         cout << "Type \"exit\" to quit..." << endl << endl;
         cout << "tts> ";
         while(read_line(line0)) {
            if(line0 == "exit") {
               break;
            }
            line = GetWC(line0.c_str());
            hr = pVoice->Speak(line, 0, NULL);
            delete [] line;
            cout <<  "tts> ";
         }
      }
      else {
         for(size_t i = 0; i < args.size(); i++) {
            line0 += args[i] + " ";
         }
         line = GetWC(line0.c_str());
         hr = pVoice->Speak(line, 0, NULL);
         delete [] line;
      }
      pVoice->Release();
      pVoice = NULL;

      ::CoUninitialize();
      return 0;
   }
};

#ifdef NO_MAIN
extern "C" {
extern int tts_main(int argc, char ** argv);
}
int tts_main(int argc, char ** argv)
#else
int main(int argc, char ** argv)
#endif
{
   int rc = 0;
   vector< string > args;
   for(int i = 1; i < argc; i++) {
      args.push_back(argv[i]);
   }
   try {
      tts TTS;
      rc = TTS.run(args);
   }
   catch(...) {
      cerr << "exception..." << endl;
      rc = 1;
   }
   return rc;
}
