

/* Pocket Smalltalk
   Copyright (c) 1998,1999 by Andrew Brault
   http://www.pocketsmalltalk.com
   See LICENSE.TXT for license information */

#include "main.h"


static void run_program(void);


#ifdef USE_MATHLIB
UInt MathLibRef;
static void init_mathlib(void);
static void close_mathlib(void);
#endif



DWord PilotMain(Word cmd, Ptr cmdPBP, Word launchFlags)
{
  if(cmd == sysAppLaunchCmdNormalLaunch) {
#ifdef USE_MATHLIB
    init_mathlib();
#endif  
    run_program();
#ifdef USE_MATHLIB
    close_mathlib();
#endif     
  }

  return 0;
}


void panic(char * message)
{
  ErrDisplay(message);
}



static void run_program(void)
{

  init_trap_dispatcher();
  if (initialize_memory()) {
	  initialize_vm();
#ifdef POSER_PROFILING
	HostProfileInit(50000, 800);
	HostProfileStart();
#endif
	  run_vm();
  };
#ifdef POSER_PROFILING
	HostProfileStop();
	HostProfileDump("profdump");
	HostProfileCleanup();
#endif
  shutdown_memory();
}


#ifdef USE_MATHLIB

static void init_mathlib(void)
{
  Err error;

  error = SysLibFind(MathLibName, &MathLibRef);
  if(error)
      error = SysLibLoad(LibType, MathLibCreator, &MathLibRef);
  if(error)
    panic("Can't find MathLib"); 
  error = MathLibOpen(MathLibRef, MathLibVersion);
  if(error)
    panic("Can't open MathLib");
}


static void close_mathlib(void)
{
  UInt usecount;
  Err error;

  error = MathLibClose(MathLibRef, &usecount);
  if(error)
    panic("Can't close MathLib");
  if(usecount == 0)
    SysLibRemove(MathLibRef);  
}
#endif




