#include "stdafx.h"
#include "DbgHelpManager.h"

#ifdef WINDOWS

DbgHelpManager::DbgHelpManager() : created(null), lock(), createCount(0) {}

DbgHelpManager::~DbgHelpManager() {
	util::Lock::L z(lock);
	if (created)
		delete created;
}

void DbgHelpManager::create() {
	util::Lock::L z(instance.lock);
	++instance.createCount;
	if (!instance.created)
		atomicWrite(instance.created, new DbgHelp());
}

DbgHelp *DbgHelpManager::createNoRef() {
	util::Lock::L z(lock);
	if (!created)
		atomicWrite(created, new DbgHelp());
	return atomicRead(created);
}

void DbgHelpManager::destroy() {
	util::Lock::L z(instance.lock);
	// Note: We are robust in case someone created the DbgHelp without an Engine.
	if (instance.createCount <= 1) {
		delete instance.created;
		atomicWrite(instance.created, (DbgHelp *)null);
		instance.createCount = 0;
	} else {
		--instance.createCount;
	}
}

DbgHelpManager DbgHelpManager::instance;

DbgHelp &DbgHelp::instance() {
	DbgHelpManager &m = DbgHelpManager::instance;

	DbgHelp *h = atomicRead(m.created);
	if (!h)
		h = m.createNoRef();

	return *h;
}

#else

DbgHelpManager::DbgHelpManager() {}

DbgHelpManager::~DbgHelpManager() {}

void DbgHelpManager::create() {}

void DbgHelpManager::destroy() {}


#endif
