#include "Math_s.hh"
#include <fstream.h>

class MathImpl : public virtual POA_Math::Std, 
		 public virtual PortableServer::RefCountServantBase
{
 public:
    MathImpl(long m) : inc_m(m) {
        cout << "New math obj created: " << m << endl;
    };
    CORBA::Long inc(long n) {
        cout << "Math obj (" << inc_m << ") inc: " << n << endl;
	return n + inc_m; 
    };
 protected:
    const long inc_m;
};

class MathBstImpl : public virtual POA_Math::Bst, 
		    public virtual PortableServer::RefCountServantBase
{
    Math::Std_ptr getit(long m) {

      	try {

	    // Create Math object
	    PortableServer::ServantBase_var servant = new MathImpl(m);
	    cout << "Created std math object." << endl;

	    // Activate it on the default POA which is root POA
	    PortableServer::POA_var default_poa = _default_POA();
	    CORBA::Object_var ref = default_poa->servant_to_reference(servant);
	    Math::Std_var mstd = Math::Std::_narrow(ref);

	    // Print out the new std math object
	    cout << "Returning std math object ref. " << endl;

	    // Return the math object reference
	    return Math::Std::_duplicate(mstd);

	} catch(const CORBA::Exception& e) {
	    cerr << "_narrow caught exception: " << e << endl;
	} 

	return Math::Std::_nil();
    };

    Math::Bst::StdSeq *getthem(long l) {

	Math::Bst::StdSeq_var listv = new Math::Bst::StdSeq(l);
	listv->length(l);
	cout << "Created sequence (" << l << ")" << endl;

	try {

	    for (CORBA::ULong i = 0; i < l; i++) {
		PortableServer::ServantBase_var servant = new MathImpl(i+1);
		cout << "Created impl (" << i + 1 << ")" << endl;
		PortableServer::POA_var default_poa = _default_POA();
		CORBA::Object_var ref = default_poa->servant_to_reference(servant);
		Math::Std_var mstd = Math::Std::_narrow(ref);
		listv[i] = Math::Std::_duplicate(mstd);
		cout << "Created object (" << i + 1 << ")" << endl;
	    }
	    
	    return listv._retn();
	
	} catch(const CORBA::Exception& e) {
	    cerr << "Caught exception: " << e << endl;
	}

	listv->length(0);
	return listv._retn();
 
    }
};
