#include "CosNaming_c.hh"
#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);
    
	// get a reference to the Naming Service root_context
	CosNaming::NamingContext_var rootContext = 
	    CosNaming::NamingContext::_narrow(
                orb->resolve_initial_references("NameService"));

	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; 

	// Decide on the ID for the servant
	PortableServer::ObjectId_var mathId =
	    PortableServer::string_to_ObjectId("Math");

	// Activate the servant with the ID on myPOA
	myPOA->activate_object_with_id(mathId, &mathServant);

	// Activate the POA Manager
	poa_manager->activate();

	// Reg reference to ns
	CORBA::Object_var ref = myPOA->id_to_reference(mathId.in());
	CosNaming::Name name;
	name.length(1);
	name[0].id = (const char *) "Math";
	name[0].kind = (const char *) "";
	rootContext->rebind(name, ref);

	cout << "Math server is ready" << endl; 

	// Wait for incoming requests
	orb->run();

    } catch(const CORBA::Exception& e) {
	cerr << e << endl;
	return 1;
    }
    return 0;
}
