// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2005.  All Rights Reserved
//
// The Wild Magic Library (WM3) source code is supplied under the terms of
// the license agreement
//     http://www.geometrictools.com/License/WildMagic3License.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.

#include "WildMagic3.h"
#include "TreeControl.h"
using namespace Wm3;

//----------------------------------------------------------------------------
static char* ProcessCommand (char* acArgument)
{
    int iLength = (int)strlen(acArgument);

    // strip off quotes if command line was built from double-clicking a file
    char* acProcessed = new char[iLength+1];
    if ( acArgument[0] == '\"' )
    {
        strcpy(acProcessed,acArgument+1);  // remove leading quote
        if ( acArgument[iLength-1] == '\"' )
            acProcessed[iLength-2] = '\0';  // remove trailing quote
    }
    else
    {
        strcpy(acProcessed,acArgument);
    }

    return acProcessed;
}
//----------------------------------------------------------------------------
static int Run (HINSTANCE hInstance, LPSTR acIFile)
{
    if ( !acIFile || strlen(acIFile) <= 0 )
        return -1;

    char* acModIFile = ProcessCommand(acIFile);

    Stream kStream;
    bool bLoaded = kStream.Load(acModIFile);
    if ( !bLoaded )
    {
        delete[] acModIFile;
        return -2;
    }

    SpatialPtr spkRoot = DynamicCast<Spatial>(kStream.GetObjectAt(0));
    if ( !spkRoot )
    {
        delete[] acModIFile;
        return -3;
    }

    spkRoot->UpdateGS();
    spkRoot->UpdateRS();

    TreeControl kTree(hInstance,0,spkRoot,acModIFile,0,0,640,480);
    delete[] acModIFile;

    MSG kMsg;
    BOOL bRet;
    while ( (bRet = GetMessage(&kMsg,0,0,0)) != 0 )
    {
        if ( bRet == -1 )
            break;

        if ( !TranslateAccelerator(0,0,&kMsg) )
        {
            TranslateMessage(&kMsg);
            DispatchMessage(&kMsg);
        }
    }

    spkRoot = 0;
    return 0;
}
//----------------------------------------------------------------------------
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE, LPSTR acIFile, int)
{
    Main::Initialize();
    int iResult = Run(hInstance,acIFile);
    Main::Terminate();
    return iResult;
}
//----------------------------------------------------------------------------



