#include <ctype.h>
#include <windows.h>
#include <string.h>
#include <wchar.h>
#include "xlcall.h"

// Even hackier version of tempstr12 - just use malloc, and don't bother to free ;)
LPXLOPER12 TempStr12(const wchar_t* lpstr)
{
	LPXLOPER12 lpx;
	XCHAR* lps;
	int len;

	len = lstrlenW(lpstr);
	lpx = (LPXLOPER12)malloc(sizeof(XLOPER12) + (len + 1) * 2);

	if (!lpx) return 0;

	lps = (XCHAR*)((CHAR*)lpx + sizeof(XLOPER12));
	lps[0] = (BYTE)len;
	wmemcpy_s(lps + 1, len + 1, lpstr, len);
	lpx->xltype = xltypeStr;
	lpx->val.str = lps;

	return lpx;
}

BOOL WINAPI DllMain(HANDLE hInstance, ULONG ul_reason_for_call,
	LPVOID lpReserved)
{
	return 1;
}

static const wchar_t* rgFuncs[][3] = {
	{L"poszero", L"B", L"poszero"},
	{L"negzero", L"B", L"negzero"},
	{0,0,0}
};

extern "C" __declspec(dllexport) double poszero() {
	return 0.0;
}

extern "C" __declspec(dllexport) double negzero() {
	return -0.0;
}

extern "C" __declspec(dllexport) int xlAutoOpen(void)
{

	static XLOPER12 xDLL;
	int i;

	Excel12(xlGetName, &xDLL, 0);
	for (i = 0; rgFuncs[i][0]; i++)
	{
		Excel12(xlfRegister, 0, 4,
			(LPXLOPER12)&xDLL,
			(LPXLOPER12)TempStr12(rgFuncs[i][0]),
			(LPXLOPER12)TempStr12(rgFuncs[i][1]),
			(LPXLOPER12)TempStr12(rgFuncs[i][2]));
	}
	Excel12(xlFree, 0, 1, (LPXLOPER12)&xDLL);

	return 1;
}