//#include <stdlib.h>
#include "scc_cfg.h"

LPTSTR GetProgramDir(void)
{
    static TCHAR    szPrgPath[MAX_PATH+2];
    DWORD           cnt;

    memset(szPrgPath, 0, sizeof(szPrgPath));
    if ((cnt = GetModuleFileName(NULL, (TCHAR*)&szPrgPath[1], sizeof(szPrgPath) / sizeof(TCHAR))) == 0) goto gprgdir_exit;
    // seach for '\'
    for (; cnt > 0;)
    {
        if (szPrgPath[--cnt] == '\\')
        {
            szPrgPath[cnt + 1] = 0;
            break;
        }
    }
    szPrgPath[0] = '"';
gprgdir_exit:
    return (LPTSTR)&szPrgPath[1];
}

BOOL load_cfg(LPTSTR cfgpath, SCC_SET *pss)
{
    DWORD           tmp, fsize = 0;
    HANDLE          fH;
    BYTE            buf[sizeof(SCC_SET) + 1], crc8;

    // open file
    if ((fH = CreateFile(cfgpath, GENERIC_READ, 0,
        NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) goto rdfile_err;
    // check file size
    if ((fsize = GetFileSize(fH, NULL)) != sizeof(buf)) goto rdfile_err;
    // reading
    if ((!ReadFile(fH, buf, fsize, &tmp, NULL)) || (tmp != fsize)) goto rdfile_err;
    // calculate CRC8
    for (crc8 = 0, tmp = 0; tmp != (sizeof(buf) - 1); tmp++) crc8 += buf[tmp];
    if (buf[tmp] != crc8) goto rdfile_err;
    memcpy(pss, buf, sizeof(SCC_SET));
    CloseHandle(fH);
    return TRUE;

rdfile_err:
    if (fH != INVALID_HANDLE_VALUE) CloseHandle(fH);
    return FALSE;
}

void save_cfg(LPTSTR cfgpath, SCC_SET *pss)
{
    DWORD       tmp;
    HANDLE      fH;
    BYTE        crc8, *buf;

    buf = (BYTE*)pss;
    // calculate CRC8
    for (crc8 = 0, tmp = 0; tmp != sizeof(SCC_SET); tmp++) crc8 += buf[tmp];
    // open file
    if ((fH = CreateFile(cfgpath, GENERIC_WRITE, 0,
        NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) goto wrfile_err;
    // writing
    if ((!WriteFile(fH, pss, sizeof(SCC_SET), &tmp, NULL)) || (tmp != sizeof(SCC_SET))) goto wrfile_err;
    if ((!WriteFile(fH, &crc8, sizeof(crc8), &tmp, NULL)) || (tmp != sizeof(crc8))) goto wrfile_err;
wrfile_err:
    if (fH != INVALID_HANDLE_VALUE) CloseHandle(fH);
    return;
}
