1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
/*
 *  ReactOS Win32 Applications
 *  Copyright (C) 2007 ReactOS Team
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
/*
 * PROJECT:         ReactOS Event Log Viewer
 * LICENSE:         GPL - See COPYING in the top level directory
 * FILE:            base/applications/mscutils/eventvwr/eventvwr.c
 * PURPOSE:         Event Log Viewer main file
 * PROGRAMMERS:     Marc Piulachs (marc.piulachs at codexchange [dot] net)
 *                  Eric Kohl
 *                  Hermes Belusca-Maito
 */

#include "eventvwr.h"
#include "evtdetctl.h"

#include <sddl.h> // For ConvertSidToStringSidW
#include <shellapi.h>
#include <shlwapi.h>

// #include "resource.h"

#define LVM_PROGRESS    (WM_APP + 1)    // Used by the subclassed ListView

static const LPCWSTR EVENTVWR_WNDCLASS = L"EVENTVWR"; /* The main window class name */
static const LPCWSTR EVENTLOG_BASE_KEY = L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\";
static const LPCWSTR EVNTVWR_PARAM_KEY = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Event Viewer";

/* The 3 system logs that should always exist in the user's system */
static const LPCWSTR SystemLogs[] =
{
    L"Application",
    L"Security",
    L"System"
};

/* MessageFile message buffer size */
#define EVENT_MESSAGE_EVENTTEXT_BUFFER  1024*10                             // NOTE: Used by evtdetctl.c
#define EVENT_MESSAGE_FILE_BUFFER       1024*10
#define EVENT_DLL_SEPARATOR             L";"
#define EVENT_CATEGORY_MESSAGE_FILE     L"CategoryMessageFile"
#define EVENT_MESSAGE_FILE              L"EventMessageFile"
#define EVENT_PARAMETER_MESSAGE_FILE    L"ParameterMessageFile"

#define MAX_LOADSTRING 255

#define SPLIT_WIDTH 4

/* Globals */
HINSTANCE hInst;                            /* Current instance */
WCHAR szTitle[MAX_LOADSTRING];              /* The title bar text */
WCHAR szTitleTemplate[MAX_LOADSTRING];      /* The logged-on title bar text */
WCHAR szStatusBarTemplate[MAX_LOADSTRING];  /* The status bar text */
WCHAR szLoadingWait[MAX_LOADSTRING];        /* The "Loading, please wait..." text */
WCHAR szEmptyList[MAX_LOADSTRING];          /* The "There are no items to show in this view" text */
WCHAR szSaveFilter[MAX_LOADSTRING];         /* Filter Mask for the save Dialog */

INT  nVSplitPos;                            /* Vertical splitter (1) position */
INT  nHSplitPos;                            /* Horizontal splitter (2) position */
BYTE bSplit = 0;                            /* Splitter state:
                                             * 0: No splitting;
                                             * 1: Vertical splitting;
                                             * 2: Horizontal splitting.
                                             */

HWND hwndMainWindow = NULL;                 /* Main window */
HWND hwndTreeView;                          /* TreeView control */
HWND hwndListView;                          /* ListView control */          // NOTE: Used by evtdetctl.c
HWND hwndEventDetails;                      /* Event details pane */
HWND hwndStatus;                            /* Status bar */
HWND hwndStatusProgress;                    /* Progress bar in the status bar */
HMENU hMainMenu;                            /* The application's main menu */

HTREEITEM htiSystemLogs = NULL, htiAppLogs = NULL, htiUserLogs = NULL;

LPWSTR lpComputerName = NULL;       /* NULL: local user computer (default) */
LPWSTR lpszzUserLogsToLoad = NULL;  /* The list of user logs to load at startup (multi-string) */
SIZE_T cbUserLogsSize = 0;

HKEY hkMachine = NULL; // Registry handle to the HKEY_LOCAL_MACHINE key of the remote computer registry.

/* Global event records cache for the current active event log filter */
DWORD g_TotalRecords = 0;
PEVENTLOGRECORD* g_RecordPtrs = NULL;

/* Lists of event logs and event log filters */
LIST_ENTRY EventLogList;
LIST_ENTRY EventLogFilterList;
PEVENTLOGFILTER ActiveFilter = NULL;

HANDLE hEnumEventsThread = NULL;
HANDLE hStopEnumEvent    = NULL;

/*
 * Setting EnumFilter to a valid pointer and raising the hStartEnumEvent event
 * triggers the event-enumerator thread to perform a new enumeration.
 */
PEVENTLOGFILTER EnumFilter = NULL;
HANDLE hStartStopEnumEvent = NULL;  // End-of-application event
HANDLE hStartEnumEvent     = NULL;  // Command event

/* Default Open/Save-As dialog box */
OPENFILENAMEW sfn;


/* Event Viewer Application Settings */
typedef struct _SETTINGS
{
    BOOL bShowDetailsPane;      /* Show (TRUE) or Hide (FALSE) the events details pane */
    BOOL bShowGrid;             /* Show (TRUE) or Hide (FALSE) the events view grid */
    BOOL bSaveSettings;         /* Save (TRUE) or do not save (FALSE) current settings on exit */
    BOOL bNewestEventsFirst;    /* Sort the displayed events the newest ones first (TRUE) or last (FALSE) */
    INT  nVSplitPos;            /* Vertical splitter position */
    INT  nHSplitPos;            /* Horizontal splitter position */
    WINDOWPLACEMENT wpPos;
} SETTINGS, *PSETTINGS;

SETTINGS Settings;


/* Forward declarations of functions included in this code module */

static DWORD WINAPI
StartStopEnumEventsThread(IN LPVOID lpParameter);

VOID OpenUserEventLogFile(IN LPCWSTR lpszFileName);

VOID BuildLogListAndFilterList(IN LPCWSTR lpComputerName);
VOID FreeLogList(VOID);
VOID FreeLogFilterList(VOID);

ATOM MyRegisterClass(HINSTANCE);
BOOL InitInstance(HINSTANCE);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR EventLogProperties(HINSTANCE, HWND, PEVENTLOGFILTER);
INT_PTR CALLBACK EventDetails(HWND, UINT, WPARAM, LPARAM);


/* MAIN FUNCTIONS *************************************************************/

VOID
ShowWin32Error(IN DWORD dwError)
{
    LPWSTR lpMessageBuffer;

    if (dwError == ERROR_SUCCESS)
        return;

    if (!FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                        FORMAT_MESSAGE_FROM_SYSTEM |
                        FORMAT_MESSAGE_IGNORE_INSERTS,
                        NULL,
                        dwError,
                        LANG_USER_DEFAULT,
                        (LPWSTR)&lpMessageBuffer,
                        0, NULL))
    {
        return;
    }

    MessageBoxW(hwndMainWindow, lpMessageBuffer, szTitle, MB_OK | MB_ICONERROR);
    LocalFree(lpMessageBuffer);
}

VOID
DisplayUsage(VOID)
{
    LPWSTR lpBuffer;
    LPCWSTR lpUsage;
    INT iUsageLen = LoadStringW(hInst, IDS_USAGE, (LPWSTR)&lpUsage, 0);

    if (iUsageLen == 0)
        return;

    lpBuffer = HeapAlloc(GetProcessHeap(), 0, (iUsageLen + 1) * sizeof(WCHAR));
    if (!lpBuffer)
        return;

    StringCchCopyNW(lpBuffer, iUsageLen + 1, lpUsage, iUsageLen);
    MessageBoxW(NULL, lpBuffer, szTitle, MB_OK | MB_ICONINFORMATION);

    HeapFree(GetProcessHeap(), 0, lpBuffer);
}

BOOL
ProcessCmdLine(IN LPWSTR lpCmdLine)
{
    BOOL Success = FALSE;
    INT i, argc;
    LPWSTR* argv;

    /* Skip any leading whitespace */
    if (lpCmdLine)
    {
        while (iswspace(*lpCmdLine))
            ++lpCmdLine;
    }

    /* No command line means no processing needed */
    if (!lpCmdLine || !*lpCmdLine)
        return TRUE;

    /* Build the arguments vector */
    argv = CommandLineToArgvW(lpCmdLine, &argc);
    if (!argv)
        return FALSE;

    /* Parse the command line for options (skip the program name) */
    for (i = 1; i < argc; ++i)
    {
        /* Check for new options */
        if (argv[i][0] == L'-' || argv[i][0] == L'/')
        {
            if (argv[i][1] == L'?' && argv[i][2] == 0)
            {
                /* Display help */
                DisplayUsage();
                goto Quit;
            }
            else
            if (argv[i][2] == L':')
            {
                switch (towupper(argv[i][1]))
                {
                    case L'L':
                    {
                        LPWSTR lpNewBuffer;
                        LPWSTR lpFileName = argv[i] + 3;
                        SIZE_T cbFileName;

                        /* Check for a quoted file name */
                        if (*lpFileName == L'\"')
                        {
                            /* Skip this quote, and the last one too if any */
                            ++lpFileName;
                            cbFileName = wcslen(lpFileName);
                            if (cbFileName > 0 && lpFileName[cbFileName - 1] == L'\"')
                                lpFileName[cbFileName - 1] = UNICODE_NULL;
                        }

                        /* Skip this one if we do not actually have a file name */
                        if (!*lpFileName)
                            continue;

                        cbFileName = (wcslen(lpFileName) + 1) * sizeof(WCHAR);

                        /* Reallocate the list of user logs to load */
                        if (lpszzUserLogsToLoad)
                        {
                            lpNewBuffer = HeapReAlloc(GetProcessHeap(),
                                                      HEAP_ZERO_MEMORY,
                                                      lpszzUserLogsToLoad,
                                                      /* Count the multi-string NULL-terminator */
                                                      cbUserLogsSize + cbFileName + sizeof(WCHAR));
                        }
                        else
                        {
                            cbUserLogsSize = 0;
                            lpNewBuffer = HeapAlloc(GetProcessHeap(),
                                                    HEAP_ZERO_MEMORY,
                                                    /* Count the multi-string NULL-terminator */
                                                    cbUserLogsSize + cbFileName + sizeof(WCHAR));
                        }

                        if (!lpNewBuffer)
                        {
                            ShowWin32Error(ERROR_NOT_ENOUGH_MEMORY);
                            goto Quit;
                        }

                        lpszzUserLogsToLoad = lpNewBuffer;
                        lpNewBuffer = (LPWSTR)((ULONG_PTR)lpNewBuffer + cbUserLogsSize);
                        cbUserLogsSize += cbFileName;

                        /* Save the file name */
                        StringCbCopyW(lpNewBuffer, cbFileName, lpFileName);

                        continue;
                    }

                    default:
                        break;
                }
            }

            /* Unknown argument: display help and bail out */
            DisplayUsage();
            goto Quit;
        }
        else
        {
            /*
             * An argument that does not start with the switch character.
             * If this is the first argument then this corresponds to the
             * optional computer name. Otherwise this is a wrong argument.
             */
            if (i == 1)
            {
                /* Store the computer name */
                LPWSTR lpTemp = argv[i];
                SIZE_T cbLength;

                /* Strip any leading backslashes */
                while (*lpTemp == L'\\')
                    ++lpTemp;

                cbLength = (wcslen(lpTemp) + 1) * sizeof(WCHAR);
                lpComputerName = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbLength);
                if (lpComputerName)
                {
                    StringCbCopyW(lpComputerName, cbLength, lpTemp);
                }
                /* else, fall back to local computer */
            }
            else
            {
                /* Invalid syntax: display help and bail out */
                DisplayUsage();
                goto Quit;
            }
        }
    }

    Success = TRUE;

Quit:
    /* In case of failure, free anything we have allocated */
    if (!Success)
    {
        if (lpszzUserLogsToLoad)
        {
            cbUserLogsSize = 0;
            HeapFree(GetProcessHeap(), 0, lpszzUserLogsToLoad);
            lpszzUserLogsToLoad = NULL;
        }
        if (lpComputerName)
        {
            HeapFree(GetProcessHeap(), 0, lpComputerName);
            lpComputerName = NULL;
        }
    }

    /* Free the arguments vector and exit */
    LocalFree(argv);
    return Success;
}

BOOL
LoadSettings(int nDefCmdShow)
{
    HKEY hKeyEventVwr;
    LONG Result;
    DWORD dwSize;
    DWORD dwType;
    DWORD Value;
    UNICODE_STRING ValueU;
    WCHAR buffer[100];

    /* Load the default values */
    Settings.bShowDetailsPane = TRUE;
    Settings.bShowGrid = FALSE;
    Settings.bSaveSettings = TRUE;
    Settings.bNewestEventsFirst = TRUE;
    Settings.nVSplitPos = 250; /* Splitter default positions */
    Settings.nHSplitPos = 250;
    ZeroMemory(&Settings.wpPos, sizeof(Settings.wpPos));
    Settings.wpPos.length = sizeof(Settings.wpPos);
    Settings.wpPos.rcNormalPosition.left = CW_USEDEFAULT;
    Settings.wpPos.rcNormalPosition.top  = CW_USEDEFAULT;
    Settings.wpPos.rcNormalPosition.right  = CW_USEDEFAULT;
    Settings.wpPos.rcNormalPosition.bottom = CW_USEDEFAULT;

    /* Try to create/open the Event Viewer user key */
    if (RegCreateKeyExW(HKEY_CURRENT_USER,
                        EVNTVWR_PARAM_KEY,
                        0,
                        NULL,
                        REG_OPTION_NON_VOLATILE,
                        KEY_READ | KEY_WRITE,
                        NULL,
                        &hKeyEventVwr,
                        NULL) != ERROR_SUCCESS)
    {
        return FALSE;
    }

    // Result = RegQueryValueExW(hKeyEventVwr, L"Filter", NULL, &dwType, (LPBYTE)&szFilter, &dwSize); // REG_SZ
    // Result = RegQueryValueExW(hKeyEventVwr, L"Find", NULL, &dwType, (LPBYTE)&szFind, &dwSize); // REG_SZ
    // Result = RegQueryValueExW(hKeyEventVwr, L"Module", NULL, &dwType, (LPBYTE)&szModule, &dwSize); // REG_SZ

    dwSize = sizeof(Value);
    Result = RegQueryValueExW(hKeyEventVwr, L"DetailsPane", NULL, &dwType, (LPBYTE)&Value, &dwSize);
    if ((Result == ERROR_SUCCESS) && (dwType == REG_SZ || dwType == REG_DWORD))
    {
        if (dwType == REG_SZ)
        {
            ValueU.Buffer = (PWSTR)&Value;
            ValueU.Length = ValueU.MaximumLength = dwSize;
            RtlUnicodeStringToInteger(&ValueU, 10, &Value);
        }
        Settings.bShowDetailsPane = !!Value;
    }

    dwSize = sizeof(Value);
    Result = RegQueryValueExW(hKeyEventVwr, L"ShowGrid", NULL, &dwType, (LPBYTE)&Value, &dwSize);
    if ((Result == ERROR_SUCCESS) && (dwType == REG_SZ || dwType == REG_DWORD))
    {
        if (dwType == REG_SZ)
        {
            ValueU.Buffer = (PWSTR)&Value;
            ValueU.Length = ValueU.MaximumLength = dwSize;
            RtlUnicodeStringToInteger(&ValueU, 10, &Value);
        }
        Settings.bShowGrid = !!Value;
    }

    dwSize = sizeof(Value);
    Result = RegQueryValueExW(hKeyEventVwr, L"SortOrder", NULL, &dwType, (LPBYTE)&Value, &dwSize);
    if ((Result == ERROR_SUCCESS) && (dwType == REG_SZ || dwType == REG_DWORD))
    {
        if (dwType == REG_SZ)
        {
            ValueU.Buffer = (PWSTR)&Value;
            ValueU.Length = ValueU.MaximumLength = dwSize;
            RtlUnicodeStringToInteger(&ValueU, 10, &Value);
        }
        Settings.bNewestEventsFirst = !!Value;
    }

    /* Retrieve the splitter positions */
    dwSize = sizeof(Value);
    Result = RegQueryValueExW(hKeyEventVwr, L"VSplitPos", NULL, &dwType, (LPBYTE)&Value, &dwSize);
    if ((Result == ERROR_SUCCESS) && (dwType == REG_SZ || dwType == REG_DWORD))
    {
        if (dwType == REG_SZ)
        {
            ValueU.Buffer = (PWSTR)&Value;
            ValueU.Length = ValueU.MaximumLength = dwSize;
            RtlUnicodeStringToInteger(&ValueU, 10, &Value);
        }
        Settings.nVSplitPos = Value;
    }

    dwSize = sizeof(Value);
    Result = RegQueryValueExW(hKeyEventVwr, L"HSplitPos", NULL, &dwType, (LPBYTE)&Value, &dwSize);
    if ((Result == ERROR_SUCCESS) && (dwType == REG_SZ || dwType == REG_DWORD))
    {
        if (dwType == REG_SZ)
        {
            ValueU.Buffer = (PWSTR)&Value;
            ValueU.Length = ValueU.MaximumLength = dwSize;
            RtlUnicodeStringToInteger(&ValueU, 10, &Value);
        }
        Settings.nHSplitPos = Value;
    }

    /* Retrieve the geometry of the main window */
    dwSize = sizeof(buffer);
    Result = RegQueryValueExW(hKeyEventVwr, L"Window", NULL, &dwType, (LPBYTE)buffer, &dwSize);
    if ((Result != ERROR_SUCCESS) || (dwType != REG_SZ))
        buffer[0] = UNICODE_NULL;

    if (swscanf(buffer, L"%d %d %d %d %d",
                &Settings.wpPos.rcNormalPosition.left,
                &Settings.wpPos.rcNormalPosition.top,
                &Settings.wpPos.rcNormalPosition.right,
                &Settings.wpPos.rcNormalPosition.bottom,
                &Settings.wpPos.showCmd) != 5)
    {
        /* Parsing failed, use defaults */
        Settings.wpPos.rcNormalPosition.left = CW_USEDEFAULT;
        Settings.wpPos.rcNormalPosition.top  = CW_USEDEFAULT;
        Settings.wpPos.rcNormalPosition.right  = CW_USEDEFAULT;
        Settings.wpPos.rcNormalPosition.bottom = CW_USEDEFAULT;
        Settings.wpPos.showCmd = nDefCmdShow; // SW_SHOWNORMAL;
    }

    dwSize = sizeof(Value);
    Result = RegQueryValueExW(hKeyEventVwr, L"SaveSettings", NULL, &dwType, (LPBYTE)&Value, &dwSize);
    if ((Result == ERROR_SUCCESS) && (dwType == REG_SZ || dwType == REG_DWORD))
    {
        if (dwType == REG_SZ)
        {
            ValueU.Buffer = (PWSTR)&Value;
            ValueU.Length = ValueU.MaximumLength = dwSize;
            RtlUnicodeStringToInteger(&ValueU, 10, &Value);
        }
        Settings.bSaveSettings = !!Value;
    }

    RegCloseKey(hKeyEventVwr);
    return TRUE;
}

BOOL
SaveSettings(VOID)
{
    HKEY hKeyEventVwr;
    DWORD dwSize;
    WCHAR buffer[100];

    /* Try to create/open the Event Viewer user key */
    if (RegCreateKeyExW(HKEY_CURRENT_USER,
                        EVNTVWR_PARAM_KEY,
                        0,
                        NULL,
                        REG_OPTION_NON_VOLATILE,
                        KEY_READ | KEY_WRITE,
                        NULL,
                        &hKeyEventVwr,
                        NULL) != ERROR_SUCCESS)
    {
        return FALSE;
    }

    dwSize = sizeof(Settings.bSaveSettings);
    RegSetValueExW(hKeyEventVwr, L"SaveSettings", 0, REG_DWORD, (LPBYTE)&Settings.bSaveSettings, dwSize);

    /* Do not save more settings if we are not asked to do so */
    if (!Settings.bSaveSettings)
        goto Quit;

    dwSize = sizeof(Settings.bShowDetailsPane);
    RegSetValueExW(hKeyEventVwr, L"DetailsPane", 0, REG_DWORD, (LPBYTE)&Settings.bShowDetailsPane, dwSize);

    dwSize = sizeof(Settings.bShowGrid);
    RegSetValueExW(hKeyEventVwr, L"ShowGrid", 0, REG_DWORD, (LPBYTE)&Settings.bShowGrid, dwSize);

    dwSize = sizeof(Settings.bNewestEventsFirst);
    RegSetValueExW(hKeyEventVwr, L"SortOrder", 0, REG_DWORD, (LPBYTE)&Settings.bNewestEventsFirst, dwSize);

    Settings.nVSplitPos = nVSplitPos;
    dwSize = sizeof(Settings.nVSplitPos);
    RegSetValueExW(hKeyEventVwr, L"VSplitPos", 0, REG_DWORD, (LPBYTE)&Settings.nVSplitPos, dwSize);

    Settings.nHSplitPos = nHSplitPos;
    dwSize = sizeof(Settings.nHSplitPos);
    RegSetValueExW(hKeyEventVwr, L"HSplitPos", 0, REG_DWORD, (LPBYTE)&Settings.nHSplitPos, dwSize);

    StringCbPrintfW(buffer, sizeof(buffer),
                    L"%d %d %d %d %d",
                    Settings.wpPos.rcNormalPosition.left,
                    Settings.wpPos.rcNormalPosition.top,
                    Settings.wpPos.rcNormalPosition.right,
                    Settings.wpPos.rcNormalPosition.bottom,
                    Settings.wpPos.showCmd);

    dwSize = (DWORD)(wcslen(buffer) * sizeof(WCHAR));
    RegSetValueExW(hKeyEventVwr, L"Window", 0, REG_SZ, (LPBYTE)buffer, dwSize);

Quit:
    RegCloseKey(hKeyEventVwr);
    return TRUE;
}

int APIENTRY
wWinMain(HINSTANCE hInstance,
         HINSTANCE hPrevInstance,
         LPWSTR    lpCmdLine,
         int       nCmdShow)
{
    HANDLE hThread;
    INITCOMMONCONTROLSEX iccx;
    HMODULE hRichEdit;
    HACCEL hAccelTable;
    MSG msg;

    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    /* Whenever any of the common controls are used in your app,
     * you must call InitCommonControlsEx() to register the classes
     * for those controls. */
    iccx.dwSize = sizeof(iccx);
    iccx.dwICC = ICC_LISTVIEW_CLASSES;
    InitCommonControlsEx(&iccx);

    /* Load the RichEdit DLL to add support for RichEdit controls */
    hRichEdit = LoadLibraryW(L"riched20.dll");
    if (!hRichEdit)
        return -1;

    msg.wParam = (WPARAM)-1;

    /* Store the instance handle in the global variable */
    hInst = hInstance;

    /* Initialize global strings */
    LoadStringW(hInstance, IDS_APP_TITLE, szTitle, ARRAYSIZE(szTitle));
    LoadStringW(hInstance, IDS_APP_TITLE_EX, szTitleTemplate, ARRAYSIZE(szTitleTemplate));
    LoadStringW(hInstance, IDS_STATUS_MSG, szStatusBarTemplate, ARRAYSIZE(szStatusBarTemplate));
    LoadStringW(hInstance, IDS_LOADING_WAIT, szLoadingWait, ARRAYSIZE(szLoadingWait));
    LoadStringW(hInstance, IDS_NO_ITEMS, szEmptyList, ARRAYSIZE(szEmptyList));

    /*
     * Process the command-line arguments. Note that we need the full
     * command-line, with the program file included, and not just what
     * WinMain() provides in its lpCmdLine parameter.
     */
    if (!ProcessCmdLine(GetCommandLineW()))
        goto Quit;

    if (!MyRegisterClass(hInstance))
        goto Quit;

    /* Load the settings */
    LoadSettings(nCmdShow);

    /* Perform application initialization */
    if (!InitInstance(hInstance))
        goto Quit;

    hAccelTable = LoadAcceleratorsW(hInstance, MAKEINTRESOURCEW(IDA_EVENTVWR));

    /* Create the Start/Stop enumerator thread */
    // Manual-reset event
    hStartStopEnumEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
    if (!hStartStopEnumEvent)
        goto Cleanup;

    // Auto-reset event
    hStartEnumEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
    if (!hStartEnumEvent)
        goto Cleanup;

    hThread = CreateThread(NULL, 0,
                           StartStopEnumEventsThread,
                           NULL, 0, NULL);
    if (!hThread)
        goto Cleanup;

    /* Retrieve the available event logs on this computer and create filters for them */
    InitializeListHead(&EventLogList);
    InitializeListHead(&EventLogFilterList);
    BuildLogListAndFilterList(lpComputerName);

    /* Open the user-specified logs if any are present on the command-line */
    if (lpszzUserLogsToLoad)
    {
        LPWSTR lpUserLog;
        for (lpUserLog = lpszzUserLogsToLoad; *lpUserLog; lpUserLog += wcslen(lpUserLog) + 1)
        {
            OpenUserEventLogFile(lpUserLog);
        }

        /* Now cleanup the list of user logs */
        cbUserLogsSize = 0;
        HeapFree(GetProcessHeap(), 0, lpszzUserLogsToLoad);
        lpszzUserLogsToLoad = NULL;
    }

    /* Main message loop */
    while (GetMessageW(&msg, NULL, 0, 0))
    {
        if (!TranslateAcceleratorW(hwndMainWindow, hAccelTable, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }

    /* Save the settings */
    SaveSettings();

    /* Disconnect from computer */
    if (hkMachine && hkMachine != HKEY_LOCAL_MACHINE)
    {
        /* We are connected to some other computer, close the old connection */
        RegCloseKey(hkMachine);
        hkMachine = NULL;
    }

    /* Stop the enumerator thread */
    SetEvent(hStartStopEnumEvent);
    WaitForSingleObject(hThread, INFINITE);
    CloseHandle(hThread);

    /* Free the filters list and the event logs list */
    FreeLogFilterList();
    FreeLogList();

Cleanup:
    /* Handle cleanup */
    if (hStartEnumEvent)
        CloseHandle(hStartEnumEvent);
    if (hStartStopEnumEvent)
        CloseHandle(hStartStopEnumEvent);

Quit:
    /* Final cleanup */
    if (lpszzUserLogsToLoad)
    {
        cbUserLogsSize = 0;
        HeapFree(GetProcessHeap(), 0, lpszzUserLogsToLoad);
        lpszzUserLogsToLoad = NULL;
    }
    if (lpComputerName)
    {
        HeapFree(GetProcessHeap(), 0, lpComputerName);
        lpComputerName = NULL;
    }
    FreeLibrary(hRichEdit);

    return (int)msg.wParam;
}


/* GENERIC HELPER FUNCTIONS ***************************************************/

VOID
EventTimeToSystemTime(IN DWORD EventTime,
                      OUT PSYSTEMTIME pSystemTime)
{
    SYSTEMTIME st1970 = { 1970, 1, 0, 1, 0, 0, 0, 0 };
    FILETIME ftLocal;
    union
    {
        FILETIME ft;
        ULONGLONG ll;
    } u1970, uUCT;

    uUCT.ft.dwHighDateTime = 0;
    uUCT.ft.dwLowDateTime = EventTime;
    SystemTimeToFileTime(&st1970, &u1970.ft);
    uUCT.ll = uUCT.ll * 10000000 + u1970.ll;
    FileTimeToLocalFileTime(&uUCT.ft, &ftLocal);
    FileTimeToSystemTime(&ftLocal, pSystemTime);
}

/*
 * This function takes in entry a path to a single DLL, in which
 * the message string of ID dwMessageId has to be searched.
 * The other parameters are similar to those of the FormatMessageW API.
 */
LPWSTR
GetMessageStringFromDll(
    IN LPCWSTR  lpMessageDll,
    IN DWORD    dwFlags, // If we always use the same flags, just remove this param...
    IN DWORD    dwMessageId,
    IN DWORD    nSize,
    IN va_list* Arguments OPTIONAL)
{
    HMODULE hLibrary;
    DWORD dwLength;
    LPWSTR lpMsgBuf = NULL;<--- Assignment 'lpMsgBuf=NULL', assigned value is 0

    hLibrary = LoadLibraryExW(lpMessageDll, NULL,
                              /* LOAD_LIBRARY_AS_IMAGE_RESOURCE | */ LOAD_LIBRARY_AS_DATAFILE);
    if (hLibrary == NULL)
        return NULL;

    /* Sanitize dwFlags */
    dwFlags &= ~FORMAT_MESSAGE_FROM_STRING;
    dwFlags |= FORMAT_MESSAGE_FROM_HMODULE;

    _SEH2_TRY
    {
        /*
         * Retrieve the message string without appending extra newlines.
         * Wrap in SEH to protect from invalid string parameters.
         */
        _SEH2_TRY
        {
            dwLength = FormatMessageW(dwFlags,
                                   /* FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE |
                                      FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, */
                                      hLibrary,
                                      dwMessageId,
                                      LANG_USER_DEFAULT,
                                      (LPWSTR)&lpMsgBuf,
                                      nSize,
                                      Arguments);
        }
        _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
        {
            dwLength = 0;

            /*
             * An exception occurred while calling FormatMessage, this is usually
             * the sign that a parameter was invalid, either 'lpMsgBuf' was NULL
             * but we did not pass the flag FORMAT_MESSAGE_ALLOCATE_BUFFER, or the
             * array pointer 'Arguments' was NULL or did not contain enough elements,
             * and we did not pass the flag FORMAT_MESSAGE_IGNORE_INSERTS, and the
             * message string expected too many inserts.
             * In this last case only, we can call again FormatMessage but ignore
             * explicitly the inserts. The string that we will return to the user
             * will not be pre-formatted.
             */
            if (((dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) || lpMsgBuf) &&<--- Condition 'lpMsgBuf' is always false
                !(dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS))
            {
                /* Remove any possible harmful flags and always ignore inserts */
                dwFlags &= ~FORMAT_MESSAGE_ARGUMENT_ARRAY;
                dwFlags |=  FORMAT_MESSAGE_IGNORE_INSERTS;

                /* If this call also throws an exception, we are really dead */
                dwLength = FormatMessageW(dwFlags,
                                          hLibrary,
                                          dwMessageId,
                                          LANG_USER_DEFAULT,
                                          (LPWSTR)&lpMsgBuf,
                                          nSize,
                                          NULL /* Arguments */);
            }
        }
        _SEH2_END;
    }
    _SEH2_FINALLY
    {
        FreeLibrary(hLibrary);
    }
    _SEH2_END;

    if (dwLength == 0)
    {
        ASSERT(lpMsgBuf == NULL);
        lpMsgBuf = NULL;
    }
    else
    {
        LPWSTR ptr;

        ASSERT(lpMsgBuf);

        /* Trim any trailing whitespace */
        ptr = lpMsgBuf + dwLength - 1;
        while (iswspace(*ptr))
            *ptr-- = UNICODE_NULL;
    }

    return lpMsgBuf;
}

/*
 * This function takes in entry a comma-separated list of DLLs, in which
 * the message string of ID dwMessageId has to be searched.
 * The other parameters are similar to those of the FormatMessageW API.
 */
LPWSTR
GetMessageStringFromDllList(
    IN LPCWSTR  lpMessageDllList,
    IN DWORD    dwFlags, // If we always use the same flags, just remove this param...
    IN DWORD    dwMessageId,
    IN DWORD    nSize,
    IN va_list* Arguments OPTIONAL)
{
    BOOL Success = FALSE;
    SIZE_T cbLength;
    LPWSTR szMessageDllList;
    LPWSTR szDll;
    LPWSTR lpMsgBuf = NULL;

    /* Allocate a local buffer for the DLL list that can be tokenized */
    // TODO: Optimize that!! Maybe we can cleverly use lpMessageDllList in read/write mode
    // and cleverly temporarily replace the ';' by UNICODE_NULL, do our job, then reverse the change.
    cbLength = (wcslen(lpMessageDllList) + 1) * sizeof(WCHAR);
    szMessageDllList = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbLength);
    if (!szMessageDllList)
        return NULL;
    RtlCopyMemory(szMessageDllList, lpMessageDllList, cbLength);

    /* Loop through the list of message DLLs */
    szDll = wcstok(szMessageDllList, EVENT_DLL_SEPARATOR);
    while ((szDll != NULL) && !Success)
    {
        // Uses LANG_USER_DEFAULT
        lpMsgBuf = GetMessageStringFromDll(szDll,
                                           dwFlags,
                                           dwMessageId,
                                           nSize,
                                           Arguments);
        if (lpMsgBuf)
        {
            /* The ID was found and the message was formatted */
            Success = TRUE;
            break;
        }

        /*
         * The DLL could not be loaded, or the message could not be found,
         * try the next DLL, if any.
         */
        szDll = wcstok(NULL, EVENT_DLL_SEPARATOR);
    }

    HeapFree(GetProcessHeap(), 0, szMessageDllList);

    return lpMsgBuf;
}


typedef struct
{
    LPWSTR pStartingAddress;    // Pointer to the beginning of a parameter string in pMessage
    LPWSTR pEndingAddress;      // Pointer to the end of a parameter string in pMessage
    DWORD  pParameterID;        // Parameter identifier found in pMessage
    LPWSTR pParameter;          // Actual parameter string
} param_strings_format_data;

DWORD
ApplyParameterStringsToMessage(
    IN LPCWSTR  lpMessageDllList,
    IN BOOL     bMessagePreFormatted,
    IN CONST LPCWSTR pMessage,
    OUT LPWSTR* pFinalMessage)
{
    /*
     * This code is heavily adapted from the MSDN example:
     * https://msdn.microsoft.com/en-us/library/windows/desktop/bb427356.aspx
     * with bugs removed.
     */

    DWORD Status = ERROR_SUCCESS;
    DWORD dwParamCount = 0; // Number of insertion strings found in pMessage
    size_t cchBuffer = 0;   // Size of the buffer in characters
    size_t cchParams = 0;   // Number of characters in all the parameter strings
    size_t cch = 0;
    DWORD i = 0;
    param_strings_format_data* pParamData = NULL; // Array of pointers holding information about each parameter string in pMessage
    LPWSTR pTempMessage = (LPWSTR)pMessage;
    LPWSTR pTempFinalMessage = NULL;

    *pFinalMessage = NULL;

    /* Determine the number of parameter insertion strings in pMessage */
    if (bMessagePreFormatted)
    {
        while ((pTempMessage = wcschr(pTempMessage, L'%')))
        {
            pTempMessage++;
            if (iswdigit(*pTempMessage))
            {
                dwParamCount++;
                while (iswdigit(*++pTempMessage)) ;
            }
        }
    }
    else
    {
        while ((pTempMessage = wcsstr(pTempMessage, L"%%")))
        {
            pTempMessage += 2;
            if (iswdigit(*pTempMessage))
            {
                dwParamCount++;
                while (iswdigit(*++pTempMessage)) ;
            }
        }
    }

    /* If there are no parameter insertion strings in pMessage, just return */
    if (dwParamCount == 0)
    {
        // *pFinalMessage = NULL;
        goto Cleanup;
    }

    /* Allocate the array of parameter string format data */
    pParamData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwParamCount * sizeof(param_strings_format_data));
    if (!pParamData)
    {
        Status = ERROR_OUTOFMEMORY;
        goto Cleanup;
    }

    /*
     * Retrieve each parameter in pMessage and the beginning and end of the
     * insertion string, as well as the message identifier of the parameter.
     */
    pTempMessage = (LPWSTR)pMessage;
    if (bMessagePreFormatted)
    {
        while ((pTempMessage = wcschr(pTempMessage, L'%')) && (i < dwParamCount))
        {
            pTempMessage++;
            if (iswdigit(*pTempMessage))
            {
                pParamData[i].pStartingAddress = pTempMessage-1;
                pParamData[i].pParameterID = (DWORD)_wtol(pTempMessage);

                while (iswdigit(*++pTempMessage)) ;

                pParamData[i].pEndingAddress = pTempMessage;
                i++;
            }
        }
    }
    else
    {
        while ((pTempMessage = wcsstr(pTempMessage, L"%%")) && (i < dwParamCount))
        {
            pTempMessage += 2;
            if (iswdigit(*pTempMessage))
            {
                pParamData[i].pStartingAddress = pTempMessage-2;
                pParamData[i].pParameterID = (DWORD)_wtol(pTempMessage);

                while (iswdigit(*++pTempMessage)) ;

                pParamData[i].pEndingAddress = pTempMessage;
                i++;
            }
        }
    }

    /* Retrieve each parameter string */
    for (i = 0; i < dwParamCount; i++)
    {
        // pParamData[i].pParameter = GetMessageString(pParamData[i].pParameterID, 0, NULL);
        pParamData[i].pParameter =
            GetMessageStringFromDllList(lpMessageDllList,
                                        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE |
                                        FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
                                        pParamData[i].pParameterID,
                                        0, NULL);
        if (!pParamData[i].pParameter)
        {
            /* Skip the insertion string */
            continue;
        }

        cchParams += wcslen(pParamData[i].pParameter);
    }

    /*
     * Allocate the final message buffer, the size of which is based on the
     * length of the original message and the length of each parameter string.
     */
    cchBuffer = wcslen(pMessage) + cchParams + 1;
    *pFinalMessage = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cchBuffer * sizeof(WCHAR));
    if (!*pFinalMessage)
    {
        Status = ERROR_OUTOFMEMORY;
        goto Cleanup;
    }

    pTempFinalMessage = *pFinalMessage;

    /* Build the final message string */
    pTempMessage = (LPWSTR)pMessage;
    for (i = 0; i < dwParamCount; i++)
    {
        /* Append the segment from pMessage */
        cch = pParamData[i].pStartingAddress - pTempMessage;
        StringCchCopyNW(pTempFinalMessage, cchBuffer, pTempMessage, cch);
        pTempMessage = pParamData[i].pEndingAddress;
        cchBuffer -= cch;
        pTempFinalMessage += cch;

        /* Append the parameter string */
        if (pParamData[i].pParameter)
        {
            StringCchCopyW(pTempFinalMessage, cchBuffer, pParamData[i].pParameter);
            cch = wcslen(pParamData[i].pParameter); // pTempFinalMessage
        }
        else
        {
            /*
             * We failed to retrieve the parameter string before, so just
             * place back the original string placeholder.
             */
            cch = pParamData[i].pEndingAddress /* == pTempMessage */ - pParamData[i].pStartingAddress;
            StringCchCopyNW(pTempFinalMessage, cchBuffer, pParamData[i].pStartingAddress, cch);
            // cch = wcslen(pTempFinalMessage);
        }
        cchBuffer -= cch;
        pTempFinalMessage += cch;
    }

    /* Append the last segment from pMessage */
    StringCchCopyW(pTempFinalMessage, cchBuffer, pTempMessage);

Cleanup:

    // if (Status != ERROR_SUCCESS)
        // *pFinalMessage = NULL;

    if (pParamData)
    {
        for (i = 0; i < dwParamCount; i++)
        {
            if (pParamData[i].pParameter)
                LocalFree(pParamData[i].pParameter);
        }

        HeapFree(GetProcessHeap(), 0, pParamData);
    }

    return Status;
}


/*
 * The following functions were adapted from
 * shell32!dialogs/filedefext.cpp:``SH_...'' functions.
 */

UINT
FormatInteger(LONGLONG Num, LPWSTR pwszResult, UINT cchResultMax)
{
    WCHAR wszNumber[24];
    WCHAR wszDecimalSep[8], wszThousandSep[8];
    NUMBERFMTW nf;
    WCHAR wszGrouping[12];
    INT cchGrouping;
    INT cchResult;
    INT i;

    // Print the number in uniform mode
    swprintf(wszNumber, L"%I64u", Num);

    // Get system strings for decimal and thousand separators.
    GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, wszDecimalSep, _countof(wszDecimalSep));
    GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, wszThousandSep, _countof(wszThousandSep));

    // Initialize format for printing the number in bytes
    ZeroMemory(&nf, sizeof(nf));
    nf.lpDecimalSep = wszDecimalSep;
    nf.lpThousandSep = wszThousandSep;

    // Get system string for groups separator
    cchGrouping = GetLocaleInfoW(LOCALE_USER_DEFAULT,
                                 LOCALE_SGROUPING,
                                 wszGrouping,
                                 _countof(wszGrouping));

    // Convert grouping specs from string to integer
    for (i = 0; i < cchGrouping; i++)
    {
        WCHAR wch = wszGrouping[i];

        if (wch >= L'0' && wch <= L'9')
            nf.Grouping = nf.Grouping * 10 + (wch - L'0');
        else if (wch != L';')
            break;
    }

    if ((nf.Grouping % 10) == 0)
        nf.Grouping /= 10;
    else
        nf.Grouping *= 10;

    // Format the number
    cchResult = GetNumberFormatW(LOCALE_USER_DEFAULT,
                                 0,
                                 wszNumber,
                                 &nf,
                                 pwszResult,
                                 cchResultMax);

    if (!cchResult)
        return 0;

    // GetNumberFormatW returns number of characters including UNICODE_NULL
    return cchResult - 1;
}

UINT
FormatByteSize(LONGLONG cbSize, LPWSTR pwszResult, UINT cchResultMax)
{
    UINT cchWritten, cchRemaining;
    LPWSTR pwszEnd;
    size_t cchStringRemaining;

    /* Write formated bytes count */
    cchWritten = FormatInteger(cbSize, pwszResult, cchResultMax);
    if (!cchWritten)
        return 0;

    /* Copy " bytes" to buffer */
    pwszEnd = pwszResult + cchWritten;
    cchRemaining = cchResultMax - cchWritten;
    StringCchCopyExW(pwszEnd, cchRemaining, L" ", &pwszEnd, &cchStringRemaining, 0);
    cchRemaining = (UINT)cchStringRemaining;
    cchWritten = LoadStringW(hInst, IDS_BYTES_FORMAT, pwszEnd, cchRemaining);
    cchRemaining -= cchWritten;

    return cchResultMax - cchRemaining;
}

LPWSTR
FormatFileSizeWithBytes(const PULARGE_INTEGER lpQwSize, LPWSTR pwszResult, UINT cchResultMax)
{
    UINT cchWritten, cchRemaining;
    LPWSTR pwszEnd;
    size_t cchCopyRemaining;

    /* Format bytes in KBs, MBs etc */
    if (StrFormatByteSizeW(lpQwSize->QuadPart, pwszResult, cchResultMax) == NULL)
        return NULL;

    /* If there is less bytes than 1KB, we have nothing to do */
    if (lpQwSize->QuadPart < 1024)
        return pwszResult;

    /* Concatenate " (" */
    cchWritten = (UINT)wcslen(pwszResult);
    pwszEnd = pwszResult + cchWritten;
    cchRemaining = cchResultMax - cchWritten;
    StringCchCopyExW(pwszEnd, cchRemaining, L" (", &pwszEnd, &cchCopyRemaining, 0);
    cchRemaining = (UINT)cchCopyRemaining;

    /* Write formated bytes count */
    cchWritten = FormatByteSize(lpQwSize->QuadPart, pwszEnd, cchRemaining);
    pwszEnd += cchWritten;
    cchRemaining -= cchWritten;

    /* Copy ")" to the buffer */
    StringCchCopyW(pwszEnd, cchRemaining, L")");

    return pwszResult;
}

/* Adapted from shell32!dialogs/filedefext.cpp:``CFileDefExt::GetFileTimeString'' */
BOOL
GetFileTimeString(LPFILETIME lpFileTime, LPWSTR pwszResult, UINT cchResult)
{
    FILETIME ft;
    SYSTEMTIME st;
    int cchWritten;
    UINT cchRemaining = cchResult;
    size_t cchCopyRemaining;
    LPWSTR pwszEnd = pwszResult;

    if (!FileTimeToLocalFileTime(lpFileTime, &ft) || !FileTimeToSystemTime(&ft, &st))
        return FALSE;

    cchWritten = GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, pwszEnd, cchRemaining);
    if (cchWritten)
        --cchWritten; // GetDateFormatW returns count with terminating zero
    // else
        // ERR("GetDateFormatW failed\n");

    cchRemaining -= cchWritten;
    pwszEnd += cchWritten;

    StringCchCopyExW(pwszEnd, cchRemaining, L", ", &pwszEnd, &cchCopyRemaining, 0);
    cchRemaining = (UINT)cchCopyRemaining;

    cchWritten = GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, pwszEnd, cchRemaining);
    if (cchWritten)
        --cchWritten; // GetTimeFormatW returns count with terminating zero
    // else
        // ERR("GetTimeFormatW failed\n");

    return TRUE;
}


HTREEITEM
TreeViewAddItem(IN HWND hTreeView,
                IN HTREEITEM hParent,
                IN LPWSTR lpText,
                IN INT Image,
                IN INT SelectedImage,
                IN LPARAM lParam)
{
    TV_INSERTSTRUCTW Insert;

    ZeroMemory(&Insert, sizeof(Insert));

    Insert.item.mask = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
    Insert.hInsertAfter = TVI_LAST;
    Insert.hParent = hParent;
    Insert.item.pszText = lpText;
    Insert.item.iImage = Image;
    Insert.item.iSelectedImage = SelectedImage;
    Insert.item.lParam = lParam;

    Insert.item.mask |= TVIF_STATE;
    Insert.item.stateMask = TVIS_OVERLAYMASK;
    Insert.item.state = INDEXTOOVERLAYMASK(1);

    return TreeView_InsertItem(hTreeView, &Insert);
}


/* LOG HELPER FUNCTIONS *******************************************************/

PEVENTLOG
AllocEventLog(IN PCWSTR ComputerName OPTIONAL,
              IN PCWSTR LogName,
              IN BOOL Permanent)
{
    PEVENTLOG EventLog;
    SIZE_T cchName;

    /* Allocate a new event log entry */
    EventLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*EventLog));
    if (!EventLog)
        return NULL;

    /* Allocate the computer name string (optional) and copy it */
    if (ComputerName)
    {
        cchName = wcslen(ComputerName) + 1;
        EventLog->ComputerName = HeapAlloc(GetProcessHeap(), 0, cchName * sizeof(WCHAR));
        if (EventLog->ComputerName)
            StringCchCopyW(EventLog->ComputerName, cchName, ComputerName);
    }

    /* Allocate the event log name string and copy it */
    cchName = wcslen(LogName) + 1;
    EventLog->LogName = HeapAlloc(GetProcessHeap(), 0, cchName * sizeof(WCHAR));
    if (!EventLog->LogName)
    {
        if (EventLog->ComputerName)
            HeapFree(GetProcessHeap(), 0, EventLog->ComputerName);
        HeapFree(GetProcessHeap(), 0, EventLog);
        return NULL;
    }
    StringCchCopyW(EventLog->LogName, cchName, LogName);

    EventLog->Permanent = Permanent;

    return EventLog;
}

VOID
EventLog_Free(IN PEVENTLOG EventLog)
{
    if (EventLog->LogName)
        HeapFree(GetProcessHeap(), 0, EventLog->LogName);

    if (EventLog->ComputerName)
        HeapFree(GetProcessHeap(), 0, EventLog->ComputerName);

    if (EventLog->FileName)
        HeapFree(GetProcessHeap(), 0, EventLog->FileName);

    HeapFree(GetProcessHeap(), 0, EventLog);
}


PWSTR
AllocAndCopyMultiStr(IN PCWSTR MultiStr OPTIONAL)
{
    PWSTR pStr;
    ULONG Length;

    if (!MultiStr)
        return NULL;

    pStr = (PWSTR)MultiStr;
    while (*pStr) pStr += (wcslen(pStr) + 1);
    Length = MultiStr - pStr + 2;

    pStr = HeapAlloc(GetProcessHeap(), 0, Length * sizeof(WCHAR));
    // NOTE: If we failed allocating the string, then fall back into no filter!
    if (pStr)
        RtlCopyMemory(pStr, MultiStr, Length * sizeof(WCHAR));

    return pStr;
}

PEVENTLOGFILTER
AllocEventLogFilter(// IN PCWSTR FilterName,
                    IN BOOL Information,
                    IN BOOL Warning,
                    IN BOOL Error,
                    IN BOOL AuditSuccess,
                    IN BOOL AuditFailure,
                    IN PCWSTR Sources OPTIONAL,
                    IN PCWSTR Users OPTIONAL,
                    IN PCWSTR ComputerNames OPTIONAL,
                    IN ULONG NumOfEventLogs,
                    IN PEVENTLOG* EventLogs)
{
    PEVENTLOGFILTER EventLogFilter;

    /* Allocate a new event log filter entry, big enough to accommodate the list of logs */
    EventLogFilter = HeapAlloc(GetProcessHeap(),
                               HEAP_ZERO_MEMORY,
                               FIELD_OFFSET(EVENTLOGFILTER, EventLogs[NumOfEventLogs]));
    if (!EventLogFilter)
        return NULL;

    EventLogFilter->Information  = Information;
    EventLogFilter->Warning      = Warning;
    EventLogFilter->Error        = Error;
    EventLogFilter->AuditSuccess = AuditSuccess;
    EventLogFilter->AuditFailure = AuditFailure;

    /* Allocate and copy the sources, users, and computers multi-strings */
    EventLogFilter->Sources = AllocAndCopyMultiStr(Sources);
    EventLogFilter->Users   = AllocAndCopyMultiStr(Users);
    EventLogFilter->ComputerNames = AllocAndCopyMultiStr(ComputerNames);

    /* Copy the list of event logs */
    EventLogFilter->NumOfEventLogs = NumOfEventLogs;
    RtlCopyMemory(EventLogFilter->EventLogs, EventLogs, NumOfEventLogs * sizeof(PEVENTLOG));

    /* Initialize the filter reference count */
    EventLogFilter->ReferenceCount = 1;

    return EventLogFilter;
}

VOID
EventLogFilter_Free(IN PEVENTLOGFILTER EventLogFilter)
{
    if (EventLogFilter->Sources)
        HeapFree(GetProcessHeap(), 0, EventLogFilter->Sources);

    if (EventLogFilter->Users)
        HeapFree(GetProcessHeap(), 0, EventLogFilter->Users);

    if (EventLogFilter->ComputerNames)
        HeapFree(GetProcessHeap(), 0, EventLogFilter->ComputerNames);

    HeapFree(GetProcessHeap(), 0, EventLogFilter);
}

LONG EventLogFilter_AddRef(IN PEVENTLOGFILTER EventLogFilter)
{
    ASSERT(EventLogFilter);
    return InterlockedIncrement(&EventLogFilter->ReferenceCount);
}

LONG EventLogFilter_Release(IN PEVENTLOGFILTER EventLogFilter)
{
    LONG RefCount;

    ASSERT(EventLogFilter);

    /* When the reference count reaches zero, delete the filter */
    RefCount = InterlockedDecrement(&EventLogFilter->ReferenceCount);
    if (RefCount <= 0)
    {
        /* Remove the filter from the list */
        /** RemoveEntryList(&EventLogFilter->ListEntry); **/
        EventLogFilter_Free(EventLogFilter);
    }

    return RefCount;
}

void
TrimNulls(LPWSTR s)
{
    WCHAR *c;

    if (s != NULL)
    {
        c = s + wcslen(s) - 1;
        while (c >= s && iswspace(*c))
            --c;
        *++c = L'\0';
    }
}

DWORD
GetExpandedFilePathName(
    IN LPCWSTR ComputerName OPTIONAL,
    IN LPCWSTR lpFileName,
    OUT LPWSTR lpFullFileName OPTIONAL,
    IN DWORD nSize)
{
    SIZE_T dwLength;

    /* Determine the needed size after expansion of any environment strings */
    dwLength = ExpandEnvironmentStringsW(lpFileName, NULL, 0);
    if (dwLength == 0)
    {
        /* We failed, bail out */
        return 0;
    }

    /* If the file path is on a remote computer, estimate its length */
    // FIXME: Use WNetGetUniversalName instead?
    if (ComputerName && *ComputerName)
    {
        /* Skip any leading backslashes */
        while (*ComputerName == L'\\')
            ++ComputerName;

        if (*ComputerName)
        {
            /* Count 2 backslashes plus the computer name and one backslash separator */
            dwLength += 2 + wcslen(ComputerName) + 1;
        }
    }

    /* Check whether we have enough space */
    if (dwLength > nSize)
    {
        /* No, return the needed size in characters (includes NULL-terminator) */
        return dwLength;
    }


    /* Now expand the file path */
    ASSERT(dwLength <= nSize);

    /* Expand any existing environment strings */
    if (ExpandEnvironmentStringsW(lpFileName, lpFullFileName, dwLength) == 0)
    {
        /* We failed, bail out */
        return 0;
    }

    /* If the file path is on a remote computer, retrieve the network share form of the file name */
    // FIXME: Use WNetGetUniversalName instead?
    if (ComputerName && *ComputerName)
    {
        /* Note that we previously skipped any potential leading backslashes */

        /* Replace ':' by '$' in the drive letter */
        if (*lpFullFileName && lpFullFileName[1] == L':')
            lpFullFileName[1] = L'$';

        /* Prepend the computer name */
        RtlMoveMemory(lpFullFileName + 2 + wcslen(ComputerName) + 1,
                      lpFullFileName, dwLength * sizeof(WCHAR) - (2 + wcslen(ComputerName) + 1) * sizeof(WCHAR));
        lpFullFileName[0] = L'\\';
        lpFullFileName[1] = L'\\';
        wcsncpy(lpFullFileName + 2, ComputerName, wcslen(ComputerName));
        lpFullFileName[2 + wcslen(ComputerName)] = L'\\';
    }

    /* Return the number of stored characters (includes NULL-terminator) */
    return dwLength;
}

BOOL
GetEventMessageFileDLL(IN LPCWSTR lpLogName,
                       IN LPCWSTR SourceName,
                       IN LPCWSTR EntryName,
                       OUT PWCHAR lpModuleName) // TODO: Add IN DWORD BufLen
{
    BOOL Success = FALSE;
    LONG Result;
    DWORD dwType, dwSize;
    WCHAR szModuleName[MAX_PATH];
    WCHAR szKeyName[MAX_PATH];
    HKEY hLogKey = NULL;
    HKEY hSourceKey = NULL;

    StringCbCopyW(szKeyName, sizeof(szKeyName), EVENTLOG_BASE_KEY);
    StringCbCatW(szKeyName, sizeof(szKeyName), lpLogName);

    Result = RegOpenKeyExW(hkMachine,
                           szKeyName,
                           0,
                           KEY_READ,
                           &hLogKey);
    if (Result != ERROR_SUCCESS)
        return FALSE;

    Result = RegOpenKeyExW(hLogKey,
                           SourceName,
                           0,
                           KEY_QUERY_VALUE,
                           &hSourceKey);
    if (Result != ERROR_SUCCESS)
    {
        RegCloseKey(hLogKey);
        return FALSE;
    }

    dwSize = sizeof(szModuleName);
    Result = RegQueryValueExW(hSourceKey,
                              EntryName,
                              NULL,
                              &dwType,
                              (LPBYTE)szModuleName,
                              &dwSize);
    if ((Result != ERROR_SUCCESS) || (dwType != REG_EXPAND_SZ && dwType != REG_SZ))
    {
        szModuleName[0] = UNICODE_NULL;
    }
    else
    {
        /* NULL-terminate the string and expand it */
        szModuleName[dwSize / sizeof(WCHAR) - 1] = UNICODE_NULL;
        GetExpandedFilePathName(lpComputerName, szModuleName, lpModuleName, ARRAYSIZE(szModuleName));
        Success = TRUE;
    }

    RegCloseKey(hSourceKey);
    RegCloseKey(hLogKey);

    return Success;
}

BOOL
GetEventCategory(IN LPCWSTR KeyName,
                 IN LPCWSTR SourceName,
                 IN PEVENTLOGRECORD pevlr,
                 OUT PWCHAR CategoryName) // TODO: Add IN DWORD BufLen
{
    BOOL Success = FALSE;
    WCHAR szMessageDLL[MAX_PATH];
    LPWSTR lpMsgBuf = NULL;

    if (!GetEventMessageFileDLL(KeyName, SourceName, EVENT_CATEGORY_MESSAGE_FILE, szMessageDLL))
        goto Quit;

    /* Retrieve the message string without appending extra newlines */
    lpMsgBuf =
    GetMessageStringFromDllList(szMessageDLL,
                                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE |
                                FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
                                pevlr->EventCategory,
                                EVENT_MESSAGE_FILE_BUFFER,
                                NULL);
    if (lpMsgBuf)
    {
        /* Trim the string */
        TrimNulls(lpMsgBuf);

        /* Copy the category name */
        StringCchCopyW(CategoryName, MAX_PATH, lpMsgBuf);

        /* Free the buffer allocated by FormatMessage */
        LocalFree(lpMsgBuf);

        /* The ID was found and the message was formatted */
        Success = TRUE;
    }

Quit:
    if (!Success)
    {
        if (pevlr->EventCategory != 0)
        {
            StringCchPrintfW(CategoryName, MAX_PATH, L"(%lu)", pevlr->EventCategory);
            Success = TRUE;
        }
    }

    return Success;
}


BOOL                                                                        // NOTE: Used by evtdetctl.c
GetEventMessage(IN LPCWSTR KeyName,
                IN LPCWSTR SourceName,
                IN PEVENTLOGRECORD pevlr,
                OUT PWCHAR EventText) // TODO: Add IN DWORD BufLen
{
    BOOL Success = FALSE;
    DWORD i;
    size_t cch;
    WCHAR SourceModuleName[1024];
    WCHAR ParameterModuleName[1024];
    BOOL IsParamModNameCached = FALSE;
    LPWSTR lpMsgBuf = NULL;
    LPWSTR szStringArray, szMessage;
    LPWSTR *szArguments;

    /* Get the event string array */
    szStringArray = (LPWSTR)((LPBYTE)pevlr + pevlr->StringOffset);

    /* NOTE: GetEventMessageFileDLL can return a comma-separated list of DLLs */
    if (!GetEventMessageFileDLL(KeyName, SourceName, EVENT_MESSAGE_FILE, SourceModuleName))
        goto Quit;

    /* Allocate space for insertion strings */
    szArguments = HeapAlloc(GetProcessHeap(), 0, pevlr->NumStrings * sizeof(LPVOID));
    if (!szArguments)
        goto Quit;

    if (!IsParamModNameCached)
    {
        /* Now that the parameter file list is loaded, no need to reload it at the next run! */
        IsParamModNameCached = GetEventMessageFileDLL(KeyName, SourceName, EVENT_PARAMETER_MESSAGE_FILE, ParameterModuleName);
        // FIXME: If the string loading failed the first time, no need to retry it just after???
    }

    if (IsParamModNameCached)
    {
        /* Not yet support for reading messages from parameter message DLL */
    }

    szMessage = szStringArray;
    /*
     * HACK:
     * We do some hackish preformatting of the cached event strings...
     * That's because after we pass the string to FormatMessage
     * (via GetMessageStringFromDllList) with the FORMAT_MESSAGE_ARGUMENT_ARRAY
     * flag, instead of ignoring the insertion parameters and do the formatting
     * by ourselves. Therefore, the resulting string should have the parameter
     * string placeholders starting with a single '%' instead of a mix of one
     * and two '%'.
     */
    /* HACK part 1: Compute the full length of the string array */
    cch = 0;
    for (i = 0; i < pevlr->NumStrings; i++)
    {
        szMessage += wcslen(szMessage) + 1;
    }
    cch = szMessage - szStringArray;

    /* HACK part 2: Now do the HACK proper! */
    szMessage = szStringArray;
    for (i = 0; i < pevlr->NumStrings; i++)
    {
        lpMsgBuf = szMessage;
        while ((lpMsgBuf = wcsstr(lpMsgBuf, L"%%")))
        {
            if (iswdigit(lpMsgBuf[2]))
            {
                RtlMoveMemory(lpMsgBuf, lpMsgBuf+1, ((szStringArray + cch) - lpMsgBuf - 1) * sizeof(WCHAR));
            }
        }

        szArguments[i] = szMessage;
        szMessage += wcslen(szMessage) + 1;
    }

    /* Retrieve the message string without appending extra newlines */
    lpMsgBuf =
    GetMessageStringFromDllList(SourceModuleName,
                                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE |
                                FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_MAX_WIDTH_MASK,
                                pevlr->EventID,
                                0,
                                (va_list*)szArguments);
    if (lpMsgBuf)
    {
        /* Trim the string */
        TrimNulls(lpMsgBuf);

        szMessage = NULL;
        Success = (ApplyParameterStringsToMessage(ParameterModuleName,
                                                  TRUE,
                                                  lpMsgBuf,
                                                  &szMessage) == ERROR_SUCCESS);
        if (Success && szMessage)
        {
            /* Free the buffer allocated by FormatMessage */
            LocalFree(lpMsgBuf);
            lpMsgBuf = szMessage;
        }

        /* Copy the event text */
        StringCchCopyW(EventText, EVENT_MESSAGE_EVENTTEXT_BUFFER, lpMsgBuf);

        /* Free the buffer allocated by FormatMessage */
        LocalFree(lpMsgBuf);
    }

    HeapFree(GetProcessHeap(), 0, szArguments);

Quit:
    if (!Success)
    {
        /* Get a read-only pointer to the "event-not-found" string */
        lpMsgBuf = HeapAlloc(GetProcessHeap(), 0, EVENT_MESSAGE_EVENTTEXT_BUFFER * sizeof(WCHAR));
        LoadStringW(hInst, IDS_EVENTSTRINGIDNOTFOUND, lpMsgBuf, EVENT_MESSAGE_EVENTTEXT_BUFFER);
        StringCchPrintfW(EventText, EVENT_MESSAGE_EVENTTEXT_BUFFER, lpMsgBuf, (pevlr->EventID & 0xFFFF), SourceName);

        /* Append the strings */
        szMessage = szStringArray;
        for (i = 0; i < pevlr->NumStrings; i++)
        {
            StringCchCatW(EventText, EVENT_MESSAGE_EVENTTEXT_BUFFER, szMessage);
            StringCchCatW(EventText, EVENT_MESSAGE_EVENTTEXT_BUFFER, L"\n");
            szMessage += wcslen(szMessage) + 1;
        }
    }

    return Success;
}

VOID
GetEventType(IN WORD dwEventType,
             OUT PWCHAR eventTypeText) // TODO: Add IN DWORD BufLen
{
    switch (dwEventType)
    {
        case EVENTLOG_ERROR_TYPE:
            LoadStringW(hInst, IDS_EVENTLOG_ERROR_TYPE, eventTypeText, MAX_LOADSTRING);
            break;
        case EVENTLOG_WARNING_TYPE:
            LoadStringW(hInst, IDS_EVENTLOG_WARNING_TYPE, eventTypeText, MAX_LOADSTRING);
            break;
        case EVENTLOG_INFORMATION_TYPE:
            LoadStringW(hInst, IDS_EVENTLOG_INFORMATION_TYPE, eventTypeText, MAX_LOADSTRING);
            break;
        case EVENTLOG_SUCCESS:
            LoadStringW(hInst, IDS_EVENTLOG_SUCCESS, eventTypeText, MAX_LOADSTRING);
            break;
        case EVENTLOG_AUDIT_SUCCESS:
            LoadStringW(hInst, IDS_EVENTLOG_AUDIT_SUCCESS, eventTypeText, MAX_LOADSTRING);
            break;
        case EVENTLOG_AUDIT_FAILURE:
            LoadStringW(hInst, IDS_EVENTLOG_AUDIT_FAILURE, eventTypeText, MAX_LOADSTRING);
            break;
        default:
            LoadStringW(hInst, IDS_EVENTLOG_UNKNOWN_TYPE, eventTypeText, MAX_LOADSTRING);
            break;
    }
}

BOOL
GetEventUserName(IN PEVENTLOGRECORD pelr,
                 IN OUT PSID *pLastSid,
                 OUT PWCHAR pszUser) // TODO: Add IN DWORD BufLen
{
    PSID pCurrentSid;
    PWSTR StringSid;
    WCHAR szName[1024];
    WCHAR szDomain[1024];
    SID_NAME_USE peUse;
    DWORD cchName = ARRAYSIZE(szName);
    DWORD cchDomain = ARRAYSIZE(szDomain);
    BOOL Success = FALSE;

    /* Point to the SID */
    pCurrentSid = (PSID)((LPBYTE)pelr + pelr->UserSidOffset);

    if (!IsValidSid(pCurrentSid))
    {
        *pLastSid = NULL;
        return FALSE;
    }
    else if (*pLastSid && EqualSid(*pLastSid, pCurrentSid))
    {
        return TRUE;
    }

    /* User SID */
    if (pelr->UserSidLength > 0)
    {
        /*
         * Try to retrieve the user account name and domain name corresponding
         * to the SID. If it cannot be retrieved, try to convert the SID to a
         * string-form. It should not be bigger than the user-provided buffer
         * 'pszUser', otherwise we return an error.
         */
        if (LookupAccountSidW(lpComputerName,
                              pCurrentSid,
                              szName,
                              &cchName,
                              szDomain,
                              &cchDomain,
                              &peUse))
        {
            StringCchCopyW(pszUser, MAX_PATH, szName);
            Success = TRUE;
        }
        else if (ConvertSidToStringSidW(pCurrentSid, &StringSid))
        {
            /* Copy the string only if the user-provided buffer is big enough */
            if (wcslen(StringSid) + 1 <= MAX_PATH) // + 1 for NULL-terminator
            {
                StringCchCopyW(pszUser, MAX_PATH, StringSid);
                Success = TRUE;
            }
            else
            {
                SetLastError(ERROR_NOT_ENOUGH_MEMORY);
                Success = FALSE;
            }

            /* Free the allocated buffer */
            LocalFree(StringSid);
        }
    }

    *pLastSid = Success ? pCurrentSid : NULL;

    return Success;
}


static VOID FreeRecords(VOID)
{
    DWORD iIndex;

    if (!g_RecordPtrs)
        return;

    for (iIndex = 0; iIndex < g_TotalRecords; iIndex++)
    {
        if (g_RecordPtrs[iIndex])
            HeapFree(GetProcessHeap(), 0, g_RecordPtrs[iIndex]);
    }
    HeapFree(GetProcessHeap(), 0, g_RecordPtrs);
    g_RecordPtrs = NULL;
    g_TotalRecords = 0;
}

BOOL
FilterByType(IN PEVENTLOGFILTER EventLogFilter,
             IN PEVENTLOGRECORD pevlr)
{
    if ((pevlr->EventType == EVENTLOG_SUCCESS          && !EventLogFilter->Information ) ||
        (pevlr->EventType == EVENTLOG_INFORMATION_TYPE && !EventLogFilter->Information ) ||
        (pevlr->EventType == EVENTLOG_WARNING_TYPE     && !EventLogFilter->Warning     ) ||
        (pevlr->EventType == EVENTLOG_ERROR_TYPE       && !EventLogFilter->Error       ) ||
        (pevlr->EventType == EVENTLOG_AUDIT_SUCCESS    && !EventLogFilter->AuditSuccess) ||
        (pevlr->EventType == EVENTLOG_AUDIT_FAILURE    && !EventLogFilter->AuditFailure))
    {
        return FALSE;
    }
    return TRUE;
}

BOOL
FilterByString(IN PCWSTR FilterString, // This is a multi-string
               IN PWSTR  String)
{
    PCWSTR pStr;

    /* The filter string is NULL so it does not filter anything */
    if (!FilterString)
        return TRUE;

    /*
     * If the filter string filters for an empty string AND the source string
     * is an empty string, we have a match (particular case of the last one).
     */
    if (!*FilterString && !*String)
        return TRUE;

    // if (*FilterString || *String)

    /*
     * If the filter string is empty BUT the source string is not empty,
     * OR vice-versa, we cannot have a match.
     */
    if ( (!*FilterString && *String) || (*FilterString && !*String) )
        return FALSE;

    /*
     * If the filter string filters for at least a non-empty string,
     * browse it and search for a string that matches the source string.
     */
    // else if (*FilterString && *String)
    {
        pStr = FilterString;
        while (*pStr)
        {
            if (wcsicmp(pStr, String) == 0)
            {
                /* We have a match, break the loop */
                break;
            }

            pStr += (wcslen(pStr) + 1);
        }
        if (!*pStr) // && *String
        {
            /* We do not have a match */
            return FALSE;
        }
    }

    /* We have a match */
    return TRUE;
}

/*
 * The events enumerator thread.
 */
static DWORD WINAPI
EnumEventsThread(IN LPVOID lpParameter)
{
    PEVENTLOGFILTER EventLogFilter = (PEVENTLOGFILTER)lpParameter;
    PEVENTLOG EventLog;

    ULONG LogIndex;
    HANDLE hEventLog;
    PEVENTLOGRECORD pEvlr = NULL;
    PBYTE pEvlrEnd;
    PBYTE pEvlrBuffer;
    DWORD dwWanted, dwRead, dwNeeded, dwStatus = ERROR_SUCCESS;
    DWORD dwTotalRecords = 0, dwCurrentRecord = 0;
    DWORD dwFlags, dwMaxLength;
    size_t cchRemaining;
    LPWSTR lpszSourceName;
    LPWSTR lpszComputerName;
    BOOL bResult = TRUE; /* Read succeeded */
    HANDLE hProcessHeap = GetProcessHeap();
    PSID pLastSid = NULL;

    UINT uStep = 0, uStepAt = 0, uPos = 0;

    WCHAR szWindowTitle[MAX_PATH];
    WCHAR szStatusText[MAX_PATH];
    WCHAR szLocalDate[MAX_PATH];
    WCHAR szLocalTime[MAX_PATH];
    WCHAR szEventID[MAX_PATH];
    WCHAR szEventTypeText[MAX_LOADSTRING];
    WCHAR szCategoryID[MAX_PATH];
    WCHAR szUsername[MAX_PATH];
    WCHAR szNoUsername[MAX_PATH];
    WCHAR szCategory[MAX_PATH];
    WCHAR szNoCategory[MAX_PATH];
    PWCHAR lpTitleTemplateEnd;

    SYSTEMTIME time;
    LVITEMW lviEventItem;

    /* Save the current event log filter globally */
    EventLogFilter_AddRef(EventLogFilter);
    ActiveFilter = EventLogFilter;


    /** HACK!! **/
    EventLog = EventLogFilter->EventLogs[0];

    // FIXME: Use something else instead of EventLog->LogName !!

    /*
     * Use a different formatting, whether the event log filter holds
     * only one log, or many logs (the latter case is WIP TODO!)
     */
    if (EventLogFilter->NumOfEventLogs <= 1)
    {
        StringCchPrintfExW(szWindowTitle,
                           ARRAYSIZE(szWindowTitle),
                           &lpTitleTemplateEnd,
                           &cchRemaining,
                           0,
                           szTitleTemplate, szTitle, EventLog->LogName); /* i = number of characters written */
        dwMaxLength = (DWORD)cchRemaining;
        if (!EventLog->ComputerName)
            GetComputerNameW(lpTitleTemplateEnd, &dwMaxLength);
        else
            StringCchCopyW(lpTitleTemplateEnd, dwMaxLength, EventLog->ComputerName);

        StringCbPrintfW(szStatusText,
                        sizeof(szStatusText),
                        szStatusBarTemplate,
                        EventLog->LogName,
                        0,
                        0);
    }
    else
    {
        // TODO: Use a different title & implement filtering for multi-log filters !!
        // (EventLogFilter->NumOfEventLogs > 1)
        MessageBoxW(hwndMainWindow,
                    L"Many-logs filtering is not implemented yet!!",
                    L"Event Log",
                    MB_OK | MB_ICONINFORMATION);
    }

    /* Set the window title */
    SetWindowTextW(hwndMainWindow, szWindowTitle);

    /* Update the status bar */
    StatusBar_SetText(hwndStatus, 0, szStatusText);


    /* Disable list view redraw */
    SendMessageW(hwndListView, WM_SETREDRAW, FALSE, 0);

    /* Clear the list view and free the cached records */
    ListView_DeleteAllItems(hwndListView);
    FreeRecords();

    SendMessageW(hwndListView, LVM_PROGRESS, 0, TRUE);
    ProgressBar_SetRange(hwndStatusProgress, 0);
    StatusBar_SetText(hwndStatus, 0, NULL);
    ShowWindow(hwndStatusProgress, SW_SHOW);

    /* Do a loop over the logs enumerated in the filter */
    // FIXME: For now we only support 1 event log per filter!
    LogIndex = 0;
    // for (LogIndex = 0; LogIndex < EventLogFilter->NumOfEventLogs; ++LogIndex)
    {

    EventLog = EventLogFilter->EventLogs[LogIndex];

    /* Open the event log */
    if (EventLog->Permanent)
        hEventLog = OpenEventLogW(EventLog->ComputerName, EventLog->LogName);
    else
        hEventLog = OpenBackupEventLogW(EventLog->ComputerName, EventLog->LogName); // FileName

    if (hEventLog == NULL)
    {
        ShowWin32Error(GetLastError());
        goto Cleanup;
    }

    // GetOldestEventLogRecord(hEventLog, &dwThisRecord);

    /* Get the total number of event log records */
    GetNumberOfEventLogRecords(hEventLog, &dwTotalRecords);

    if (dwTotalRecords > 0)
    {
        EnableMenuItem(hMainMenu, IDM_CLEAR_EVENTS, MF_BYCOMMAND | MF_ENABLED);
        EnableMenuItem(hMainMenu, IDM_SAVE_EVENTLOG, MF_BYCOMMAND | MF_ENABLED);
    }
    else
    {
        EnableMenuItem(hMainMenu, IDM_CLEAR_EVENTS, MF_BYCOMMAND | MF_GRAYED);
        EnableMenuItem(hMainMenu, IDM_SAVE_EVENTLOG, MF_BYCOMMAND | MF_GRAYED);
    }

    /* Set up the event records cache */
    g_RecordPtrs = HeapAlloc(hProcessHeap, HEAP_ZERO_MEMORY, dwTotalRecords * sizeof(*g_RecordPtrs));
    if (!g_RecordPtrs)
    {
        // ShowWin32Error(GetLastError());
        goto Quit;
    }
    g_TotalRecords = dwTotalRecords;

    if (WaitForSingleObject(hStopEnumEvent, 0) == WAIT_OBJECT_0)
        goto Quit;

    LoadStringW(hInst, IDS_NOT_AVAILABLE, szNoUsername, ARRAYSIZE(szNoUsername));
    LoadStringW(hInst, IDS_NONE, szNoCategory, ARRAYSIZE(szNoCategory));

    ProgressBar_SetRange(hwndStatusProgress, MAKELPARAM(0, 100));
    uStepAt = (dwTotalRecords / 100) + 1;

    dwFlags = EVENTLOG_SEQUENTIAL_READ | (Settings.bNewestEventsFirst ? EVENTLOG_FORWARDS_READ : EVENTLOG_BACKWARDS_READ);

    /* 0x7ffff is the maximum buffer size ReadEventLog will accept */
    dwWanted = 0x7ffff;
    pEvlr = HeapAlloc(hProcessHeap, 0, dwWanted);

    if (!pEvlr)
        goto Quit;

    while (dwStatus == ERROR_SUCCESS)
    {
        bResult =  ReadEventLogW(hEventLog, dwFlags, 0, pEvlr, dwWanted, &dwRead, &dwNeeded);
        dwStatus = GetLastError();

        if (!bResult && dwStatus == ERROR_INSUFFICIENT_BUFFER)
        {
            pEvlr = HeapReAlloc(hProcessHeap, 0, pEvlr, dwNeeded);
            dwWanted = dwNeeded;

            if (!pEvlr)
                break;

            bResult =  ReadEventLogW(hEventLog, dwFlags, 0, pEvlr, dwNeeded, &dwRead, &dwNeeded);

            if (!bResult)
                break;
        }
        else if (!bResult)
        {
            /* Exit on other errors (ERROR_HANDLE_EOF) */
            break;
        }

        pEvlrBuffer = (LPBYTE)pEvlr;
        pEvlrEnd = pEvlrBuffer + dwRead;

        while (pEvlrBuffer < pEvlrEnd)
        {
            PEVENTLOGRECORD pEvlrTmp = (PEVENTLOGRECORD)pEvlrBuffer;
            PWSTR lpszUsername, lpszCategoryName;
            g_RecordPtrs[dwCurrentRecord] = NULL;

            // ProgressBar_StepIt(hwndStatusProgress);
            uStep++;
            if (uStep % uStepAt == 0)
            {
                ++uPos;
                ProgressBar_SetPos(hwndStatusProgress, uPos);
            }

           if (WaitForSingleObject(hStopEnumEvent, 0) == WAIT_OBJECT_0)
                goto Quit;

            /* Filter by event type */
            if (!FilterByType(EventLogFilter, pEvlrTmp))
                goto SkipEvent;

            /* Get the event source name and filter it */
            lpszSourceName = (LPWSTR)(pEvlrBuffer + sizeof(EVENTLOGRECORD));
            if (!FilterByString(EventLogFilter->Sources, lpszSourceName))
                goto SkipEvent;

            /* Get the computer name and filter it */
            lpszComputerName = (LPWSTR)(pEvlrBuffer + sizeof(EVENTLOGRECORD) + (wcslen(lpszSourceName) + 1) * sizeof(WCHAR));
            if (!FilterByString(EventLogFilter->ComputerNames, lpszComputerName))
                goto SkipEvent;

            /* Compute the event time */
            EventTimeToSystemTime(pEvlrTmp->TimeWritten, &time);
            GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &time, NULL, szLocalDate, ARRAYSIZE(szLocalDate));
            GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &time, NULL, szLocalTime, ARRAYSIZE(szLocalTime));

            /* Get the username that generated the event, and filter it */
            lpszUsername = GetEventUserName(pEvlrTmp, &pLastSid, szUsername) ? szUsername : szNoUsername;

            if (!FilterByString(EventLogFilter->Users, lpszUsername))
                goto SkipEvent;

            // TODO: Filter by event ID and category
            GetEventType(pEvlrTmp->EventType, szEventTypeText);

            lpszCategoryName = GetEventCategory(EventLog->LogName, lpszSourceName, pEvlrTmp, szCategory) ? szCategory : szNoCategory;

            StringCbPrintfW(szEventID, sizeof(szEventID), L"%u", (pEvlrTmp->EventID & 0xFFFF));
            StringCbPrintfW(szCategoryID, sizeof(szCategoryID), L"%u", pEvlrTmp->EventCategory);

            g_RecordPtrs[dwCurrentRecord] = HeapAlloc(hProcessHeap, 0, pEvlrTmp->Length);
            RtlCopyMemory(g_RecordPtrs[dwCurrentRecord], pEvlrTmp, pEvlrTmp->Length);

            lviEventItem.mask = LVIF_IMAGE | LVIF_TEXT | LVIF_PARAM;
            lviEventItem.iItem = 0;
            lviEventItem.iSubItem = 0;
            lviEventItem.lParam = (LPARAM)g_RecordPtrs[dwCurrentRecord];
            lviEventItem.pszText = szEventTypeText;

            switch (pEvlrTmp->EventType)
            {
                case EVENTLOG_SUCCESS:
                case EVENTLOG_INFORMATION_TYPE:
                    lviEventItem.iImage = 0;
                    break;

                case EVENTLOG_WARNING_TYPE:
                    lviEventItem.iImage = 1;
                    break;

                case EVENTLOG_ERROR_TYPE:
                    lviEventItem.iImage = 2;
                    break;

                case EVENTLOG_AUDIT_SUCCESS:
                    lviEventItem.iImage = 3;
                    break;

                case EVENTLOG_AUDIT_FAILURE:
                    lviEventItem.iImage = 4;
                    break;
            }

            lviEventItem.iItem = ListView_InsertItem(hwndListView, &lviEventItem);

            ListView_SetItemText(hwndListView, lviEventItem.iItem, 1, szLocalDate);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 2, szLocalTime);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 3, lpszSourceName);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 4, lpszCategoryName);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 5, szEventID);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 6, lpszUsername);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 7, lpszComputerName);

SkipEvent:
            pEvlrBuffer += pEvlrTmp->Length;
            dwCurrentRecord++;
        }
    }

Quit:

    if (pEvlr)
        HeapFree(hProcessHeap, 0, pEvlr);

    /* Close the event log */
    CloseEventLog(hEventLog);

    } // end-for (LogIndex)

    /* All events loaded */

Cleanup:

    ShowWindow(hwndStatusProgress, SW_HIDE);
    SendMessageW(hwndListView, LVM_PROGRESS, 0, FALSE);

    // FIXME: Use something else instead of EventLog->LogName !!

    /*
     * Use a different formatting, whether the event log filter holds
     * only one log, or many logs (the latter case is WIP TODO!)
     */
    if (EventLogFilter->NumOfEventLogs <= 1)
    {
        StringCbPrintfW(szStatusText,
                        sizeof(szStatusText),
                        szStatusBarTemplate,
                        EventLog->LogName,
                        dwTotalRecords,
                        ListView_GetItemCount(hwndListView));
    }
    else
    {
        // TODO: Use a different title & implement filtering for multi-log filters !!
        // (EventLogFilter->NumOfEventLogs > 1)
    }

    /* Update the status bar */
    StatusBar_SetText(hwndStatus, 0, szStatusText);

    /* Resume list view redraw */
    SendMessageW(hwndListView, WM_SETREDRAW, TRUE, 0);

    EventLogFilter_Release(EventLogFilter);

    CloseHandle(hStopEnumEvent);
    InterlockedExchangePointer((PVOID*)&hStopEnumEvent, NULL);

    return 0;
}

/*
 * The purpose of this thread is to serialize the creation of the events
 * enumeration thread, since the Event Log Viewer currently only supports
 * one view, one event list, one enumeration.
 */
static DWORD WINAPI
StartStopEnumEventsThread(IN LPVOID lpParameter)
{
    HANDLE WaitHandles[2];
    DWORD  WaitResult;

    WaitHandles[0] = hStartStopEnumEvent; // End-of-application event
    WaitHandles[1] = hStartEnumEvent;     // Command event

    while (TRUE)
    {
        WaitResult = WaitForMultipleObjects(ARRAYSIZE(WaitHandles),
                                            WaitHandles,
                                            FALSE, // WaitAny
                                            INFINITE);
        switch (WaitResult)
        {
            case WAIT_OBJECT_0 + 0:
            {
                /* End-of-application event signaled, quit this thread */

                /* Stop the previous enumeration */
                if (hEnumEventsThread)
                {
                    if (hStopEnumEvent)
                    {
                        SetEvent(hStopEnumEvent);
                        WaitForSingleObject(hEnumEventsThread, INFINITE);
                        // NOTE: The following is done by the enumeration thread just before terminating.
                        // hStopEnumEvent = NULL;
                    }

                    CloseHandle(hEnumEventsThread);
                    hEnumEventsThread = NULL;
                }

                /* Clear the list view and free the cached records */
                ListView_DeleteAllItems(hwndListView);
                FreeRecords();

                /* Reset the active filter */
                ActiveFilter = NULL;

                return 0;
            }

            case WAIT_OBJECT_0 + 1:
            {
                /* Restart a new enumeration if needed */
                PEVENTLOGFILTER EventLogFilter;

                /* Stop the previous enumeration */
                if (hEnumEventsThread)
                {
                    if (hStopEnumEvent)
                    {
                        SetEvent(hStopEnumEvent);
                        WaitForSingleObject(hEnumEventsThread, INFINITE);
                        // NOTE: The following is done by the enumeration thread just before terminating.
                        // hStopEnumEvent = NULL;
                    }

                    CloseHandle(hEnumEventsThread);
                    hEnumEventsThread = NULL;
                }

                /* Clear the list view and free the cached records */
                ListView_DeleteAllItems(hwndListView);
                FreeRecords();

                /* Reset the active filter */
                ActiveFilter = NULL;

                EventLogFilter = InterlockedExchangePointer((PVOID*)&EnumFilter, NULL);
                if (!EventLogFilter)
                    break;

                // Manual-reset event
                hStopEnumEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
                if (!hStopEnumEvent)
                    break;

                hEnumEventsThread = CreateThread(NULL,
                                                 0,
                                                 EnumEventsThread,
                                                 (LPVOID)EventLogFilter,
                                                 CREATE_SUSPENDED,
                                                 NULL);
                if (!hEnumEventsThread)
                {
                    CloseHandle(hStopEnumEvent);
                    hStopEnumEvent = NULL;
                    break;
                }
                // CloseHandle(hEnumEventsThread);
                ResumeThread(hEnumEventsThread);

                break;
            }

            default:
            {
                /* Unknown command, must never go there! */
                return GetLastError();
            }
        }
    }

    return 0;
}

VOID
EnumEvents(IN PEVENTLOGFILTER EventLogFilter)
{
    /* Signal the enumerator thread we want to enumerate events */
    InterlockedExchangePointer((PVOID*)&EnumFilter, EventLogFilter);
    SetEvent(hStartEnumEvent);
    return;
}


PEVENTLOGFILTER
GetSelectedFilter(OUT HTREEITEM* phti OPTIONAL)
{
    TVITEMEXW tvItemEx;
    HTREEITEM hti;

    if (phti)
        *phti = NULL;

    /* Get index of selected item */
    hti = TreeView_GetSelection(hwndTreeView);
    if (hti == NULL)
        return NULL; // No filter

    tvItemEx.mask = TVIF_PARAM;
    tvItemEx.hItem = hti;

    TreeView_GetItem(hwndTreeView, &tvItemEx);

    if (phti)
        *phti = tvItemEx.hItem;

    return (PEVENTLOGFILTER)tvItemEx.lParam;
}


VOID
OpenUserEventLogFile(IN LPCWSTR lpszFileName)
{
    WIN32_FIND_DATAW FindData;
    HANDLE hFind;
    PEVENTLOG EventLog;
    PEVENTLOGFILTER EventLogFilter;
    SIZE_T cchFileName;
    HTREEITEM hItem = NULL;

    /* Check whether the file actually exists */
    hFind = FindFirstFileW(lpszFileName, &FindData);
    if (hFind == INVALID_HANDLE_VALUE)
    {
        ShowWin32Error(GetLastError());
        return;
    }
    FindClose(hFind);

    /* Allocate a new event log entry */
    EventLog = AllocEventLog(NULL, lpszFileName, FALSE);
    if (EventLog == NULL)
    {
        ShowWin32Error(ERROR_NOT_ENOUGH_MEMORY);
        return;
    }

    /* Allocate a new event log filter entry for this event log */
    EventLogFilter = AllocEventLogFilter(// LogName,
                                         TRUE, TRUE, TRUE, TRUE, TRUE,
                                         NULL, NULL, NULL,
                                         1, &EventLog);
    if (EventLogFilter == NULL)
    {
        ShowWin32Error(ERROR_NOT_ENOUGH_MEMORY);
        EventLog_Free(EventLog);
        return;
    }

    /* Add the event log and the filter into their lists */
    InsertTailList(&EventLogList, &EventLog->ListEntry);
    InsertTailList(&EventLogFilterList, &EventLogFilter->ListEntry);

    /* Retrieve and cache the event log file */
    cchFileName = wcslen(lpszFileName) + 1;
    EventLog->FileName = HeapAlloc(GetProcessHeap(), 0, cchFileName * sizeof(WCHAR));
    if (EventLog->FileName)
        StringCchCopyW(EventLog->FileName, cchFileName, lpszFileName);

    hItem = TreeViewAddItem(hwndTreeView, htiUserLogs,
                            (LPWSTR)lpszFileName,
                            2, 3, (LPARAM)EventLogFilter);

    /* Select the event log */
    if (hItem)
    {
        // TreeView_Expand(hwndTreeView, htiUserLogs, TVE_EXPAND);
        TreeView_SelectItem(hwndTreeView, hItem);
        TreeView_EnsureVisible(hwndTreeView, hItem);
    }
    InvalidateRect(hwndTreeView, NULL, FALSE);
    SetFocus(hwndTreeView);
}

VOID
OpenUserEventLog(VOID)
{
    WCHAR szFileName[MAX_PATH];

    ZeroMemory(szFileName, sizeof(szFileName));

    sfn.lpstrFile = szFileName;
    sfn.nMaxFile  = ARRAYSIZE(szFileName);

    if (!GetOpenFileNameW(&sfn))
        return;
    sfn.lpstrFile[sfn.nMaxFile-1] = UNICODE_NULL;

    OpenUserEventLogFile(sfn.lpstrFile);
}

VOID
SaveEventLog(IN PEVENTLOGFILTER EventLogFilter)
{
    PEVENTLOG EventLog;
    HANDLE hEventLog;
    WCHAR szFileName[MAX_PATH];

    /* Bail out if there is no available filter */
    if (!EventLogFilter)
        return;

    ZeroMemory(szFileName, sizeof(szFileName));

    sfn.lpstrFile = szFileName;
    sfn.nMaxFile  = ARRAYSIZE(szFileName);

    if (!GetSaveFileNameW(&sfn))
        return;

    EventLogFilter_AddRef(EventLogFilter);

    EventLog = EventLogFilter->EventLogs[0];
    hEventLog = OpenEventLogW(EventLog->ComputerName, EventLog->LogName);

    EventLogFilter_Release(EventLogFilter);

    if (!hEventLog)
    {
        ShowWin32Error(GetLastError());
        return;
    }

    if (!BackupEventLogW(hEventLog, szFileName))
        ShowWin32Error(GetLastError());

    CloseEventLog(hEventLog);
}

VOID
CloseUserEventLog(IN PEVENTLOGFILTER EventLogFilter, IN HTREEITEM hti)
{
    /* Bail out if there is no available filter */
    if (!EventLogFilter)
        return;

    if (InterlockedCompareExchangePointer((PVOID*)&ActiveFilter, NULL, NULL) == EventLogFilter)
    {
        /* Signal the enumerator thread we want to stop enumerating events */
        // EnumEvents(NULL);
        InterlockedExchangePointer((PVOID*)&EnumFilter, NULL);
        SetEvent(hStartEnumEvent);
    }

    /*
     * The deletion of the item automatically triggers a TVN_SELCHANGED
     * notification, that will reset the ActiveFilter (in case the item
     * selected is a filter). Otherwise we reset it there.
     */
    TreeView_DeleteItem(hwndTreeView, hti);

    /* Remove the filter from the list */
    RemoveEntryList(&EventLogFilter->ListEntry);
    EventLogFilter_Release(EventLogFilter);

    // /* Select the default event log */
    // // TreeView_Expand(hwndTreeView, htiUserLogs, TVE_EXPAND);
    // TreeView_SelectItem(hwndTreeView, hItem);
    // TreeView_EnsureVisible(hwndTreeView, hItem);
    InvalidateRect(hwndTreeView, NULL, FALSE);
    SetFocus(hwndTreeView);
}


BOOL
ClearEvents(IN PEVENTLOGFILTER EventLogFilter)
{
    BOOL Success;
    PEVENTLOG EventLog;
    HANDLE hEventLog;
    WCHAR szFileName[MAX_PATH];
    WCHAR szMessage[MAX_LOADSTRING];

    /* Bail out if there is no available filter */
    if (!EventLogFilter)
        return FALSE;

    ZeroMemory(szFileName, sizeof(szFileName));
    ZeroMemory(szMessage, sizeof(szMessage));

    LoadStringW(hInst, IDS_CLEAREVENTS_MSG, szMessage, ARRAYSIZE(szMessage));

    sfn.lpstrFile = szFileName;
    sfn.nMaxFile  = ARRAYSIZE(szFileName);

    switch (MessageBoxW(hwndMainWindow, szMessage, szTitle, MB_YESNOCANCEL | MB_ICONINFORMATION))
    {
        case IDCANCEL:
            return FALSE;

        case IDNO:
            sfn.lpstrFile = NULL;
            break;

        case IDYES:
            if (!GetSaveFileNameW(&sfn))
                return FALSE;
            break;
    }

    EventLogFilter_AddRef(EventLogFilter);

    EventLog = EventLogFilter->EventLogs[0];
    hEventLog = OpenEventLogW(EventLog->ComputerName, EventLog->LogName);

    EventLogFilter_Release(EventLogFilter);

    if (!hEventLog)
    {
        ShowWin32Error(GetLastError());
        return FALSE;
    }

    Success = ClearEventLogW(hEventLog, sfn.lpstrFile);
    if (!Success)
        ShowWin32Error(GetLastError());

    CloseEventLog(hEventLog);
    return Success;
}


VOID
Refresh(IN PEVENTLOGFILTER EventLogFilter)
{
    /* Bail out if there is no available filter */
    if (!EventLogFilter)
        return;

    /* Reenumerate the events through the filter */
    EnumEvents(EventLogFilter);
}


ATOM
MyRegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEXW wcex;

    wcex.cbSize = sizeof(wcex);
    wcex.style = 0;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_EVENTVWR));
    wcex.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_ARROW));
    wcex.hbrBackground = (HBRUSH)(COLOR_3DFACE + 1); // COLOR_WINDOW + 1
    wcex.lpszMenuName = MAKEINTRESOURCEW(IDM_EVENTVWR);
    wcex.lpszClassName = EVENTVWR_WNDCLASS;
    wcex.hIconSm = (HICON)LoadImageW(hInstance,
                                     MAKEINTRESOURCEW(IDI_EVENTVWR),
                                     IMAGE_ICON,
                                     16,
                                     16,
                                     LR_SHARED);

    return RegisterClassExW(&wcex);
}


BOOL
GetDisplayNameFileAndID(IN LPCWSTR lpLogName,
                        OUT PWCHAR lpModuleName, // TODO: Add IN DWORD BufLen
                        OUT PDWORD pdwMessageID)
{
    BOOL Success = FALSE;
    LONG Result;
    HKEY hLogKey;
    WCHAR *KeyPath;
    SIZE_T cbKeyPath;
    DWORD dwType, cbData;
    DWORD dwMessageID = 0;
    WCHAR szModuleName[MAX_PATH];

    /* Use a default value for the message ID */
    *pdwMessageID = 0;

    cbKeyPath = (wcslen(EVENTLOG_BASE_KEY) + wcslen(lpLogName) + 1) * sizeof(WCHAR);
    KeyPath = HeapAlloc(GetProcessHeap(), 0, cbKeyPath);
    if (!KeyPath)
    {
        ShowWin32Error(ERROR_NOT_ENOUGH_MEMORY);
        return FALSE;
    }

    StringCbCopyW(KeyPath, cbKeyPath, EVENTLOG_BASE_KEY);
    StringCbCatW(KeyPath, cbKeyPath, lpLogName);

    Result = RegOpenKeyExW(hkMachine, KeyPath, 0, KEY_QUERY_VALUE, &hLogKey);
    HeapFree(GetProcessHeap(), 0, KeyPath);
    if (Result != ERROR_SUCCESS)
    {
        ShowWin32Error(Result);
        return FALSE;
    }

    cbData = sizeof(szModuleName);
    Result = RegQueryValueExW(hLogKey,
                              L"DisplayNameFile",
                              NULL,
                              &dwType,
                              (LPBYTE)szModuleName,
                              &cbData);
    if ((Result != ERROR_SUCCESS) || (dwType != REG_EXPAND_SZ && dwType != REG_SZ))
    {
        szModuleName[0] = UNICODE_NULL;
    }
    else
    {
        /* NULL-terminate the string and expand it */
        szModuleName[cbData / sizeof(WCHAR) - 1] = UNICODE_NULL;
        GetExpandedFilePathName(lpComputerName, szModuleName, lpModuleName, ARRAYSIZE(szModuleName));
        Success = TRUE;
    }

    /*
     * If we have a 'DisplayNameFile', query for 'DisplayNameID';
     * otherwise it's not really useful. 'DisplayNameID' is optional.
     */
    if (Success)
    {
        cbData = sizeof(dwMessageID);
        Result = RegQueryValueExW(hLogKey,
                                  L"DisplayNameID",
                                  NULL,
                                  &dwType,
                                  (LPBYTE)&dwMessageID,
                                  &cbData);
        if ((Result != ERROR_SUCCESS) || (dwType != REG_DWORD))
            dwMessageID = 0;

        *pdwMessageID = dwMessageID;
    }

    RegCloseKey(hLogKey);

    return Success;
}


VOID
BuildLogListAndFilterList(IN LPCWSTR lpComputerName)
{
    LONG Result;
    HKEY hEventLogKey, hLogKey;
    DWORD dwNumLogs = 0;
    DWORD dwIndex, dwMaxKeyLength;
    DWORD dwType;
    PEVENTLOG EventLog;
    PEVENTLOGFILTER EventLogFilter;
    LPWSTR LogName = NULL;
    WCHAR szModuleName[MAX_PATH];
    DWORD lpcName;
    DWORD dwMessageID;
    LPWSTR lpDisplayName;
    HTREEITEM hRootNode = NULL, hItem = NULL, hItemDefault = NULL;

    if (hkMachine && hkMachine != HKEY_LOCAL_MACHINE)
    {
        /* We are connected to some other computer, close the old connection */
        RegCloseKey(hkMachine);
        hkMachine = NULL;
    }
    if (!lpComputerName || !*lpComputerName)
    {
        /* Use the local computer registry */
        hkMachine = HKEY_LOCAL_MACHINE;
    }
    else
    {
        /* Connect to the remote computer registry */
        Result = RegConnectRegistry(lpComputerName, HKEY_LOCAL_MACHINE, &hkMachine);
        if (Result != ERROR_SUCCESS)
        {
            /* Connection failed, display a message and bail out */
            hkMachine = NULL;
            ShowWin32Error(GetLastError());
            return;
        }
    }

    /* Open the EventLog key */
    Result = RegOpenKeyExW(hkMachine, EVENTLOG_BASE_KEY, 0, KEY_READ, &hEventLogKey);
    if (Result != ERROR_SUCCESS)
    {
        return;
    }

    /* Retrieve the number of event logs enumerated as registry keys */
    Result = RegQueryInfoKeyW(hEventLogKey, NULL, NULL, NULL, &dwNumLogs, &dwMaxKeyLength,
                              NULL, NULL, NULL, NULL, NULL, NULL);
    if (Result != ERROR_SUCCESS)
    {
        goto Quit;
    }
    if (!dwNumLogs)
        goto Quit;

    /* Take the NULL terminator into account */
    ++dwMaxKeyLength;

    /* Allocate the temporary buffer */
    LogName = HeapAlloc(GetProcessHeap(), 0, dwMaxKeyLength * sizeof(WCHAR));
    if (!LogName)
        goto Quit;

    /* Enumerate and retrieve each event log name */
    for (dwIndex = 0; dwIndex < dwNumLogs; dwIndex++)
    {
        lpcName = dwMaxKeyLength;
        Result = RegEnumKeyExW(hEventLogKey, dwIndex, LogName, &lpcName, NULL, NULL, NULL, NULL);
        if (Result != ERROR_SUCCESS)
            continue;

        /* Take the NULL terminator into account */
        ++lpcName;

        /* Allocate a new event log entry */
        EventLog = AllocEventLog(lpComputerName, LogName, TRUE);
        if (EventLog == NULL)
            continue;

        /* Allocate a new event log filter entry for this event log */
        EventLogFilter = AllocEventLogFilter(// LogName,
                                             TRUE, TRUE, TRUE, TRUE, TRUE,
                                             NULL, NULL, NULL,
                                             1, &EventLog);
        if (EventLogFilter == NULL)
        {
            EventLog_Free(EventLog);
            continue;
        }

        /* Add the event log and the filter into their lists */
        InsertTailList(&EventLogList, &EventLog->ListEntry);
        InsertTailList(&EventLogFilterList, &EventLogFilter->ListEntry);

        EventLog->FileName = NULL;

        /* Retrieve and cache the event log file */
        Result = RegOpenKeyExW(hEventLogKey,
                               LogName,
                               0,
                               KEY_QUERY_VALUE,
                               &hLogKey);
        if (Result == ERROR_SUCCESS)
        {
            lpcName = 0;
            Result = RegQueryValueExW(hLogKey,
                                      L"File",
                                      NULL,
                                      &dwType,
                                      NULL,
                                      &lpcName);
            if ((Result != ERROR_SUCCESS) || (dwType != REG_EXPAND_SZ && dwType != REG_SZ))
            {
                // Windows' EventLog uses some kind of default value, we do not.
                EventLog->FileName = NULL;
            }
            else
            {
                lpcName = ROUND_DOWN(lpcName, sizeof(WCHAR));
                EventLog->FileName = HeapAlloc(GetProcessHeap(), 0, lpcName);
                if (EventLog->FileName)
                {
                    Result = RegQueryValueExW(hLogKey,
                                              L"File",
                                              NULL,
                                              &dwType,
                                              (LPBYTE)EventLog->FileName,
                                              &lpcName);
                    if (Result != ERROR_SUCCESS)
                    {
                        HeapFree(GetProcessHeap(), 0, EventLog->FileName);
                        EventLog->FileName = NULL;
                    }
                    else
                    {
                        EventLog->FileName[lpcName / sizeof(WCHAR) - 1] = UNICODE_NULL;
                    }
                }
            }

            RegCloseKey(hLogKey);
        }

        /* Get the display name for the event log */
        lpDisplayName = NULL;

        ZeroMemory(szModuleName, sizeof(szModuleName));
        if (GetDisplayNameFileAndID(LogName, szModuleName, &dwMessageID))
        {
            /* Retrieve the message string without appending extra newlines */
            lpDisplayName =
            GetMessageStringFromDll(szModuleName,
                                    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE |
                                    FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
                                    dwMessageID,
                                    0,
                                    NULL);
        }

        /*
         * Select the correct tree root node, whether the log is a System
         * or an Application log. Default to Application log otherwise.
         */
        hRootNode = htiAppLogs;
        for (lpcName = 0; lpcName < ARRAYSIZE(SystemLogs); ++lpcName)
        {
            /* Check whether the log name is part of the system logs */
            if (wcsicmp(LogName, SystemLogs[lpcName]) == 0)
            {
                hRootNode = htiSystemLogs;
                break;
            }
        }

        hItem = TreeViewAddItem(hwndTreeView, hRootNode,
                                (lpDisplayName ? lpDisplayName : LogName),
                                2, 3, (LPARAM)EventLogFilter);

        /* Try to get the default event log: "Application" */
        if ((hItemDefault == NULL) && (wcsicmp(LogName, SystemLogs[0]) == 0))
        {
            hItemDefault = hItem;
        }

        /* Free the buffer allocated by FormatMessage */
        if (lpDisplayName)
            LocalFree(lpDisplayName);
    }

    HeapFree(GetProcessHeap(), 0, LogName);

Quit:
    RegCloseKey(hEventLogKey);

    /* Select the default event log */
    if (hItemDefault)
    {
        // TreeView_Expand(hwndTreeView, hRootNode, TVE_EXPAND);
        TreeView_SelectItem(hwndTreeView, hItemDefault);
        TreeView_EnsureVisible(hwndTreeView, hItemDefault);
    }
    InvalidateRect(hwndTreeView, NULL, FALSE);
    SetFocus(hwndTreeView);

    return;
}

VOID
FreeLogList(VOID)
{
    PLIST_ENTRY Entry;
    PEVENTLOG EventLog;

    while (!IsListEmpty(&EventLogList))
    {
        Entry = RemoveHeadList(&EventLogList);
        EventLog = (PEVENTLOG)CONTAINING_RECORD(Entry, EVENTLOG, ListEntry);
        EventLog_Free(EventLog);
    }

    return;
}

VOID
FreeLogFilterList(VOID)
{
    PLIST_ENTRY Entry;
    PEVENTLOGFILTER EventLogFilter;

    while (!IsListEmpty(&EventLogFilterList))
    {
        Entry = RemoveHeadList(&EventLogFilterList);
        EventLogFilter = (PEVENTLOGFILTER)CONTAINING_RECORD(Entry, EVENTLOGFILTER, ListEntry);
        EventLogFilter_Free(EventLogFilter);
    }

    ActiveFilter = NULL;

    return;
}

BOOL
InitInstance(HINSTANCE hInstance)
{
    RECT rcClient, rs;
    LONG StatusHeight;
    HIMAGELIST hSmall;
    LVCOLUMNW lvc = {0};
    WCHAR szTemp[256];

    /* Create the main window */
    rs = Settings.wpPos.rcNormalPosition;
    hwndMainWindow = CreateWindowW(EVENTVWR_WNDCLASS,
                                   szTitle,
                                   WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
                                   rs.left, rs.top,
                                   (rs.right  != CW_USEDEFAULT && rs.left != CW_USEDEFAULT) ? rs.right - rs.left : CW_USEDEFAULT,
                                   (rs.bottom != CW_USEDEFAULT && rs.top  != CW_USEDEFAULT) ? rs.bottom - rs.top : CW_USEDEFAULT,
                                   NULL,
                                   NULL,
                                   hInstance,
                                   NULL);
    if (!hwndMainWindow)
        return FALSE;

    /* Create the status bar */
    hwndStatus = CreateWindowExW(0,                                  // no extended styles
                                 STATUSCLASSNAMEW,                   // status bar
                                 L"",                                // no text
                                 WS_CHILD | WS_VISIBLE | CCS_BOTTOM | SBARS_SIZEGRIP, // styles
                                 0, 0, 0, 0,                         // x, y, cx, cy
                                 hwndMainWindow,                     // parent window
                                 (HMENU)100,                         // window ID
                                 hInstance,                          // instance
                                 NULL);                              // window data

    GetClientRect(hwndMainWindow, &rcClient);
    GetWindowRect(hwndStatus, &rs);
    StatusHeight = rs.bottom - rs.top;

    /* Create a progress bar in the status bar (hidden by default) */
    StatusBar_GetItemRect(hwndStatus, 0, &rs);
    hwndStatusProgress = CreateWindowExW(0,                          // no extended styles
                                         PROGRESS_CLASSW,            // status bar
                                         NULL,                       // no text
                                         WS_CHILD | PBS_SMOOTH,      // styles
                                         rs.left, rs.top,            // x, y
                                         rs.right - rs.left, rs.bottom - rs.top, // cx, cy
                                         hwndStatus,                 // parent window
                                         NULL,                       // window ID
                                         hInstance,                  // instance
                                         NULL);                      // window data
    /* Remove its static edge */
    SetWindowLongPtrW(hwndStatusProgress, GWL_EXSTYLE,
                      GetWindowLongPtrW(hwndStatusProgress, GWL_EXSTYLE) & ~WS_EX_STATICEDGE);
    ProgressBar_SetStep(hwndStatusProgress, 1);

    /* Initialize the splitter default positions */
    nVSplitPos = Settings.nVSplitPos;
    nHSplitPos = Settings.nHSplitPos;

    /* Create the TreeView */
    hwndTreeView = CreateWindowExW(WS_EX_CLIENTEDGE,
                                   WC_TREEVIEWW,
                                   NULL,
                                   // WS_CHILD | WS_VISIBLE | TVS_HASLINES | TVS_SHOWSELALWAYS,
                                   WS_CHILD | WS_VISIBLE | /* WS_TABSTOP | */ TVS_HASLINES | TVS_HASBUTTONS | TVS_LINESATROOT | TVS_EDITLABELS | TVS_SHOWSELALWAYS,
                                   0, 0,
                                   nVSplitPos - SPLIT_WIDTH/2,
                                   (rcClient.bottom - rcClient.top) - StatusHeight,
                                   hwndMainWindow,
                                   NULL,
                                   hInstance,
                                   NULL);

    /* Create the ImageList */
    hSmall = ImageList_Create(GetSystemMetrics(SM_CXSMICON),
                              GetSystemMetrics(SM_CYSMICON),
                              ILC_COLOR32 | ILC_MASK, // ILC_COLOR24
                              1, 1);

    /* Add event type icons to the ImageList: closed/opened folder, event log (normal/viewed) */
    ImageList_AddIcon(hSmall, LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_CLOSED_CATEGORY)));
    ImageList_AddIcon(hSmall, LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_OPENED_CATEGORY)));
    ImageList_AddIcon(hSmall, LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_EVENTLOG)));
    ImageList_AddIcon(hSmall, LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_EVENTVWR)));

    /* Assign the ImageList to the Tree View */
    TreeView_SetImageList(hwndTreeView, hSmall, TVSIL_NORMAL);

    /* Add the event logs nodes */
    // "System Logs"
    LoadStringW(hInstance, IDS_EVENTLOG_SYSTEM, szTemp, ARRAYSIZE(szTemp));
    htiSystemLogs = TreeViewAddItem(hwndTreeView, NULL, szTemp, 0, 1, (LPARAM)NULL);
    // "Application Logs"
    LoadStringW(hInstance, IDS_EVENTLOG_APP, szTemp, ARRAYSIZE(szTemp));
    htiAppLogs = TreeViewAddItem(hwndTreeView, NULL, szTemp, 0, 1, (LPARAM)NULL);
    // "User Logs"
    LoadStringW(hInstance, IDS_EVENTLOG_USER, szTemp, ARRAYSIZE(szTemp));
    htiUserLogs = TreeViewAddItem(hwndTreeView, NULL, szTemp, 0, 1, (LPARAM)NULL);

    /* Create the Event details pane (optional) */
    hwndEventDetails = CreateEventDetailsCtrl(hInst, hwndMainWindow, (LPARAM)NULL);
    if (hwndEventDetails)
    {
    SetWindowLongPtrW(hwndEventDetails, GWL_EXSTYLE,
                      GetWindowLongPtrW(hwndEventDetails, GWL_EXSTYLE) | WS_EX_CLIENTEDGE);
    SetWindowPos(hwndEventDetails, NULL,
                 nVSplitPos + SPLIT_WIDTH/2,
                 nHSplitPos + SPLIT_WIDTH/2,
                 (rcClient.right - rcClient.left) - nVSplitPos - SPLIT_WIDTH/2,
                 (rcClient.bottom - rcClient.top) - nHSplitPos - SPLIT_WIDTH/2 - StatusHeight,
                 SWP_NOZORDER | SWP_NOACTIVATE | (Settings.bShowDetailsPane ? SWP_SHOWWINDOW : SWP_HIDEWINDOW));
    }

    /* Create the ListView */
    hwndListView = CreateWindowExW(WS_EX_CLIENTEDGE,
                                   WC_LISTVIEWW,
                                   NULL,
                                   WS_CHILD | WS_VISIBLE | LVS_SHOWSELALWAYS | LVS_REPORT,
                                   nVSplitPos + SPLIT_WIDTH/2,
                                   0,
                                   (rcClient.right - rcClient.left) - nVSplitPos - SPLIT_WIDTH/2,
                                   hwndEventDetails && Settings.bShowDetailsPane
                                       ? nHSplitPos - SPLIT_WIDTH/2
                                       : (rcClient.bottom - rcClient.top) - StatusHeight,
                                   hwndMainWindow,
                                   NULL,
                                   hInstance,
                                   NULL);

    /* Add the extended ListView styles */
    ListView_SetExtendedListViewStyle(hwndListView, LVS_EX_HEADERDRAGDROP | LVS_EX_FULLROWSELECT | LVS_EX_LABELTIP | (Settings.bShowGrid ? LVS_EX_GRIDLINES : 0));

    /* Create the ImageList */
    hSmall = ImageList_Create(GetSystemMetrics(SM_CXSMICON),
                              GetSystemMetrics(SM_CYSMICON),
                              ILC_COLOR32 | ILC_MASK, // ILC_COLOR24
                              1, 1);

    /* Add event type icons to the ImageList */
    ImageList_AddIcon(hSmall, LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_INFORMATIONICON)));
    ImageList_AddIcon(hSmall, LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_WARNINGICON)));
    ImageList_AddIcon(hSmall, LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_ERRORICON)));
    ImageList_AddIcon(hSmall, LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_AUDITSUCCESSICON)));
    ImageList_AddIcon(hSmall, LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_AUDITFAILUREICON)));

    /* Assign the ImageList to the List View */
    ListView_SetImageList(hwndListView, hSmall, LVSIL_SMALL);

    /* Now set up the listview with its columns */
    lvc.mask = LVCF_TEXT | LVCF_WIDTH;
    lvc.cx = 90;
    LoadStringW(hInstance,
                IDS_COLUMNTYPE,
                szTemp,
                ARRAYSIZE(szTemp));
    lvc.pszText = szTemp;
    ListView_InsertColumn(hwndListView, 0, &lvc);

    lvc.cx = 70;
    LoadStringW(hInstance,
                IDS_COLUMNDATE,
                szTemp,
                ARRAYSIZE(szTemp));
    lvc.pszText = szTemp;
    ListView_InsertColumn(hwndListView, 1, &lvc);

    lvc.cx = 70;
    LoadStringW(hInstance,
                IDS_COLUMNTIME,
                szTemp,
                ARRAYSIZE(szTemp));
    lvc.pszText = szTemp;
    ListView_InsertColumn(hwndListView, 2, &lvc);

    lvc.cx = 150;
    LoadStringW(hInstance,
                IDS_COLUMNSOURCE,
                szTemp,
                ARRAYSIZE(szTemp));
    lvc.pszText = szTemp;
    ListView_InsertColumn(hwndListView, 3, &lvc);

    lvc.cx = 100;
    LoadStringW(hInstance,
                IDS_COLUMNCATEGORY,
                szTemp,
                ARRAYSIZE(szTemp));
    lvc.pszText = szTemp;
    ListView_InsertColumn(hwndListView, 4, &lvc);

    lvc.cx = 60;
    LoadStringW(hInstance,
                IDS_COLUMNEVENT,
                szTemp,
                ARRAYSIZE(szTemp));
    lvc.pszText = szTemp;
    ListView_InsertColumn(hwndListView, 5, &lvc);

    lvc.cx = 120;
    LoadStringW(hInstance,
                IDS_COLUMNUSER,
                szTemp,
                ARRAYSIZE(szTemp));
    lvc.pszText = szTemp;
    ListView_InsertColumn(hwndListView, 6, &lvc);

    lvc.cx = 100;
    LoadStringW(hInstance,
                IDS_COLUMNCOMPUTER,
                szTemp,
                ARRAYSIZE(szTemp));
    lvc.pszText = szTemp;
    ListView_InsertColumn(hwndListView, 7, &lvc);

    /* Initialize the save Dialog */
    ZeroMemory(&sfn, sizeof(sfn));
    ZeroMemory(szSaveFilter, sizeof(szSaveFilter));

    LoadStringW(hInst, IDS_SAVE_FILTER, szSaveFilter, ARRAYSIZE(szSaveFilter));

    sfn.lStructSize     = sizeof(sfn);
    sfn.hwndOwner       = hwndMainWindow;
    sfn.hInstance       = hInstance;
    sfn.lpstrFilter     = szSaveFilter;
    sfn.lpstrInitialDir = NULL;
    sfn.Flags           = OFN_HIDEREADONLY | OFN_SHAREAWARE;
    sfn.lpstrDefExt     = NULL;

    ShowWindow(hwndMainWindow, Settings.wpPos.showCmd);
    UpdateWindow(hwndMainWindow);

    return TRUE;
}

VOID ResizeWnd(INT cx, INT cy)
{
    RECT rs;
    LONG StatusHeight;
    LONG_PTR dwExStyle;
    HDWP hdwp;

    /* Resize the status bar -- now done in WM_SIZE */
    // SendMessageW(hwndStatus, WM_SIZE, 0, 0);
    GetWindowRect(hwndStatus, &rs);
    StatusHeight = rs.bottom - rs.top;

    /*
     * Move the progress bar -- Take into account for extra size due to the static edge
     * (AdjustWindowRectEx() does not seem to work for the progress bar).
     */
    StatusBar_GetItemRect(hwndStatus, 0, &rs);
    dwExStyle = GetWindowLongPtrW(hwndStatusProgress, GWL_EXSTYLE);
    SetWindowLongPtrW(hwndStatusProgress, GWL_EXSTYLE, dwExStyle | WS_EX_STATICEDGE);
    MoveWindow(hwndStatusProgress,
               rs.left, rs.top, rs.right - rs.left, rs.bottom - rs.top,
               IsWindowVisible(hwndStatusProgress) ? TRUE : FALSE);
    SetWindowLongPtrW(hwndStatusProgress, GWL_EXSTYLE, dwExStyle);

    /*
     * TODO: Adjust the splitter positions:
     * - Vertical splitter (1)  : fixed position from the left window side.
     * - Horizontal splitter (2): fixed position from the bottom window side.
     */
    nVSplitPos = min(max(nVSplitPos, SPLIT_WIDTH/2), cx - SPLIT_WIDTH/2); // OK
    nHSplitPos = min(max(nHSplitPos, SPLIT_WIDTH/2), cy - SPLIT_WIDTH/2 - StatusHeight); // FIXME!

    hdwp = BeginDeferWindowPos(3);

    if (hdwp)
        hdwp = DeferWindowPos(hdwp,
                              hwndTreeView,
                              HWND_TOP,
                              0, 0,
                              nVSplitPos - SPLIT_WIDTH/2,
                              cy - StatusHeight,
                              SWP_NOZORDER | SWP_NOACTIVATE);

    if (hdwp)
        hdwp = DeferWindowPos(hdwp,
                              hwndListView,
                              HWND_TOP,
                              nVSplitPos + SPLIT_WIDTH/2, 0,
                              cx - nVSplitPos - SPLIT_WIDTH/2,
                              hwndEventDetails && Settings.bShowDetailsPane
                                  ? nHSplitPos - SPLIT_WIDTH/2
                                  : cy - StatusHeight,
                              SWP_NOZORDER | SWP_NOACTIVATE);

    if (hwndEventDetails && Settings.bShowDetailsPane && hdwp)
        hdwp = DeferWindowPos(hdwp,
                              hwndEventDetails,
                              HWND_TOP,
                              nVSplitPos + SPLIT_WIDTH/2,
                              nHSplitPos + SPLIT_WIDTH/2,
                              cx - nVSplitPos - SPLIT_WIDTH/2,
                              cy - nHSplitPos - SPLIT_WIDTH/2 - StatusHeight,
                              SWP_NOZORDER | SWP_NOACTIVATE);

    if (hdwp)
        EndDeferWindowPos(hdwp);
}


LRESULT CALLBACK
WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    RECT rect;

    switch (uMsg)
    {
        case WM_CREATE:
            hMainMenu = GetMenu(hWnd);
            break;

        case WM_DESTROY:
        {
            GetWindowPlacement(hwndMainWindow, &Settings.wpPos);
            PostQuitMessage(0);
            break;
        }

        case WM_NOTIFY:
        {
            LPNMHDR hdr = (LPNMHDR)lParam;

            if (hdr->hwndFrom == hwndListView)
            {
                switch (hdr->code)
                {
                    case LVN_ITEMCHANGED:
                    {
                        LPNMLISTVIEW pnmv = (LPNMLISTVIEW)lParam;

                        if ( (pnmv->uChanged  & LVIF_STATE) && /* The state has changed */
                             (pnmv->uNewState & LVIS_SELECTED) /* The item has been (de)selected */ )
                        {
                            if (hwndEventDetails)
                                SendMessageW(hwndEventDetails, EVT_DISPLAY, 0, 0);
                        }
                        break;
                    }

                    case NM_DBLCLK:
                    case NM_RETURN:
                        SendMessageW(hWnd, WM_COMMAND, IDM_EVENT_DETAILS, 0);
                        break;
                }
            }
            else if (hdr->hwndFrom == hwndTreeView)
            {
                switch (hdr->code)
                {
                    case TVN_BEGINLABELEDIT:
                    {
                        HTREEITEM hItem = ((LPNMTVDISPINFO)lParam)->item.hItem;

                        /* Disable label editing for root nodes */
                        return ((hItem == htiSystemLogs) ||
                                (hItem == htiAppLogs)    ||
                                (hItem == htiUserLogs));
                    }

                    case TVN_ENDLABELEDIT:
                    {
                        TVITEMW item = ((LPNMTVDISPINFO)lParam)->item;
                        HTREEITEM hItem = item.hItem;

                        /* Disable label editing for root nodes */
                        if ((hItem == htiSystemLogs) ||
                            (hItem == htiAppLogs)    ||
                            (hItem == htiUserLogs))
                        {
                            return FALSE;
                        }

                        if (item.pszText)
                        {
                            LPWSTR pszText = item.pszText;

                            /* Trim leading whitespace */
                            while (*pszText && iswspace(*pszText))
                                ++pszText;

                            if (!*pszText)
                                return FALSE;

                            return TRUE;
                        }
                        else
                        {
                            return FALSE;
                        }
                    }

                    case TVN_SELCHANGED:
                    {
                        PEVENTLOGFILTER EventLogFilter =
                            (PEVENTLOGFILTER)((LPNMTREEVIEW)lParam)->itemNew.lParam;

                        // FIXME: It might be nice to reference here the filter,
                        // so that we don't have to reference/dereference it many times
                        // in the other functions???

                        // FIXME: This is a hack!!
                        if (hwndEventDetails && EventLogFilter)
                        {
                            SendMessageW(hwndEventDetails, EVT_SETFILTER, 0, (LPARAM)EventLogFilter);
                        }

                        if (EventLogFilter)
                        {
                            /*
                             * If we have selected a filter, enable the menu commands;
                             * they will possibly be updated after events enumeration.
                             */
                            EnableMenuItem(hMainMenu, IDM_SAVE_EVENTLOG, MF_BYCOMMAND | MF_ENABLED);
                            EnableMenuItem(hMainMenu, IDM_CLOSE_EVENTLOG, MF_BYCOMMAND | MF_ENABLED);
                            EnableMenuItem(hMainMenu, IDM_CLEAR_EVENTS, MF_BYCOMMAND | MF_ENABLED);
                            EnableMenuItem(hMainMenu, IDM_RENAME_EVENTLOG, MF_BYCOMMAND | MF_ENABLED);
                            EnableMenuItem(hMainMenu, IDM_EVENTLOG_SETTINGS, MF_BYCOMMAND | MF_ENABLED);
                        }
                        else
                        {
                            EnableMenuItem(hMainMenu, IDM_SAVE_EVENTLOG, MF_BYCOMMAND | MF_GRAYED);
                            EnableMenuItem(hMainMenu, IDM_CLOSE_EVENTLOG, MF_BYCOMMAND | MF_GRAYED);
                            EnableMenuItem(hMainMenu, IDM_CLEAR_EVENTS, MF_BYCOMMAND | MF_GRAYED);
                            EnableMenuItem(hMainMenu, IDM_RENAME_EVENTLOG, MF_BYCOMMAND | MF_GRAYED);
                            EnableMenuItem(hMainMenu, IDM_EVENTLOG_SETTINGS, MF_BYCOMMAND | MF_GRAYED);
                        }

                        /*
                         * The enumeration thread that is triggered by EnumEvents
                         * will set a new value for the 'ActiveFilter'.
                         */
                        if (EventLogFilter)
                            EnumEvents(EventLogFilter);

                        break;
                    }
                }
            }
            break;
        }

        case WM_COMMAND:
        {
            /* Parse the menu selections */
            switch (LOWORD(wParam))
            {
                case IDM_OPEN_EVENTLOG:
                    OpenUserEventLog();
                    break;

                case IDM_SAVE_EVENTLOG:
                    SaveEventLog(GetSelectedFilter(NULL));
                    break;

                case IDM_CLOSE_EVENTLOG:
                {
                    HTREEITEM hti;
                    PEVENTLOGFILTER EventLogFilter = GetSelectedFilter(&hti);
                    CloseUserEventLog(EventLogFilter, hti);
                    break;
                }

                case IDM_CLEAR_EVENTS:
                {
                    PEVENTLOGFILTER EventLogFilter = GetSelectedFilter(NULL);
                    if (EventLogFilter && ClearEvents(EventLogFilter))
                        Refresh(EventLogFilter);
                    break;
                }

                case IDM_RENAME_EVENTLOG:
                    if (GetFocus() == hwndTreeView)
                        TreeView_EditLabel(hwndTreeView, TreeView_GetSelection(hwndTreeView));
                    break;

                case IDM_EVENTLOG_SETTINGS:
                {
                    PEVENTLOGFILTER EventLogFilter = GetSelectedFilter(NULL);
                    // TODO: Check the returned value?
                    if (EventLogFilter)
                        EventLogProperties(hInst, hWnd, EventLogFilter);
                    break;
                }

                case IDM_LIST_NEWEST:
                {
                    CheckMenuRadioItem(hMainMenu, IDM_LIST_NEWEST, IDM_LIST_OLDEST, IDM_LIST_NEWEST, MF_BYCOMMAND);
                    if (!Settings.bNewestEventsFirst)
                    {
                        Settings.bNewestEventsFirst = TRUE;
                        Refresh(GetSelectedFilter(NULL));
                    }
                    break;
                }

                case IDM_LIST_OLDEST:
                {
                    CheckMenuRadioItem(hMainMenu, IDM_LIST_NEWEST, IDM_LIST_OLDEST, IDM_LIST_OLDEST, MF_BYCOMMAND);
                    if (Settings.bNewestEventsFirst)
                    {
                        Settings.bNewestEventsFirst = FALSE;
                        Refresh(GetSelectedFilter(NULL));
                    }
                    break;
                }

                case IDM_EVENT_DETAILS:
                {
                    // LPNMITEMACTIVATE lpnmitem = (LPNMITEMACTIVATE)lParam;
                    PEVENTLOGFILTER EventLogFilter = GetSelectedFilter(NULL);
                    if (/*lpnmitem->iItem != -1 &&*/ EventLogFilter)
                    {
                        EventLogFilter_AddRef(EventLogFilter);
                        DialogBoxParamW(hInst,
                                        MAKEINTRESOURCEW(IDD_EVENTDETAILS_DLG),
                                        hWnd,
                                        EventDetails,
                                        (LPARAM)EventLogFilter);
                        EventLogFilter_Release(EventLogFilter);
                    }
                    break;
                }

                case IDM_REFRESH:
                    Refresh(GetSelectedFilter(NULL));
                    break;

                case IDM_EVENT_DETAILS_VIEW:
                {
                    Settings.bShowDetailsPane = !Settings.bShowDetailsPane;
                    CheckMenuItem(hMainMenu, IDM_EVENT_DETAILS_VIEW,
                                  MF_BYCOMMAND | (Settings.bShowDetailsPane ? MF_CHECKED : MF_UNCHECKED));

                    GetClientRect(hWnd, &rect);
                    if (Settings.bShowDetailsPane)
                    {
                        ResizeWnd(rect.right - rect.left, rect.bottom - rect.top);
                        ShowWindow(hwndEventDetails, SW_SHOW);
                    }
                    else
                    {
                        ShowWindow(hwndEventDetails, SW_HIDE);
                        ResizeWnd(rect.right - rect.left, rect.bottom - rect.top);
                    }

                    break;
                }

                case IDM_LIST_GRID_LINES:
                {
                    Settings.bShowGrid = !Settings.bShowGrid;
                    CheckMenuItem(hMainMenu, IDM_LIST_GRID_LINES,
                                  MF_BYCOMMAND | (Settings.bShowGrid ? MF_CHECKED : MF_UNCHECKED));

                    ListView_SetExtendedListViewStyleEx(hwndListView, LVS_EX_GRIDLINES, (Settings.bShowGrid ? LVS_EX_GRIDLINES : 0));
                    break;
                }

                case IDM_SAVE_SETTINGS:
                {
                    Settings.bSaveSettings = !Settings.bSaveSettings;
                    CheckMenuItem(hMainMenu, IDM_SAVE_SETTINGS,
                                  MF_BYCOMMAND | (Settings.bSaveSettings ? MF_CHECKED : MF_UNCHECKED));
                    break;
                }

                case IDM_ABOUT:
                {
                    HICON hIcon;
                    WCHAR szCopyright[MAX_LOADSTRING];

                    hIcon = LoadIconW(hInst, MAKEINTRESOURCEW(IDI_EVENTVWR));
                    LoadStringW(hInst, IDS_COPYRIGHT, szCopyright, ARRAYSIZE(szCopyright));
                    ShellAboutW(hWnd, szTitle, szCopyright, hIcon);
                    DeleteObject(hIcon);
                    break;
                }

                case IDM_HELP:
                    MessageBoxW(hwndMainWindow,
                                L"Help not implemented yet!",
                                L"Event Log",
                                MB_OK | MB_ICONINFORMATION);
                                break;

                case IDM_EXIT:
                    DestroyWindow(hWnd);
                    break;

                default:
                    return DefWindowProcW(hWnd, uMsg, wParam, lParam);
            }
            break;
        }

        case WM_INITMENU:
        {
            if ((HMENU)wParam != hMainMenu)
                break;

            CheckMenuRadioItem(hMainMenu, IDM_LIST_NEWEST, IDM_LIST_OLDEST,
                               Settings.bNewestEventsFirst ? IDM_LIST_NEWEST : IDM_LIST_OLDEST,
                               MF_BYCOMMAND);

            if (!hwndEventDetails)
            {
                EnableMenuItem(hMainMenu, IDM_EVENT_DETAILS_VIEW,
                               MF_BYCOMMAND | MF_GRAYED);
            }
            CheckMenuItem(hMainMenu, IDM_EVENT_DETAILS_VIEW,
                          MF_BYCOMMAND | (Settings.bShowDetailsPane ? MF_CHECKED : MF_UNCHECKED));

            CheckMenuItem(hMainMenu, IDM_LIST_GRID_LINES,
                          MF_BYCOMMAND | (Settings.bShowGrid ? MF_CHECKED : MF_UNCHECKED));

            CheckMenuItem(hMainMenu, IDM_SAVE_SETTINGS,
                          MF_BYCOMMAND | (Settings.bSaveSettings ? MF_CHECKED : MF_UNCHECKED));

            break;
        }

#if 0
        case WM_INITMENUPOPUP:
            lParam = lParam;
            break;

        case WM_CONTEXTMENU:
            lParam = lParam;
            break;
#endif

        case WM_SETCURSOR:
        {
            POINT pt;

            if (LOWORD(lParam) != HTCLIENT)
                goto Default;

            GetCursorPos(&pt);
            ScreenToClient(hWnd, &pt);

            /* Set the cursor for the vertical splitter */
            if (pt.x >= nVSplitPos - SPLIT_WIDTH/2 && pt.x < nVSplitPos + SPLIT_WIDTH/2 + 1)
            {
                RECT rs;
                GetClientRect(hWnd, &rect);
                GetWindowRect(hwndStatus, &rs);
                if (pt.y >= rect.top && pt.y < rect.bottom - (rs.bottom - rs.top))
                {
                    SetCursor(LoadCursorW(NULL, IDC_SIZEWE));
                    return TRUE;
                }
            }
            else
            /* Set the cursor for the horizontal splitter, if the Event details pane is displayed */
            if (hwndEventDetails && Settings.bShowDetailsPane &&
                (pt.y >= nHSplitPos - SPLIT_WIDTH/2 && pt.y < nHSplitPos + SPLIT_WIDTH/2 + 1))
            {
                // RECT rs;
                GetClientRect(hWnd, &rect);
                // GetWindowRect(hwndStatus, &rs);
                if (pt.x >= nVSplitPos + SPLIT_WIDTH/2 + 1 /* rect.left + (rs.bottom - rs.top) */ &&
                    pt.x < rect.right)
                {
                    SetCursor(LoadCursorW(NULL, IDC_SIZENS));
                    return TRUE;
                }
            }
            goto Default;
        }

        case WM_LBUTTONDOWN:
        {
            INT x = GET_X_LPARAM(lParam);
            INT y = GET_Y_LPARAM(lParam);

            /* Reset the splitter state */
            bSplit = 0;

            /* Capture the cursor for the vertical splitter */
            if (x >= nVSplitPos - SPLIT_WIDTH/2 && x < nVSplitPos + SPLIT_WIDTH/2 + 1)
            {
                bSplit = 1;
                SetCapture(hWnd);
            }
            else
            /* Capture the cursor for the horizontal splitter, if the Event details pane is displayed */
            if (hwndEventDetails && Settings.bShowDetailsPane &&
                (y >= nHSplitPos - SPLIT_WIDTH/2 && y < nHSplitPos + SPLIT_WIDTH/2 + 1))
            {
                bSplit = 2;
                SetCapture(hWnd);
            }
            break;
        }

        case WM_LBUTTONUP:
        case WM_RBUTTONDOWN:
        {
            if (GetCapture() != hWnd)
                break;

            /* Adjust the correct splitter position */
            if (bSplit == 1)
                nVSplitPos = GET_X_LPARAM(lParam);
            else if (bSplit == 2)
                nHSplitPos = GET_Y_LPARAM(lParam);

            /* If we are splitting, resize the windows */
            if (bSplit != 0)
            {
                GetClientRect(hWnd, &rect);
                ResizeWnd(rect.right - rect.left, rect.bottom - rect.top);
            }

            /* Reset the splitter state */
            bSplit = 0;

            ReleaseCapture();
            break;
        }

        case WM_MOUSEMOVE:
        {
            if (GetCapture() != hWnd)
                break;

            /* Move the correct splitter */
            if (bSplit == 1)
            {
                INT x = GET_X_LPARAM(lParam);

                GetClientRect(hWnd, &rect);

                x = min(max(x, SPLIT_WIDTH/2), rect.right - rect.left - SPLIT_WIDTH/2);
                if (nVSplitPos != x)
                {
                    nVSplitPos = x;
                    ResizeWnd(rect.right - rect.left, rect.bottom - rect.top);
                }
            }
            else if (bSplit == 2)
            {
                RECT rs;
                INT y = GET_Y_LPARAM(lParam);

                GetClientRect(hWnd, &rect);
                GetWindowRect(hwndStatus, &rs);

                y = min(max(y, SPLIT_WIDTH/2), rect.bottom - rect.top - SPLIT_WIDTH/2 - (rs.bottom - rs.top));
                if (nHSplitPos != y)
                {
                    nHSplitPos = y;
                    ResizeWnd(rect.right - rect.left, rect.bottom - rect.top);
                }
            }
            break;
        }

        case WM_SIZE:
        {
            if (wParam != SIZE_MINIMIZED)
            {
                SendMessageW(hwndStatus, WM_SIZE, 0, 0);
                ResizeWnd(LOWORD(lParam), HIWORD(lParam));
                break;
            }
            /* Fall through the default case */
        }

        default: Default:
            return DefWindowProcW(hWnd, uMsg, wParam, lParam);
    }

    return 0;
}


static
VOID
InitPropertiesDlg(HWND hDlg, PEVENTLOG EventLog)
{
    LPWSTR lpLogName = EventLog->LogName;

    DWORD Result, dwType;
    DWORD dwMaxSize = 0, dwRetention = 0;
    BOOL Success;
    WIN32_FIND_DATAW FileInfo; // WIN32_FILE_ATTRIBUTE_DATA
    ULARGE_INTEGER FileSize;
    WCHAR wszBuf[MAX_PATH];
    WCHAR szTemp[MAX_LOADSTRING];
    LPWSTR FileName;

    HKEY hLogKey;
    WCHAR *KeyPath;
    DWORD cbData;
    SIZE_T cbKeyPath;

    if (EventLog->Permanent)
    {

    cbKeyPath = (wcslen(EVENTLOG_BASE_KEY) + wcslen(lpLogName) + 1) * sizeof(WCHAR);
    KeyPath = HeapAlloc(GetProcessHeap(), 0, cbKeyPath);
    if (!KeyPath)
    {
        ShowWin32Error(ERROR_NOT_ENOUGH_MEMORY);
        goto Quit;
    }

    StringCbCopyW(KeyPath, cbKeyPath, EVENTLOG_BASE_KEY);
    StringCbCatW(KeyPath, cbKeyPath, lpLogName);

    Result = RegOpenKeyExW(hkMachine, KeyPath, 0, KEY_QUERY_VALUE, &hLogKey);
    HeapFree(GetProcessHeap(), 0, KeyPath);
    if (Result != ERROR_SUCCESS)
    {
        ShowWin32Error(Result);
        goto Quit;
    }


    cbData = sizeof(dwMaxSize);
    Result = RegQueryValueExW(hLogKey,
                              L"MaxSize",
                              NULL,
                              &dwType,
                              (LPBYTE)&dwMaxSize,
                              &cbData);
    if ((Result != ERROR_SUCCESS) || (dwType != REG_DWORD))
    {
        // dwMaxSize = 512 * 1024; /* 512 kBytes */
        /* Workstation: 512 KB; Server: 16384 KB */
        dwMaxSize = 16384 * 1024;
    }
    /* Convert in KB */
    dwMaxSize /= 1024;

    cbData = sizeof(dwRetention);
    Result = RegQueryValueExW(hLogKey,
                              L"Retention",
                              NULL,
                              &dwType,
                              (LPBYTE)&dwRetention,
                              &cbData);
    if ((Result != ERROR_SUCCESS) || (dwType != REG_DWORD))
    {
        /* By default, it is 604800 (secs) == 7 days. On Server, the retention is zeroed out. */
        dwRetention = 0;
    }
    /* Convert in days, rounded up */    
    if (dwRetention != INFINITE)
        dwRetention = (dwRetention + 24*3600 - 1) / (24*3600);

    RegCloseKey(hLogKey);

    }

Quit:

    SetDlgItemTextW(hDlg, IDC_DISPLAYNAME, lpLogName); // FIXME!
    SetDlgItemTextW(hDlg, IDC_LOGNAME, lpLogName);

    FileName = EventLog->FileName;
    if (FileName && *FileName)
    {
        /* Expand the file name. If the log file is on a remote computer, retrieve the network share form of the file name. */
        GetExpandedFilePathName(EventLog->ComputerName, FileName, wszBuf, ARRAYSIZE(wszBuf));
        FileName = wszBuf;
    }
    else
    {
        FileName = L"";
    }
    SetDlgItemTextW(hDlg, IDC_LOGFILE, FileName);

    if (FileName && *FileName)
    {
        /*
         * The general problem here (and in the shell as well) is that
         * GetFileAttributesEx fails for files that are opened without
         * shared access. To retrieve file information for those we need
         * to use something else: FindFirstFile, on the full file name.
         */
        Success = GetFileAttributesExW(FileName,
                                       GetFileExInfoStandard,
                                       (LPWIN32_FILE_ATTRIBUTE_DATA)&FileInfo);
        if (!Success)
        {
            HANDLE hFind = FindFirstFileW(FileName, &FileInfo);
            Success = (hFind != INVALID_HANDLE_VALUE);
            if (Success)
                FindClose(hFind);
        }
    }
    else
    {
        Success = FALSE;
    }

    /* Starting there, FileName becomes invalid because we are reusing wszBuf */

    if (Success)
    {
        FileSize.u.LowPart = FileInfo.nFileSizeLow;
        FileSize.u.HighPart = FileInfo.nFileSizeHigh;
        if (FormatFileSizeWithBytes(&FileSize, wszBuf, ARRAYSIZE(wszBuf)))
            SetDlgItemTextW(hDlg, IDC_SIZE_LABEL, wszBuf);

        LoadStringW(hInst, IDS_NOT_AVAILABLE, szTemp, ARRAYSIZE(szTemp));

        if (GetFileTimeString(&FileInfo.ftCreationTime, wszBuf, ARRAYSIZE(wszBuf)))
            SetDlgItemTextW(hDlg, IDC_CREATED_LABEL, wszBuf);
        else
            SetDlgItemTextW(hDlg, IDC_CREATED_LABEL, szTemp);

        if (GetFileTimeString(&FileInfo.ftLastWriteTime, wszBuf, ARRAYSIZE(wszBuf)))
            SetDlgItemTextW(hDlg, IDC_MODIFIED_LABEL, wszBuf);
        else
            SetDlgItemTextW(hDlg, IDC_MODIFIED_LABEL, szTemp);

        if (GetFileTimeString(&FileInfo.ftLastAccessTime, wszBuf, ARRAYSIZE(wszBuf)))
            SetDlgItemTextW(hDlg, IDC_ACCESSED_LABEL, wszBuf);
        else
            SetDlgItemTextW(hDlg, IDC_MODIFIED_LABEL, szTemp);
    }
    else
    {
        LoadStringW(hInst, IDS_NOT_AVAILABLE, szTemp, ARRAYSIZE(szTemp));

        SetDlgItemTextW(hDlg, IDC_SIZE_LABEL, szTemp);
        SetDlgItemTextW(hDlg, IDC_CREATED_LABEL, szTemp);
        SetDlgItemTextW(hDlg, IDC_MODIFIED_LABEL, szTemp);
        SetDlgItemTextW(hDlg, IDC_ACCESSED_LABEL, szTemp);
    }

    if (EventLog->Permanent)
    {
        SendDlgItemMessageW(hDlg, IDC_UPDOWN_MAXLOGSIZE, UDM_SETRANGE32, (WPARAM)1, (LPARAM)0x3FFFC0);
        SendDlgItemMessageW(hDlg, IDC_UPDOWN_EVENTS_AGE, UDM_SETRANGE, 0, (LPARAM)MAKELONG(365, 1));

        SetDlgItemInt(hDlg, IDC_EDIT_MAXLOGSIZE, dwMaxSize, FALSE);
        SetDlgItemInt(hDlg, IDC_EDIT_EVENTS_AGE, (dwRetention == 0) ? 7 : dwRetention, FALSE);

        if (dwRetention == 0)
        {
            CheckRadioButton(hDlg, IDC_OVERWRITE_AS_NEEDED, IDC_NO_OVERWRITE, IDC_OVERWRITE_AS_NEEDED);
            EnableDlgItem(hDlg, IDC_EDIT_EVENTS_AGE, FALSE);
            EnableDlgItem(hDlg, IDC_UPDOWN_EVENTS_AGE, FALSE);
        }
        else if (dwRetention == INFINITE)
        {
            CheckRadioButton(hDlg, IDC_OVERWRITE_AS_NEEDED, IDC_NO_OVERWRITE, IDC_NO_OVERWRITE);
            EnableDlgItem(hDlg, IDC_EDIT_EVENTS_AGE, FALSE);
            EnableDlgItem(hDlg, IDC_UPDOWN_EVENTS_AGE, FALSE);
        }
        else
        {
            CheckRadioButton(hDlg, IDC_OVERWRITE_AS_NEEDED, IDC_NO_OVERWRITE, IDC_OVERWRITE_OLDER_THAN);
            EnableDlgItem(hDlg, IDC_EDIT_EVENTS_AGE, TRUE);
            EnableDlgItem(hDlg, IDC_UPDOWN_EVENTS_AGE, TRUE);
        }
    }
    else
    {
        // TODO: Hide the unused controls! Or, just use another type of property sheet!
    }
}

static
VOID
SavePropertiesDlg(HWND hDlg, PEVENTLOG EventLog)
{
    LPWSTR lpLogName = EventLog->LogName;

    LONG Result;
    DWORD dwMaxSize = 0, dwRetention = 0;
    HKEY hLogKey;
    WCHAR *KeyPath;    
    SIZE_T cbKeyPath;

    if (!EventLog->Permanent)
        return;

    cbKeyPath = (wcslen(EVENTLOG_BASE_KEY) + wcslen(lpLogName) + 1) * sizeof(WCHAR);
    KeyPath = HeapAlloc(GetProcessHeap(), 0, cbKeyPath);
    if (!KeyPath)
    {
        ShowWin32Error(ERROR_NOT_ENOUGH_MEMORY);
        return;
    }

    StringCbCopyW(KeyPath, cbKeyPath, EVENTLOG_BASE_KEY);
    StringCbCatW(KeyPath, cbKeyPath, lpLogName);

    Result = RegOpenKeyExW(hkMachine, KeyPath, 0, KEY_SET_VALUE, &hLogKey);
    HeapFree(GetProcessHeap(), 0, KeyPath);
    if (Result != ERROR_SUCCESS)
    {
        ShowWin32Error(Result);
        return;
    }

    dwMaxSize = GetDlgItemInt(hDlg, IDC_EDIT_MAXLOGSIZE, NULL, FALSE) * 1024;
    RegSetValueExW(hLogKey,
                   L"MaxSize",
                   0,
                   REG_DWORD,
                   (LPBYTE)&dwMaxSize,
                   sizeof(dwMaxSize));    

    if (IsDlgButtonChecked(hDlg, IDC_OVERWRITE_AS_NEEDED) == BST_CHECKED)
        dwRetention = 0;
    else if (IsDlgButtonChecked(hDlg, IDC_NO_OVERWRITE) == BST_CHECKED)
        dwRetention = INFINITE;
    else // if (IsDlgButtonChecked(hDlg, IDC_OVERWRITE_OLDER_THAN) == BST_CHECKED)
        dwRetention = GetDlgItemInt(hDlg, IDC_EDIT_EVENTS_AGE, NULL, FALSE) * (24*3600);

    RegSetValueExW(hLogKey,
                   L"Retention",
                   0,
                   REG_DWORD,
                   (LPBYTE)&dwRetention,
                   sizeof(dwRetention));
    
    RegCloseKey(hLogKey);
}

/* Message handler for EventLog Properties dialog */
INT_PTR CALLBACK
EventLogPropProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    PEVENTLOG EventLog;
    WCHAR szText[MAX_LOADSTRING];

    EventLog = (PEVENTLOG)GetWindowLongPtrW(hDlg, DWLP_USER);

    switch (uMsg)
    {
        case WM_INITDIALOG:
        {
            EventLog = (PEVENTLOG)((LPPROPSHEETPAGE)lParam)->lParam;
            SetWindowLongPtrW(hDlg, DWLP_USER, (LONG_PTR)EventLog);

            InitPropertiesDlg(hDlg, EventLog);

            PropSheet_UnChanged(GetParent(hDlg), hDlg);
            return (INT_PTR)TRUE;
        }

        case WM_DESTROY:
            return (INT_PTR)TRUE;

        case WM_NOTIFY:
            switch (((LPNMHDR)lParam)->code)
            {                
                case PSN_APPLY:
                    PropSheet_UnChanged(GetParent(hDlg), hDlg);
                    SavePropertiesDlg(hDlg, EventLog);
                    return (INT_PTR)TRUE;
            }
            break;
                        
        case WM_COMMAND:
            switch (LOWORD(wParam))
            {
                case IDOK:
                case IDCANCEL:
                    EndDialog(hDlg, LOWORD(wParam));
                    return (INT_PTR)TRUE;

                case ID_CLEARLOG:
                {
                    PEVENTLOGFILTER EventLogFilter = GetSelectedFilter(NULL);
                    if (EventLogFilter && ClearEvents(EventLogFilter))
                    {
                        Refresh(EventLogFilter);
                        InitPropertiesDlg(hDlg, EventLog);
                    }
                    return (INT_PTR)TRUE;
                }
                
                case IDC_EDIT_EVENTS_AGE:
                case IDC_EDIT_MAXLOGSIZE:
                    if (HIWORD(wParam) == EN_CHANGE)
                    {
                        PropSheet_Changed(GetParent(hDlg), hDlg);
                    }
                    return (INT_PTR)TRUE;
                    
                case IDC_OVERWRITE_AS_NEEDED:
                {
                    CheckRadioButton(hDlg, IDC_OVERWRITE_AS_NEEDED, IDC_NO_OVERWRITE, IDC_OVERWRITE_AS_NEEDED);
                    EnableDlgItem(hDlg, IDC_EDIT_EVENTS_AGE, FALSE);
                    EnableDlgItem(hDlg, IDC_UPDOWN_EVENTS_AGE, FALSE);
                    PropSheet_Changed(GetParent(hDlg), hDlg);
                    return (INT_PTR)TRUE;
                }

                case IDC_OVERWRITE_OLDER_THAN:
                {
                    CheckRadioButton(hDlg, IDC_OVERWRITE_AS_NEEDED, IDC_NO_OVERWRITE, IDC_OVERWRITE_OLDER_THAN);
                    EnableDlgItem(hDlg, IDC_EDIT_EVENTS_AGE, TRUE);
                    EnableDlgItem(hDlg, IDC_UPDOWN_EVENTS_AGE, TRUE);
                    PropSheet_Changed(GetParent(hDlg), hDlg);
                    return (INT_PTR)TRUE;
                }

                case IDC_NO_OVERWRITE:
                {
                    CheckRadioButton(hDlg, IDC_OVERWRITE_AS_NEEDED, IDC_NO_OVERWRITE, IDC_NO_OVERWRITE);
                    EnableDlgItem(hDlg, IDC_EDIT_EVENTS_AGE, FALSE);
                    EnableDlgItem(hDlg, IDC_UPDOWN_EVENTS_AGE, FALSE);
                    PropSheet_Changed(GetParent(hDlg), hDlg);
                    return (INT_PTR)TRUE;
                }
                
                case IDC_RESTOREDEFAULTS:
                {
                    LoadStringW(hInst, IDS_RESTOREDEFAULTS, szText, _countof(szText));

                    if (MessageBoxW(hDlg, szText, szTitle, MB_YESNO | MB_ICONQUESTION) == IDYES)
                    {
                        CheckRadioButton(hDlg, IDC_OVERWRITE_AS_NEEDED, IDC_NO_OVERWRITE, IDC_OVERWRITE_AS_NEEDED);
                        /* Workstation: 512 KB; Server: 16384 KB */
                        SetDlgItemInt(hDlg, IDC_EDIT_MAXLOGSIZE, 5120, FALSE);
                        SetDlgItemInt(hDlg, IDC_EDIT_EVENTS_AGE, 7, FALSE);
                        EnableDlgItem(hDlg, IDC_EDIT_EVENTS_AGE, FALSE);
                        EnableDlgItem(hDlg, IDC_UPDOWN_EVENTS_AGE, FALSE);
                        PropSheet_Changed(GetParent(hDlg), hDlg);
                    }
                    return (INT_PTR)TRUE;
                }

                case IDHELP:
                    MessageBoxW(hDlg,
                                L"Help not implemented yet!",
                                L"Event Log",
                                MB_OK | MB_ICONINFORMATION);
                    return (INT_PTR)TRUE;

                default:
                    break;
            }
            break;
    }

    return (INT_PTR)FALSE;
}

INT_PTR
EventLogProperties(HINSTANCE hInstance, HWND hWndParent, PEVENTLOGFILTER EventLogFilter)
{
    INT_PTR ret = 0;
    PROPSHEETHEADERW psh;
    PROPSHEETPAGEW   psp[1]; // 2

    /*
     * Bail out if there is no available filter, or if the filter
     * contains more than one log.
     */
    if (!EventLogFilter)
        return 0;

    EventLogFilter_AddRef(EventLogFilter);

    if (EventLogFilter->NumOfEventLogs > 1 ||
        EventLogFilter->EventLogs[0] == NULL)
    {
        goto Quit;
    }

    /* Header */
    psh.dwSize      = sizeof(psh);
    psh.dwFlags     = PSH_PROPSHEETPAGE /*| PSH_USEICONID */ | PSH_PROPTITLE | PSH_HASHELP /*| PSH_NOCONTEXTHELP */ /*| PSH_USECALLBACK */;
    psh.hInstance   = hInstance;
    psh.hwndParent  = hWndParent;
    // psh.pszIcon     = MAKEINTRESOURCEW(IDI_APPICON); // Disabled because it only sets the small icon; the big icon is a stretched version of the small one.
    psh.pszCaption  = EventLogFilter->EventLogs[0]->LogName;
    psh.nStartPage  = 0;
    psh.ppsp        = psp;
    psh.nPages      = ARRAYSIZE(psp);
    // psh.pfnCallback = PropSheetCallback;

    /* Log properties page */
    psp[0].dwSize      = sizeof(psp[0]);
    psp[0].dwFlags     = PSP_HASHELP;
    psp[0].hInstance   = hInstance;
    psp[0].pszTemplate = MAKEINTRESOURCEW(IDD_LOGPROPERTIES_GENERAL);
    psp[0].pfnDlgProc  = EventLogPropProc;
    psp[0].lParam      = (LPARAM)EventLogFilter->EventLogs[0];

#if 0
    /* TODO: Log sources page */
    psp[1].dwSize      = sizeof(psp[1]);
    psp[1].dwFlags     = PSP_HASHELP;
    psp[1].hInstance   = hInstance;
    psp[1].pszTemplate = MAKEINTRESOURCEW(IDD_GENERAL_PAGE);
    psp[1].pfnDlgProc  = GeneralPageWndProc;
    psp[1].lParam      = (LPARAM)EventLogFilter->EventLogs[0];
#endif

    /* Create the property sheet */
    ret = PropertySheetW(&psh);

Quit:
    EventLogFilter_Release(EventLogFilter);
    return ret;
}

/* Message handler for Event Details dialog */
static HWND hWndDetailsCtrl = NULL; // May go into the DWLP_USER
static HWND hWndGrip = NULL;
static INT cxMin, cyMin;    // In window coordinates
static INT cxOld, cyOld;    // In client coordinates

INT_PTR CALLBACK
EventDetails(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_INITDIALOG:
        {
            LONG_PTR dwStyle;
            INT sbVXSize, sbHYSize;
            RECT rcWnd, rect;

            hWndDetailsCtrl = CreateEventDetailsCtrl(hInst, hDlg, lParam);
            if (!hWndDetailsCtrl)
            {
                EndDialog(hDlg, 0);
                return (INT_PTR)TRUE;
            }

            /* Create a size grip if the dialog has a sizing border */
            GetClientRect(hDlg, &rcWnd);
            dwStyle  = GetWindowLongPtrW(hDlg, GWL_STYLE);
            sbVXSize = GetSystemMetrics(SM_CXVSCROLL);
            sbHYSize = GetSystemMetrics(SM_CYHSCROLL);
            if (dwStyle & WS_THICKFRAME /* == WS_SIZEBOX */)
            {
                hWndGrip = CreateWindowW(WC_SCROLLBARW,
                                         NULL,
                                         WS_CHILD | WS_VISIBLE | /**/ WS_CLIPSIBLINGS | /**/ SBS_SIZEGRIP | SBS_SIZEBOXBOTTOMRIGHTALIGN,
                                         rcWnd.right - sbVXSize,
                                         rcWnd.bottom - sbHYSize,
                                         sbVXSize, sbHYSize,
                                         hDlg,
                                         NULL,
                                         hInst,
                                         NULL);
            }

            // SetWindowLongPtrW(hDlg, DWLP_USER, (LONG_PTR)hWndDetailsCtrl);

            /*
             * Compute the minimum window size (in window coordinates) by
             * adding the widths/heights of the "Help" and "Close" buttons,
             * together with the margins, and add some minimal spacing
             * between the buttons.
             */
            GetWindowRect(hDlg, &rcWnd);
            cxMin = cyMin = 0;

            GetWindowRect(GetDlgItem(hDlg, IDHELP), &rect);
            cxMin += (rect.right - rect.left) + (rect.left - rcWnd.left); // == (rect.right - rcWnd.left);
            cyMin += (rect.bottom - rect.top) + (rcWnd.bottom - rect.bottom); // == (rcWnd.bottom - rect.top);

            GetWindowRect(GetDlgItem(hDlg, IDOK), &rect);
            cxMin += (rect.right - rect.left) + (rcWnd.right - rect.right); // == (rcWnd.right - rect.left);
            cyMin += (rect.bottom - rect.top) + (rcWnd.bottom - rect.bottom); // == (rcWnd.bottom - rect.top);

            /*
             * Convert the window rect from window to client coordinates
             * in order to retrieve the sizes of the left and top margins,
             * and add some extra space.
             */
            MapWindowPoints(HWND_DESKTOP /*NULL*/, hDlg, (LPPOINT)&rcWnd, sizeof(RECT)/sizeof(POINT));

            cxMin += -2*rcWnd.left;   // Minimal spacing between the buttons == 2 * left margin
            cyMin += -rcWnd.top + 12; // Add some space on top

            GetClientRect(hDlg, &rcWnd);
            cxOld = rcWnd.right - rcWnd.left;
            cyOld = rcWnd.bottom - rcWnd.top;

            /* Show event info on dialog control */
            SendMessageW(hWndDetailsCtrl, EVT_DISPLAY, 0, 0);

            // SetWindowPos(hWndDetailsCtrl, NULL,
                         // 0, 0,
                         // (rcWnd.right - rcWnd.left),
                         // (rcWnd.bottom - rcWnd.top),
                         // SWP_NOZORDER | SWP_NOACTIVATE | SWP_SHOWWINDOW);

            /*
             * Hide the placeholder static control and show the event details
             * control instead. Note that the placeholder is here so far just
             * to get the dimensions right in the dialog resource editor.
             * I plan to remove it and use a custom control with a suitable
             * window class for it, that would create the event details control
             * instead.
             */
            ShowWindow(GetDlgItem(hDlg, IDC_STATIC), SW_HIDE);
            ShowWindow(hWndDetailsCtrl, SW_SHOW);
            return (INT_PTR)TRUE;
        }

        case WM_DESTROY:
            if (IsWindow(hWndDetailsCtrl))
                DestroyWindow(hWndDetailsCtrl);
            hWndDetailsCtrl = NULL;
            return (INT_PTR)TRUE;

        case WM_COMMAND:
            switch (LOWORD(wParam))
            {
                case IDOK:
                case IDCANCEL:
                    EndDialog(hDlg, LOWORD(wParam));
                    return (INT_PTR)TRUE;

                case IDHELP:
                    MessageBoxW(hDlg,
                                L"Help not implemented yet!",
                                L"Event Log",
                                MB_OK | MB_ICONINFORMATION);
                    return (INT_PTR)TRUE;

                default:
                    break;
            }
            break;

        case WM_SETCURSOR:
            if (((HWND)wParam == hWndGrip) && (LOWORD(lParam) == HTCLIENT))
            {
                SetCursor(LoadCursorW(NULL, IDC_SIZENWSE));
                SetWindowLongPtrW(hDlg, DWLP_MSGRESULT, TRUE);
                return (INT_PTR)TRUE;
            }
            break;

        case WM_SIZING:
        {
            /* Forbid resizing the dialog smaller than its minimal size */
            PRECT dragRect = (PRECT)lParam;

            if ((wParam == WMSZ_LEFT) || (wParam == WMSZ_TOPLEFT) || (wParam == WMSZ_BOTTOMLEFT))
            {
                if (dragRect->right - dragRect->left < cxMin)
                    dragRect->left = dragRect->right - cxMin;
            }

            if ((wParam == WMSZ_RIGHT) || (wParam == WMSZ_TOPRIGHT) || (wParam == WMSZ_BOTTOMRIGHT))
            {
                if (dragRect->right - dragRect->left < cxMin)
                    dragRect->right = dragRect->left + cxMin;
            }

            if ((wParam == WMSZ_TOP) || (wParam == WMSZ_TOPLEFT) || (wParam == WMSZ_TOPRIGHT))
            {
                if (dragRect->bottom - dragRect->top < cyMin)
                    dragRect->top = dragRect->bottom - cyMin;
            }

            if ((wParam == WMSZ_BOTTOM) || (wParam == WMSZ_BOTTOMLEFT) || (wParam == WMSZ_BOTTOMRIGHT))
            {
                if (dragRect->bottom - dragRect->top < cyMin)
                    dragRect->bottom = dragRect->top + cyMin;
            }

            SetWindowLongPtrW(hDlg, DWLP_MSGRESULT, TRUE);
            return (INT_PTR)TRUE;
        }

        case WM_SIZE:
        {
            INT cx = LOWORD(lParam);
            INT cy = HIWORD(lParam);

            HDWP hdwp;
            HWND hItemWnd;
            RECT rect;

            hdwp = BeginDeferWindowPos(4);

            /* Resize the event details control window */

            hItemWnd = hWndDetailsCtrl;
            GetWindowRect(hItemWnd, &rect);
            MapWindowPoints(HWND_DESKTOP /*NULL*/, hDlg, (LPPOINT)&rect, sizeof(RECT)/sizeof(POINT));

            if (hdwp)
                hdwp = DeferWindowPos(hdwp,
                                      hItemWnd,
                                      HWND_TOP,
                                      0, 0,
                                      (rect.right - rect.left) + (cx - cxOld),
                                      (rect.bottom - rect.top) + (cy - cyOld),
                                      SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);

            /* Move the buttons */

            hItemWnd = GetDlgItem(hDlg, IDHELP);
            GetWindowRect(hItemWnd, &rect);
            MapWindowPoints(HWND_DESKTOP /*NULL*/, hDlg, (LPPOINT)&rect, sizeof(RECT)/sizeof(POINT));

            if (hdwp)
                hdwp = DeferWindowPos(hdwp,
                                      hItemWnd,
                                      HWND_TOP,
                                      rect.left,
                                      rect.top + (cy - cyOld),
                                      0, 0,
                                      SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);

            hItemWnd = GetDlgItem(hDlg, IDOK);
            GetWindowRect(hItemWnd, &rect);
            MapWindowPoints(HWND_DESKTOP /*NULL*/, hDlg, (LPPOINT)&rect, sizeof(RECT)/sizeof(POINT));

            if (hdwp)
                hdwp = DeferWindowPos(hdwp,
                                      hItemWnd,
                                      HWND_TOP,
                                      rect.left + (cx - cxOld),
                                      rect.top  + (cy - cyOld),
                                      0, 0,
                                      SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);

            /* Move the size grip */
            if (hWndGrip && hdwp)
            {
                GetWindowRect(hWndGrip, &rect);
                MapWindowPoints(HWND_DESKTOP /*NULL*/, hDlg, (LPPOINT)&rect, sizeof(RECT)/sizeof(POINT));

                hdwp = DeferWindowPos(hdwp,
                                      hWndGrip,
                                      HWND_TOP,
                                      rect.left + (cx - cxOld),
                                      rect.top  + (cy - cyOld),
                                      0, 0,
                                      SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
            }

            if (hdwp)
                EndDeferWindowPos(hdwp);

            /* Hide the size grip if we are in maximized mode */
            if (hWndGrip)
                ShowWindow(hWndGrip, (wParam == SIZE_MAXIMIZED) ? SW_HIDE : SW_SHOW);

            cxOld = cx;
            cyOld = cy;

            SetWindowLongPtrW(hDlg, DWLP_MSGRESULT, 0);
            return (INT_PTR)TRUE;
        }
    }

    return (INT_PTR)FALSE;
}