//	Album List for Winamp
//	Copyright (C) 1999-2001 Safai Ma
//
//	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., 675 Mass Ave, Cambridge, MA 02139, USA.
/*
 * WINSOCK2.CPP
 *
 * Interface glue code to the Winsock
 */
#include "stdafx.h"

#define WINSOCK_API_LINKAGE
#include <winsock2.h>

static HINSTANCE hDllWS2 = 0L;
static DWORD	 nRef = 0L;

static int (WSAAPI *pWSAStartup)(WORD, LPWSADATA)						= NULL;
static int (WSAAPI *pWSACleanup)(void)									= NULL;
static struct hostent FAR *(WSAAPI *pgethostbyname)(const char FAR *)	= NULL;
static int (WSAAPI *pgethostname)(char FAR *, int)						= NULL;

void WinsockFree();
BOOL WinsockLoad()
{
	// check for multiple instances and increment reference counts.
	if (nRef != 0)
	{
		nRef++;
		return TRUE;
	}

	hDllWS2 = LoadLibrary("WS2_32.DLL");
	if (!hDllWS2)
	{
		WinsockFree();
		return FALSE;
	}

	pWSAStartup		= (int (WSAAPI *)(WORD, LPWSADATA))						GetProcAddress(hDllWS2, "WSAStartup");
	pWSACleanup		= (int (WSAAPI *)(void))								GetProcAddress(hDllWS2, "WSACleanup");
	pgethostbyname	= (struct hostent FAR *(WSAAPI *)(const char FAR *))	GetProcAddress(hDllWS2, "gethostbyname");
	pgethostname	= (int (WSAAPI *)(char FAR *, int))						GetProcAddress(hDllWS2, "gethostname");

	WORD wVersionRequested = MAKEWORD(1, 1);
	WSADATA wsaData;
	WSAStartup( wVersionRequested, &wsaData );

	// increment reference counts
	nRef++;

	return TRUE;
}

void WinsockFree()
{
	// check reference count first
	if (nRef == 0) return;
	if (--nRef != 0) return;

	WSACleanup();

	pWSAStartup		= NULL;
	pWSACleanup		= NULL;
	pgethostbyname	= NULL;
	pgethostname	= NULL;

	FreeLibrary(hDllWS2);
	hDllWS2 = NULL;
}

extern "C"
struct hostent FAR *WSAAPI gethostbyname(const char FAR * name)
{
	return pgethostbyname ? pgethostbyname(name) : NULL;
}

int WSAAPI gethostname(char FAR * name, int namelen)
{
	return pgethostname ? pgethostname(name, namelen) : SOCKET_ERROR;
}

int WSAAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
{
	return pWSAStartup ? pWSAStartup(wVersionRequested, lpWSAData) : WSAVERNOTSUPPORTED;
}

int WSAAPI WSACleanup(void)
{
	return pWSACleanup ? pWSACleanup() : 0;
}
