// $Id: main.cc,v 1.17 2003/05/13 08:14:39 ta_muto Exp $
// startup function

#include <common.h>
#include <CConfig.h>
#include <CEnvironment.h>
#include <CRequest.h>
#include <CStdoutWrapper.h>
#include <IDispatch.h>
#include <CScriptlet.h>
#include <CStdError.h>

int main(int argc, char** argv)
{
	wax::commonInit();
	wax::CStdoutWrapper out;
	wax::IError::registerErrorHandler(new wax::CStdError(&out));

	bool rc = wax::CConfig::init(NULL);
	if(rc == false) {
		wax::IError::outputError();
		return 0;
	}
/*
	xmlChar* cfg = wax::trimPath((const xmlChar*)argv[0]);
	cfg = xmlStrcat(cfg, (const xmlChar*)"config.waxml");
	xmlFree(cfg);
*/

	wax::CRequest request;
	if(request.init() == false) {
		wax::IError::outputError();
		return 0;
	}

	char* translatedPath = getenv("PATH_TRANSLATED");
	if(translatedPath == NULL || !strcmp(translatedPath, "")) {
		wax::IError::message(wax::ERR_PATHTRANSLATED);
		wax::IError::outputError();
		return 0;
	}

	xmlChar* targetScript = xmlStrdup((const xmlChar*)translatedPath);
	if(targetScript == NULL) {
		wax::IError::message(wax::ERR_OUTOFMEMORY, LOCATION);
		wax::IError::outputError();
		return 0;
	}

	bool error = false;
	wax::CEnvironment runenv(&request);
	if(runenv.prepare(targetScript) == false) {
		error = true;
	} else {
		wax::IDispatch* dispatch = wax::CScriptlet::parse(&runenv);
		if(dispatch == NULL) {
			error = true;
		} else {
			if(dispatch->execute() == false) {
				error = true;
			} else {
				dispatch->output(&out);
			}
			delete dispatch;
		}
	}
	if(error == true) {
		wax::IError::outputError();
	}
	xmlFree(targetScript);

	wax::CConfig::free();
	wax::IError::unregisterErrorHandler();

	wax::commonExit();
	return 0;
}
