// RollCode2.cpp : Defines the entry point for the application.
//

#include "stdafx.h"

//===========================================================================

#define	USER_FILE_NAME		"Sonix5"		// Please update to your code name

#define	ROLLING_ADDRESS		"0x200"			// Start address for rolling code

#define	ROLLING_LENGTH		2				// n * Word, Max is 16

#define	INIT_ROLLCODE		"12345678"		// first rolling code, length = n * 4 nibble


/////////////////////////////////////////////////////////////////////////////
// The one and only application object

//using namespace std;

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	char	localfilepath[_MAX_PATH];
	char	exedrive[_MAX_DRIVE], exedir[_MAX_DIR], file[_MAX_FNAME], ext[_MAX_EXT];

	GetModuleFileName(NULL, localfilepath, _MAX_PATH);
	_splitpath(localfilepath, exedrive, exedir, file, ext);
	_makepath(localfilepath, exedrive, exedir, USER_FILE_NAME, "INI");

#ifdef	ROLLING_ADDRESS
	WritePrivateProfileString("Rolling Code", "Address",		ROLLING_ADDRESS,	localfilepath);
#endif
	CString	str;
	str.Format("%d", ROLLING_LENGTH);
	WritePrivateProfileString("Rolling Code", "Word_Length",	str,		localfilepath);
	str.Format("%s%s", file, ext);
	WritePrivateProfileString("Rolling Code", "ExeFile",		str,		localfilepath);

	const	int		UC_MAX_LENGTH	=	16;
	char	TempBuf[UC_MAX_LENGTH*4+1];

//	If fist inital, set to value = INIT_ROLLCODE
	GetPrivateProfileString("Rolling Code", "Way", "", TempBuf, UC_MAX_LENGTH*4+1, localfilepath);
	WritePrivateProfileString("Rolling Code", "Way",	"EXE",		localfilepath);
	if (TempBuf[0] == 0)
	{
		WritePrivateProfileString("Rolling Code", "Count", INIT_ROLLCODE, localfilepath);
		return 0;
	}

//	If fist inital, set to value = INIT_ROLLCODE
	GetPrivateProfileString("Rolling Code", "Count", "", TempBuf, UC_MAX_LENGTH*4+1, localfilepath);
	if (TempBuf[0] == 0)
	{
		WritePrivateProfileString("Rolling Code", "Count", INIT_ROLLCODE, localfilepath);
		return 0;
	}

//	Read Initial value

	UINT	uc_Length	=	ROLLING_LENGTH, i, j;
	UINT	len = strlen(TempBuf);
	UINT	uc_Count[UC_MAX_LENGTH];

	for (i = 0, j = 0; i < uc_Length; i++, j+=4)
	{
		if (len > j)
		{
			char	TempVal[] = "0000";
			strncpy(TempVal, TempBuf + j, 4);
			uc_Count[i] = (UINT)strtol(TempVal, NULL, 16);
		}
		else uc_Count[i] = 0;
	}

//	Add value, please modify for youself

	UINT	add	=	5;

	for (i = 0; i < uc_Length; i++)
	{
		uc_Count[i] += add;
		if (uc_Count[i] < 0x10000) break;
		uc_Count[i] &= 0xFFFF;	add = 1;
	}

//	Save to INI file

	for (i = 0; i < uc_Length; i++)
	{
		sprintf(TempBuf + i*4, "%04X", uc_Count[i]);
	}
	WritePrivateProfileString("Rolling Code", "Count", TempBuf, localfilepath);

	return 0;
}



