/* reg.c */
#include "windows.h"

static HKEY key_get(HKEY htopkey, char *keypath){
	HKEY hkey;
	DWORD dwErr;
	if(keypath==0 || keypath[0]==0)
		return htopkey;
	dwErr= RegCreateKeyEx(htopkey, keypath, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkey, NULL);
	return dwErr==ERROR_SUCCESS? hkey : 0;
}
int key_getvalue(HKEY htopkey, char *keypath, char *keyname, unsigned char *Buf, int nb){
	DWORD dw= nb;
	DWORD dwValueType;
	HKEY hkey;
	int ret= 0;
	DWORD dwErr= RegOpenKeyEx(htopkey, keypath, 0, KEY_ALL_ACCESS, &hkey);

	if(dwErr!=ERROR_SUCCESS)
		return 0;
	dwErr= RegQueryValueEx(hkey,keyname,0,&dwValueType,Buf,&dw);
	if(dwErr==ERROR_SUCCESS){
		ret= 2;	/* Flag integer return */
		switch(dwValueType){
		case REG_SZ:
			ret= 1;
			Buf[dw]= 0; break;
		case REG_DWORD_BIG_ENDIAN:
			dw= Buf[3]+256L*(Buf[2]+256L*(Buf[1]+256L*Buf[0]));
			*(DWORD *)Buf= dw;
			break;
		default:
		case REG_BINARY:
			dw= Buf[0]+256L*(Buf[1]+256L*(Buf[2]+256L*Buf[3]));
			*(DWORD *)Buf= dw;
			break;
		}
	}
	if(hkey!=htopkey)
		RegCloseKey(hkey);
	return ret;
}
int key_setint(HKEY htopkey, char *keypath, char *keyname, DWORD dw){
	HKEY hkey= key_get(htopkey, keypath);
	int ret;

	if(hkey==0)
		return 0;	
	ret= ERROR_SUCCESS == RegSetValueEx(hkey, keyname, 0, REG_BINARY, (CONST BYTE *)(&dw), sizeof(dw));
	if(hkey!=htopkey)
		RegCloseKey(hkey);
	return ret;
}
int key_setstring(HKEY htopkey, char *keypath, char *keyname, char *stg){
	HKEY hkey= key_get(htopkey, keypath);
	int ret;

	if(hkey==0)
		return 0;	
	ret= ERROR_SUCCESS == RegSetValueEx(hkey, keyname, 0, REG_SZ, (CONST BYTE *)stg, strlen(stg));
	if(hkey!=htopkey)
		RegCloseKey(hkey);
	return ret;
}


