#include <string>
#include <stdio.h>
#include <strings.h>

#include "exception.h"

PammmException::PammmException(const char *msg) {
	m_msg = msg;
}

PammmException::PammmException(const char *const msg, const char *const detail){
	char buf[sizeof(msg)+sizeof(detail)+10];
	sprintf("%s: %s", msg, detail);
	m_msg = buf;
}

PammmException::~PammmException() { }

void PammmException::Show() { std::cout << m_msg << "\n"; }


WindowsException::WindowsException(int error, const char *error_source) :
		PammmException(format_message(error, error_source).c_str()) { }


std::string WindowsException::format_message(int error, const char *format){

	static struct ErrorMap { int errcode; const char *format; }
		error_map[] =
		{ {193, "%d is not a valid Win32 executable."}

		};

	std::string msgbuf("Error: ");

	/*  Look for error among known error codes */

	unsigned int ii;
	const char *format_ptr = 0;
	char *buf;
	for ( ii=0 ; ii<sizeof(error_map)/sizeof(ErrorMap) ; ii++ ){
		if ( error_map[ii].errcode== error ){
			int len = strlen(error_map[ii].format)+20;				// @@@ bad
			buf = new char[len];
			format_ptr = error_map[ii].format;
			}
		}
	if ( ii>=sizeof(error_map)/sizeof(ErrorMap) ){
		buf = new char[20];
		format_ptr = "%d";
		}
	sprintf(buf, format_ptr, error);
	msgbuf += buf;
	return msgbuf;
}
