#include <windows.h>
#include "postman1.h"

struct
    {
    BOOL    bColor;
    int     nWindows,
            nLevel;
    HWINFO  hWinfo;
    LPWINFO lpWinfo;
    } ListStats = {FALSE, 0, 0, NULL, 0L};

static void winlist_enum  (HWND hwnd);
static void winlist_count (HWND hwnd);





void winlist_enumAll (HWND hwnd)
    {
    HWND hwndFirst = GetWindow (hwnd, GW_HWNDFIRST);

    ListStats.nWindows   = 0;
    ListStats.nLevel     = 0;
    ListStats.bColor     = FALSE;
    winlist_count (hwndFirst);

    if (ListStats.hWinfo) GlobalFree (ListStats.hWinfo);
    ListStats.hWinfo  = (HWINFO)  GlobalAlloc (GMEM_MOVEABLE, ListStats.nWindows*sizeof(WINFO));
    ListStats.lpWinfo = (LPWINFO) GlobalLock  (ListStats.hWinfo);
    winlist_enum (hwndFirst);
    GlobalUnlock (ListStats.hWinfo);
    }


static void winlist_count (HWND hwnd)
     {
     HWND hwndChild,
          hwndSibling;

     ListStats.nWindows++;

     if (hwndChild = GetWindow (hwnd, GW_CHILD))  // count children
          winlist_count (hwndChild);

     if (hwndSibling = GetWindow(hwnd, GW_HWNDNEXT)) // count siblings
          winlist_count (hwndSibling);
     }


static void winlist_enum (HWND hwnd)
     {
     HWND hwndChild,
          hwndSibling;
     int  nLength;

     GetClassName  (hwnd, ListStats.lpWinfo->szClassName, CLASSNAMEMAX);
     ListStats.lpWinfo->szClassName [CLASSNAMEMAX - 1] = '\0';

     nLength = GetWindowText (hwnd, ListStats.lpWinfo->szTitle, WINDOWTITLEMAX);
     ListStats.lpWinfo->szTitle [nLength] = '\0';

     ListStats.lpWinfo->hwnd    = hwnd;
     ListStats.lpWinfo->hwndParent = GetParent (hwnd);
     ListStats.lpWinfo->dwStyle = GetWindowLong (hwnd, GWL_STYLE);
     ListStats.lpWinfo->bColor  = ListStats.bColor ;
     ListStats.lpWinfo->nLevel  = ListStats.nLevel ;
     ListStats.lpWinfo->hIcon   = GetClassWord (hwnd, GCW_HICON) ;
     ListStats.lpWinfo++;

     if (hwndChild = GetWindow (hwnd, GW_CHILD))  // enum children
          {
          ListStats.nLevel++;
          winlist_enum (hwndChild);
          }

     if (hwndSibling = GetWindow (hwnd, GW_HWNDNEXT)) // enum siblings
          {
          if (GetWindowTask (hwndSibling) != GetWindowTask (hwnd))
               {
               ListStats.bColor = !ListStats.bColor;
               }
          winlist_enum (hwndSibling);
          }
     else
          {
          ListStats.nLevel--;
          }
     }



int winlist_getCount ()
    {
    return ListStats.nWindows;
    }


HWINFO winlist_getWinfo ()
    {
    return ListStats.hWinfo;
    }


void winlist_destroy ()
    {
    GlobalFree (ListStats.hWinfo);
    }
