Subversion Repositories Games.Chess Giants

Rev

Rev 57 | Rev 62 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. // util.cpp
  2.  
  3. #include "common.h"
  4.  
  5.  
  6. // internal typedefs
  7. typedef struct wsaerror_s
  8. {
  9.    int number;
  10.    const wchar_t *description;
  11. } wsaerror_t;
  12.  
  13.  
  14. const wchar_t *GetDirectoryPath (const wchar_t *pathname, wchar_t *path)
  15. {
  16.    // this function builds a directory path out of a full file pathname
  17.  
  18.    int char_index;
  19.    int length;
  20.  
  21.    length = (int) wcslen (pathname); // get length of pathname first
  22.    if (length > MAX_PATH - 1)
  23.       length = MAX_PATH - 1; // bound it to MAX_PATH characters max
  24.  
  25.    for (char_index = 0; char_index < length; char_index++)
  26.    {
  27.       path[char_index] = pathname[char_index]; // now copy pathname in the destination string
  28.       if (pathname[char_index] == 0)
  29.          break; // don't copy beyond the end of source
  30.    }
  31.    path[length] = 0; // terminate the string
  32.  
  33.    // now scan the destination string starting from the end until a field separator is found
  34.    while ((length > 0) && !((path[length] == '\\') || (path[length] == '/')) && (path[length] != ':'))
  35.       length--; // go back one character after the other as long as it's not the case
  36.  
  37.    // given the type of field separator we stopped on, keep it or not
  38.    if (path[length] == ':')
  39.       length++; // if it's a disk letter separator, keep it
  40.  
  41.    path[length] = 0; // terminate the string at this position
  42.    return (path); // and return a pointer to it
  43. }
  44.  
  45.  
  46. void CreateOrUpdateApplicationMenu (void)
  47. {
  48.    // this function creates or re-creates the main application menu and its accelerator table
  49.  
  50.    HMENU hDropDownMenu;
  51.    ACCEL accelerators[] =
  52.    {
  53.       {FVIRTKEY | FCONTROL, L'O',     MENUID_GAME_LOAD},
  54.       {FVIRTKEY | FCONTROL, L'S',     MENUID_GAME_SAVE},
  55.       {FVIRTKEY | FCONTROL, L'Z',     MENUID_CHESSBOARD_CANCELLASTMOVE},
  56.       {FVIRTKEY,            VK_HOME,  MENUID_CHESSBOARD_BEGINNINGOFGAME},
  57.       {FVIRTKEY,            VK_LEFT,  MENUID_CHESSBOARD_PREVIOUSMOVE},
  58.       {FVIRTKEY,            VK_RIGHT, MENUID_CHESSBOARD_NEXTMOVE},
  59.       {FVIRTKEY,            VK_END,   MENUID_CHESSBOARD_CURRENTSTATEOFGAME},
  60.       {FVIRTKEY | FCONTROL, L'G',     MENUID_CHESSBOARD_GOTOMOVE},
  61.       {FVIRTKEY,            VK_F1,    MENUID_HELP_HELP},
  62.       {FVIRTKEY,            VK_F2,    MENUID_GAME_NEWGAME},
  63.       {FVIRTKEY,            VK_F3,    MENUID_GAME_STATISTICS},
  64.       {FVIRTKEY,            VK_F4,    MENUID_GAME_OPTIONS},
  65.       {FVIRTKEY,            VK_F5,    MENUID_CHESSBOARD_TOPVIEW},
  66.       {FVIRTKEY,            VK_F6,    MENUID_CHESSBOARD_DEFAULTVIEW},
  67.       {FVIRTKEY,            VK_F7,    MENUID_CHESSBOARD_RESETVIEW},
  68.       {FVIRTKEY,            VK_UP,    MENUID_CHESSBOARD_ZOOMIN},
  69.       {FVIRTKEY,            VK_DOWN,  MENUID_CHESSBOARD_ZOOMOUT},
  70.       {FVIRTKEY | FCONTROL, VK_DOWN,  MENUID_CHESSBOARD_DISPLAYWINDOWSDESKTOP},
  71.       {FVIRTKEY,            VK_F8,    MENUID_CHESSBOARD_CHANGEAPPEARANCE},
  72.       {FVIRTKEY,            VK_F9,    MENUID_INTERNET_SHOWONLINEPLAYERS},
  73.       {FVIRTKEY,            VK_F10,   MENUID_INTERNET_SHOWSOUGHTGAMES},
  74.    };
  75.  
  76.    // if needed, destroy the accelerators table and the application menu object
  77.    if (hMainAccelerators)
  78.       DestroyAcceleratorTable (hMainAccelerators);
  79.    hMainAccelerators = NULL;
  80.    if (IsMenu (hMainMenu))
  81.       DestroyMenu (hMainMenu);
  82.    hMainMenu = NULL;
  83.  
  84.    // now create the menu again
  85.    hMainMenu = CreateMenu ();
  86.    hDropDownMenu = CreateMenu (); // create the first drop-down item
  87.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_NEWGAME, LOCALIZE (L"Menu_GameNewGame"));
  88.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_LOAD, LOCALIZE (L"Menu_GameLoadGame"));
  89.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_SETUPPOSITION, LOCALIZE (L"Menu_GameSetupPosition"));
  90.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_GAME_SAVE, LOCALIZE (L"Menu_GameSaveGame")); // initially grayed
  91.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_GAME_SAVEAS, LOCALIZE (L"Menu_GameSaveGameAs")); // initially grayed
  92.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_GAME_SAVEPOSITIONAS, LOCALIZE (L"Menu_GameSavePositionAs")); // initially grayed
  93.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_RESIGN, LOCALIZE (L"Menu_GameResign"));
  94.    AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
  95.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_GAME_STATISTICS, LOCALIZE (L"Menu_GameStatistics"));
  96.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_OPTIONS, LOCALIZE (L"Menu_GameOptions"));
  97.    AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
  98.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_QUIT, LOCALIZE (L"Menu_GameQuit"));
  99.    AppendMenu (hMainMenu, MF_POPUP, (UINT) hDropDownMenu, LOCALIZE (L"Menu_Game"));
  100.    DestroyMenu (hDropDownMenu);
  101.    hDropDownMenu = CreateMenu (); // create the second drop-down item
  102.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_CHESSBOARD_SUGGESTMOVE, LOCALIZE (L"Menu_ChessboardSuggestMove")); // initially grayed
  103.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_CHESSBOARD_CANCELLASTMOVE, LOCALIZE (L"Menu_ChessboardCancelLastMove")); // initially grayed
  104.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_CHESSBOARD_COMMENTMOVE, LOCALIZE (L"Menu_ChessboardCommentMove")); // initially grayed
  105.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_CHESSBOARD_GOTOMOVE, LOCALIZE (L"Menu_ChessboardGoToMove")); // initially grayed
  106.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_CHESSBOARD_SWAPSIDES, LOCALIZE (L"Menu_ChessboardSwapSides")); // initially grayed
  107.    AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
  108.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_TOPVIEW, LOCALIZE (L"Menu_ChessboardTopView"));
  109.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_DEFAULTVIEW, LOCALIZE (L"Menu_ChessboardDefaultView"));
  110.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_RESETVIEW, LOCALIZE (L"Menu_ChessboardResetView"));
  111.    AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
  112.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_CHANGEAPPEARANCE, LOCALIZE (L"Menu_ChessboardChangeAppearance"));
  113.    if (options.want_fullscreen)
  114.    {
  115.       AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
  116.       AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_DISPLAYWINDOWSDESKTOP, LOCALIZE (L"Menu_ChessboardDisplayWindowsDesktop"));
  117.    }
  118.    AppendMenu (hMainMenu, MF_POPUP, (UINT) hDropDownMenu, LOCALIZE (L"Menu_Chessboard"));
  119.    DestroyMenu (hDropDownMenu);
  120.    hDropDownMenu = CreateMenu (); // create the third drop-down item
  121.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_INTERNET_SHOWONLINEPLAYERS, LOCALIZE (L"Menu_InternetShowOnlinePlayers")); // initially grayed
  122.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_INTERNET_SHOWSOUGHTGAMES, LOCALIZE (L"Menu_InternetShowSoughtGames")); // initially grayed
  123.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_INTERNET_SEEKGAME, LOCALIZE (L"Menu_InternetSeekGame")); // initially grayed
  124.    AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
  125.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_INTERNET_CHATTERCHANNELS, LOCALIZE (L"Menu_InternetChatterChannels")); // initially grayed
  126.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_INTERNET_ENTERCHATTEXT, LOCALIZE (L"Menu_InternetEnterChatText")); // initially grayed
  127.    AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
  128.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_INTERNET_DISPLAYPLAYERCARD, LOCALIZE (L"Menu_InternetDisplayPlayerCard")); // initially grayed
  129.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_INTERNET_DISPLAYYOURCARD, LOCALIZE (L"Menu_InternetDisplayYourCard")); // initially grayed
  130.    AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
  131.    AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_INTERNET_MOTD, LOCALIZE (L"Menu_InternetDisplayMOTD")); // initially grayed
  132.    AppendMenu (hMainMenu, MF_POPUP, (UINT) hDropDownMenu, LOCALIZE (L"Menu_Internet"));
  133.    DestroyMenu (hDropDownMenu);
  134.    hDropDownMenu = CreateMenu (); // create the fourth drop-down item
  135.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_HELP, LOCALIZE (L"Menu_HelpDisplayHelp"));
  136.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_GETCHESSGAMES, LOCALIZE (L"Menu_HelpGetChessGames"));
  137.    AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
  138.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_ADDMODIFYVISUALTHEMES, LOCALIZE (L"Menu_HelpAddModifyThemes"));
  139.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_ADDMODIFYENGINES, LOCALIZE (L"Menu_HelpAddModifyEngines"));
  140.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_ADDMODIFYTRANSLATIONS, LOCALIZE (L"Menu_HelpAddModifyTranslations"));
  141.    AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
  142.    AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_ABOUT, LOCALIZE (L"Menu_HelpAbout"));
  143.    AppendMenu (hMainMenu, MF_POPUP, (UINT) hDropDownMenu, LOCALIZE (L"Menu_Help"));
  144.    DestroyMenu (hDropDownMenu);
  145.  
  146.    // finally, set this menu to be the app's menu
  147.    SetMenu (hMainWnd, hMainMenu);
  148.  
  149.    // (re-)create the accelerators
  150.    hMainAccelerators = CreateAcceleratorTable (accelerators, sizeof (accelerators) / sizeof (ACCEL));
  151.  
  152.    return; // finished, application menu is (re)created
  153. }
  154.  
  155.  
  156. void CenterWindow (HWND hWnd, HWND hParentWnd)
  157. {
  158.    // this function centers the specified window on the specified parent.
  159.  
  160.    RECT rRect;
  161.    RECT rParentRect;
  162.    int width;
  163.    int height;
  164.    int parent_width;
  165.    int parent_height;
  166.    int x;
  167.    int y;
  168.  
  169.    // get the current rectangle of the current window
  170.    GetWindowRect (hWnd, &rRect);
  171.    width = rRect.right - rRect.left;
  172.    height = rRect.bottom - rRect.top;
  173.  
  174.    // does this window have a parent AND it is NOT the desktop ?
  175.    if (IsWindow (hParentWnd) && (hParentWnd != GetDesktopWindow ()))
  176.    {
  177.       // get the rectangle of the parent window
  178.       GetWindowRect (hParentWnd, &rParentRect);
  179.       parent_width = rParentRect.right - rParentRect.left;
  180.       parent_height = rParentRect.bottom - rParentRect.top;
  181.  
  182.       // now compute the new X and Y positions so as to have the window centered in its parent
  183.       x = rParentRect.left + parent_width / 2 - width / 2;
  184.       y = rParentRect.top + parent_height / 2 - height / 2;
  185.    }
  186.    else
  187.    {
  188.       // else draw window in the center of the screen
  189.       x = GetSystemMetrics (SM_CXSCREEN) / 2 - width / 2;
  190.       y = GetSystemMetrics (SM_CYSCREEN) / 2 - height / 2;
  191.    }
  192.  
  193.    // now ask to change the position of the window
  194.    SetWindowPos (hWnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
  195.  
  196.    return; // finished
  197. }
  198.  
  199.  
  200. void HintWindow (HWND hWnd)
  201. {
  202.    // this function makes a window blink to the foreground for one second, playing a "ding" sound
  203.  
  204.    FLASHWINFO fw;
  205.  
  206.    PlaySound (L"SystemDefault", NULL, SND_ALIAS | SND_ASYNC); // play a beep
  207.    SetForegroundWindow (hWnd); // modal dialog windows have priority over all others
  208.  
  209.    fw.cbSize = sizeof (fw);
  210.    fw.hwnd = hWnd;
  211.    fw.dwFlags = FLASHW_CAPTION;
  212.    fw.dwTimeout = 50;
  213.    fw.uCount = 3;
  214.    FlashWindowEx (&fw); // flash it so the user notices it
  215.  
  216.    return; // finished
  217. }
  218.  
  219.  
  220. float ProcessTime (void)
  221. {
  222.    // this function returns the time in seconds elapsed since the executable process started.
  223.    // The rollover check ensures the program will continue running after clock() will have
  224.    // overflown its integer value (it does so every 24 days or so). With this rollover check
  225.    // we have a lifetime of more than billion years, w00t!
  226.    // thanks to botmeister for the rollover check idea.
  227.  
  228.    static long prev_clock = 0;
  229.    static long rollover_count = 0;
  230.    long current_clock;
  231.    double time_in_seconds;
  232.  
  233.    current_clock = clock (); // get system clock
  234.  
  235.    // has the clock overflown ?
  236.    if (current_clock < prev_clock)
  237.       rollover_count++; // omg, it has, we're running for more than 24 days!
  238.  
  239.    // now convert the time to seconds since last rollover
  240.    time_in_seconds = (double) current_clock / CLOCKS_PER_SEC; // convert clock to seconds
  241.  
  242.    prev_clock = current_clock; // keep track of current time for future calls of this function
  243.  
  244.    // and return the time in seconds, adding the overflow differences if necessary.
  245.    // HACK: grant the timer to start at 60 seconds to ensure all timer checks work well
  246.    return ((float) (60.0f + time_in_seconds + (((double) LONG_MAX + 1.0) / CLOCKS_PER_SEC) * rollover_count));
  247. }
  248.  
  249.  
  250. float WrapAngle (float angle)
  251. {
  252.    // this function adds or substracts 360 enough times needed to angle to clamp it into the
  253.    // [-180, 180[ bounds.
  254.  
  255.    if (angle < -180.0f)
  256.       angle += 360.0f * abs (((int) angle - 180) / 360);
  257.    else if (angle >= 180)
  258.       angle -= 360.0f * abs (((int) angle + 180) / 360);
  259.  
  260.    if (angle == 180.0f)
  261.       angle = -180.0f; // needs 2nd pass to check for floating-point rounding errors
  262.  
  263.    return (angle); // finished
  264. }
  265.  
  266.  
  267. bool SafeTerminateProcess (HANDLE hProcess, unsigned int uExitCode)
  268. {
  269.    // taken from Dr. Dobbs : how to terminate any process cleanly. Simple : Create a remote
  270.    // thread in it, and make its start address point right into kernel32's ExitProcess()
  271.    // function. This of course assumes that remote code injection is possible.
  272.  
  273.    unsigned long dwTID;
  274.    unsigned long dwCode;
  275.    unsigned long dwErr = 0;
  276.    HMODULE hModule;
  277.    HANDLE hProcessDup;
  278.    HANDLE hRT;
  279.    bool bSuccess = false;
  280.    bool bDup;
  281.    
  282.    bDup = (DuplicateHandle (GetCurrentProcess (), hProcess, GetCurrentProcess (), &hProcessDup, PROCESS_ALL_ACCESS, FALSE, 0) != 0);
  283.  
  284.    // detect the special case where the process is already dead
  285.    if (GetExitCodeProcess (bDup ? hProcessDup : hProcess, &dwCode) && (dwCode == STILL_ACTIVE))
  286.    {
  287.       hModule = GetModuleHandle (L"Kernel32");
  288.       if (hModule)
  289.       {
  290.          hRT = CreateRemoteThread (bDup ? hProcessDup : hProcess, NULL, 0,
  291.                                    (LPTHREAD_START_ROUTINE) GetProcAddress (hModule, "ExitProcess"),
  292.                                    (void *) uExitCode, 0, &dwTID);
  293.          if (hRT != NULL)
  294.          {
  295.             // must wait process to terminate to guarantee that it has exited
  296.             WaitForSingleObject (bDup ? hProcessDup : hProcess, INFINITE);
  297.             CloseHandle (hRT);
  298.             bSuccess = true;
  299.          }
  300.          else
  301.             dwErr = GetLastError ();
  302.       }
  303.       else
  304.          dwErr = GetLastError ();
  305.    }
  306.    else
  307.       dwErr = ERROR_PROCESS_ABORTED;
  308.  
  309.    if (bDup)
  310.       CloseHandle (hProcessDup);
  311.  
  312.    if (!bSuccess)
  313.       SetLastError (dwErr);
  314.  
  315.    return (bSuccess);
  316. }
  317.  
  318.  
  319. wchar_t *ReachBeginningOfCurrentLine (wchar_t *string, wchar_t *current_pos)
  320. {
  321.    // this function parses string backwards from current_pos until it finds either a line feed,
  322.    // or the beginning of string, and returns the first character of the line.
  323.  
  324.    while ((current_pos > string) && (*current_pos != L'\n'))
  325.       current_pos--; // find the previous line feed
  326.  
  327.    if (*current_pos == L'\n')
  328.       current_pos++; // if we've found one, skip it
  329.  
  330.    return (current_pos); // and return where we are
  331. }
  332.  
  333.  
  334. wchar_t *ReachBeginningOfNextLine (wchar_t *string, wchar_t *current_pos)
  335. {
  336.    // this function parses string forward from current_pos until it finds either a line feed,
  337.    // or the end of string, and returns the first character of the line (or NULL).
  338.  
  339.    current_pos = wcschr (current_pos, L'\n'); // find the next line feed
  340.    if (current_pos != NULL)
  341.       current_pos++; // if we've found one, skip it
  342.    if (*current_pos == 0)
  343.       current_pos = NULL; // if it's the end of the string, don't return anything
  344.  
  345.    return (current_pos); // and return what we've found
  346. }
  347.  
  348.  
  349. wchar_t *ReadACompleteLine (wchar_t *destination_line, int max_length, wchar_t *source_buffer)
  350. {
  351.    // copy a line from a given string, ONLY if it ends with a carriage return.
  352.    // use it like:
  353.    // while (blah = sgets (dest, sizeof (dest), blah)) != NULL)
  354.  
  355.    wchar_t *pointer;
  356.    int char_index;
  357.    int source_length;
  358.  
  359.    if (source_buffer[0] == 0)
  360.    {
  361.       destination_line[0] = 0;
  362.       return (NULL); // if EOS return a NULL pointer
  363.    }
  364.  
  365.    pointer = wcschr (source_buffer, L'\n'); // get to the first carriage return we can find
  366.  
  367.    // found none ?
  368.    if (pointer == NULL)
  369.    {
  370.       destination_line[0] = 0;
  371.       return (NULL); // if none return a NULL pointer
  372.    }
  373.  
  374.    // get the number of remaining characters in source string
  375.    source_length = wcslen (source_buffer);
  376.  
  377.    // as long as we haven't filled the destination string...
  378.    for (char_index = 0; char_index < max_length; char_index++)
  379.    {
  380.       destination_line[char_index] = source_buffer[char_index]; // copy the line we found
  381.       if ((char_index + 1 == source_length) || (source_buffer[char_index] == '\n'))
  382.          break; // don't copy beyond the end of source string, nor beyond the end of line
  383.    }
  384.    if (char_index < max_length)
  385.       destination_line[char_index] = 0; // terminate string ourselves
  386.    else
  387.       destination_line[max_length - 1] = 0;
  388.  
  389.    return (&pointer[1]); // and return next line's source buffer pointer
  390. }
  391.  
  392.  
  393. wchar_t *wcsgets (wchar_t *destination_line, int max_length, wchar_t *source_buffer)
  394. {
  395.    // copy a line from a given string. Kinda like fgets() when you're reading from a string.
  396.    // use it like:
  397.    // while (blah = sgets (dest, sizeof (dest), blah)) != NULL)
  398.  
  399.    wchar_t *pointer;
  400.    int char_index;
  401.    int source_length;
  402.  
  403.    if (source_buffer[0] == 0)
  404.    {
  405.       destination_line[0] = 0;
  406.       return (NULL); // if EOS return a NULL pointer
  407.    }
  408.  
  409.    pointer = wcschr (source_buffer, L'\n'); // get to the first carriage return we can find
  410.  
  411.    // found none ?
  412.    if (pointer == NULL)
  413.    {
  414.       // if so, copy the line we found
  415.       for (char_index = 0; char_index < max_length; char_index++)
  416.       {
  417.          destination_line[char_index] = source_buffer[char_index]; // copy the line we found
  418.          if (source_buffer[char_index] == 0)
  419.             break; // don't copy beyond the end of source
  420.       }
  421.  
  422.       if (char_index == max_length)
  423.          destination_line[max_length - 1] = 0; // ensure string is terminated
  424.  
  425.       return (&source_buffer[wcslen (source_buffer)]); // and return a pointer to the end of the string
  426.    }
  427.    else
  428.       pointer++; // else if a carriage return was found, skip it
  429.  
  430.    // get the number of remaining characters in source string
  431.    source_length = wcslen (source_buffer);
  432.  
  433.    // as long as we haven't filled the destination string...
  434.    for (char_index = 0; char_index < max_length; char_index++)
  435.    {
  436.       destination_line[char_index] = source_buffer[char_index]; // copy the line we found
  437.       if ((char_index + 1 == source_length) || (source_buffer[char_index] == '\n'))
  438.          break; // don't copy beyond the end of source string, nor beyond the end of line
  439.    }
  440.    if (char_index < max_length)
  441.       destination_line[char_index] = 0; // terminate string ourselves
  442.    else
  443.       destination_line[max_length - 1] = 0;
  444.  
  445.    return (pointer); // and return next line's source buffer pointer
  446. }
  447.  
  448.  
  449. wchar_t *wcsistr (const wchar_t *haystack, const wchar_t *needle)
  450. {
  451.    // windows has no wcsistr() implementation, so here is mine.
  452.  
  453.    const wchar_t *ptr_upper;
  454.    const wchar_t *ptr_lower;
  455.    const wchar_t *ptr_either;
  456.    size_t needle_length;
  457.  
  458.    needle_length = wcslen (needle); // get needle length
  459.    ptr_either = haystack; // start searching at the beginning of haystack
  460.  
  461.    for (;;) // endless loop
  462.    {
  463.       ptr_upper = wcschr (haystack, towupper (*needle)); // find occurence of first character (uppercase)
  464.       ptr_lower = wcschr (haystack, towlower (*needle)); // find occurence of first character (lowercase)
  465.  
  466.       if ((ptr_upper == NULL) && (ptr_lower == NULL))
  467.          break; // if no occurence in either case, then haystack doesn't contain needle
  468.       else if (ptr_upper == NULL)
  469.          ptr_either = ptr_lower; // no uppercase, check in lowercase
  470.       else if (ptr_lower == NULL)
  471.          ptr_either = ptr_upper; // no lowercase, check in uppercase
  472.       else if (ptr_lower < ptr_upper)
  473.          ptr_either = ptr_lower; // both occurences found, take the first one
  474.       else
  475.          ptr_either = ptr_upper; // both occurences found, take the first one
  476.  
  477.       if (_wcsnicmp (ptr_either, needle, needle_length) == 0) // now compare needle case insensitively at that position in haystack
  478.          return ((wchar_t *) ptr_either); // if we find something, return its position
  479.  
  480.       haystack = ptr_either + 1; // else advance in haystack
  481.    }
  482.  
  483.    return (NULL); // haystack doesn't contain needle
  484. }
  485.  
  486.  
  487. void ConvertCRLFsToSingleSpaces (wchar_t *multiline_string)
  488. {
  489.    // this function modifies multiline_string by removing CRs and turning LFs into single spaces
  490.  
  491.    int length;
  492.    int char_index;
  493.    int char_index2;
  494.  
  495.    length = wcslen (multiline_string); // get input string length
  496.  
  497.    // for each character in string that is NOT a carriage return...
  498.    char_index2 = 0;
  499.    for (char_index = 0; char_index < length; char_index++)
  500.       if (multiline_string[char_index] != L'\r')
  501.       {
  502.          if (multiline_string[char_index] == L'\n')
  503.             multiline_string[char_index2] = L' '; // convert newlines to spaces
  504.          else
  505.             multiline_string[char_index2] = multiline_string[char_index]; // else overwrite string with itself
  506.  
  507.          char_index2++; // we've written one character more
  508.       }
  509.    multiline_string[char_index2] = 0; // finish string
  510.  
  511.    return; // finished, string is now single-line
  512. }
  513.  
  514.  
  515. void ConvertTo7BitASCII (char *dest, size_t dest_size_in_bytes, wchar_t *source)
  516. {
  517.    // helper function to quickly convert a wide char string to 7-bit ASCII
  518.  
  519.    // do the conversion. Use WideCharToMultiByte() preferentially because wcstombs()
  520.    // stops at the first non-convertible character, whereas the former doesn't.
  521.    WideCharToMultiByte (20127, 0, source, -1, dest, dest_size_in_bytes, NULL, NULL); // 20127 is 7-bit US-ASCII code page
  522.    return;
  523. }
  524.  
  525.  
  526. void ConvertToWideChar (wchar_t *dest, size_t dest_size_in_wchars, char *source)
  527. {
  528.    // helper function to quickly convert an ASCII string to wide char
  529.  
  530.    size_t converted_count;
  531.  
  532.    // do the conversion
  533.    mbstowcs_s (&converted_count, dest, dest_size_in_wchars, source, _TRUNCATE);
  534.    return;
  535. }
  536.  
  537.  
  538. void MinutesToWideCharString (wchar_t *dest, size_t dest_size_in_wchars, int minutes)
  539. {
  540.    // helper function to convert a time in minutes in a string mentioning days, hours and minutes
  541.  
  542.    int days;
  543.    int hours;
  544.  
  545.    days = minutes / (60 * 24); // count the number of days
  546.    minutes -= days * (60 * 24); // substract the result
  547.    hours = minutes / 60; // count the number of hours
  548.    minutes -= hours * 60; // substract the result
  549.  
  550.    // now choose the right display format
  551.    if (days > 0)
  552.       swprintf_s (dest, dest_size_in_wchars, L"%d %s %d %s %d %s", days, LOCALIZE (L"Days"), hours, LOCALIZE (L"Hours"), minutes, LOCALIZE (L"Minutes"));
  553.    else if (hours > 0)
  554.       swprintf_s (dest, dest_size_in_wchars, L"%d %s %d %s", hours, LOCALIZE (L"Hours"), minutes, LOCALIZE (L"Minutes"));
  555.    else
  556.       swprintf_s (dest, dest_size_in_wchars, L"%d %s", minutes, LOCALIZE (L"Minutes"));
  557.  
  558.    return; // finished
  559. }
  560.  
  561.  
  562. void SecondsToWideCharString (wchar_t *dest, size_t dest_size_in_wchars, int seconds)
  563. {
  564.    // helper function to convert a time in seconds in a string mentioning days, hours, minutes and seconds
  565.  
  566.    int days;
  567.    int hours;
  568.    int minutes;
  569.  
  570.    days = seconds / (60 * 60 * 24); // count the number of days
  571.    seconds -= days * (60 * 60 * 24); // substract the result
  572.    hours = seconds / (60 * 60); // count the number of hours
  573.    seconds -= hours * (60 * 60); // substract the result
  574.    minutes = seconds / 60; // count the number of minutes
  575.    seconds -= minutes * 60; // substract the result
  576.  
  577.    // now choose the right display format
  578.    if (days > 0)
  579.       swprintf_s (dest, dest_size_in_wchars, L"%d %s %d %s %d %s %d %s", days, LOCALIZE (L"Days"), hours, LOCALIZE (L"Hours"), minutes, LOCALIZE (L"Minutes"), seconds, LOCALIZE (L"Seconds"));
  580.    else if (hours > 0)
  581.       swprintf_s (dest, dest_size_in_wchars, L"%d %s %d %s %d %s", hours, LOCALIZE (L"Hours"), minutes, LOCALIZE (L"Minutes"), seconds, LOCALIZE (L"Seconds"));
  582.    else if (minutes > 0)
  583.       swprintf_s (dest, dest_size_in_wchars, L"%d %s %d %s", minutes, LOCALIZE (L"Minutes"), seconds, LOCALIZE (L"Seconds"));
  584.    else
  585.       swprintf_s (dest, dest_size_in_wchars, L"%d %s", seconds, LOCALIZE (L"Seconds"));
  586.  
  587.    return; // finished
  588. }
  589.  
  590.  
  591. int MonthStringToNumber (wchar_t *month_string)
  592. {
  593.    // helper function to convert a month string to its equivalent number
  594.  
  595.    if (_wcsnicmp (month_string, L"jan", 3) == 0) return (1); // january
  596.    else if (_wcsnicmp (month_string, L"feb", 3) == 0) return (2); // february
  597.    else if (_wcsnicmp (month_string, L"mar", 3) == 0) return (3); // march
  598.    else if (_wcsnicmp (month_string, L"apr", 3) == 0) return (4); // april
  599.    else if (_wcsnicmp (month_string, L"may", 3) == 0) return (5); // may
  600.    else if (_wcsnicmp (month_string, L"jun", 3) == 0) return (6); // june
  601.    else if (_wcsnicmp (month_string, L"jul", 3) == 0) return (7); // july
  602.    else if (_wcsnicmp (month_string, L"aug", 3) == 0) return (8); // august
  603.    else if (_wcsnicmp (month_string, L"sep", 3) == 0) return (9); // september
  604.    else if (_wcsnicmp (month_string, L"oct", 3) == 0) return (10); // october
  605.    else if (_wcsnicmp (month_string, L"nov", 3) == 0) return (11); // november
  606.    else if (_wcsnicmp (month_string, L"dec", 3) == 0) return (12); // december
  607.  
  608.    return (0); // month not found or not a month
  609. }
  610.  
  611.  
  612. bool GetImageSize (const wchar_t *imagefile_pathname, int *width, int *height)
  613. {
  614.    // routine to get the size of a DDS/JPG/PNG/TGA/BMP image. JPEG code courtesy of wischik.com.
  615.  
  616.    wchar_t valid_pathname[MAX_PATH];
  617.    unsigned char buffer[26];
  618.    struct _stat fileinfo;
  619.    FILE *fp;
  620.    int length;
  621.    int pos;
  622.  
  623.    length = wcslen (imagefile_pathname); // get pathname length
  624.  
  625.    // does the pathname we want end with a wildcard ?
  626.    if ((length > 0) && (imagefile_pathname[length - 1] == L'*'))
  627.    {
  628.       // test if a corresponding .dds, .jpg, .jpeg, .png, .tga or .bmp file exists
  629.       wcsncpy_s (valid_pathname, WCHAR_SIZEOF (valid_pathname), imagefile_pathname, length - 1);
  630.  
  631.       // try these extensions one after the other...
  632.       wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"dds");
  633.       if (_wstat (valid_pathname, &fileinfo) != 0)
  634.       {
  635.          wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"jpg");
  636.          if (_wstat (valid_pathname, &fileinfo) != 0)
  637.          {
  638.             wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"jpeg");
  639.             if (_wstat (valid_pathname, &fileinfo) != 0)
  640.             {
  641.                wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"png");
  642.                if (_wstat (valid_pathname, &fileinfo) != 0)
  643.                {
  644.                   wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"tga");
  645.                   if (_wstat (valid_pathname, &fileinfo) != 0)
  646.                   {
  647.                      wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"bmp");
  648.                      if (_wstat (valid_pathname, &fileinfo) != 0)
  649.                         return (false); // if none of these extensions match, bomb out
  650.                   }
  651.                }
  652.             }
  653.          }
  654.       }
  655.    }
  656.    else
  657.       wcscpy_s (valid_pathname, WCHAR_SIZEOF (valid_pathname), imagefile_pathname); // the filename we want is known
  658.  
  659.    // open the file for binary reading first
  660.    _wfopen_s (&fp, valid_pathname, L"rb");
  661.    if (fp == NULL)
  662.       return (false); // if unable to open the file, return FALSE
  663.  
  664.    // get file length
  665.    fseek (fp, 0, SEEK_END);
  666.    length = ftell (fp);
  667.    fseek (fp, 0, SEEK_SET);
  668.  
  669.    // if file is not large enough to hold a single chunk of data, it can't possibly be a valid image
  670.    if (length < 26)
  671.    {
  672.       fclose (fp); // so close it
  673.       return (FALSE); // and return FALSE
  674.    }
  675.  
  676.   // Strategy:
  677.   // reading JPEG dimensions requires scanning through jpeg chunks
  678.   // reading PNG dimensions requires the first 24 bytes of the file
  679.   // reading BMP dimensions requires the first 26 bytes of the file
  680.   // In all formats, the file is at least 26 bytes big, so we'll read that always
  681.    fread (buffer, 26, 1, fp);
  682.  
  683.    // For DDS files, dimensions are given at bytes 12 (height) and 16 (width)
  684.    if ((buffer[0] == 'D') && (buffer[1] == 'D') && (buffer[2] == 'S') && (buffer[3] == ' '))
  685.    {
  686.       memcpy (width, &buffer[16], sizeof (unsigned long));
  687.       memcpy (height, &buffer[12], sizeof (unsigned long));
  688.       fclose (fp); // close file now
  689.       return (true); // copy out the width and height and return TRUE
  690.    }
  691.  
  692.    // For JPEGs, we need to read the first 12 bytes of each chunk.
  693.    // We'll read those 12 bytes at buf+2...buf+14, i.e. overwriting the existing buf.
  694.    else if ((buffer[0] == 0xFF) && (buffer[1] == 0xD8) && (buffer[2] == 0xFF))
  695.    {
  696.       pos = 2; // start at the beginning
  697.  
  698.       // as long as there's the beginning of a new chunk to parse in our buffer...
  699.       while (buffer[2] == 0xFF)
  700.       {
  701.          // is that chunk the one we want ?
  702.          if ((buffer[2 + 1] == 0xC0) || (buffer[2 + 1] == 0xC1) || (buffer[2 + 1] == 0xC2) || (buffer[2 + 1] == 0xC3))
  703.          {
  704.             *height = 256 * (int) buffer[2 + 5] + (int) buffer[2 + 6]; // copy out the height and width
  705.             *width = 256 * (int) buffer[2 + 7] + (int) buffer[2 + 8];
  706.             fclose (fp); // close file now
  707.             return (true); // and return TRUE
  708.          }
  709.  
  710.          pos += 2 + 256 * (int) buffer[2 + 2] + (int) buffer[2 + 3]; // else increase pos by the size of the chunk
  711.          if (pos >= length)
  712.          {
  713.             fclose (fp); // close file now
  714.             return (false); // stop searching if end of file is reached
  715.          }
  716.  
  717.          fseek (fp, pos, SEEK_SET); // seek at beginning of next block
  718.          fread (&buffer[2], 10, 1, fp); // and read another 10-byte block
  719.       }
  720.    }
  721.  
  722.    // PNG: the first frame is by definition an IHDR frame, which gives dimensions
  723.    else if ((buffer[0] == 0x89) && (buffer[1] == 'P') && (buffer[2] == 'N') && (buffer[3] == 'G')
  724.             && (buffer[4] == 0x0D) && (buffer[5] == 0x0A) && (buffer[6] == 0x1A) && (buffer[7] == 0x0A)
  725.             && (buffer[12] == 'I') && (buffer[13] == 'H') && (buffer[14] == 'D') && (buffer[15]=='R'))
  726.    {
  727.       *width = (buffer[16] << 24) | (buffer[17] << 16) | (buffer[18] << 8) | (buffer[19] << 0);
  728.       *height = (buffer[20] << 24) | (buffer[21] << 16) | (buffer[22] << 8) | (buffer[23] << 0);
  729.       fclose (fp); // close file now
  730.       return (true); // copy out the width and height and return TRUE
  731.    }
  732.  
  733.    // TGA: read the image size from the TGA header
  734.    else if ((buffer[0] == 0x00) && ((buffer[1] == 0x00) || (buffer[1] == 0x01)))
  735.    {
  736.       *width = (buffer[13] << 8) | (buffer[12] << 0);
  737.       *height = (buffer[15] << 8) | (buffer[14] << 0);
  738.       fclose (fp); // close file now
  739.       return (true); // copy out the width and height and return TRUE
  740.    }
  741.  
  742.    // BMP: read the bitmap file header, then the image header
  743.    else if ((buffer[0] == 'B') && (buffer[1] == 'M')
  744.             && (buffer[6] == 0) && (buffer[7] == 0) && (buffer[8] == 0) && (buffer[9] == 0))
  745.    {
  746.       memcpy (width, &buffer[18], sizeof (unsigned long));
  747.       memcpy (height, &buffer[22], sizeof (unsigned long));
  748.       fclose (fp); // close file now
  749.       return (true); // copy out the width and height and return TRUE
  750.    }
  751.  
  752.    fclose (fp); // close file now
  753.    return (false); // file is probably not a DDS, BMP, PNG, TGA or JPEG image
  754. }
  755.  
  756.  
  757. void Debug_Init (const wchar_t *logfile_name)
  758. {
  759.    // helper function for debug log file initialization
  760.  
  761.    FILE *fp;
  762.  
  763.    // build the log file full qualified path name
  764.    swprintf_s (logfile_pathname, WCHAR_SIZEOF (logfile_pathname), L"%s/%s", app_path, logfile_name);
  765.  
  766.    // open it and erase it
  767.    _wfopen_s (&fp, logfile_pathname, L"wb");
  768.    if (fp != NULL)
  769.    {
  770.       fwprintf_s (fp, L"===LOG FILE RESET===\n"); // write the log initialization string
  771.       fclose (fp); // flush buffers and close file
  772.    }
  773.  
  774.    return; // finished
  775. }
  776.  
  777.  
  778. void Debug_Log (const wchar_t *fmt, ...)
  779. {
  780.    // helper function for debug logging
  781.  
  782.    FILE *fp;
  783.    va_list argptr;
  784.  
  785.    // open the log file in append mode
  786.    _wfopen_s (&fp, logfile_pathname, L"ab");
  787.    if (fp != NULL)
  788.    {
  789.       va_start (argptr, fmt);
  790.       vfwprintf_s (fp, fmt, argptr); // concatenate all the arguments in one string
  791.       va_end (argptr);
  792.       fclose (fp); // flush buffers and close it
  793.    }
  794.  
  795.    return; // finished
  796. }
  797.  
  798.  
  799. const wchar_t *GetLastNetworkError (void)
  800. {
  801.    // this function retrieves and translates the last WSA error code into a full text string
  802.  
  803.    static const wsaerror_t wsa_errors[] =
  804.    {
  805.       {6, L"WSA_INVALID_HANDLE: Specified event object handle is invalid. [An application attempts to use an event object, but the specified handle is not valid. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
  806.       {8, L"WSA_NOT_ENOUGH_MEMORY: Insufficient memory available. [An application used a Windows Sockets function that directly maps to a Windows function. The Windows function is indicating a lack of required memory resources. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
  807.       {87, L"WSA_INVALID_PARAMETER: One or more parameters are invalid. [An application used a Windows Sockets function which directly maps to a Windows function. The Windows function is indicating a problem with one or more parameters. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
  808.       {995, L"WSA_OPERATION_ABORTED: Overlapped operation aborted. [An overlapped operation was canceled due to the closure of the socket, or the execution of the SIO_FLUSH command in WSAIoctl. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
  809.       {996, L"WSA_IO_INCOMPLETE: Overlapped I/O event object not in signaled state. [The application has tried to determine the status of an overlapped operation which is not yet completed. Applications that use WSAGetOverlappedResult (with the fWait flag set to FALSE) in a polling mode to determine when an overlapped operation has completed, get this error code until the operation is complete. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
  810.       {997, L"WSA_IO_PENDING: Overlapped operations will complete later. [The application has initiated an overlapped operation that cannot be completed immediately. A completion indication will be given later when the operation has been completed. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
  811.       {10004, L"WSAEINTR: Interrupted function call. [A blocking operation was interrupted by a call to WSACancelBlockingCall.]"},
  812.       {10009, L"WSAEBADF: File handle is not valid. [The file handle supplied is not valid.]"},
  813.       {10013, L"WSAEACCES: Permission denied. [An attempt was made to access a socket in a way forbidden by its access permissions. An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO_BROADCAST). Another possible reason for the WSAEACCES error is that when the bind function is called (on Windows NT 4 SP4 or later), another application, service, or kernel mode driver is bound to the same address with exclusive access. Such exclusive access is a new feature of Windows NT 4 SP4 and later, and is implemented by using the SO_EXCLUSIVEADDRUSE option.]"},
  814.       {10014, L"WSAEFAULT: Bad address. [The system detected an invalid pointer address in attempting to use a pointer argument of a call. This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small. For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).]"},
  815.       {10022, L"WSAEINVAL: Invalid argument. [Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function). In some instances, it also refers to the current state of the socket—for instance, calling accept on a socket that is not listening.]"},
  816.       {10024, L"WSAEMFILE: Too many open files. [Too many open sockets. Each implementation may have a maximum number of socket handles available, either globally, per process, or per thread.]"},
  817.       {10035, L"WSAEWOULDBLOCK: Resource temporarily unavailable. [This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket. It is a nonfatal error, and the operation should be retried later. It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse for the connection to be established.]"},
  818.       {10036, L"WSAEINPROGRESS: Operation now in progress. [A blocking operation is currently executing. Windows Sockets only allows a single blocking operation—per- task or thread—to be outstanding, and if any other function call is made (whether or not it references that or any other socket) the function fails with the WSAEINPROGRESS error.]"},
  819.       {10037, L"WSAEALREADY: Operation already in progress. [An operation was attempted on a nonblocking socket with an operation already in progress—that is, calling connect a second time on a nonblocking socket that is already connecting, or canceling an asynchronous request (WSAAsyncGetXbyY) that has already been canceled or completed.]"},
  820.       {10038, L"WSAENOTSOCK: Socket operation on nonsocket. [An operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid.]"},
  821.       {10039, L"WSAEDESTADDRREQ: Destination address required. [A required address was omitted from an operation on a socket. For example, this error is returned if sendto is called with the remote address of ADDR_ANY.]"},
  822.       {10040, L"WSAEMSGSIZE: Message too long. [A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram was smaller than the datagram itself.]"},
  823.       {10041, L"WSAEPROTOTYPE: Protocol wrong type for socket. [A protocol was specified in the socket function call that does not support the semantics of the socket type requested. For example, the ARPA Internet UDP protocol cannot be specified with a socket type of SOCK_STREAM.]"},
  824.       {10042, L"WSAENOPROTOOPT: Bad protocol option. [An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call.]"},
  825.       {10043, L"WSAEPROTONOSUPPORT: Protocol not supported. [The requested protocol has not been configured into the system, or no implementation for it exists. For example, a socket call requests a SOCK_DGRAM socket, but specifies a stream protocol.]"},
  826.       {10044, L"WSAESOCKTNOSUPPORT: Socket type not supported. [The support for the specified socket type does not exist in this address family. For example, the optional type SOCK_RAW might be selected in a socket call, and the implementation does not support SOCK_RAW sockets at all.]"},
  827.       {10045, L"WSAEOPNOTSUPP: Operation not supported. [The attempted operation is not supported for the type of object referenced. Usually this occurs when a socket descriptor to a socket that cannot support this operation is trying to accept a connection on a datagram socket.]"},
  828.       {10046, L"WSAEPFNOSUPPORT: Protocol family not supported. [The protocol family has not been configured into the system or no implementation for it exists. This message has a slightly different meaning from WSAEAFNOSUPPORT. However, it is interchangeable in most cases, and all Windows Sockets functions that return one of these messages also specify WSAEAFNOSUPPORT.]"},
  829.       {10047, L"WSAEAFNOSUPPORT: Address family not supported by protocol family. [An address incompatible with the requested protocol was used. All sockets are created with an associated address family (that is, AF_INET for Internet Protocols) and a generic protocol type (that is, SOCK_STREAM). This error is returned if an incorrect protocol is explicitly requested in the socket call, or if an address of the wrong family is used for a socket, for example, in sendto.]"},
  830.       {10048, L"WSAEADDRINUSE: Address already in use. [Typically, only one usage of each socket address (protocol/IP address/port) is permitted. This error occurs if an application attempts to bind a socket to an IP address/port that has already been used for an existing socket, or a socket that was not closed properly, or one that is still in the process of closing. For server applications that need to bind multiple sockets to the same port number, consider using setsockopt (SO_REUSEADDR). Client applications usually need not call bind at all— connect chooses an unused port automatically. When bind is called with a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is committed. This could happen with a call to another function later, including connect, listen, WSAConnect, or WSAJoinLeaf.]"},
  831.       {10049, L"WSAEADDRNOTAVAIL: Cannot assign requested address. [The requested address is not valid in its context. This normally results from an attempt to bind to an address that is not valid for the local computer. This can also result from connect, sendto, WSAConnect, WSAJoinLeaf, or WSASendTo when the remote address or port is not valid for a remote computer (for example, address or port 0).]"},
  832.       {10050, L"WSAENETDOWN: Network is down. [A socket operation encountered a dead network. This could indicate a serious failure of the network system (that is, the protocol stack that the Windows Sockets DLL runs over), the network interface, or the local network itself.]"},
  833.       {10051, L"WSAENETUNREACH: Network is unreachable. [A socket operation was attempted to an unreachable network. This usually means the local software knows no route to reach the remote host.]"},
  834.       {10052, L"WSAENETRESET: Network dropped connection on reset. [The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. It can also be returned by setsockopt if an attempt is made to set SO_KEEPALIVE on a connection that has already failed.]"},
  835.       {10053, L"WSAECONNABORTED: Software caused connection abort. [An established connection was aborted by the software in your host computer, possibly due to a data transmission time-out or protocol error.]"},
  836.       {10054, L"WSAECONNRESET: Connection reset by peer. [An existing connection was forcibly closed by the remote host. This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close (see setsockopt for more information on the SO_LINGER option on the remote socket). This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.]"},
  837.       {10055, L"WSAENOBUFS: No buffer space available. [An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.]"},
  838.       {10056, L"WSAEISCONN: Socket is already connected. [A connect request was made on an already-connected socket. Some implementations also return this error if sendto is called on a connected SOCK_DGRAM socket (for SOCK_STREAM sockets, the to parameter in sendto is ignored) although other implementations treat this as a legal occurrence.]"},
  839.       {10057, L"WSAENOTCONN: Socket is not connected. [A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using sendto) no address was supplied. Any other type of operation might also return this error—for example, setsockopt setting SO_KEEPALIVE if the connection has been reset.]"},
  840.       {10058, L"WSAESHUTDOWN: Cannot send after socket shutdown. [A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call. By calling shutdown a partial close of a socket is requested, which is a signal that sending or receiving, or both have been discontinued.]"},
  841.       {10059, L"WSAETOOMANYREFS: Too many references. [Too many references to some kernel object.]"},
  842.       {10060, L"WSAETIMEDOUT: Connection timed out. [A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond.]"},
  843.       {10061, L"WSAECONNREFUSED: Connection refused. [No connection could be made because the target computer actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.]"},
  844.       {10062, L"WSAELOOP: Cannot translate name. [Cannot translate a name.]"},
  845.       {10063, L"WSAENAMETOOLONG: Name too long. [A name component or a name was too long.]"},
  846.       {10064, L"WSAEHOSTDOWN: Host is down. [A socket operation failed because the destination host is down. A socket operation encountered a dead host. Networking activity on the local host has not been initiated. These conditions are more likely to be indicated by the error WSAETIMEDOUT.]"},
  847.       {10065, L"WSAEHOSTUNREACH: No route to host. [A socket operation was attempted to an unreachable host. See WSAENETUNREACH.]"},
  848.       {10066, L"WSAENOTEMPTY: Directory not empty. [Cannot remove a directory that is not empty.]"},
  849.       {10067, L"WSAEPROCLIM: Too many processes. [A Windows Sockets implementation may have a limit on the number of applications that can use it simultaneously.WSAStartup may fail with this error if the limit has been reached.]"},
  850.       {10068, L"WSAEUSERS: User quota exceeded. [Ran out of user quota.]"},
  851.       {10069, L"WSAEDQUOT: Disk quota exceeded. [Ran out of disk quota.]"},
  852.       {10070, L"WSAESTALE: Stale file handle reference. [The file handle reference is no longer available.]"},
  853.       {10071, L"WSAEREMOTE: Item is remote. [The item is not available locally.]"},
  854.       {10091, L"WSASYSNOTREADY: Network subsystem is unavailable. [This error is returned by WSAStartup if the Windows Sockets implementation cannot function at this time because the underlying system it uses to provide network services is currently unavailable. Users should check that the appropriate Windows Sockets DLL file is in the current path, that they are not trying to use more than one Windows Sockets implementation simultaneously. If there is more than one Winsock DLL on your system, be sure the first one in the path is appropriate for the network subsystem currently loaded, that the Windows Sockets implementation documentation to be sure all necessary components are currently installed and configured correctly.]"},
  855.       {10092, L"WSAVERNOTSUPPORTED: Winsock.dll version out of range. [The current Windows Sockets implementation does not support the Windows Sockets specification version requested by the application. Check that no old Windows Sockets DLL files are being accessed.]"},
  856.       {10093, L"WSANOTINITIALISED: Successful WSAStartup not yet performed. [Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times.]"},
  857.       {10101, L"WSAEDISCON: Graceful shutdown in progress. [Returned by WSARecv and WSARecvFrom to indicate that the remote party has initiated a graceful shutdown sequence.]"},
  858.       {10102, L"WSAENOMORE: No more results. [No more results can be returned by the WSALookupServiceNext function.]"},
  859.       {10103, L"WSAECANCELLED: Call has been canceled. [A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.]"},
  860.       {10104, L"WSAEINVALIDPROCTABLE: Procedure call table is invalid. [The service provider procedure call table is invalid. A service provider returned a bogus procedure table to Ws2_32.dll. This is usually caused by one or more of the function pointers being NULL.]"},
  861.       {10105, L"WSAEINVALIDPROVIDER: Service provider is invalid. [The requested service provider is invalid. This error is returned by the WSCGetProviderInfo and WSCGetProviderInfo32 functions if the protocol entry specified could not be found. This error is also returned if the service provider returned a version number other than 2.0.]"},
  862.       {10106, L"WSAEPROVIDERFAILEDINIT: Service provider failed to initialize. [The requested service provider could not be loaded or initialized. This error is returned if either a service provider's DLL could not be loaded (LoadLibrary failed) or the provider's WSPStartup or NSPStartup function failed.]"},
  863.       {10107, L"WSASYSCALLFAILURE: System call failure. [A system call that should never fail has failed. This is a generic error code, returned under various condition. Returned when a system call that should never fail does fail. For example, if a call to WaitForMultipleEvents fails or one of the registry functions fails trying to manipulate the protocol/namespace catalogs. Returned when a provider does not return SUCCESS and does not provide an extended error code. Can indicate a service provider implementation error.]"},
  864.       {10108, L"WSASERVICE_NOT_FOUND: Service not found. [No such service is known. The service cannot be found in the specified name space.]"},
  865.       {10109, L"WSATYPE_NOT_FOUND: Class type not found. [The specified class was not found.]"},
  866.       {10110, L"WSA_E_NO_MORE: No more results. [No more results can be returned by the WSALookupServiceNext function.]"},
  867.       {10111, L"WSA_E_CANCELLED: Call was canceled. [A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.]"},
  868.       {10112, L"WSAEREFUSED: Database query was refused. [A database query failed because it was actively refused.]"},
  869.       {11001, L"WSAHOST_NOT_FOUND: Host not found. [No such host is known. The name is not an official host name or alias, or it cannot be found in the database(s) being queried. This error may also be returned for protocol and service queries, and means that the specified name could not be found in the relevant database.]"},
  870.       {11002, L"WSATRY_AGAIN: Nonauthoritative host not found. [This is usually a temporary error during host name resolution and means that the local server did not receive a response from an authoritative server. A retry at some time later may be successful.]"},
  871.       {11003, L"WSANO_RECOVERY: This is a nonrecoverable error. [This indicates that some sort of nonrecoverable error occurred during a database lookup. This may be because the database files (for example, BSD-compatible HOSTS, SERVICES, or PROTOCOLS files) could not be found, or a DNS request was returned by the server with a severe error.]"},
  872.       {11004, L"WSANO_DATA: Valid name, no data record of requested type. [The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for. The usual example for this is a host name-to-address translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server). An MX record is returned but no A record—indicating the host itself exists, but is not directly reachable.]"},
  873.       {11005, L"WSA_QOS_RECEIVERS: QOS receivers. [At least one QOS reserve has arrived.]"},
  874.       {11006, L"WSA_QOS_SENDERS: QOS senders. [At least one QOS send path has arrived.]"},
  875.       {11007, L"WSA_QOS_NO_SENDERS: No QOS senders. [There are no QOS senders.]"},
  876.       {11008, L"WSA_QOS_NO_RECEIVERS: QOS no receivers. [There are no QOS receivers.]"},
  877.       {11009, L"WSA_QOS_REQUEST_CONFIRMED: QOS request confirmed. [The QOS reserve request has been confirmed.]"},
  878.       {11010, L"WSA_QOS_ADMISSION_FAILURE: QOS admission error. [A QOS error occurred due to lack of resources.]"},
  879.       {11011, L"WSA_QOS_POLICY_FAILURE: QOS policy failure. [The QOS request was rejected because the policy system couldn't allocate the requested resource within the existing policy.]"},
  880.       {11012, L"WSA_QOS_BAD_STYLE: QOS bad style. [An unknown or conflicting QOS style was encountered.]"},
  881.       {11013, L"WSA_QOS_BAD_OBJECT: QOS bad object. [A problem was encountered with some part of the filterspec or the provider-specific buffer in general.]"},
  882.       {11014, L"WSA_QOS_TRAFFIC_CTRL_ERROR: QOS traffic control error. [An error with the underlying traffic control (TC) API as the generic QOS request was converted for local enforcement by the TC API. This could be due to an out of memory error or to an internal QOS provider error.]"},
  883.       {11015, L"WSA_QOS_GENERIC_ERROR: QOS generic error. [A general QOS error.]"},
  884.       {11016, L"WSA_QOS_ESERVICETYPE: QOS service type error. [An invalid or unrecognized service type was found in the QOS flowspec.]"},
  885.       {11017, L"WSA_QOS_EFLOWSPEC: QOS flowspec error. [An invalid or inconsistent flowspec was found in the QOS structure.]"},
  886.       {11018, L"WSA_QOS_EPROVSPECBUF: Invalid QOS provider buffer. [An invalid QOS provider-specific buffer.]"},
  887.       {11019, L"WSA_QOS_EFILTERSTYLE: Invalid QOS filter style. [An invalid QOS filter style was used.]"},
  888.       {11020, L"WSA_QOS_EFILTERTYPE: Invalid QOS filter type. [An invalid QOS filter type was used.]"},
  889.       {11021, L"WSA_QOS_EFILTERCOUNT: Incorrect QOS filter count. [An incorrect number of QOS FILTERSPECs were specified in the FLOWDESCRIPTOR.]"},
  890.       {11022, L"WSA_QOS_EOBJLENGTH: Invalid QOS object length. [An object with an invalid ObjectLength field was specified in the QOS provider-specific buffer.]"},
  891.       {11023, L"WSA_QOS_EFLOWCOUNT: Incorrect QOS flow count. [An incorrect number of flow descriptors was specified in the QOS structure.]"},
  892.       {11024, L"WSA_QOS_EUNKOWNPSOBJ: Unrecognized QOS object. [An unrecognized object was found in the QOS provider-specific buffer.]"},
  893.       {11025, L"WSA_QOS_EPOLICYOBJ: Invalid QOS policy object. [An invalid policy object was found in the QOS provider-specific buffer.]"},
  894.       {11026, L"WSA_QOS_EFLOWDESC: Invalid QOS flow descriptor. [An invalid QOS flow descriptor was found in the flow descriptor list.]"},
  895.       {11027, L"WSA_QOS_EPSFLOWSPEC: Invalid QOS provider-specific flowspec. [An invalid or inconsistent flowspec was found in the QOS provider-specific buffer.]"},
  896.       {11028, L"WSA_QOS_EPSFILTERSPEC: Invalid QOS provider-specific filterspec. [An invalid FILTERSPEC was found in the QOS provider-specific buffer.]"},
  897.       {11029, L"WSA_QOS_ESDMODEOBJ: Invalid QOS shape discard mode object. [An invalid shape discard mode object was found in the QOS provider-specific buffer.]"},
  898.       {11030, L"WSA_QOS_ESHAPERATEOBJ: Invalid QOS shaping rate object. [An invalid shaping rate object was found in the QOS provider-specific buffer.]"},
  899.       {11031, L"WSA_QOS_RESERVED_PETYPE: Reserved policy QOS element type. [A reserved policy element was found in the QOS provider-specific buffer.]"}
  900.    };
  901.    size_t error_index;
  902.    int error;
  903.  
  904.    error = WSAGetLastError (); // first get the error code from the system
  905.  
  906.    // for each error code we know, see if it's the one we want
  907.    for (error_index = 0; error_index < sizeof (wsa_errors) / sizeof (wsaerror_t); error_index++)
  908.       if (wsa_errors[error_index].number == error)
  909.          return (wsa_errors[error_index].description); // if it's that one, return its description
  910.  
  911.    // error code not found
  912.    return (L"Unknown error.");
  913. }
  914.  
  915.  
  916. HICON W32LoadIcon (const wchar_t *fmt, ...)
  917. {
  918.    // this function loads an icon from a file into an icon handle.
  919.  
  920.    static wchar_t icofile_pathname[MAX_PATH];
  921.    va_list argptr;
  922.  
  923.    // concatenate all the arguments in one string
  924.    va_start (argptr, fmt);
  925.    wvsprintf (icofile_pathname, fmt, argptr);
  926.    va_end (argptr);
  927.  
  928.    // load the icon from file and return the resulting handle
  929.    return ((HICON) LoadImage (NULL, icofile_pathname, IMAGE_ICON, 0, 0, LR_LOADFROMFILE));
  930. }
  931.  
  932.  
  933. HBITMAP W32LoadImage (const wchar_t *fmt, ...)
  934. {
  935.    // this function loads an image from a file into a bitmap handle.
  936.  
  937.    static wchar_t imgfile_pathname[MAX_PATH];
  938.    va_list argptr;
  939.  
  940.    // concatenate all the arguments in one string
  941.    va_start (argptr, fmt);
  942.    wvsprintf (imgfile_pathname, fmt, argptr);
  943.    va_end (argptr);
  944.  
  945.    // load the image from file and return the resulting handle
  946.    return ((HBITMAP) LoadImage (NULL, imgfile_pathname, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE));
  947. }
  948.  
  949.  
  950. bool IsRegistrationCorrect (const wchar_t *email, const unsigned long code)
  951. {
  952.    // quick helper to see if the program is registered. It contains an address to potential crackers.
  953.    // Notice: user's email address may be a wchar_t array, and thus may contain Unicode characters.
  954.    // /!\ WARNING: THE CRACKER MESSAGE SHOULD NEVER CHANGE, AND NEITHER SHOULD THE ALGORITHM BELOW /!\
  955.  
  956.    static const char crackermsg[] = "Please, respect my work. DON'T PUBLISH if you crack my program. Thank you and happy cracking :)";
  957.  
  958.    unsigned long correct_activationcode;
  959.    int byte_index;
  960.    int length;
  961.  
  962.    // compute the maximal length of the string for which we need to checksum
  963.    length = wcslen (email);
  964.    if (length > sizeof (crackermsg) - 1)
  965.       length = sizeof (crackermsg) - 1; // bound it to the length of the cracker message
  966.  
  967.    // hash the supplied e-mail
  968.    correct_activationcode = 5381; // start value
  969.    for (byte_index = 0; byte_index < sizeof (crackermsg) - 1; byte_index++)
  970.       correct_activationcode = ((correct_activationcode << 5) + correct_activationcode)
  971.                                  + ((unsigned long) (length > 0 ? towlower (email[byte_index % length]) : 1) // prevent zero divide
  972.                                     ^ (unsigned long) crackermsg[byte_index]); // hash = hash * 33 + (char(email) ^ char(crackermsg))
  973.    correct_activationcode &= 0x7FFFFFFF; // make sure the results remain positive
  974.  
  975.    // as usuals, it alls boils down to a single test :(
  976.    return ((length > sizeof ("a@b.c") - 1) && (code == correct_activationcode));
  977. }
  978.