/** @file sample which is called by spwan
 *
 * Last CVS checkin:
 * $Date: $
 * $Author: scheff $
 */

/**************************************************************************/

// standard C/C++ header:
#include <exception>
#include <iostream>
#include <string>

// Gnome header:
#include <glib/gtimer.h>
#include <glibmm/timer.h>

using namespace std;

/**************************************************************************/

/// provides an exception for abort.
class Abort: public exception {
  /// returns text with exception description.
  public: virtual const char* what(void) const;
};

/**************************************************************************/

const char* Abort::what(void) const
{
  return "Intentional abort thrown.";
}

/**************************************************************************/

/// @name Settings & Options
//@{
static double tWait = 3.0; ///< sleep time
static int ret = 0; ///< main function return value
static bool forceAbort = false; ///< flag: true ... throw Abort()
static bool noPause = false; ///< flag: true ... skip user confirm
//@}

/** waits for user confirm.
 *
 * @param action text with next action
 */
static void pause(const char *action)
{
  if (!noPause) {
    cout << "test-spawn: Press [ENTER] to " << action << ": " << flush;
    string str; getline(cin, str);
  }
}

/** provides the main function of application.
 *
 * @param argc number of command line arguments
 * @param argv pointer to array of pointers to strings with command line
 *        arguments
 * @return 0 ... application exited regularly\n
 *         else ... execution of application aborted
 */
int main(int argc, char *argv[])
{
  cout << "test-spawn: start" << endl;
  // process options
  for (int i = 1; i < argc; ++i) {
    string arg = argv[i];
    /* unused:
    if (arg == "-wait") {
      ++i; tWait = strtod(argv[i], 0);
      cout << "test-spawn: wait = " << tWait << endl;
    } else*/ if (arg == "-return") {
      ++i; ret = atoi(argv[i]);
      cout << "test-spawn: return = " << ret << endl;
    } else if (arg == "-throw") {
      forceAbort = true;
      cout << "test-spawn: will abort" << endl;
    } else if (arg == "-nopause") noPause = true;
  }
  // write to console
  pause("continue");
  cout << "test-spawn: Output to cout" << endl;
  cerr << "test-spawn: Output to cerr" << endl;
  cout << "test-spawn: Another output to cout" << endl;
  cerr << "test-spawn: Another output to cerr" << endl;
  // consume some time
  cout << "test-spawn: Waiting for " << tWait << " s..." << endl;
  Glib::usleep((gulong)(G_USEC_PER_SEC * tWait));
  // abort?
  if (forceAbort) throw Abort();
  // done
  pause("finish");
  return ret;
}

