#include "MathImpl.h"
#include <fstream.h>

int main(int argc, char* const* argv) 
{
    try {

	//
	// The following is not application specific
	//

	// Initialize the ORB.
	CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

	// get a reference to the root POA
	CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
	PortableServer::POA_var rootPOA = PortableServer::POA::_narrow(obj);
    
	CORBA::PolicyList policies;
	policies.length(1);
	policies[(CORBA::ULong)0] = 
	    rootPOA->create_lifespan_policy(PortableServer::PERSISTENT);

	// get the POA Manager
	PortableServer::POAManager_var poa_manager = rootPOA->the_POAManager();

	// Create myPOA with the right policies
	PortableServer::POA_var myPOA = 
	    rootPOA->create_POA("math_poa", poa_manager, policies); 

	//
	// Create and activate servant
	//

	// Create the servant 
	MathImpl mathServant;
	MathBstImpl mathBstServant;

	// Decide on the ID for the servant
	PortableServer::ObjectId_var mathId =
	    PortableServer::string_to_ObjectId("Math");
	PortableServer::ObjectId_var mathBstId =
	    PortableServer::string_to_ObjectId("BstMath");

	// Activate the servant with the ID on myPOA
	myPOA->activate_object_with_id(mathId, &mathServant);
	myPOA->activate_object_with_id(mathBstId, &mathBstServant);

	// Activate the POA Manager
	poa_manager->activate();

	// Write reference to file

	CORBA::Object_var ref;
	CORBA::String_var string_ref;
	ofstream refFile;

	ref = myPOA->id_to_reference(mathId.in());
	string_ref = orb->object_to_string(ref.in());
	refFile.open("ior.dat");
	refFile << string_ref << endl;
	refFile.close();

	ref = myPOA->id_to_reference(mathBstId.in());
	string_ref = orb->object_to_string(ref.in());
	refFile.open("iior.dat");
	refFile << string_ref << endl;
	refFile.close();

	cout << "Math server is ready" << endl; 

	// Wait for incoming requests
	orb->run();

    } catch(const CORBA::Exception& e) {
	cerr << e << endl;
	return 1;
    }
    return 0;
}
