/******************************************************************************
 * $LastChangedDate: 2011-04-23 21:07:07 -0400 (Sat, 23 Apr 2011) $
 * @file
 * @author  Jim E. Brooks  http://www.palomino3d.org
 * @brief   Glue the modules together.
 *//*
 * LEGAL:   COPYRIGHT (C) 2007 JIM E. BROOKS
 *          THIS SOURCE CODE IS RELEASED UNDER THE TERMS
 *          OF THE GNU GENERAL PUBLIC LICENSE VERSION 2 (GPL 2).
 ******************************************************************************/

#define GLUE_MODULE_CC 1
#include "base/module.hh"
#include "base/misc.hh"
#include "base/stream.hh"
using namespace base;
#include "glue/module.hh"
#include "glue/conf.hh"
#include "glue/sim_time.hh"
#include "glue/core2lua.hh"

#if COMPILE_SDL
#include <SDL.h>
// SDL header defines a main() macro, undefine it.
#undef main
#endif // COMPILE_SDL

namespace glue {

/*****************************************************************************
 * Initialize module.
 *****************************************************************************/
void
Init( const base::InitArgs& initArgs )
{

BEGIN_ONCE {

    // Initialize Conf struct.
    // Not MODULE_CONF macro since mValid isn't true yet.
    glue::global::gConf.Init( initArgs ); // glue-specific

    for ( int i = 1; i < initArgs.mArgc; ++i )
    {
        if ( STREQ( initArgs.mArgv[i], "-hour" ) )
        {
            // -hour fp (not int)
            ++i;  // to arg's value
            const fp hour = Argf( i, initArgs.mArgc, initArgs.mArgv );
            GET_SIM_TIME().SetHour( hour );
            CLOG << "Set hour to " << hour << std::endl;
        }
    }

    // Glue between C++ core and Lua.
    Core2Lua::GetInstance();  // subtle way to initialize

#if COMPILE_SDL
    // Initialize SDL.
    if ( GLUE_CONF.mEnableSDL )
    {
        // Even though SDL video isn't used, SDL_INIT_VIDEO is needed for joystick.
        if ( SDL_Init( SDL_INIT_NOPARACHUTE | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO ) == 0 )
        {
            COUT << "Enabled SDL." << std::endl;
            atexit( SDL_Quit );
        }
        else
        {
            throw Exception( string("ERROR: Failed to initialize SDL ") + string(SDL_GetError()) );
        }
    }
#endif // COMPILE_SDL

} END_ONCE

}

/*****************************************************************************
 * Start module.
 *****************************************************************************/
void
Start( void )
{
    // NOP
}

} // namespace glue
