File size: 55,993 Bytes
493404f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# FileOrganizer.ps1 - Modern File Organizer with GUI & CLI
# A professional-grade Windows utility for organizing files by type
#
# Default config.json (auto-created if missing):
# <#
# {
#   "categories": {
#     "Word Files": ["doc", "docx", "docm", "dotx"],
#     "PowerPoint Files": ["ppt", "pptx", "pptm"],
#     "Excel Files": ["xls", "xlsx", "xlsm", "csv"],
#     "PDF Files": ["pdf"],
#     "Images": ["jpg", "jpeg", "png", "gif", "bmp", "svg", "webp", "tiff"],
#     "Videos": ["mp4", "avi", "mkv", "mov", "wmv", "flv"],
#     "Executables": ["exe", "msi", "bat", "cmd", "ps1"],
#     "Archives": ["zip", "rar", "7z", "tar", "gz"],
#     "Audio": ["mp3", "wav", "flac", "ogg", "aac", "wma"],
#     "Code": ["ps1", "py", "js", "ts", "cpp", "c", "h", "cs", "java", "rb", "go", "rs"],
#     "Text": ["txt", "md", "log", "rtf", "json", "xml", "yaml", "yml", "ini", "cfg"]
#   },
#   "excludePatterns": ["Thumbs.db", ".DS_Store", "desktop.ini", "*.tmp", "~$*"],
#   "createTypeSubfolder": true,
#   "defaultAction": "Move",
#   "defaultDepth": 100
# }
# #>
#
# Usage:
#   .\FileOrganizer.ps1                                    # Interactive GUI mode
#   .\FileOrganizer.ps1 -SourcePath "C:\Downloads" -DestPath "D:\Organized" -DryRun
#   .\FileOrganizer.ps1 -SourcePath "C:\Src" -DestPath "D:\Dest" -Action Copy -Depth 2
#   .\FileOrganizer.ps1 -CategoriesFile "custom.json"
#   Get-Help .\FileOrganizer.ps1 -Detailed

#Requires -Version 5.1

# ============================================================
# IMPORTANT: param() MUST come first before any executable code
# ============================================================

[CmdletBinding()]
param (
    [Parameter(HelpMessage = "Source folder path to scan")]
    [string]$SourcePath,

    [Parameter(HelpMessage = "Destination folder path")]
    [string]$DestPath,

    [Parameter(HelpMessage = "Scan depth: 0=Main only, 1=Subfolders, 2=SubSubfolders, 100=All")]
    [ValidateRange(0, 100)]
    [int]$Depth = 100,

    [Parameter(HelpMessage = "Action to perform: Move or Copy")]
    [ValidateSet("Move", "Copy")]
    [string]$Action = "Move",

    [Parameter(HelpMessage = "Simulate operation without moving/copying files")]
    [switch]$DryRun,

    [Parameter(HelpMessage = "Path to custom categories JSON file")]
    [string]$CategoriesFile,

    [Parameter(HelpMessage = "Run without looping for additional tasks")]
    [switch]$NoLoop,

    [Parameter(HelpMessage = "Use separate destination folder per file type")]
    [switch]$SeparateDestinations,

    [Parameter(HelpMessage = "Show this help message")]
    [switch]$Help
)

# ============================================================
# Now we can have executable code after param()
# ============================================================

# Early error handling - don't let script silently fail
$ErrorActionPreference = "Continue"
$Script:StartupError = $null

# Check execution policy
try {
    $execPolicy = Get-ExecutionPolicy -ErrorAction SilentlyContinue
    if ($execPolicy -eq "Restricted") {
        Write-Host "WARNING: Execution Policy is Restricted." -ForegroundColor Yellow
        Write-Host "Run: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser" -ForegroundColor Yellow
    }
}
catch {
    Write-Verbose "Could not get ExecutionPolicy"
}

# Fix for $PSScriptRoot being empty when run via right-click "Run with PowerShell"
$Script:ScriptPath = if ($PSScriptRoot) { $PSScriptRoot } elseif ($PSCommandPath) { Split-Path -Parent $PSCommandPath } else { Split-Path -Parent $MyInvocation.MyCommand.Path }
if (-not $Script:ScriptPath) { $Script:ScriptPath = Get-Location }

# Pre-load Windows Forms (needed for GUI dialogs)
try {
    Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop
}
catch {
    $errMsg = $_.Exception.Message
    $Script:StartupError = "Failed to load Windows Forms - $errMsg"
}

#region Global Variables
$Script:Config = $null
$Script:LastUsed = $null
$Script:ScriptName = "FileOrganizer"
$Script:LogFile = $null
$Script:IsElevated = $false
$Script:PSVersion = $PSVersionTable.PSVersion.Major
#endregion

# Check for startup errors
if ($Script:StartupError) {
    Write-Host "ERROR: $Script:StartupError" -ForegroundColor Red
    Write-Host "Press Enter to exit..." -ForegroundColor Yellow
    Read-Host
    exit 1
}

# Show startup banner
Write-Host ""
Write-Host "======================================" -ForegroundColor Cyan
Write-Host "   FileOrganizer v2.0 - Loading..." -ForegroundColor Cyan
Write-Host "======================================" -ForegroundColor Cyan
Write-Host "Script Path: $Script:ScriptPath" -ForegroundColor Gray
Write-Host "PowerShell: $($Script:PSVersion)" -ForegroundColor Gray
Write-Host ""

#region Comment-Based Help
<#

.SYNOPSIS

    Organizes files by type into destination folders.



.DESCRIPTION

    FileOrganizer is a professional-grade Windows utility that scans a source folder,

    categorizes files by type (Word, PDF, Images, etc.), and moves or copies them to

    destination folders. Supports both CLI and interactive GUI modes.



    Features:

    - CLI and Interactive GUI hybrid operation

    - Configurable file categories via JSON

    - Move or Copy operations

    - Dry-Run mode for safe testing

    - Modern Out-GridView selection

    - Remembers last used folders

    - Comprehensive logging



.PARAMETER SourcePath

    Source folder to scan. If not provided, launches interactive folder browser.



.PARAMETER DestPath

    Destination folder for organized files. If not provided, launches interactive browser.



.PARAMETER Depth

    Scan depth: 0=Main folder only, 1=One level deep, 2=Two levels, 100=All (default).



.PARAMETER Action

    Operation type: "Move" (default) or "Copy". Use Copy for safer testing.



.PARAMETER DryRun

    Simulates the operation without actually moving/copying files. Shows what would happen.



.PARAMETER CategoriesFile

    Path to custom JSON file with file type categories.



.PARAMETER NoLoop

    Runs single operation without prompting for additional tasks.



.PARAMETER SeparateDestinations

    Use separate destination folder per file type (prompts for each).



.EXAMPLE

    .\FileOrganizer.ps1



    Launches interactive GUI mode with folder browsers and selections.



.EXAMPLE

    .\FileOrganizer.ps1 -SourcePath "C:\Downloads" -DestPath "D:\Organized" -DryRun



    Scans Downloads, shows what would be organized to D:\Organized without making changes.



.EXAMPLE

    .\FileOrganizer.ps1 -SourcePath "C:\Files" -Action Copy -Depth 2



    Copies files from C:\Files (including subfolders 2 levels deep) with interactive destination.



.NOTES

    Author: FileOrganizer Team

    Version: 2.0.0

    Requires: PowerShell 5.1+

#>
#endregion

#region Initialization Functions

function Initialize-Environment {
    <#

    .SYNOPSIS

        Initializes the script environment - logging, config, paths

    #>
    [CmdletBinding()]
    param()

    # Set up log file path
    $logDate = Get-Date -Format "yyyy-MM-dd"
    $Script:LogFile = Join-Path $Script:ScriptPath "$($Script:ScriptName)_$logDate.log"

    # Create script path if it doesn't exist (for when running from other locations)
    if (-not $Script:ScriptPath) {
        $Script:ScriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
    }

    # Load configuration
    Load-Config -CategoriesFile $CategoriesFile

    # Load last used paths
    Load-LastUsed

    # Check PowerShell version for feature compatibility
    if ($Script:PSVersion -lt 5) {
        Write-Warning "PowerShell version 5.1 or higher recommended. Current: $($Script:PSVersion)"
    }

    Write-Log "INFO" "FileOrganizer started - PS Version: $($Script:PSVersion)"
}

function Load-Config {
    <#

    .SYNOPSIS

        Loads configuration from JSON file or creates default

    #>
    [CmdletBinding()]
    param(
        [string]$CategoriesFile
    )

    # Determine config file path
    if ($CategoriesFile) {
        $configPath = $CategoriesFile
    }
    else {
        $configPath = Join-Path $Script:ScriptPath "config.json"
    }

    # Default configuration
    $defaultConfig = @{
        categories          = @{
            "Word Files"       = @("doc", "docx", "docm", "dotx")
            "PowerPoint Files" = @("ppt", "pptx", "pptm")
            "Excel Files"      = @("xls", "xlsx", "xlsm", "csv")
            "PDF Files"        = @("pdf")
            "Images"           = @("jpg", "jpeg", "png", "gif", "bmp", "svg", "webp", "tiff")
            "Videos"           = @("mp4", "avi", "mkv", "mov", "wmv", "flv")
            "Executables"      = @("exe", "msi", "bat", "cmd")
            "Archives"         = @("zip", "rar", "7z", "tar", "gz")
            "Audio"            = @("mp3", "wav", "flac", "ogg", "aac", "wma")
            "Code"             = @("ps1", "py", "js", "ts", "cpp", "c", "h", "cs", "java", "rb", "go", "rs")
            "Text"             = @("txt", "md", "log", "rtf", "json", "xml", "yaml", "yml", "ini", "cfg")
        }
        excludePatterns     = @("Thumbs.db", ".DS_Store", "desktop.ini", "*.tmp", "~$*")
        createTypeSubfolder = $true
        defaultAction       = "Move"
        defaultDepth        = 100
    }

    # Load existing or create default config
    if (Test-Path $configPath) {
        try {
            $configContent = Get-Content $configPath -Raw -ErrorAction Stop
            # Handle PS 5.1 vs PS 6+ compatibility
            if ($Script:PSVersion -ge 6) {
                $Script:Config = $configContent | ConvertFrom-Json -AsHashtable -ErrorAction Stop
            }
            else {
                $loadedConfig = $configContent | ConvertFrom-Json -ErrorAction Stop
                # Convert PSObject to Hashtable for PS 5.1 compatibility
                $Script:Config = @{}
                $loadedConfig.PSObject.Properties | ForEach-Object {
                    $Script:Config[$_.Name] = $_.Value
                }
            }
            Write-Log "INFO" "Configuration loaded from: $configPath"
        }
        catch {
            $errMsg = $_.Exception.Message
            Write-Warning "Failed to load config, using defaults - $errMsg"
            $Script:Config = $defaultConfig
            Save-Config -Config $Script:Config -Path $configPath
        }
    }
    else {
        # Create default config file
        $Script:Config = $defaultConfig
        try {
            Save-Config -Config $Script:Config -Path $configPath
            Write-Host "Created default config: $configPath" -ForegroundColor Cyan
        }
        catch {
            $errMsg = $_.Exception.Message
            Write-Warning "Could not create config file - $errMsg"
        }
    }

    # Ensure required keys exist
    if (-not $Script:Config.categories) { $Script:Config.categories = $defaultConfig.categories }
    if (-not $Script:Config.excludePatterns) { $Script:Config.excludePatterns = $defaultConfig.excludePatterns }
    if ($null -eq $Script:Config.createTypeSubfolder) { $Script:Config.createTypeSubfolder = $true }
}

function Save-Config {
    <#

    .SYNOPSIS

        Saves configuration to JSON file

    #>
    [CmdletBinding()]
    param(
        [hashtable]$Config,
        [string]$Path
    )

    try {
        $Config | ConvertTo-Json -Depth 10 | Set-Content $Path -Force -ErrorAction Stop
    }
    catch {
        $errMsg = $_.Exception.Message
        Write-Warning "Failed to save config - $errMsg"
    }
}

function Load-LastUsed {
    <#

    .SYNOPSIS

        Loads last used source/destination paths

    #>
    [CmdletBinding()]
    param()

    $lastUsedPath = Join-Path $Script:ScriptPath "lastused.json"

    if (Test-Path $lastUsedPath) {
        try {
            $content = Get-Content $lastUsedPath -Raw
            # Handle PS 5.1 vs PS 6+ compatibility
            if ($Script:PSVersion -ge 6) {
                $Script:LastUsed = $content | ConvertFrom-Json -AsHashtable -ErrorAction Stop
            }
            else {
                $loaded = $content | ConvertFrom-Json -ErrorAction Stop
                # Convert PSObject to Hashtable for PS 5.1 compatibility
                $Script:LastUsed = @{}
                $loaded.PSObject.Properties | ForEach-Object {
                    $Script:LastUsed[$_.Name] = $_.Value
                }
            }
        }
        catch {
            $Script:LastUsed = @{ sourcePath = ""; destPath = "" }
        }
    }
    else {
        $Script:LastUsed = @{ sourcePath = ""; destPath = "" }
    }
}

function Save-LastUsed {
    <#

    .SYNOPSIS

        Saves last used paths for future sessions

    #>
    [CmdletBinding()]
    param(
        [string]$SourcePath,
        [string]$DestPath
    )

    $lastUsedPath = Join-Path $Script:ScriptPath "lastused.json"

    $Script:LastUsed.sourcePath = $SourcePath
    $Script:LastUsed.destPath = $DestPath

    try {
        $Script:LastUsed | ConvertTo-Json | Set-Content $lastUsedPath -Force
    }
    catch {
        $errMsg = $_.Exception.Message
        Write-Warning "Could not save last used paths - $errMsg"
    }
}

function Write-Log {
    <#

    .SYNOPSIS

        Writes timestamped log entry to file

    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Level,

        [Parameter(Mandatory)]
        [string]$Message
    )

    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] $Message"

    # Write to log file
    try {
        Add-Content -Path $Script:LogFile -Value $logEntry -ErrorAction SilentlyContinue
    }
    catch {
        Write-Verbose "Logging silently failed"
    }

    # Also output to console based on level
    switch ($Level) {
        "ERROR" { Write-Host $logEntry -ForegroundColor Red }
        "WARN" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Verbose $logEntry }
        "DRYRUN" { Write-Host $logEntry -ForegroundColor Cyan }
    }
}

#endregion

#region GUI Helper Functions

function Test-OutGridViewAvailable {
    <#

    .SYNOPSIS

        Checks if Out-GridView is available (Windows only)

    #>
    if ($IsWindows -or (-not $IsLinux -and -not $IsMacOS)) {
        return $true
    }
    return $false
}

function Select-SourceFolder {
    <#

    .SYNOPSIS

        Shows folder browser dialog for source selection

    #>
    [CmdletBinding()]
    param(
        [string]$InitialPath
    )

    # Use last used path if available and no initial path provided
    if (-not $InitialPath -and $Script:LastUsed.sourcePath) {
        if (Test-Path $Script:LastUsed.sourcePath) {
            $InitialPath = $Script:LastUsed.sourcePath
        }
    }

    # Use Windows Forms folder browser
    Add-Type -AssemblyName System.Windows.Forms
    $dialog = New-Object System.Windows.Forms.FolderBrowserDialog
    $dialog.Description = "Select Source Folder to Scan"
    $dialog.ShowNewFolderButton = $false

    if ($InitialPath -and (Test-Path $InitialPath)) {
        $dialog.SelectedPath = $InitialPath
    }

    $result = $dialog.ShowDialog()

    if ($result -eq "OK") {
        Write-Log "INFO" "Source folder selected: $($dialog.SelectedPath)"
        return $dialog.SelectedPath
    }

    return $null
}

function Select-DestinationFolder {
    <#

    .SYNOPSIS

        Shows folder browser dialog for destination selection

    #>
    [CmdletBinding()]
    param(
        [string]$Description = "Select Destination Folder",
        [string]$InitialPath
    )

    # Use last used path if available
    if (-not $InitialPath -and $Script:LastUsed.destPath) {
        if (Test-Path $Script:LastUsed.destPath) {
            $InitialPath = $Script:LastUsed.destPath
        }
    }

    Add-Type -AssemblyName System.Windows.Forms
    $dialog = New-Object System.Windows.Forms.FolderBrowserDialog
    $dialog.Description = $Description
    $dialog.ShowNewFolderButton = $true

    if ($InitialPath -and (Test-Path $InitialPath)) {
        $dialog.SelectedPath = $InitialPath
    }

    $result = $dialog.ShowDialog()

    if ($result -eq "OK") {
        Write-Log "INFO" "Destination folder selected: $($dialog.SelectedPath)"
        return $dialog.SelectedPath
    }

    return $null
}

function Select-DepthGUI {
    <#

    .SYNOPSIS

        Shows depth selection via modern Windows Forms

    #>
    [CmdletBinding()]
    param()

    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing

    $form = New-Object System.Windows.Forms.Form
    $form.Text = "FileOrganizer - Scan Depth"
    $form.Size = New-Object System.Drawing.Size(460, 320)
    $form.StartPosition = "CenterScreen"
    $form.FormBorderStyle = "FixedDialog"
    $form.MaximizeBox = $false
    $form.MinimizeBox = $false
    $form.BackColor = [System.Drawing.Color]::FromArgb(245, 245, 250)
    $form.Font = New-Object System.Drawing.Font("Segoe UI", 10)

    $headerPanel = New-Object System.Windows.Forms.Panel
    $headerPanel.Dock = "Top"
    $headerPanel.Height = 50
    $headerPanel.BackColor = [System.Drawing.Color]::FromArgb(55, 71, 133)

    $headerLabel = New-Object System.Windows.Forms.Label
    $headerLabel.Text = "  Select Scan Depth"
    $headerLabel.ForeColor = [System.Drawing.Color]::White
    $headerLabel.Font = New-Object System.Drawing.Font("Segoe UI Semibold", 14)
    $headerLabel.Dock = "Fill"
    $headerLabel.TextAlign = "MiddleLeft"
    $headerPanel.Controls.Add($headerLabel)

    $radio0 = New-Object System.Windows.Forms.RadioButton
    $radio0.Location = New-Object System.Drawing.Point(40, 70)
    $radio0.Size = New-Object System.Drawing.Size(380, 28)
    $radio0.Text = "Main Folder Only (Current folder only)"
    $radio0.FlatStyle = "Flat"

    $radio1 = New-Object System.Windows.Forms.RadioButton
    $radio1.Location = New-Object System.Drawing.Point(40, 105)
    $radio1.Size = New-Object System.Drawing.Size(380, 28)
    $radio1.Text = "Subfolders (1 level deep)"
    $radio1.FlatStyle = "Flat"

    $radio2 = New-Object System.Windows.Forms.RadioButton
    $radio2.Location = New-Object System.Drawing.Point(40, 140)
    $radio2.Size = New-Object System.Drawing.Size(380, 28)
    $radio2.Text = "Sub-Subfolders (2 levels deep)"
    $radio2.FlatStyle = "Flat"

    $radio100 = New-Object System.Windows.Forms.RadioButton
    $radio100.Location = New-Object System.Drawing.Point(40, 175)
    $radio100.Size = New-Object System.Drawing.Size(380, 28)
    $radio100.Text = "All Subfolders (Recursive)"
    $radio100.Checked = $true
    $radio100.FlatStyle = "Flat"

    $okButton = New-Object System.Windows.Forms.Button
    $okButton.Location = New-Object System.Drawing.Point(170, 225)
    $okButton.Size = New-Object System.Drawing.Size(100, 36)
    $okButton.Text = "OK"
    $okButton.Font = New-Object System.Drawing.Font("Segoe UI Semibold", 10)
    $okButton.FlatStyle = "Flat"
    $okButton.BackColor = [System.Drawing.Color]::FromArgb(55, 71, 133)
    $okButton.ForeColor = [System.Drawing.Color]::White
    $okButton.Cursor = "Hand"
    $okButton.DialogResult = "OK"

    $form.Controls.AddRange(@($headerPanel, $radio0, $radio1, $radio2, $radio100, $okButton))
    $form.AcceptButton = $okButton

    $result = $form.ShowDialog()
    $form.Dispose()

    if ($result -eq "OK") {
        if ($radio0.Checked) { return 0 }
        if ($radio1.Checked) { return 1 }
        if ($radio2.Checked) { return 2 }
        if ($radio100.Checked) { return 100 }
    }

    return 100 # default
}

function Select-FileType {
    <#

    .SYNOPSIS

        Shows type selection using custom modern Windows Forms CheckedListBox

    #>
    [CmdletBinding()]
    param(
        [hashtable]$TypeCounts
    )

    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing

    $form = New-Object System.Windows.Forms.Form
    $form.Text = "FileOrganizer - File Types"
    $form.Size = New-Object System.Drawing.Size(420, 500)
    $form.StartPosition = "CenterScreen"
    $form.FormBorderStyle = "FixedDialog"
    $form.MaximizeBox = $false
    $form.MinimizeBox = $false
    $form.BackColor = [System.Drawing.Color]::FromArgb(245, 245, 250)
    $form.Font = New-Object System.Drawing.Font("Segoe UI", 10)

    $headerPanel = New-Object System.Windows.Forms.Panel
    $headerPanel.Dock = "Top"
    $headerPanel.Height = 50
    $headerPanel.BackColor = [System.Drawing.Color]::FromArgb(55, 71, 133)

    $headerLabel = New-Object System.Windows.Forms.Label
    $headerLabel.Text = "  Select File Types"
    $headerLabel.ForeColor = [System.Drawing.Color]::White
    $headerLabel.Font = New-Object System.Drawing.Font("Segoe UI Semibold", 14)
    $headerLabel.Dock = "Fill"
    $headerLabel.TextAlign = "MiddleLeft"
    $headerPanel.Controls.Add($headerLabel)

    $listBox = New-Object System.Windows.Forms.CheckedListBox
    $listBox.Location = New-Object System.Drawing.Point(20, 95)
    $listBox.Size = New-Object System.Drawing.Size(360, 280)
    $listBox.Font = New-Object System.Drawing.Font("Segoe UI", 10.5)
    $listBox.CheckOnClick = $true

    # Store plain string items so we can easily map them back
    $itemList = @()
    foreach ($type in ($TypeCounts.Keys | Sort-Object)) {
        $count = $TypeCounts[$type]
        $display = "$type ($count files)"
        $listBox.Items.Add($display, $true) | Out-Null
        $itemList += [PSCustomObject]@{ Display = $display; Type = $type }
    }

    $selectAllBtn = New-Object System.Windows.Forms.Button
    $selectAllBtn.Location = New-Object System.Drawing.Point(20, 395)
    $selectAllBtn.Size = New-Object System.Drawing.Size(100, 32)
    $selectAllBtn.Text = "Select All"
    $selectAllBtn.FlatStyle = "Flat"
    $selectAllBtn.BackColor = [System.Drawing.Color]::FromArgb(220, 220, 225)
    $selectAllBtn.Cursor = "Hand"
    $selectAllBtn.Add_Click({
            for ($i = 0; $i -lt $listBox.Items.Count; $i++) {
                $listBox.SetItemChecked($i, $true)
            }
        })

    $clearAllBtn = New-Object System.Windows.Forms.Button
    $clearAllBtn.Location = New-Object System.Drawing.Point(130, 395)
    $clearAllBtn.Size = New-Object System.Drawing.Size(100, 32)
    $clearAllBtn.Text = "Clear All"
    $clearAllBtn.FlatStyle = "Flat"
    $clearAllBtn.BackColor = [System.Drawing.Color]::FromArgb(220, 220, 225)
    $clearAllBtn.Cursor = "Hand"
    $clearAllBtn.Add_Click({
            for ($i = 0; $i -lt $listBox.Items.Count; $i++) {
                $listBox.SetItemChecked($i, $false)
            }
        })

    $okButton = New-Object System.Windows.Forms.Button
    $okButton.Location = New-Object System.Drawing.Point(280, 390)
    $okButton.Size = New-Object System.Drawing.Size(100, 40)
    $okButton.Text = "OK"
    $okButton.Font = New-Object System.Drawing.Font("Segoe UI Semibold", 10.5)
    $okButton.FlatStyle = "Flat"
    $okButton.BackColor = [System.Drawing.Color]::FromArgb(55, 71, 133)
    $okButton.ForeColor = [System.Drawing.Color]::White
    $okButton.Cursor = "Hand"
    $okButton.DialogResult = "OK"

    $form.Controls.AddRange(@($headerPanel, $listBox, $selectAllBtn, $clearAllBtn, $okButton))
    $form.AcceptButton = $okButton

    # Loop until valid selection or cancelled
    $selectedTypes = @()
    while ($true) {
        $result = $form.ShowDialog()

        if ($result -eq "OK") {
            foreach ($item in $listBox.CheckedItems) {
                # Map display back to type name
                $mappedType = ($itemList | Where-Object { $_.Display -eq $item }).Type
                $selectedTypes += $mappedType
            }

            if ($selectedTypes.Count -gt 0) {
                break
            }
            else {
                [System.Windows.Forms.MessageBox]::Show("Please select at least one file type.", "No Selection", "OK", "Warning")
            }
        }
        else {
            break # Cancelled/closed
        }
    }

    $form.Dispose()

    if ($selectedTypes.Count -eq 0) { return @() }
    return $selectedTypes
}

function Select-ActionMode {
    <#

    .SYNOPSIS

        Shows Move/Copy selection dialog (modern styled)

    #>
    [CmdletBinding()]
    param()

    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing

    $form = New-Object System.Windows.Forms.Form
    $form.Text = "FileOrganizer - Select Operation"
    $form.Size = New-Object System.Drawing.Size(440, 220)
    $form.StartPosition = "CenterScreen"
    $form.FormBorderStyle = "FixedDialog"
    $form.MaximizeBox = $false
    $form.MinimizeBox = $false
    $form.BackColor = [System.Drawing.Color]::FromArgb(245, 245, 250)
    $form.Font = New-Object System.Drawing.Font("Segoe UI", 10)

    $headerPanel = New-Object System.Windows.Forms.Panel
    $headerPanel.Dock = "Top"
    $headerPanel.Height = 50
    $headerPanel.BackColor = [System.Drawing.Color]::FromArgb(55, 71, 133)

    $headerLabel = New-Object System.Windows.Forms.Label
    $headerLabel.Text = "  Select Operation Mode"
    $headerLabel.ForeColor = [System.Drawing.Color]::White
    $headerLabel.Font = New-Object System.Drawing.Font("Segoe UI Semibold", 14)
    $headerLabel.Dock = "Fill"
    $headerLabel.TextAlign = "MiddleLeft"
    $headerPanel.Controls.Add($headerLabel)

    $moveRadio = New-Object System.Windows.Forms.RadioButton
    $moveRadio.Location = New-Object System.Drawing.Point(40, 70)
    $moveRadio.Size = New-Object System.Drawing.Size(160, 30)
    $moveRadio.Text = "Move (default)"
    $moveRadio.Font = New-Object System.Drawing.Font("Segoe UI", 10)
    $moveRadio.Checked = $true
    $moveRadio.FlatStyle = "Flat"

    $copyRadio = New-Object System.Windows.Forms.RadioButton
    $copyRadio.Location = New-Object System.Drawing.Point(230, 70)
    $copyRadio.Size = New-Object System.Drawing.Size(160, 30)
    $copyRadio.Text = "Copy (safer)"
    $copyRadio.Font = New-Object System.Drawing.Font("Segoe UI", 10)
    $copyRadio.FlatStyle = "Flat"

    $okButton = New-Object System.Windows.Forms.Button
    $okButton.Location = New-Object System.Drawing.Point(110, 125)
    $okButton.Size = New-Object System.Drawing.Size(100, 36)
    $okButton.Text = "OK"
    $okButton.Font = New-Object System.Drawing.Font("Segoe UI Semibold", 10)
    $okButton.FlatStyle = "Flat"
    $okButton.BackColor = [System.Drawing.Color]::FromArgb(55, 71, 133)
    $okButton.ForeColor = [System.Drawing.Color]::White
    $okButton.Cursor = "Hand"
    $okButton.DialogResult = "OK"

    $cancelButton = New-Object System.Windows.Forms.Button
    $cancelButton.Location = New-Object System.Drawing.Point(225, 125)
    $cancelButton.Size = New-Object System.Drawing.Size(100, 36)
    $cancelButton.Text = "Cancel"
    $cancelButton.Font = New-Object System.Drawing.Font("Segoe UI", 10)
    $cancelButton.FlatStyle = "Flat"
    $cancelButton.BackColor = [System.Drawing.Color]::FromArgb(220, 220, 225)
    $cancelButton.Cursor = "Hand"
    $cancelButton.DialogResult = "Cancel"

    $form.Controls.AddRange(@($headerPanel, $moveRadio, $copyRadio, $okButton, $cancelButton))
    $form.AcceptButton = $okButton
    $form.CancelButton = $cancelButton

    $result = $form.ShowDialog()

    if ($result -eq "OK") {
        if ($copyRadio.Checked) {
            return "Copy"
        }
    }

    return "Move"
}

function Confirm-Summary {
    <#

    .SYNOPSIS

        Shows modern confirmation dialog with operation summary

    #>
    [CmdletBinding()]
    param(
        [string]$SourcePath,
        [string[]]$SelectedTypes,
        [hashtable]$TypeCounts,
        [string]$Action,
        [hashtable]$Destinations,
        [bool]$DryRun
    )

    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing

    # Calculate total files
    $totalFiles = 0
    foreach ($type in $SelectedTypes) {
        $totalFiles += $TypeCounts[$type]
    }

    # Build summary lines using ASCII-safe characters
    $summaryLines = @()
    $summaryLines += "Source Folder: $SourcePath"
    $summaryLines += ""
    $summaryLines += "Selected Types ($($SelectedTypes.Count) categories):"

    foreach ($type in $SelectedTypes | Sort-Object) {
        $count = $TypeCounts[$type]
        $dest = $Destinations[$type]
        $summaryLines += "  - $type : $count files"
        $summaryLines += "    -> $dest"
    }

    $dryRunText = if ($DryRun) { " (DRY RUN - No changes)" } else { "" }
    $summaryLines += ""
    $summaryLines += "Operation: $Action$dryRunText"
    $summaryLines += "Total Files: $totalFiles"

    $summaryText = $summaryLines -join "`r`n"

    # Create modern styled confirmation form
    $form = New-Object System.Windows.Forms.Form
    $form.Text = "FileOrganizer - Confirm Operation"
    $form.Size = New-Object System.Drawing.Size(520, 420)
    $form.StartPosition = "CenterScreen"
    $form.FormBorderStyle = "FixedDialog"
    $form.MaximizeBox = $false
    $form.MinimizeBox = $false
    $form.BackColor = [System.Drawing.Color]::FromArgb(245, 245, 250)
    $form.Font = New-Object System.Drawing.Font("Segoe UI", 10)

    # Header panel
    $headerPanel = New-Object System.Windows.Forms.Panel
    $headerPanel.Dock = "Top"
    $headerPanel.Height = 50
    $accentColor = if ($DryRun) { [System.Drawing.Color]::FromArgb(0, 120, 180) } else { [System.Drawing.Color]::FromArgb(55, 71, 133) }
    $headerPanel.BackColor = $accentColor

    $headerLabel = New-Object System.Windows.Forms.Label
    $headerText = if ($DryRun) { "  Confirm Operation (Dry Run)" } else { "  Confirm Operation" }
    $headerLabel.Text = $headerText
    $headerLabel.ForeColor = [System.Drawing.Color]::White
    $headerLabel.Font = New-Object System.Drawing.Font("Segoe UI Semibold", 14)
    $headerLabel.Dock = "Fill"
    $headerLabel.TextAlign = "MiddleLeft"
    $headerPanel.Controls.Add($headerLabel)

    # Summary text box (read-only)
    $textBox = New-Object System.Windows.Forms.TextBox
    $textBox.Location = New-Object System.Drawing.Point(20, 65)
    $textBox.Size = New-Object System.Drawing.Size(462, 240)
    $textBox.Multiline = $true
    $textBox.ReadOnly = $true
    $textBox.ScrollBars = "Vertical"
    $textBox.Font = New-Object System.Drawing.Font("Segoe UI", 9.5)
    $textBox.BackColor = [System.Drawing.Color]::White
    $textBox.BorderStyle = "FixedSingle"
    $textBox.Text = $summaryText

    # Question label
    $questionLabel = New-Object System.Windows.Forms.Label
    $questionLabel.Location = New-Object System.Drawing.Point(20, 315)
    $questionLabel.Size = New-Object System.Drawing.Size(460, 25)
    $questionLabel.Text = "Proceed with this operation?"
    $questionLabel.Font = New-Object System.Drawing.Font("Segoe UI Semibold", 10)

    # Yes button
    $yesButton = New-Object System.Windows.Forms.Button
    $yesButton.Location = New-Object System.Drawing.Point(140, 345)
    $yesButton.Size = New-Object System.Drawing.Size(110, 36)
    $yesButton.Text = "Yes, Proceed"
    $yesButton.Font = New-Object System.Drawing.Font("Segoe UI Semibold", 10)
    $yesButton.FlatStyle = "Flat"
    $yesButton.BackColor = $accentColor
    $yesButton.ForeColor = [System.Drawing.Color]::White
    $yesButton.Cursor = "Hand"
    $yesButton.DialogResult = "Yes"

    # No button
    $noButton = New-Object System.Windows.Forms.Button
    $noButton.Location = New-Object System.Drawing.Point(265, 345)
    $noButton.Size = New-Object System.Drawing.Size(110, 36)
    $noButton.Text = "Cancel"
    $noButton.Font = New-Object System.Drawing.Font("Segoe UI", 10)
    $noButton.FlatStyle = "Flat"
    $noButton.BackColor = [System.Drawing.Color]::FromArgb(220, 220, 225)
    $noButton.Cursor = "Hand"
    $noButton.DialogResult = "No"

    $form.Controls.AddRange(@($headerPanel, $textBox, $questionLabel, $yesButton, $noButton))
    $form.AcceptButton = $yesButton
    $form.CancelButton = $noButton

    $result = $form.ShowDialog()
    $form.Dispose()

    return ($result -eq "Yes")
}

function Select-DestinationMode {
    <#

    .SYNOPSIS

        Shows destination mode selection (modern styled)

    #>
    [CmdletBinding()]
    param()

    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing

    $form = New-Object System.Windows.Forms.Form
    $form.Text = "FileOrganizer - Destination Mode"
    $form.Size = New-Object System.Drawing.Size(480, 240)
    $form.StartPosition = "CenterScreen"
    $form.FormBorderStyle = "FixedDialog"
    $form.MaximizeBox = $false
    $form.MinimizeBox = $false
    $form.BackColor = [System.Drawing.Color]::FromArgb(245, 245, 250)
    $form.Font = New-Object System.Drawing.Font("Segoe UI", 10)

    $headerPanel = New-Object System.Windows.Forms.Panel
    $headerPanel.Dock = "Top"
    $headerPanel.Height = 50
    $headerPanel.BackColor = [System.Drawing.Color]::FromArgb(55, 71, 133)

    $headerLabel = New-Object System.Windows.Forms.Label
    $headerLabel.Text = "  Select Destination Mode"
    $headerLabel.ForeColor = [System.Drawing.Color]::White
    $headerLabel.Font = New-Object System.Drawing.Font("Segoe UI Semibold", 14)
    $headerLabel.Dock = "Fill"
    $headerLabel.TextAlign = "MiddleLeft"
    $headerPanel.Controls.Add($headerLabel)

    $singleRadio = New-Object System.Windows.Forms.RadioButton
    $singleRadio.Location = New-Object System.Drawing.Point(40, 70)
    $singleRadio.Size = New-Object System.Drawing.Size(400, 28)
    $singleRadio.Text = "Single Destination (all types to one folder)"
    $singleRadio.Font = New-Object System.Drawing.Font("Segoe UI", 10)
    $singleRadio.Checked = $true
    $singleRadio.FlatStyle = "Flat"

    $separateRadio = New-Object System.Windows.Forms.RadioButton
    $separateRadio.Location = New-Object System.Drawing.Point(40, 105)
    $separateRadio.Size = New-Object System.Drawing.Size(400, 28)
    $separateRadio.Text = "Separate Destination (pick folder per file type)"
    $separateRadio.Font = New-Object System.Drawing.Font("Segoe UI", 10)
    $separateRadio.FlatStyle = "Flat"

    $okButton = New-Object System.Windows.Forms.Button
    $okButton.Location = New-Object System.Drawing.Point(130, 150)
    $okButton.Size = New-Object System.Drawing.Size(100, 36)
    $okButton.Text = "OK"
    $okButton.Font = New-Object System.Drawing.Font("Segoe UI Semibold", 10)
    $okButton.FlatStyle = "Flat"
    $okButton.BackColor = [System.Drawing.Color]::FromArgb(55, 71, 133)
    $okButton.ForeColor = [System.Drawing.Color]::White
    $okButton.Cursor = "Hand"
    $okButton.DialogResult = "OK"

    $cancelButton = New-Object System.Windows.Forms.Button
    $cancelButton.Location = New-Object System.Drawing.Point(245, 150)
    $cancelButton.Size = New-Object System.Drawing.Size(100, 36)
    $cancelButton.Text = "Cancel"
    $cancelButton.Font = New-Object System.Drawing.Font("Segoe UI", 10)
    $cancelButton.FlatStyle = "Flat"
    $cancelButton.BackColor = [System.Drawing.Color]::FromArgb(220, 220, 225)
    $cancelButton.Cursor = "Hand"
    $cancelButton.DialogResult = "Cancel"

    $form.Controls.AddRange(@($headerPanel, $singleRadio, $separateRadio, $okButton, $cancelButton))
    $form.AcceptButton = $okButton
    $form.CancelButton = $cancelButton

    $result = $form.ShowDialog()
    $form.Dispose()

    if ($result -eq "OK") {
        if ($separateRadio.Checked) {
            return "Separate"
        }
    }

    return "Single"
}

#endregion

#region Core Processing Functions

function Get-FileType {
    <#

    .SYNOPSIS

        Determines file category based on extension

    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Extension
    )

    $ext = $Extension.TrimStart('.').ToLower()

    # Handle PS 5.1 (PSCustomObject) vs PS 6+ (Hashtable)
    $categories = $Script:Config.categories
    if ($categories -is [System.Collections.Hashtable]) {
        $categoryList = $categories.Keys
    }
    else {
        # PS 5.1 - convert PSObject to collection
        $categoryList = $categories.PSObject.Properties.Name
    }

    foreach ($category in $categoryList) {
        if ($categories -is [System.Collections.Hashtable]) {
            $extensions = $categories[$category]
        }
        else {
            $extensions = $categories.$category
        }
        if ($extensions -contains $ext) {
            return $category
        }
    }

    return "Others"
}

function Test-ShouldExclude {
    <#

    .SYNOPSIS

        Checks if file matches any exclude patterns

    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$FileName
    )

    # Get exclude patterns - handle PS 5.1 PSObject vs array
    $patterns = $Script:Config.excludePatterns
    if ($patterns -is [PSObject] -and $patterns -isnot [Array]) {
        $patterns = @($patterns)
    }
    if (-not $patterns) { return $false }

    foreach ($pattern in $patterns) {
        # Handle wildcard patterns
        if ($pattern.Contains("*")) {
            if ($FileName -like $pattern) {
                return $true
            }
        }
        # Handle prefix patterns like ~$ (temporary Office files)
        elseif ($pattern.StartsWith("~")) {
            if ($FileName.StartsWith($pattern)) {
                return $true
            }
        }
        # Exact match
        else {
            if ($FileName -eq $pattern) {
                return $true
            }
        }
    }

    return $false
}

function Scan-SourceFiles {
    <#

    .SYNOPSIS

        Scans source folder and returns file list with metadata

    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$SourcePath,

        [Parameter(Mandatory)]
        [int]$Depth
    )

    Write-Host "`nScanning files..." -ForegroundColor Cyan
    Write-Log "INFO" "Scanning source: $SourcePath with depth: $Depth"

    $files = @()

    try {
        # PowerShell 7+ has -Depth parameter
        if ($Script:PSVersion -ge 7) {
            $files = @(Get-ChildItem -Path $SourcePath -File -Recurse -Depth $Depth -ErrorAction SilentlyContinue)
        }
        else {
            # PowerShell 5.1 - simulate depth limit
            if ($Depth -ge 100) {
                $files = @(Get-ChildItem -Path $SourcePath -File -Recurse -ErrorAction SilentlyContinue)
            }
            else {
                # Manual depth filtering for PS 5.1
                # Normalize source path to remove trailing backslash for consistent counting
                $normalizedSource = $SourcePath.TrimEnd([IO.Path]::DirectorySeparatorChar)
                $sourceDepth = $normalizedSource.Split([IO.Path]::DirectorySeparatorChar).Count
                $files = @(Get-ChildItem -Path $SourcePath -File -Recurse -ErrorAction SilentlyContinue |
                    Where-Object {
                        $fileDepth = $_.DirectoryName.TrimEnd([IO.Path]::DirectorySeparatorChar).Split([IO.Path]::DirectorySeparatorChar).Count
                        ($fileDepth - $sourceDepth) -le $Depth
                    })
            }
        }
    }
    catch {
        $errMsg = $_.Exception.Message
        Write-Log "ERROR" "Error scanning source - $errMsg"
        throw "Failed to scan source folder - $errMsg"
    }

    # Filter out excluded files
    $filteredFiles = @()
    foreach ($file in $files) {
        if (-not (Test-ShouldExclude -FileName $file.Name)) {
            $filteredFiles += $file
        }
    }

    Write-Host "Found $($filteredFiles.Count) files (excluding $($files.Count - $filteredFiles.Count) matches)" -ForegroundColor Green

    return $filteredFiles
}

function Get-TypeSummary {
    <#

    .SYNOPSIS

        Counts files by category

    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [array]$Files
    )

    $typeCount = @{}

    foreach ($file in $Files) {
        $typeName = Get-FileType -Extension $file.Extension

        if (-not $typeCount.ContainsKey($typeName)) {
            $typeCount[$typeName] = 0
        }
        $typeCount[$typeName]++
    }

    return $typeCount
}

function Get-UniqueFileName {
    <#

    .SYNOPSIS

        Generates unique filename to avoid conflicts

    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$DestinationPath,

        [Parameter(Mandatory)]
        [string]$FileName
    )

    $fullPath = Join-Path $DestinationPath $FileName

    if (-not (Test-Path $fullPath)) {
        return $FileName
    }

    # File exists, generate unique name
    $baseName = [IO.Path]::GetFileNameWithoutExtension($FileName)
    $extension = [IO.Path]::GetExtension($FileName)

    $counter = 1
    do {
        $newName = "${baseName}_${counter}${extension}"
        $fullPath = Join-Path $DestinationPath $newName
        $counter++
    } while (Test-Path $fullPath)

    return $newName
}

function Test-Cancel {
    <#

    .SYNOPSIS

        Checks if user pressed Escape to cancel operation

    #>
    [CmdletBinding()]
    param()

    if ($Script:PSVersion -ge 7 -and [Console]::IsInputRedirected) {
        return $false
    }

    if ([Console]::KeyAvailable) {
        $key = [Console]::ReadKey($true)
        if ($key.Key -eq "Escape") {
            Write-Host "`nOperation Cancelled by user." -ForegroundColor Yellow
            Write-Log "WARN" "Operation cancelled by user"
            return $true
        }
    }
    return $false
}

#endregion

#region File Operation Functions

function Process-Files {
    <#

    .SYNOPSIS

        Main file processing loop with progress and cancellation

    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [array]$Files,

        [Parameter(Mandatory)]
        [string[]]$SelectedTypes,

        [Parameter(Mandatory)]
        [hashtable]$TypeDestinationMap,

        [Parameter(Mandatory)]
        [string]$Action,

        [bool]$DryRun,

        [bool]$CreateTypeSubfolder
    )

    $processedCount = 0
    $errorCount = 0
    $total = $Files.Count
    $index = 0

    $operationVerb = if ($Action -eq "Move") { "Moving" } else { "Copying" }
    $logAction = if ($DryRun) { "DRYRUN" } else { "INFO" }

    Write-Host "`n$operationVerb files..." -ForegroundColor $(if ($DryRun) { "Cyan" }else { "Yellow" })

    foreach ($file in $Files) {
        # Check for cancellation
        if (Test-Cancel) {
            Write-Host "`nOperation cancelled. Stopping..." -ForegroundColor Yellow
            break
        }

        $index++
        $percent = [math]::Round(($index / $total) * 100)
        Write-Progress -Activity "$operationVerb Files ($Action)" -Status "$index of $total files" -PercentComplete $percent

        # Determine file type
        $typeName = Get-FileType -Extension $file.Extension

        # Get destination path
        $baseDest = $TypeDestinationMap[$typeName]

        # Create type subfolder if enabled
        if ($CreateTypeSubfolder) {
            $destPath = Join-Path $baseDest $typeName
        }
        else {
            $destPath = $baseDest
        }

        # Create destination if it doesn't exist
        if (-not (Test-Path $destPath)) {
            try {
                New-Item -ItemType Directory -Path $destPath -Force | Out-Null
                Write-Log "INFO" "Created directory: $destPath"
            }
            catch {
                $errMsg = $_.Exception.Message
                Write-Log "ERROR" "Failed to create directory $destPath - $errMsg"
                $errorCount++
                continue
            }
        }

        # Get unique filename
        $newFileName = Get-UniqueFileName -DestinationPath $destPath -FileName $file.Name
        $newFullPath = Join-Path $destPath $newFileName

        # Perform the operation
        if ($DryRun) {
            # Dry run - just log what would happen
            Write-Log "DRYRUN" "Would $Action '$($file.FullName)' -> '$newFullPath'"
            $processedCount++
        }
        else {
            # Actual move or copy
            try {
                if ($Action -eq "Move") {
                    Move-Item -Path $file.FullName -Destination $newFullPath -Force -ErrorAction Stop
                }
                else {
                    Copy-Item -Path $file.FullName -Destination $newFullPath -Force -ErrorAction Stop
                }

                Write-Log "INFO" "$Action completed: $($file.Name) -> $newFullPath"
                $processedCount++
            }
            catch {
                $errMsg = $_.Exception.Message
                $fileName = $file.Name
                Write-Log "ERROR" "Failed to $Action '$fileName' - $errMsg"
                $errorCount++
            }
        }
    }

    Write-Progress -Activity "$operationVerb Files" -Completed

    # Return summary
    return @{
        Processed = $processedCount
        Errors    = $errorCount
    }
}

#endregion

#region Interactive Mode

function Start-InteractiveMode {
    <#

    .SYNOPSIS

        Runs the interactive GUI-based workflow

    #>
    [CmdletBinding()]
    param()

    Write-Host "`n=== FileOrganizer - Interactive Mode ===" -ForegroundColor Cyan
    Write-Host "Press ESC anytime to cancel operation`n" -ForegroundColor Gray

    # Give user a moment to see the startup
    Start-Sleep -Milliseconds 500

    # Step 1: Select source
    Write-Host "Step 1: Select Source Folder (a dialog will open)" -ForegroundColor Yellow
    Write-Host ">>> Click Browse and select a folder <<<" -ForegroundColor Magenta
    $sourceFolder = Select-SourceFolder

    if (-not $sourceFolder) {
        Write-Host "No source folder selected. Exiting." -ForegroundColor Yellow
        return
    }

    # Step 2: Select depth
    Write-Host "`nStep 2: Select Scan Depth" -ForegroundColor Yellow
    $depth = Select-DepthGUI
    Write-Host "Using depth: $depth" -ForegroundColor Gray

    # Step 3: Scan files
    $files = Scan-SourcePath -SourcePath $sourceFolder -Depth $depth

    if ($files.Count -eq 0) {
        Write-Host "No files found in source folder." -ForegroundColor Yellow
        return
    }

    # Step 4: Get type summary
    $typeCounts = Get-TypeSummary -Files $files

    # Step 5: Select types
    Write-Host "`nStep 3: Select File Types" -ForegroundColor Yellow
    $selectedTypes = Select-FileType -TypeCounts $typeCounts

    if ($selectedTypes.Count -eq 0) {
        Write-Host "No file types selected. Exiting." -ForegroundColor Yellow
        return
    }

    # Step 6: Select action (Move/Copy)
    Write-Host "`nStep 4: Select Operation" -ForegroundColor Yellow
    $action = Select-ActionMode
    Write-Host "Operation: $action" -ForegroundColor Gray

    # Step 7: Destination mode
    Write-Host "`nStep 5: Select Destination Mode" -ForegroundColor Yellow
    $destMode = Select-DestinationMode

    $typeDestinationMap = @{}

    if ($destMode -eq "Separate") {
        # Separate destination per type
        foreach ($type in $selectedTypes) {
            Write-Host "`nSelect destination for: $type" -ForegroundColor Cyan
            $dest = Select-DestinationFolder -Description "Select destination for $type"

            if (-not $dest) {
                Write-Host "Destination not selected. Using source folder." -ForegroundColor Yellow
                $dest = $sourceFolder
            }

            $typeDestinationMap[$type] = $dest
        }
    }
    else {
        # Single destination
        Write-Host "`nSelect single destination folder" -ForegroundColor Cyan
        $singleDest = Select-DestinationFolder -Description "Select destination for all files"

        if (-not $singleDest) {
            Write-Host "No destination selected. Using source folder." -ForegroundColor Yellow
            $singleDest = $sourceFolder
        }

        foreach ($type in $selectedTypes) {
            $typeDestinationMap[$type] = $singleDest
        }
    }

    # Step 8: DryRun option
    Write-Host "`nStep 6: Dry Run Mode?" -ForegroundColor Yellow
    $dryRunChoice = Read-Host "Run as Dry Run (simulate only)? y/n (default: n)"
    $dryRun = ($dryRunChoice -eq "y")

    if ($dryRun) {
        Write-Host "`n*** DRY RUN MODE - No files will be modified ***" -ForegroundColor Cyan
    }

    # Step 9: Confirm summary
    Write-Host "`nStep 7: Confirm Operation" -ForegroundColor Yellow
    $confirmed = Confirm-Summary -SourcePath $sourceFolder -SelectedTypes $selectedTypes -TypeCounts $typeCounts -Action $action -Destinations $typeDestinationMap -DryRun $dryRun

    if (-not $confirmed) {
        Write-Host "Operation cancelled by user." -ForegroundColor Yellow
        return
    }

    # Step 10: Filter files to only selected types, then process
    $filteredFiles = @($files | Where-Object {
            $typeName = Get-FileType -Extension $_.Extension
            @($selectedTypes) -contains $typeName
        })

    Write-Host "`nFiles to process: $($filteredFiles.Count) (of $($files.Count) total scanned)" -ForegroundColor Gray

    $createSubfolder = [bool]$Script:Config.createTypeSubfolder
    $result = Process-Files -Files $filteredFiles -SelectedTypes @($selectedTypes) -TypeDestinationMap $typeDestinationMap -Action $action -DryRun $dryRun -CreateTypeSubfolder $createSubfolder

    # Step 11: Show results
    Write-Host "`n=== Operation Complete ===" -ForegroundColor Green
    Write-Host "Files processed: $($result.Processed)" -ForegroundColor White

    if ($result.Errors -gt 0) {
        Write-Host "Errors: $($result.Errors)" -ForegroundColor Red
    }

    Write-Log "INFO" "Operation completed - Processed: $($result.Processed), Errors: $($result.Errors)"

    # Save last used paths on success
    if ($result.Processed -gt 0 -and -not $dryRun) {
        $firstDest = ($typeDestinationMap.Values | Select-Object -First 1)
        Save-LastUsed -SourcePath $sourceFolder -DestPath $firstDest
    }
}

function Scan-SourcePath {
    <#

    .SYNOPSIS

        Wrapper for scanning with user feedback

    #>
    [CmdletBinding()]
    param(
        [string]$SourcePath,
        [int]$Depth
    )

    return Scan-SourceFiles -SourcePath $SourcePath -Depth $Depth
}

function Start-CLIMode {
    <#

    .SYNOPSIS

        Runs the command-line interface mode with provided parameters

    #>
    [CmdletBinding()]
    param()

    Write-Host "`n=== FileOrganizer - CLI Mode ===" -ForegroundColor Cyan

    # Validate source path
    if (-not $SourcePath) {
        Write-Error "SourcePath is required in CLI mode. Use -SourcePath parameter."
        return
    }

    if (-not (Test-Path $SourcePath)) {
        Write-Error "Source path does not exist: $SourcePath"
        return
    }

    # Set default destination if not provided
    if (-not $DestPath) {
        $DestPath = $SourcePath
        Write-Host "No destination specified, using source path: $DestPath" -ForegroundColor Yellow
    }

    # Scan files
    $files = Scan-SourceFiles -SourcePath $SourcePath -Depth $Depth

    if ($files.Count -eq 0) {
        Write-Host "No files found." -ForegroundColor Yellow
        return
    }

    # Get type summary
    $typeCounts = Get-TypeSummary -Files $files

    # Show summary
    Write-Host "`nFile Type Summary:" -ForegroundColor Green
    foreach ($type in ($typeCounts.Keys | Sort-Object)) {
        Write-Host "  $type : $($typeCounts[$type]) files" -ForegroundColor White
    }

    # Determine selected types (all by default in CLI)
    $selectedTypes = $typeCounts.Keys

    # Set up destination map
    $typeDestinationMap = @{}

    if ($SeparateDestinations) {
        Write-Host "`nSeparate destinations requested but not implemented in CLI mode." -ForegroundColor Yellow
        Write-Host "Using single destination: $DestPath" -ForegroundColor Yellow
    }

    foreach ($type in $selectedTypes) {
        $typeDestinationMap[$type] = $DestPath
    }

    # Show dry run status
    if ($DryRun) {
        Write-Host "`n*** DRY RUN MODE - No files will be modified ***" -ForegroundColor Cyan
    }

    # Filter files to selected types, then process
    $filteredFiles = @($files | Where-Object {
            $typeName = Get-FileType -Extension $_.Extension
            @($selectedTypes) -contains $typeName
        })

    $createSubfolder = [bool]$Script:Config.createTypeSubfolder
    $result = Process-Files -Files $filteredFiles -TypeDestinationMap $typeDestinationMap -Action $Action -DryRun $DryRun -CreateTypeSubfolder $createSubfolder

    # Show results
    Write-Host "`n=== Operation Complete ===" -ForegroundColor Green
    Write-Host "Files processed: $($result.Processed)" -ForegroundColor White

    if ($result.Errors -gt 0) {
        Write-Host "Errors: $($result.Errors)" -ForegroundColor Red
    }

    Write-Log "INFO" "CLI operation completed - Processed: $($result.Processed), Errors: $($result.Errors)"

    # Save last used paths
    if ($result.Processed -gt 0 -and -not $DryRun) {
        Save-LastUsed -SourcePath $SourcePath -DestPath $DestPath
    }
}

#endregion

#region Main Entry Point

function Main {
    <#

    .SYNOPSIS

        Main entry point for the script

    #>
    [CmdletBinding()]
    param()

    # Initialize environment
    Initialize-Environment

    # Check if Help requested
    if ($Help) {
        Get-Help $MyInvocation.MyCommand.Path -Detailed
        return
    }

    # Determine mode: CLI or Interactive
    $isCLIMode = $SourcePath -and $DestPath

    if ($isCLIMode) {
        # Run in CLI mode
        Start-CLIMode
    }
    else {
        # Run in Interactive mode
        Start-InteractiveMode

        # Loop for additional tasks unless -NoLoop specified
        if (-not $NoLoop) {
            while ($true) {
                Write-Host "`n" -NoNewline
                $again = Read-Host "Do another task? y/n"

                if ($again -ne "y") {
                    break
                }

                Start-InteractiveMode
            }
        }
    }

    Write-Host "`nGoodbye!" -ForegroundColor Cyan
    Write-Log "INFO" "FileOrganizer ended"

    # Pause to keep window open
    Write-Host "`nPress Enter to exit..." -ForegroundColor Gray
    try { [void](Read-Host) } catch { Start-Sleep -Seconds 5 }
}

# Run main function
try {
    Main
}
catch {
    $errMsg = $_.Exception.Message
    $stackTrace = $_.ScriptStackTrace
    Write-Host "`n" -ForegroundColor Red
    Write-Host "FATAL ERROR: $errMsg" -ForegroundColor Red
    Write-Host "Stack Trace: $stackTrace" -ForegroundColor Red
    Write-Host "`nPress Enter to exit..." -ForegroundColor Yellow
    try { Read-Host } catch { Start-Sleep -Seconds 5 }
    exit 1
}

#endregion