/* 
    This is very much based on the handle<> from Bjarne Stroustrup's C++ book
	ISBN 0-201-88954-4

    Copyright (C) 2000 Ben Martin

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/


#ifndef INCLUDED_FAMPP_HANDLE_H
#define INCLUDED_FAMPP_HANDLE_H


template<class X> class FamppHandle {

	X* rep;
	int* pcount;

public:

	X* operator->() { return rep; }

	FamppHandle(X* pp): rep(pp), pcount(new int(1)) {
	}
	FamppHandle(const FamppHandle& r): rep(r.rep), pcount(r.pcount) {
		(*pcount)++;
	}

	FamppHandle& operator=(const FamppHandle& r) {
		
		if( rep == r.rep) return *this;
		if( --(*pcount) == 0 ) {
			delete rep;
			delete pcount;
		}

		rep = r.rep;
		pcount = r.pcount;
		(*pcount)++;
		return *this;
	}

	~FamppHandle() {
		if(--(*pcount) == 0) {
			delete rep;
			delete pcount;
		}
	}


	// Needed so that a Handle can be an instance member

	void bind( X* pp ) {
		if( pp != rep ) {

			if(--(*pcount) == 0 ) {
				delete rep;
				*pcount = 1; // recycle pcount
			}
			else
				pcount = new int(1); // new pcount
			
			rep = pp;
		}
	}

  void unbind() 
  {
    --(*pcount);			
    rep = 0;
  }


	X* get_rep() {
		return rep;
	}

};


#endif
