#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include "ack_w32.h"

static HKEY hKey;
static char expanded[1000];

void
AcksysOpenReg(HKEY hive,char *path)
{
	int rc;
	if(ERROR_SUCCESS != (rc=RegOpenKeyEx( hive, path,
		0,KEY_QUERY_VALUE,&hKey))){
		printf("ERROR: RegOpenKeyEx, error %d\n", rc);
		exit(1);
	}
}

void
AcksysOpenMcxParams(char *cardNumber/*1..N*/)
{
	int rc;

	if(strnicmp(cardNumber,"Mcx",3) == 0)
		cardNumber += 3;
	sprintf(expanded,
		"SYSTEM\\CurrentControlSet\\Services\\Mcx\\Parameters\\Mcx%s",
		cardNumber);
	rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE,expanded,0,
			KEY_QUERY_VALUE|KEY_SET_VALUE,&hKey);
	if(rc != ERROR_SUCCESS){
		printf("ERROR: RegOpenKeyEx, error %d\n", rc);
		exit(1);
	}
}

DWORD
AcksysGetRegDword(char *nom)
{
	DWORD type, value, len, rc;

	len = sizeof(value);

	if(ERROR_SUCCESS != (rc=RegQueryValueEx( hKey, nom,
		NULL, &type, (LPBYTE)&value, &len))){
		//printf("ERROR: RegQueryValueEx, error %d\n", rc);
		//exit(1);
		return 0;
	}else if(type != REG_DWORD){
		printf("%s value is not a REG_DWORD\n",nom);
		exit(1);
	}
	SetLastError(ERROR_SUCCESS);
	return value;
}

PCHAR
AcksysGetRegExpandedString(char *nom)
{
	DWORD type, len, rc;
	char value[1000];

	len = sizeof(value);

	if(ERROR_SUCCESS != (rc=RegQueryValueEx( hKey, nom,
		NULL, &type, (LPBYTE)&value, &len))){
		printf("ERROR: RegQueryValueEx, error %d\n", rc);
		exit(1);
	}else if(type != REG_EXPAND_SZ){
		printf("%s value is not a REG_EXPAND_SZ\n",nom);
		exit(1);
	}
	if(ExpandEnvironmentStrings(value,expanded,sizeof(expanded)) == 0){
		printf("Cannot expand <%s>\n",value);
		exit(1);
	}
	return expanded;
}

PCHAR
AcksysGetRegString(char *nom)
{
	DWORD type, len, rc;
	char value[1000];

	len = sizeof(value);

	if(ERROR_SUCCESS != (rc=RegQueryValueEx( hKey, nom,
		NULL, &type, (LPBYTE)&expanded, &len))){
		printf("ERROR: RegQueryValueEx, error %d\n", rc);
		exit(1);
	}else if(type != REG_SZ){
		printf("%s value is not a REG_SZ\n",nom);
		exit(1);
	}
	return expanded;
}

BOOL
AcksysSetRegDword(char *nom,DWORD value)
{
	DWORD len, rc;

	len = sizeof(value);
	rc = RegSetValueEx( hKey, nom, 0, REG_DWORD, (LPBYTE)&value, len );
	SetLastError(rc);
	return (rc == ERROR_SUCCESS);
}
