/** @file main.cpp
    \brief This file contains the main function of the program.

    It tries to open the GUI dynamic library if it can establish a
    connection to a X server and starts the GUI if everything goes
    right.
*/

#include <cmath>
#include <iostream>
#include <sstream>
#include <vector>

#include "dynload.h"
#include "popassert.h"
#include "CColor.h"
#include "CVector3f.h"
#include "compute.h"
#include "CMathExpression.h"
#include "CVectBase.h"
#include "CRenderObj.h"
#include "CCommand.h"
#include "CCommandParser.h"
#include "CCommandExecutor.h"

int (* GetGuiFunc(LIBHANDLE* pGuiLibHandle))(int, char**);


/**
   \brief This is the main function of the program.

   It tries to start the GUI.  If it can't, it starts the console
   interface.
*/
int main(int argc, char** argv)
{
  LIBHANDLE pGuiLibHandle = NULL;
  int (*GuiFunc)(int, char**) = NULL;

  if (argc > 2)
    {
      std::cerr << "Usage: mathray [-nw]" << std::endl;
      return 1;
    }
  else if (argc == 2)
    {
      if (strcmp(argv[1],"-nw") != 0)
        {
          std::cerr << "Usage: mathray [-nw]" << std::endl;
          return 1;
        }
    }
  else
    {
      GuiFunc = GetGuiFunc(&pGuiLibHandle);
    }

  if (GuiFunc)
    {
      // GUI
      int ReturnValue = GuiFunc(argc, argv);
      if (pGuiLibHandle)
        FreeLibrary(pGuiLibHandle);
      return ReturnValue;
    }
  else
    {
      // Console interface
      CCommand Com;
      std::string strCommand;
      CRenderObj surfaceobj;
      while(1)
        {
          Com = CCommand();
          strCommand = "";

          std::cout << "< mathray > ";
          GetLine(std::cin, strCommand);

          Com = CCommandParser::getInstance()->Parse(strCommand);
          CCommandExecutor::getInstance()->Execute(Com, surfaceobj);
        }

      return 0;
    }
}
