qsv 16.1.0

A Blazing-Fast Data-wrangling toolkit.
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
static USAGE: &str = r#"
Compute a frequency distribution table on input data. It has CSV and JSON output modes.
https://en.wikipedia.org/wiki/Frequency_(statistics)#Frequency_distribution_table

In CSV output mode (default), the table is formatted as CSV data with the following
columns - field,value,count,percentage,rank.

The rank column is 1-based and is calculated based on the count of the values,
with the most frequent having a rank of 1. In case of ties, the rank is calculated
based on the rank-strategy option - "min" (default), "max", "dense", "ordinal", or "average".

Only the top N values (set by the --limit option) are computed, with the rest of the values
grouped into an "Other" category with a special rank of 0. The "Other" category includes
the count of remaining unique values that are not in the top N values.

In JSON output mode, the table is formatted as nested JSON data. In addition to
the columns above, the JSON output also includes the row count, field count, rank-strategy,
each field's data type, cardinality, nullcount, sparsity, uniqueness_ratio and its stats.

Since this command computes an exact frequency distribution table, memory proportional
to the cardinality of each column would be normally required.

However, this is problematic for columns with ALL unique values (e.g. an ID column),
as the command will need to allocate memory proportional to the column's cardinality.

To overcome this, the frequency command uses several mechanisms:

STATS CACHE:
If the stats cache exists for the input file, it is used to get column cardinality information.
This short-circuits frequency compilation for columns with all unique values (i.e. where
rowcount == cardinality), eliminating the need to maintain an in-memory hashmap for ID columns.
This allows `frequency` to handle larger-than-memory datasets with the added benefit of also
making it faster when working with datasets with ID columns.

That's why for MAXIMUM PERFORMANCE, it's HIGHLY RECOMMENDED to create an index (`qsv index data.csv`)
and pre-populate the stats cache (`qsv stats data.csv --cardinality --stats-jsonl`)
BEFORE running `frequency`.

MEMORY-AWARE CHUNKING:
When working with large datasets, memory-aware chunking is automatically enabled. Chunk size
is dynamically calculated based on available memory and record sampling.

You can override this behavior by setting the QSV_FREQ_CHUNK_MEMORY_MB environment variable.
(set to 0 for dynamic sizing, or a positive number for a fixed memory limit per chunk,
or -1 for CPU-based chunking (1 chunk = num records/number of CPUs)), or by setting the --jobs option.

NOTE: "Complete" Frequency Tables:

    By default, ID columns will have an "<ALL UNIQUE>" value with count equal to
    rowcount and percentage set to 100 with a rank of 0. This is done by using the
    stats cache to fetch each column's cardinality - allowing qsv to short-circuit
    frequency compilation and eliminate the need to maintain a hashmap for ID columns.

    If you wish to compile a "complete" frequency table even for ID columns, set
    QSV_STATSCACHE_MODE to "none". This will force the frequency command to compute
    frequencies for all columns regardless of cardinality, even for ID columns.

    In this case, the unique limit (--unq-limit) option is particularly useful when
    a column has all unique values  and --limit is set to 0.
    Without a unique limit, the frequency table for that column will be the same as
    the number of rows in the data.
    With a unique limit, the frequency table will be a sample of N unique values,
    all with a count of 1.

    The --lmt-threshold option also allows you to apply the --limit and --unq-limit
    options only when the number of unique items in a column >= threshold.
    This is useful when you want to apply limits only to columns with a large number
    of unique items and not to columns with a small number of unique items.

For examples, see https://github.com/dathere/qsv/blob/master/tests/test_frequency.rs.

Usage:
    qsv frequency [options] [<input>]
    qsv frequency --help

frequency options:
    -s, --select <arg>      Select a subset of columns to compute frequencies
                            for. See 'qsv select --help' for the format
                            details. This is provided here because piping 'qsv
                            select' into 'qsv frequency' will disable the use
                            of indexing.
    -l, --limit <arg>       Limit the frequency table to the N most common
                            items. Set to '0' to disable a limit.
                            If negative, only return values with an occurrence
                            count >= absolute value of the negative limit.
                            e.g. --limit -2 will only return values with an
                            occurrence count >= 2.
                            [default: 10]
    -u, --unq-limit <arg>   If a column has all unique values, limit the
                            frequency table to a sample of N unique items.
                            Set to '0' to disable a unique_limit.
                            [default: 10]
    --lmt-threshold <arg>   The threshold for which --limit and --unq-limit
                            will be applied. If the number of unique items
                            in a column >= threshold, the limits will be applied.
                            Set to '0' to disable the threshold and always apply limits.
                            [default: 0]
-r, --rank-strategy <arg>   The strategy to use when there are count-tied values in the frequency table.
                            See https://en.wikipedia.org/wiki/Ranking for more info.
                            Valid values are:
                              * dense: Assigns consecutive integers regardless of ties,
                                incrementing by 1 for each new count value (AKA "1223" ranking).
                              * min: Tied items receive the minimum rank position (AKA "1224" ranking).
                              * max: Tied items receive the maximum rank position (AKA "1334" ranking).
                              * ordinal: The next rank is the current rank plus 1 (AKA "1234" ranking).
                              * average: Tied items receive the average of their ordinal positions
                                (AKA "1 2.5 2.5 4" ranking).
                            Note that tied values with the same rank are sorted alphabetically.
                            [default: dense]
    --pct-dec-places <arg>  The number of decimal places to round the percentage to.
                            If negative, the number of decimal places will be set
                            automatically to the minimum number of decimal places needed
                            to represent the percentage accurately, up to the absolute
                            value of the negative number.
                            [default: -5]
    --other-sorted          By default, the "Other" category is placed at the
                            end of the frequency table for a field. If this is enabled, the
                            "Other" category will be sorted with the rest of the
                            values by count.
    --other-text <arg>      The text to use for the "Other" category. If set to "<NONE>",
                            the "Other" category will not be included in the frequency table.
                            [default: Other]
    --no-other              Don't include the "Other" category in the frequency table.
                            This is equivalent to --other-text "<NONE>".
    --null-sorted           By default, the NULL category (controlled by --null-text)
                            is placed at the end of the frequency table for a field,
                            after "Other" if present. If this is enabled, the NULL
                            category will be sorted with the rest of the values by count.
    -a, --asc               Sort the frequency tables in ascending order by count.
                            The default is descending order. Note that this option will
                            also reverse ranking - i.e. the LEAST frequent values will
                            have a rank of 1.
    --no-trim               Don't trim whitespace from values when computing frequencies.
                            The default is to trim leading and trailing whitespaces.
    --null-text <arg>       The text to use for NULL values. If set to "<NONE>",
                            NULLs will not be included in the frequency table
                            (equivalent to --no-nulls).
                            [default: (NULL)]
    --no-nulls              Don't include NULLs in the frequency table.
                            This is equivalent to --null-text "<NONE>".
    --pct-nulls             Include NULL values in percentage and rank calculations.
                            When disabled (default), percentages are "valid percentages"
                            calculated with NULLs excluded from the denominator, and
                            NULL entries display empty percentage and rank values.
                            When enabled, NULLs are included in the denominator
                            (original behavior).
                            Has no effect when --no-nulls is set.
    -i, --ignore-case       Ignore case when computing frequencies.
    --no-float <cols>       Exclude Float columns from frequency analysis.
                            Floats typically contain continuous values where
                            frequency tables are not meaningful.
                            To exclude ALL Float columns, use --no-float "*"
                            To exclude Floats except specific columns, specify
                            a comma-separated list of Float columns to INCLUDE.
                            e.g. "--no-float *" excludes all Floats
                                 "--no-float price,rate" excludes Floats
                                    except 'price' and 'rate'
                            Requires stats cache for type detection.
    --stats-filter <expr>   Filter columns based on their statistics using a Luau expression.
                            Columns where the expression evaluates to `true` are EXCLUDED.
                            Available fields: field, type, is_ascii, cardinality, nullcount,
                            sum, min, max, range, sort_order, min_length, max_length, mean,
                            stddev, variance, cv, sparsity, q1, q2_median, q3, iqr, mad,
                            skewness, mode, antimode, n_negative, n_zero, n_positive, etc.
                            e.g. "nullcount > 1000" - exclude columns with many nulls
                                 "type == 'Float'" - exclude Float columns
                                 "cardinality > 500 and nullcount > 0" - compound expression
                            Requires stats cache and the "luau" feature.
   --all-unique-text <arg>  The text to use for the "<ALL_UNIQUE>" category.
                            [default: <ALL_UNIQUE>]
    --vis-whitespace        Visualize whitespace characters in the output. See
                            https://github.com/dathere/qsv/wiki/Supplemental#whitespace-markers
                            for the list of whitespace markers.
    -j, --jobs <arg>        The number of jobs to run in parallel when the given CSV data has
                            an index. Note that a file handle is opened for each job.
                            When not set, defaults to the number of CPUs detected.

                            FREQUENCY CACHE OPTIONS:
    --frequency-jsonl       Write the complete frequency distribution as a
                            JSONL cache file (FILESTEM.freq.csv.data.jsonl).
                            Requires a non-stdin input file. The cache contains
                            metadata and per-column frequency data.
                            ALL_UNIQUE columns (rowcount == cardinality) get a single
                            ALL_UNIQUE sentinel. HIGH_CARDINALITY columns (cardinality
                            exceeds the smaller of --high-card-threshold/--high-card-pct
                            of rowcount) get a single HIGH_CARDINALITY sentinel.
                            When a valid (fresh) cache already exists, frequency will
                            automatically reuse it instead of recomputing from the CSV.
                            Use --force to regenerate the cache even when it is valid.
                            Cache is NOT used when --ignore-case, --no-trim, or --weight
                            are active, as these change how values are computed.
    --high-card-threshold <arg>  Absolute cardinality threshold for HIGH_CARDINALITY
                                 classification in the frequency cache.
                                 Can also be set with QSV_FREQ_HIGH_CARD_THRESHOLD env var
                                 (env var takes precedence when CLI value equals the default).
                                 Only used with --frequency-jsonl.
                                 [default: 100]
    --high-card-pct <arg>   Percentage of rowcount threshold for HIGH_CARDINALITY
                            classification in the frequency cache. Must be between 1 and 100.
                            Can also be set with QSV_FREQ_HIGH_CARD_PCT env var
                            (env var takes precedence when CLI value equals the default).
                            Only used with --frequency-jsonl.
                            [default: 90]
    --force                 Force recomputation and cache regeneration even when a
                            valid frequency cache exists. Use with --frequency-jsonl
                            to regenerate the cache.

                            JSON OUTPUT OPTIONS:
    --json                  Output frequency table as nested JSON instead of CSV.
                            The JSON output includes additional metadata: row count, field count,
                            data type, cardinality, null count, sparsity, uniqueness_ratio and
                            17 additional stats (e.g. sum, min, max, range, sort_order, mean, sem, etc.).
    --pretty-json           Same as --json but pretty prints the JSON output.
    --toon                  Output frequency table and select stats in TOON format instead of CSV.
                            TOON is a compact, human-readable encoding of the JSON data model for LLM prompts.
                            See https://toonformat.dev/ for more info.
    --no-stats              When using the JSON or TOON output mode, do not include the additional stats.
    --weight <column>       Compute weighted frequencies using the specified column as weights.
                            The weight column must be numeric. When specified, frequency counts
                            are multiplied by the weight value for each row. The weight column is
                            automatically excluded from frequency computation. Missing or
                            unparsable weights default to 1.0. Zero, negative, NaN and infinite
                            weights are ignored and do not contribute to frequencies.

Common options:
    -h, --help             Display this message
    -o, --output <file>    Write output to <file> instead of stdout.
    -n, --no-headers       When set, the first row will NOT be included
                           in the frequency table. Additionally, the 'field'
                           column will be 1-based indices instead of header
                           names.
    -d, --delimiter <arg>  The field delimiter for reading CSV data.
                           Must be a single character. (default: ,)
    --memcheck             Check if there is enough memory to load the entire
                           CSV into memory using CONSERVATIVE heuristics.
"#;

use std::{fs, io, str::FromStr, sync::OnceLock};

use crossbeam_channel;
use foldhash::{HashMap, HashMapExt, HashSet, HashSetExt};
use indicatif::HumanCount;
use rust_decimal::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::{self, Value as JsonValue};
use stats::{Frequencies, merge_all};
use threadpool::ThreadPool;
use toon_format::{EncodeOptions, encode};

use crate::{
    CliResult,
    cmd::stats::StatsData,
    config::{Config, Delimiter},
    index::Indexed,
    select::{SelectColumns, Selection},
    util::{self, ByteString, StatsMode, get_stats_records},
};

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RankStrategy {
    Min,
    Max,
    Dense,
    Ordinal,
    Average,
}

impl FromStr for RankStrategy {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "min" => Ok(RankStrategy::Min),
            "max" => Ok(RankStrategy::Max),
            "dense" => Ok(RankStrategy::Dense),
            "ordinal" => Ok(RankStrategy::Ordinal),
            "average" => Ok(RankStrategy::Average),
            _ => Err(format!(
                "Invalid rank-strategy: '{s}'. Valid values are: dense, min, max, ordinal, average"
            )),
        }
    }
}

#[allow(clippy::unsafe_derive_deserialize)]
#[derive(Clone, Deserialize)]
pub struct Args {
    pub arg_input:                Option<String>,
    pub flag_select:              SelectColumns,
    pub flag_limit:               isize,
    pub flag_unq_limit:           usize,
    pub flag_lmt_threshold:       usize,
    pub flag_rank_strategy:       RankStrategy,
    pub flag_pct_dec_places:      isize,
    pub flag_other_sorted:        bool,
    pub flag_other_text:          String,
    pub flag_no_other:            bool,
    pub flag_null_sorted:         bool,
    pub flag_asc:                 bool,
    pub flag_no_trim:             bool,
    pub flag_null_text:           String,
    pub flag_no_nulls:            bool,
    pub flag_pct_nulls:           bool,
    pub flag_ignore_case:         bool,
    pub flag_no_float:            Option<String>,
    #[cfg(feature = "luau")]
    pub flag_stats_filter:        Option<String>,
    pub flag_all_unique_text:     String,
    pub flag_jobs:                Option<usize>,
    pub flag_output:              Option<String>,
    pub flag_no_headers:          bool,
    pub flag_delimiter:           Option<Delimiter>,
    pub flag_memcheck:            bool,
    pub flag_vis_whitespace:      bool,
    pub flag_frequency_jsonl:     bool,
    pub flag_high_card_threshold: usize,
    pub flag_high_card_pct:       u8,
    pub flag_force:               bool,
    pub flag_json:                bool,
    pub flag_pretty_json:         bool,
    pub flag_toon:                bool,
    pub flag_no_stats:            bool,
    pub flag_weight:              Option<String>,
}

const NON_UTF8_ERR: &str = "<Non-UTF8 ERROR>";
const EMPTY_BYTE_VEC: Vec<u8> = Vec::new();

static STATS_RECORDS: OnceLock<HashMap<String, StatsData>> = OnceLock::new();
static NULL_VAL: OnceLock<Vec<u8>> = OnceLock::new();
static UNIQUE_COLUMNS_VEC: OnceLock<Vec<usize>> = OnceLock::new();
static COL_CARDINALITY_VEC: OnceLock<Vec<(String, u64)>> = OnceLock::new();
static FREQ_ROW_COUNT: OnceLock<u64> = OnceLock::new();
static FLOAT_COLUMNS_TO_SKIP: OnceLock<Vec<usize>> = OnceLock::new();
#[cfg(feature = "luau")]
static STATS_FILTER_COLUMNS_TO_SKIP: OnceLock<Vec<usize>> = OnceLock::new();
static EMPTY_VEC: Vec<(String, u64)> = Vec::new();
static EMPTY_USIZE_VEC: Vec<usize> = Vec::new();
static ALL_UNIQUE_TEXT: OnceLock<Vec<u8>> = OnceLock::new();
// Partial frequency cache: when some columns are cached but others need computation,
// FREQ_CACHE_SKIP marks which columns to skip in ftables_unweighted (true = cached),
// and FREQ_CACHE_FTABLES holds their pre-built FTables for merging after computation.
static FREQ_CACHE_SKIP: OnceLock<Vec<bool>> = OnceLock::new();
static FREQ_CACHE_FTABLES: OnceLock<FTables> = OnceLock::new();
// FrequencyCacheEntry and FrequencyCacheValue are structs for --frequency-jsonl JSON cache
#[derive(Serialize, Deserialize)]
struct FrequencyCacheEntry {
    field:       String,
    cardinality: u64,
    frequencies: Vec<FrequencyCacheValue>,
}

#[derive(Serialize, Deserialize)]
struct FrequencyCacheValue {
    value:      String,
    count:      u64,
    percentage: f64,
}

// FrequencyCacheMetadata stores how the cache was generated.
// Written as the first line of a JSONL cache file (.freq.csv.data.jsonl),
// followed by one FrequencyCacheEntry per subsequent line.
// Similar to StatsArgs in stats.rs, the metadata fields enable cache validation.
#[derive(Serialize, Deserialize)]
struct FrequencyCacheMetadata {
    arg_input:                String,
    flag_high_card_threshold: usize,
    flag_high_card_pct:       u8,
    flag_no_nulls:            bool,
    flag_no_headers:          bool,
    flag_delimiter:           String,
    record_count:             u64,
    column_count:             usize,
    date_generated:           String,
    qsv_version:              String,
}

// FrequencyEntry, FrequencyField and FrequencyOutput are
// structs for JSON output
#[derive(Serialize)]
struct FrequencyEntry {
    value:      String,
    count:      u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    percentage: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    rank:       Option<f64>,
}

#[derive(Serialize)]
struct FrequencyField {
    field:            String,
    r#type:           String,
    cardinality:      u64,
    nullcount:        u64,
    sparsity:         f64,
    uniqueness_ratio: f64,
    stats:            Vec<FieldStats>,
    frequencies:      Vec<FrequencyEntry>,
}

#[derive(Serialize, Clone)]
struct FieldStats {
    name:  String,
    value: JsonValue,
}

#[derive(Serialize)]
struct FrequencyOutput {
    input:         String,
    description:   String,
    rowcount:      u64,
    fieldcount:    usize,
    fields:        Vec<FrequencyField>,
    rank_strategy: RankStrategy,
}

// Shared frequency processing result
// used by both CSV and JSON output
#[derive(Clone)]
struct ProcessedFrequency {
    count:                u64,
    percentage:           f64,
    formatted_percentage: String,
    value:                Vec<u8>,
    rank:                 f64,
}

/// Estimates memory usage per record for frequency table computation.
///
/// This function calculates the approximate memory footprint of a single CSV record
/// when computing frequency tables. The estimate includes:
/// - Base record size (sum of field lengths)
/// - Hashmap overhead for storing unique values in Frequencies<Vec<u8>>
///
/// # Arguments
///
/// * `record` - The CSV record to estimate memory for
///
/// # Returns
///
/// Estimated memory in bytes per record
fn estimate_record_memory_for_frequency(record: &csv::ByteRecord) -> usize {
    // Base memory: sum of all field lengths
    let base_size: usize = record.iter().map(<[u8]>::len).sum();

    // Hashmap overhead: Frequencies<Vec<u8>> stores unique values
    // Each hashmap entry has overhead (~24 bytes) plus the value size
    // We estimate based on average field size
    let avg_field_size = if record.is_empty() {
        0
    } else {
        base_size / record.len()
    };

    // Estimate hashmap overhead: ~24 bytes per entry + value size
    // For frequency tables, we store each unique value once
    // Conservative estimate: assume we'll store all field values
    let hashmap_overhead = record.len() * (24 + avg_field_size);

    // Add overhead for Vec capacity
    let overhead = base_size / 4;

    base_size + hashmap_overhead + overhead
}

/// Helper function to calculate average record size from samples
fn calculate_avg_record_size_for_frequency(samples: &[csv::ByteRecord]) -> usize {
    if samples.is_empty() {
        1024 // Default: 1KB per record
    } else {
        let total_size: usize = samples
            .iter()
            .map(estimate_record_memory_for_frequency)
            .sum();
        (total_size / samples.len()).max(1024)
    }
}

/// Estimates total memory required for processing a chunk of records for frequency tables.
///
/// # Arguments
///
/// * `record_count` - Number of records in the chunk
/// * `avg_record_size` - Average size of a record in bytes
/// * `field_count` - Number of fields in the record
///
/// # Returns
///
/// Estimated total memory in bytes for the chunk
const fn estimate_chunk_memory_for_frequency(
    record_count: usize,
    avg_record_size: usize,
    field_count: usize,
) -> usize {
    // Base memory for records
    let base_memory = record_count.saturating_mul(avg_record_size);

    // Hashmap overhead: frequency tables store unique values
    // Estimate based on cardinality (assume 10% of records are unique per field)
    // Each hashmap entry: ~24 bytes overhead + value size
    let estimated_unique_per_field = if record_count / 10 > 0 {
        record_count / 10
    } else {
        1
    };
    let field_count_divisor = if field_count > 0 { field_count } else { 1 };
    let hashmap_overhead = estimated_unique_per_field
        .saturating_mul(field_count)
        .saturating_mul(avg_record_size / field_count_divisor + 24);

    // Add overhead for data structures (Frequencies objects, Vec capacity, etc.)
    // Estimate 20% overhead
    let overhead = (base_memory + hashmap_overhead) / 5;

    base_memory
        .saturating_add(hashmap_overhead)
        .saturating_add(overhead)
}

/// Calculates memory-aware chunk size for parallel frequency table processing.
///
/// This function determines an appropriate chunk size based on:
/// - Available memory per chunk (if configured)
/// - Dynamic estimation via sampling (if max_chunk_memory_mb is Some(0))
/// - CPU-based chunking (fallback)
///
/// # Arguments
///
/// * `idx_count` - Total number of records in the file
/// * `njobs` - Number of parallel jobs
/// * `max_chunk_memory_mb` - Maximum memory per chunk in MB ( None = dynamic sizing based on
///   available memory, Some(0) = dynamic sizing based on sampling, Some(n) = fixed limit)
/// * `field_count` - Number of fields in the record
/// * `sample_records` - Optional slice of sample records for dynamic sizing
///
/// # Returns
///
/// Calculated chunk size (number of records per chunk)
fn calculate_memory_aware_chunk_size_for_frequency(
    idx_count: u64,
    njobs: usize,
    max_chunk_memory_mb: Option<u64>,
    sample_records: Option<&[csv::ByteRecord]>,
) -> usize {
    // Frequency always uses memory-aware chunking since it builds hash tables.
    // This function has three configuration paths:
    //   - None: dynamic sizing based on sample records and estimated memory usage.
    //   - Some(0): dynamic sizing, also based on sample records and estimated memory usage.
    //   - Some(n): fixed memory limit per chunk.
    // In all cases, chunk size is calculated using memory-based estimates, not CPU-based chunking.
    match max_chunk_memory_mb {
        None => {
            // No memory limit configured, use dynamic sizing
            util::calculate_dynamic_chunk_size(
                idx_count,
                njobs,
                sample_records,
                estimate_record_memory_for_frequency,
            )
        },
        Some(0) => {
            // Dynamic sizing: sample records to estimate average size
            util::calculate_dynamic_chunk_size(
                idx_count,
                njobs,
                sample_records,
                estimate_record_memory_for_frequency,
            )
        },
        Some(limit_mb) => {
            // Fixed memory limit per chunk
            #[allow(clippy::cast_precision_loss)]
            let max_memory_bytes = (limit_mb as usize * 1024 * 1024) as f64 * util::SAFETY_MARGIN;

            // Estimate average record size
            // If we can't estimate, use a conservative default (1KB per record)
            let avg_record_size = if let Some(samples) = sample_records {
                if samples.is_empty() {
                    1024 // Default: 1KB per record
                } else {
                    let total_size: usize = samples
                        .iter()
                        .map(estimate_record_memory_for_frequency)
                        .sum();
                    debug_assert!(total_size > 0, "total_size should be positive here");
                    (total_size / samples.len()).max(1024) // ensure minimum 1KB estimate, samples.len() is guaranteed to be positive here
                }
            } else {
                1024 // Default: 1KB per record
            };

            // Calculate chunk size based on memory limit
            #[allow(clippy::cast_precision_loss)]
            let chunk_size = (max_memory_bytes / (avg_record_size as f64).max(1.0)) as usize;

            // Ensure chunk size is reasonable
            chunk_size.max(1).min(idx_count as usize)
        },
    }
}

pub fn run(argv: &[&str]) -> CliResult<()> {
    let mut args: Args = util::get_args(USAGE, argv)?;

    // Handle --no-other flag (alias for --other-text "<NONE>")
    if args.flag_no_other {
        args.flag_other_text = "<NONE>".to_string();
    }

    // Handle --null-text "<NONE>" (alias for --no-nulls)
    if args.flag_null_text == "<NONE>" {
        args.flag_no_nulls = true;
    }

    let mut rconfig = args.rconfig();

    let is_stdin = rconfig.is_stdin();

    // Validate --frequency-jsonl early, before any computation
    if args.flag_frequency_jsonl && is_stdin {
        return fail_clierror!("--frequency-jsonl requires a file input, not stdin.");
    }

    // if stdin and args.flag_json is true, save stdin to tempfile
    // so we can derive stats
    let mut stdin_temp_file;
    let is_json = args.flag_json || args.flag_pretty_json || args.flag_toon;
    if is_stdin && is_json {
        let temp_dir = std::env::temp_dir();
        stdin_temp_file = tempfile::Builder::new()
            .suffix(".csv")
            .tempfile_in(&temp_dir)?;
        io::copy(&mut io::stdin(), &mut stdin_temp_file)?;
        args.arg_input = Some(stdin_temp_file.path().to_string_lossy().to_string());
        rconfig = args.rconfig();
    }

    // Check if we have an index and will use parallel processing
    // If so, skip mem_file_check since memory-aware chunking will handle it
    let mut indexed_result = args.rconfig().indexed()?;
    let will_use_parallel = match &indexed_result {
        Some(_) => {
            // We have an index, check if we'll use parallel processing
            match args.flag_jobs {
                Some(num_jobs) => num_jobs != 1,
                _ => true, // Default to parallel when index exists
            }
        },
        None => false, // No index, will use sequential
    };

    // we're loading the entire file into memory, we need to check avail mem
    // Skip this check for parallel processing since memory-aware chunking handles it
    if !will_use_parallel && let Some(path) = rconfig.path.clone() {
        // Try mem_file_check, and if it fails for an unindexed file, auto-create index
        match util::mem_file_check(&path, false, args.flag_memcheck) {
            Ok(_) => {
                // Memory check passed, proceed with sequential processing
            },
            Err(e) => {
                // Memory check failed - if we don't have an index, try creating one
                if indexed_result.is_none() && !rconfig.is_stdin() {
                    log::info!(
                        "File too large for sequential processing. Auto-creating index to enable \
                         parallel processing..."
                    );

                    // Create index and retry
                    match util::create_index_for_file(&path, &rconfig) {
                        Ok(()) => {
                            // Re-check for index after creation
                            indexed_result = args.rconfig().indexed()?;
                            if indexed_result.is_some() {
                                log::info!(
                                    "Index created successfully. Switching to parallel processing."
                                );
                                // Continue - the match statement below will use
                                // indexed_result to determine parallel/sequential
                            } else {
                                // Index creation succeeded but we still can't get it
                                // Return the original memory error
                                return Err(e);
                            }
                        },
                        Err(index_err) => {
                            // Index creation failed, return the original memory error
                            log::warn!("Failed to auto-create index: {index_err}");
                            return Err(e);
                        },
                    }
                } else {
                    // Either we already have an index or it's stdin - return the error
                    return Err(e);
                }
            },
        }
    }

    // Create NULL_VAL, ALL_UNIQUE_TEXT & HIGH_CARDINALITY_TEXT once at the start to avoid
    // repeated string & vec allocations in hot loops.
    // safety: we're initializing the OnceLocks at the start of the program
    NULL_VAL
        .set(args.flag_null_text.as_bytes().to_vec())
        .unwrap();

    ALL_UNIQUE_TEXT
        .set(args.flag_all_unique_text.as_bytes().to_vec())
        .unwrap();

    if args.flag_frequency_jsonl {
        // Guard: --frequency-jsonl is incompatible with computation-changing flags
        if args.flag_ignore_case {
            return fail_incorrectusage_clierror!(
                "--frequency-jsonl cannot be used with --ignore-case."
            );
        }
        if args.flag_no_trim {
            return fail_incorrectusage_clierror!(
                "--frequency-jsonl cannot be used with --no-trim."
            );
        }
        if args.flag_weight.is_some() {
            return fail_incorrectusage_clierror!(
                "--frequency-jsonl cannot be used with --weight."
            );
        }

        // Override high-card thresholds from env vars when CLI defaults are used
        if args.flag_high_card_threshold == 100
            && let Ok(val) = std::env::var("QSV_FREQ_HIGH_CARD_THRESHOLD")
            && let Ok(parsed) = val.parse::<usize>()
        {
            args.flag_high_card_threshold = parsed;
        }
        if args.flag_high_card_pct == 90
            && let Ok(val) = std::env::var("QSV_FREQ_HIGH_CARD_PCT")
            && let Ok(parsed) = val.parse::<u8>()
        {
            args.flag_high_card_pct = parsed;
        }

        // Validate --high-card-pct is in range 1-100
        if args.flag_high_card_pct == 0 || args.flag_high_card_pct > 100 {
            return fail_incorrectusage_clierror!(
                "--high-card-pct must be between 1 and 100, got {}.",
                args.flag_high_card_pct
            );
        }
    }

    // Try to use frequency cache before computing FTables.
    // Cache is eligible when: not stdin, not JSON output, not --force,
    // and no computation-changing flags (--ignore-case, --no-trim, --weight).
    // Also skip when --no-float or --stats-filter are active (these need stats cache lookups).
    #[cfg(feature = "luau")]
    let has_stats_filter = args.flag_stats_filter.is_some();
    #[cfg(not(feature = "luau"))]
    let has_stats_filter = false;

    let can_use_freq_cache = !is_stdin
        && !is_json
        && !args.flag_force
        && !args.flag_frequency_jsonl
        && !args.flag_ignore_case
        && !args.flag_no_trim
        && args.flag_weight.is_none()
        && args.flag_no_float.is_none()
        && !has_stats_filter;

    if can_use_freq_cache && args.try_output_from_cache(&rconfig, is_json)? {
        return Ok(());
    }

    let (headers, mut tables, weighted_tables) = if let Some(idx) = indexed_result
        && util::njobs(args.flag_jobs) > 1
    {
        args.parallel_ftables(&idx)
    } else {
        args.sequential_ftables()
    }?;

    // Merge cached frequency tables for columns that were skipped during computation.
    // In the partial cache path, some columns have pre-built FTables from the frequency
    // cache (non-HIGH_CARDINALITY), while HIGH_CARDINALITY columns were computed above.
    if let (Some(cache_skip), Some(cached_ftables)) =
        (FREQ_CACHE_SKIP.get(), FREQ_CACHE_FTABLES.get())
    {
        debug_assert_eq!(
            cache_skip.len(),
            tables.len(),
            "FREQ_CACHE_SKIP length ({}) != tables length ({})",
            cache_skip.len(),
            tables.len()
        );
        debug_assert_eq!(
            cached_ftables.len(),
            tables.len(),
            "FREQ_CACHE_FTABLES length ({}) != tables length ({})",
            cached_ftables.len(),
            tables.len()
        );
        for (i, &is_cached) in cache_skip.iter().enumerate() {
            if is_cached && i < tables.len() && i < cached_ftables.len() {
                tables[i] = cached_ftables[i].clone();
            }
        }
    }

    // Write frequency cache if --frequency-jsonl is set.
    // Always write when explicitly requested — the user may be regenerating
    // with different thresholds or after data changes.
    if args.flag_frequency_jsonl {
        args.write_frequency_jsonl(&headers, &tables, &rconfig)?;
    }

    if is_json {
        return args.output_json(
            &headers,
            tables,
            weighted_tables.as_ref(),
            &rconfig,
            argv,
            is_stdin,
        );
    }

    // amortize allocations
    #[allow(unused_assignments)]
    let mut header_vec: Vec<u8> = Vec::with_capacity(tables.len());
    let mut itoa_buffer = itoa::Buffer::new();
    let mut zmij_buffer = zmij::Buffer::new();
    let mut rank_buffer = String::with_capacity(20);
    let mut row: Vec<&[u8]>;

    let head_ftables = headers.iter().zip(tables);
    let row_count = *FREQ_ROW_COUNT.get().unwrap_or(&0);
    let abs_dec_places = args.flag_pct_dec_places.unsigned_abs() as u32;

    #[allow(unused_assignments)]
    let mut processed_frequencies: Vec<ProcessedFrequency> = Vec::with_capacity(head_ftables.len());
    #[allow(unused_assignments)]
    let mut value_str = String::with_capacity(100);
    let vis_whitespace = args.flag_vis_whitespace;

    // safety: we know that UNIQUE_COLUMNS has been previously set
    // when compiling frequencies by sel_headers fn in either sequential or parallel mode
    let unique_headers_vec = UNIQUE_COLUMNS_VEC.get().unwrap();

    let mut wtr = Config::new(args.flag_output.as_ref()).writer()?;
    // write headers
    wtr.write_record(vec!["field", "value", "count", "percentage", "rank"])?;

    // Handle weighted vs unweighted frequencies
    if let Some(ref weighted) = weighted_tables {
        // Process weighted frequencies
        for (i, header) in headers.iter().enumerate() {
            header_vec = if rconfig.no_headers {
                (i + 1).to_string().into_bytes()
            } else {
                header.to_vec()
            };

            if i < weighted.len() {
                args.process_frequencies_weighted(
                    unique_headers_vec.contains(&i),
                    abs_dec_places,
                    row_count,
                    &weighted[i],
                    &mut processed_frequencies,
                );
            }

            for processed_freq in &processed_frequencies {
                // Format rank: show as integer if whole number, otherwise with decimals
                // Sentinel value -1.0 indicates NULL entry with --pct-nulls=false (empty rank)
                rank_buffer.clear();
                if processed_freq.rank >= 0.0 {
                    if processed_freq.rank.fract() == 0.0 {
                        rank_buffer.push_str(itoa_buffer.format(processed_freq.rank as u64));
                    } else {
                        rank_buffer.push_str(zmij_buffer.format(processed_freq.rank));
                    }
                }

                row = vec![
                    &*header_vec,
                    if vis_whitespace {
                        value_str = util::visualize_whitespace(&String::from_utf8_lossy(
                            &processed_freq.value,
                        ));
                        value_str.as_bytes()
                    } else {
                        &processed_freq.value
                    },
                    itoa_buffer.format(processed_freq.count).as_bytes(),
                    processed_freq.formatted_percentage.as_bytes(),
                    rank_buffer.as_bytes(),
                ];
                wtr.write_record(row)?;
            }
            processed_frequencies.clear();
        }
    } else {
        // Process unweighted frequencies (original code)
        for (i, (header, ftab)) in head_ftables.enumerate() {
            header_vec = if rconfig.no_headers {
                (i + 1).to_string().into_bytes()
            } else {
                header.to_vec()
            };

            args.process_frequencies(
                unique_headers_vec.contains(&i),
                abs_dec_places,
                row_count,
                &ftab,
                &mut processed_frequencies,
            );

            for processed_freq in &processed_frequencies {
                // Format rank: show as integer if whole number, otherwise with decimals
                // Sentinel value -1.0 indicates NULL entry with --pct-nulls=false (empty rank)
                rank_buffer.clear();
                if processed_freq.rank >= 0.0 {
                    if processed_freq.rank.fract() == 0.0 {
                        rank_buffer.push_str(itoa_buffer.format(processed_freq.rank as u64));
                    } else {
                        rank_buffer.push_str(zmij_buffer.format(processed_freq.rank));
                    }
                }

                row = vec![
                    &*header_vec,
                    if vis_whitespace {
                        value_str = util::visualize_whitespace(&String::from_utf8_lossy(
                            &processed_freq.value,
                        ));
                        value_str.as_bytes()
                    } else {
                        &processed_freq.value
                    },
                    itoa_buffer.format(processed_freq.count).as_bytes(),
                    processed_freq.formatted_percentage.as_bytes(),
                    rank_buffer.as_bytes(),
                ];
                wtr.write_record(row)?;
            }
            processed_frequencies.clear();
        }
    }
    Ok(wtr.flush()?)
}

type Headers = csv::ByteRecord;
type FTable = Frequencies<Vec<u8>>;
type FTables = Vec<Frequencies<Vec<u8>>>;
// Weighted frequency tables: HashMap for each column storing value -> weighted count
type WeightedFTables = Vec<HashMap<Vec<u8>, f64>>;

/// Apply ranking strategy to grouped unweighted frequency values (u64 counts)
///
/// # Arguments
/// * `groups` - A list of `(count, values)` pairs, where each `values` vector contains all distinct
///   values that share the same unweighted count.
/// * `strategy` - The ranking strategy to apply when assigning ranks to counts (for example, min,
///   max, dense, ordinal, or average).
/// * `pct_factor` - Multiplier used to convert counts into percentage values (typically derived
///   from the total row count).
/// * `null_val` - Byte representation used to identify or label null or missing values.
///
/// # Returns
/// A tuple `(counts_final, count_sum, pct_sum)` where:
/// * `counts_final` - The flattened list of `(value, count, percentage, rank)` tuples for each
///   grouped value after ranking.
/// * `count_sum` - The sum of all counts in `counts_final`.
/// * `pct_sum` - The sum of all percentage values in `counts_final`.
#[allow(clippy::cast_precision_loss)]
fn apply_ranking_strategy_unweighted(
    groups: Vec<(u64, Vec<Vec<u8>>)>,
    strategy: RankStrategy,
    pct_factor: f64,
    null_val: &[u8],
    pct_nulls: bool,
) -> (Vec<(Vec<u8>, u64, f64, f64)>, u64, f64) {
    let mut counts_final: Vec<(Vec<u8>, u64, f64, f64)> =
        Vec::with_capacity(groups.iter().map(|(_, group)| group.len()).sum::<usize>() + 1);
    let mut current_rank = 1.0_f64;
    let mut count_sum = 0_u64;
    let mut pct_sum = 0.0_f64;

    match strategy {
        RankStrategy::Dense => {
            // Dense ranking (1223)
            for (count, mut group) in groups {
                group.sort_unstable();
                for byte_string in group {
                    count_sum += count;

                    if byte_string.is_empty() {
                        if pct_nulls {
                            // Original behavior: include NULL in percentage
                            let pct = count as f64 * pct_factor;
                            pct_sum += pct;
                            counts_final.push((null_val.to_vec(), count, pct, current_rank));
                        } else {
                            // New behavior: exclude NULL from percentage/rank
                            // Use -1.0 as sentinel values for empty percentage and rank
                            counts_final.push((null_val.to_vec(), count, -1.0, -1.0));
                        }
                    } else {
                        let pct = count as f64 * pct_factor;
                        pct_sum += pct;
                        counts_final.push((byte_string, count, pct, current_rank));
                    }
                }
                current_rank += 1.0;
            }
        },
        RankStrategy::Min => {
            // Standard competition ranking (1224)
            for (count, mut group) in groups {
                group.sort_unstable();
                let group_len = group.len();
                for byte_string in group {
                    count_sum += count;

                    if byte_string.is_empty() {
                        if pct_nulls {
                            let pct = count as f64 * pct_factor;
                            pct_sum += pct;
                            counts_final.push((null_val.to_vec(), count, pct, current_rank));
                        } else {
                            counts_final.push((null_val.to_vec(), count, -1.0, -1.0));
                        }
                    } else {
                        let pct = count as f64 * pct_factor;
                        pct_sum += pct;
                        counts_final.push((byte_string, count, pct, current_rank));
                    }
                }
                current_rank += group_len as f64;
            }
        },
        RankStrategy::Max => {
            // Modified competition ranking (1334)
            for (count, mut group) in groups {
                group.sort_unstable();
                let group_len = group.len();
                let max_rank = current_rank + group_len as f64 - 1.0;
                for byte_string in group {
                    count_sum += count;

                    if byte_string.is_empty() {
                        if pct_nulls {
                            let pct = count as f64 * pct_factor;
                            pct_sum += pct;
                            counts_final.push((null_val.to_vec(), count, pct, max_rank));
                        } else {
                            counts_final.push((null_val.to_vec(), count, -1.0, -1.0));
                        }
                    } else {
                        let pct = count as f64 * pct_factor;
                        pct_sum += pct;
                        counts_final.push((byte_string, count, pct, max_rank));
                    }
                }
                current_rank += group_len as f64;
            }
        },
        RankStrategy::Ordinal => {
            // Ordinal ranking (1234)
            for (count, mut group) in groups {
                group.sort_unstable();
                for byte_string in group {
                    count_sum += count;

                    if byte_string.is_empty() {
                        if pct_nulls {
                            let pct = count as f64 * pct_factor;
                            pct_sum += pct;
                            counts_final.push((null_val.to_vec(), count, pct, current_rank));
                        } else {
                            counts_final.push((null_val.to_vec(), count, -1.0, -1.0));
                        }
                    } else {
                        let pct = count as f64 * pct_factor;
                        pct_sum += pct;
                        counts_final.push((byte_string, count, pct, current_rank));
                    }
                    current_rank += 1.0;
                }
            }
        },
        RankStrategy::Average => {
            // Fractional ranking (1 2.5 2.5 4)
            for (count, mut group) in groups {
                group.sort_unstable();
                let group_len = group.len();
                let avg_rank = current_rank + (group_len as f64 - 1.0) / 2.0;
                for byte_string in group {
                    count_sum += count;

                    if byte_string.is_empty() {
                        if pct_nulls {
                            let pct = count as f64 * pct_factor;
                            pct_sum += pct;
                            counts_final.push((null_val.to_vec(), count, pct, avg_rank));
                        } else {
                            counts_final.push((null_val.to_vec(), count, -1.0, -1.0));
                        }
                    } else {
                        let pct = count as f64 * pct_factor;
                        pct_sum += pct;
                        counts_final.push((byte_string, count, pct, avg_rank));
                    }
                }
                current_rank += group_len as f64;
            }
        },
    }

    (counts_final, count_sum, pct_sum)
}

/// Apply a ranking strategy to grouped weighted frequency values.
///
/// This function takes pre-aggregated weighted frequency groups and flattens them into a list
/// of individual values with their associated weight, percentage, and rank. The rank assigned
/// to each value depends on the provided `strategy`, and percentages are computed using
/// `pct_factor`. The `null_val` is treated specially as the null/other bucket when present.
///
/// # Arguments
///
/// * `groups` - A vector of tuples where each tuple contains:
///   * the total weight for the group of values (`f64`), and
///   * a vector of the grouped values (`Vec<u8>` for each value) that share that weight. Typically,
///     these groups represent distinct values with their aggregated weights after applying any
///     limiting or bucketing logic.
/// * `strategy` - The ranking strategy (`RankStrategy`) used to assign ranks to values based on
///   their weights. This controls how ties are handled (e.g., minimum, maximum, dense, ordinal, or
///   average ranks).
/// * `pct_factor` - A scaling factor used to convert weights into percentage values. For example,
///   this is often the reciprocal of the total weight so that the resulting percentages sum to
///   approximately 100.
/// * `null_val` - The byte representation of the value that should be treated as the null/other
///   bucket. This is used to identify and correctly label null/other values in the output.
///
/// # Returns
///
/// A tuple `(counts_final, count_sum, pct_sum)` where:
///
/// * `counts_final` - The flattened list of `(value, weight, percentage, rank)` tuples for each
///   grouped value after ranking has been applied.
/// * `count_sum` - The sum of all weights in `counts_final`.
/// * `pct_sum` - The sum of all percentage values in `counts_final`.
#[allow(clippy::cast_precision_loss)]
fn apply_ranking_strategy_weighted(
    groups: Vec<(f64, Vec<Vec<u8>>)>,
    strategy: RankStrategy,
    pct_factor: f64,
    null_val: &[u8],
    pct_nulls: bool,
) -> (Vec<(Vec<u8>, f64, f64, f64)>, f64, f64) {
    let mut counts_final: Vec<(Vec<u8>, f64, f64, f64)> =
        Vec::with_capacity(groups.iter().map(|(_, group)| group.len()).sum::<usize>() + 1);
    let mut current_rank = 1.0_f64;
    let mut count_sum = 0.0_f64;
    let mut pct_sum = 0.0_f64;

    match strategy {
        RankStrategy::Dense => {
            // Dense ranking (1223)
            for (weight, mut group) in groups {
                group.sort_unstable();
                for byte_string in group {
                    count_sum += weight;

                    if byte_string.is_empty() {
                        if pct_nulls {
                            let pct = weight * pct_factor;
                            pct_sum += pct;
                            counts_final.push((null_val.to_vec(), weight, pct, current_rank));
                        } else {
                            counts_final.push((null_val.to_vec(), weight, -1.0, -1.0));
                        }
                    } else {
                        let pct = weight * pct_factor;
                        pct_sum += pct;
                        counts_final.push((byte_string, weight, pct, current_rank));
                    }
                }
                current_rank += 1.0;
            }
        },
        RankStrategy::Min => {
            // Standard competition ranking (1224)
            for (weight, mut group) in groups {
                group.sort_unstable();
                let group_len = group.len();
                for byte_string in group {
                    count_sum += weight;

                    if byte_string.is_empty() {
                        if pct_nulls {
                            let pct = weight * pct_factor;
                            pct_sum += pct;
                            counts_final.push((null_val.to_vec(), weight, pct, current_rank));
                        } else {
                            counts_final.push((null_val.to_vec(), weight, -1.0, -1.0));
                        }
                    } else {
                        let pct = weight * pct_factor;
                        pct_sum += pct;
                        counts_final.push((byte_string, weight, pct, current_rank));
                    }
                }
                current_rank += group_len as f64;
            }
        },
        RankStrategy::Max => {
            // Modified competition ranking (1334)
            for (weight, mut group) in groups {
                group.sort_unstable();
                let group_len = group.len();
                let max_rank = current_rank + group_len as f64 - 1.0;
                for byte_string in group {
                    count_sum += weight;

                    if byte_string.is_empty() {
                        if pct_nulls {
                            let pct = weight * pct_factor;
                            pct_sum += pct;
                            counts_final.push((null_val.to_vec(), weight, pct, max_rank));
                        } else {
                            counts_final.push((null_val.to_vec(), weight, -1.0, -1.0));
                        }
                    } else {
                        let pct = weight * pct_factor;
                        pct_sum += pct;
                        counts_final.push((byte_string, weight, pct, max_rank));
                    }
                }
                current_rank += group_len as f64;
            }
        },
        RankStrategy::Ordinal => {
            // Ordinal ranking (1234)
            for (weight, mut group) in groups {
                group.sort_unstable();
                for byte_string in group {
                    count_sum += weight;

                    if byte_string.is_empty() {
                        if pct_nulls {
                            let pct = weight * pct_factor;
                            pct_sum += pct;
                            counts_final.push((null_val.to_vec(), weight, pct, current_rank));
                        } else {
                            counts_final.push((null_val.to_vec(), weight, -1.0, -1.0));
                        }
                    } else {
                        let pct = weight * pct_factor;
                        pct_sum += pct;
                        counts_final.push((byte_string, weight, pct, current_rank));
                    }
                    current_rank += 1.0;
                }
            }
        },
        RankStrategy::Average => {
            // Fractional ranking (1 2.5 2.5 4)
            for (weight, mut group) in groups {
                group.sort_unstable();
                let group_len = group.len();
                let avg_rank = current_rank + (group_len as f64 - 1.0) / 2.0;
                for byte_string in group {
                    count_sum += weight;

                    if byte_string.is_empty() {
                        if pct_nulls {
                            let pct = weight * pct_factor;
                            pct_sum += pct;
                            counts_final.push((null_val.to_vec(), weight, pct, avg_rank));
                        } else {
                            counts_final.push((null_val.to_vec(), weight, -1.0, -1.0));
                        }
                    } else {
                        let pct = weight * pct_factor;
                        pct_sum += pct;
                        counts_final.push((byte_string, weight, pct, avg_rank));
                    }
                }
                current_rank += group_len as f64;
            }
        },
    }

    (counts_final, count_sum, pct_sum)
}

/// Apply limits to weighted frequency counts
///
/// # Arguments
/// * `counts` - Mutable reference to vector of `(value, weight)` pairs
/// * `limit` - Limit value; if positive, keep only the top N weighted values; if negative, keep
///   only values with weight greater than or equal to the absolute value of this limit; if zero, no
///   limits are applied
/// * `lmt_threshold` - Threshold controlling when limits are applied. Limits are applied when this
///   is 0 or when it is greater than or equal to the number of unique values; when this is a
///   positive number less than the unique count, no limits are applied.
fn apply_limits_weighted(counts: &mut Vec<(Vec<u8>, f64)>, limit: isize, lmt_threshold: usize) {
    let unique_counts_len = counts.len();
    if lmt_threshold == 0 || lmt_threshold >= unique_counts_len {
        let abs_limit = limit.unsigned_abs();

        #[allow(clippy::cast_precision_loss)]
        if limit > 0 {
            counts.truncate(abs_limit);
        } else if limit < 0 {
            let count_limit = abs_limit as f64;
            counts.retain(|(_, weight)| *weight >= count_limit);
        }
    }
}

/// Apply limits to unweighted frequency counts
///
/// # Arguments
/// * `counts` - Mutable reference to counts vector
/// * `limit` - Limit value (positive = top N, negative = threshold)
/// * `unq_limit` - Unique limit for all-unique columns
/// * `lmt_threshold` - Threshold controlling when limits are applied. Limits are applied when this
///   is 0 or when it is >= the number of unique values. When this is a positive number less than
///   the unique count, no limits are applied.
/// * `all_unique` - Whether the column has all unique values
fn apply_limits_unweighted(
    counts: &mut Vec<(Vec<u8>, u64)>,
    limit: isize,
    unq_limit: usize,
    lmt_threshold: usize,
    all_unique: bool,
) {
    let unique_counts_len = counts.len();
    if lmt_threshold == 0 || lmt_threshold >= unique_counts_len {
        let abs_limit = limit.unsigned_abs();
        let unique_limited = if all_unique && limit > 0 && unq_limit != abs_limit && unq_limit > 0 {
            counts.truncate(unq_limit);
            true
        } else {
            false
        };

        if limit > 0 {
            counts.truncate(abs_limit);
        } else if limit < 0 && !unique_limited {
            // if limit < 0, only return values with an occurrence count >= abs value of limit
            // Only do this if we haven't already unique limited the values
            let count_limit = abs_limit as u64;
            counts.retain(|(_, count)| *count >= count_limit);
        }
    }
}

/// Group unweighted frequency values by count.
///
/// # Arguments
/// * `counts` - A vector of `(value, count)` pairs, where `value` is the byte-string representation
///   of the category and `count` is its frequency.
///
/// # Returns
/// A vector of `(count, values)` pairs, where `values` is the list of
/// byte-strings that share the same `count`.
fn group_by_count(counts: Vec<(Vec<u8>, u64)>) -> Vec<(u64, Vec<Vec<u8>>)> {
    let mut count_groups: Vec<(u64, Vec<Vec<u8>>)> = Vec::new();
    let mut current_count = None;
    let mut current_group = Vec::new();

    for (byte_string, count) in counts {
        if let Some(prev_count) = current_count
            && count != prev_count
            && !current_group.is_empty()
        {
            count_groups.push((prev_count, std::mem::take(&mut current_group)));
        }

        current_count = Some(count);
        current_group.push(byte_string);
    }
    if !current_group.is_empty() {
        // safety: we know that current_count is Some
        count_groups.push((current_count.unwrap(), current_group));
    }

    count_groups
}

/// Group weighted frequency values by weight (with tolerance).
///
/// # Arguments
///
/// * `counts` - A list of `(value, weight)` pairs, where `value` is a byte string and `weight` is
///   the numeric weight used for grouping. The vector is expected to be ordered by `weight` so that
///   equal (or near-equal) weights are adjacent.
/// * `tolerance` - The maximum absolute difference between consecutive weights for them to be
///   treated as belonging to the same group.
fn group_by_weight(counts: Vec<(Vec<u8>, f64)>, tolerance: f64) -> Vec<(f64, Vec<Vec<u8>>)> {
    let mut weight_groups: Vec<(f64, Vec<Vec<u8>>)> = Vec::new();
    let mut current_weight: Option<f64> = None;
    let mut current_group: Vec<Vec<u8>> = Vec::new();

    for (byte_string, weight) in counts {
        if let Some(prev_weight) = current_weight
            && (prev_weight - weight).abs() > tolerance
            && !current_group.is_empty()
        {
            weight_groups.push((prev_weight, std::mem::take(&mut current_group)));
        }

        current_weight = Some(weight);
        current_group.push(byte_string);
    }
    if !current_group.is_empty() {
        // safety: we know that current_weight is Some
        weight_groups.push((current_weight.unwrap(), current_group));
    }

    weight_groups
}

/// Implementation of helper methods for frequency command arguments.
/// Provides configuration helpers and post-processing utilities for results.
impl Args {
    pub fn rconfig(&self) -> Config {
        Config::new(self.arg_input.as_ref())
            .delimiter(self.flag_delimiter)
            .no_headers_flag(self.flag_no_headers)
            .select(self.flag_select.clone())
    }

    /// Write the complete frequency distribution as a JSON cache file
    /// (`.freq.csv.data.json`). The cache combines metadata (args,
    /// thresholds) and per-column data in a single JSON object.
    /// ALL_UNIQUE columns get a single `<ALL_UNIQUE>` sentinel entry.
    /// HIGH_CARDINALITY columns get a single `<HIGH_CARDINALITY>` sentinel entry.
    /// Normal columns get complete frequency data (all values, counts, percentages).
    #[allow(clippy::cast_precision_loss)]
    fn write_frequency_jsonl(
        &self,
        headers: &Headers,
        tables: &FTables,
        rconfig: &Config,
    ) -> CliResult<()> {
        let path = rconfig.path.as_ref().ok_or_else(|| {
            crate::CliError::Other("--frequency-jsonl requires a file input, not stdin".to_string())
        })?;

        let unique_headers = UNIQUE_COLUMNS_VEC.get().unwrap_or(&EMPTY_USIZE_VEC);
        let row_count = *FREQ_ROW_COUNT.get().unwrap_or(&0);
        if row_count == 0 {
            wwarn!(
                "--frequency-jsonl: row count is 0, skipping frequency cache (no data to cache). \
                 Run 'qsv stats --cardinality --stats-jsonl' first."
            );
            return Ok(());
        }
        let col_cardinality = COL_CARDINALITY_VEC.get().unwrap_or(&EMPTY_VEC);

        // Compute HIGH_CARDINALITY effective threshold
        #[allow(clippy::cast_precision_loss)]
        let high_card_pct_limit =
            (row_count as f64 * self.flag_high_card_pct as f64 / 100.0) as u64;
        let effective_threshold = (self.flag_high_card_threshold as u64).min(high_card_pct_limit);

        // Collect all column entries
        let mut entries: Vec<FrequencyCacheEntry> = Vec::with_capacity(headers.len());
        for (i, header) in headers.iter().enumerate() {
            let field_name = if rconfig.no_headers {
                (i + 1).to_string()
            } else {
                String::from_utf8_lossy(header).to_string()
            };

            let cardinality = col_cardinality
                .iter()
                .find(|(name, _)| name == &field_name)
                .map_or(0, |(_, card)| *card);

            let is_high_cardinality =
                !unique_headers.contains(&i) && cardinality > effective_threshold;

            let entry = if unique_headers.contains(&i) {
                // ALL_UNIQUE: single sentinel entry
                FrequencyCacheEntry {
                    field: field_name,
                    cardinality,
                    frequencies: vec![FrequencyCacheValue {
                        value:      "<ALL_UNIQUE>".to_string(),
                        count:      row_count,
                        percentage: 100.0,
                    }],
                }
            } else if is_high_cardinality {
                // HIGH_CARDINALITY: single sentinel entry
                FrequencyCacheEntry {
                    field: field_name,
                    cardinality,
                    frequencies: vec![FrequencyCacheValue {
                        value:      "<HIGH_CARDINALITY>".to_string(),
                        count:      row_count,
                        percentage: 100.0,
                    }],
                }
            } else if i < tables.len() {
                // Normal column: complete frequency data from FTable
                let ftab = &tables[i];
                let (counts_ref, total_count) = ftab.par_frequent(false); // descending
                let pct_factor = if total_count > 0 {
                    100.0 / total_count as f64
                } else {
                    0.0
                };

                let frequencies: Vec<FrequencyCacheValue> = counts_ref
                    .into_iter()
                    .map(|(value, count)| {
                        // Use empty string for null values in the cache so we can
                        // round-trip: FTable vec![] → cache "" → read vec![]
                        let val_str = if value.is_empty() {
                            String::new()
                        } else {
                            String::from_utf8_lossy(value).to_string()
                        };
                        FrequencyCacheValue {
                            value: val_str,
                            count,
                            percentage: count as f64 * pct_factor,
                        }
                    })
                    .collect();

                FrequencyCacheEntry {
                    field: field_name,
                    cardinality,
                    frequencies,
                }
            } else {
                continue;
            };

            entries.push(entry);
        }

        // Build metadata struct (written as first JSONL line)
        let metadata = FrequencyCacheMetadata {
            arg_input:                self.arg_input.clone().unwrap_or_default(),
            flag_high_card_threshold: self.flag_high_card_threshold,
            flag_high_card_pct:       self.flag_high_card_pct,
            flag_no_nulls:            self.flag_no_nulls,
            flag_no_headers:          self.flag_no_headers,
            flag_delimiter:           self
                .flag_delimiter
                .as_ref()
                .map_or_else(|| ",".to_string(), |d| (d.as_byte() as char).to_string()),
            record_count:             row_count,
            column_count:             headers.len(),
            date_generated:           chrono::Utc::now().to_rfc3339(),
            qsv_version:              env!("CARGO_PKG_VERSION").to_string(),
        };
        let num_cache_columns = entries.len();

        // Serialize as JSONL: metadata line + one entry per line
        let mut jsonl = String::with_capacity(entries.len() * 100 + 500); // rough estimate
        jsonl.push_str(&serde_json::to_string(&metadata)?);
        jsonl.push('\n');
        for entry in &entries {
            jsonl.push_str(&serde_json::to_string(entry)?);
            jsonl.push('\n');
        }

        let cache_path = path.with_extension("freq.csv.data.jsonl");
        let cache_len = jsonl.len();
        fs::write(&cache_path, jsonl)?;

        winfo!(
            "Frequency cache written: {} ({} bytes, {} columns, {} rows).",
            cache_path.display(),
            cache_len,
            num_cache_columns,
            row_count
        );

        Ok(())
    }

    /// Read and validate the frequency JSONL cache file.
    /// Returns None if cache doesn't exist, is stale, or is incompatible.
    fn read_frequency_cache(&self, rconfig: &Config) -> Option<Vec<FrequencyCacheEntry>> {
        use filetime::FileTime;

        let path = rconfig.path.as_ref()?;
        let cache_path = path.with_extension("freq.csv.data.jsonl");

        if !cache_path.exists() {
            log::info!("Frequency cache not found: {}", cache_path.display());
            return None;
        }

        // Compare mtime: cache must be newer than source CSV
        let csv_metadata = fs::metadata(path).ok()?;
        let cache_metadata = fs::metadata(&cache_path).ok()?;
        let csv_mtime = FileTime::from_last_modification_time(&csv_metadata);
        let cache_mtime = FileTime::from_last_modification_time(&cache_metadata);

        if cache_mtime <= csv_mtime {
            winfo!(
                "Frequency cache is stale (older than source CSV). Recomputing. Use \
                 --frequency-jsonl to regenerate."
            );
            return None;
        }

        // Read JSONL cache: line 1 = metadata, remaining lines = entries
        let jsonl_content = fs::read_to_string(&cache_path).ok()?;
        let mut lines = jsonl_content.lines();

        let metadata_line = lines.next()?;
        let metadata: FrequencyCacheMetadata = serde_json::from_str(metadata_line)
            .map_err(|e| {
                wwarn!("Failed to deserialize frequency cache metadata: {e}");
                e
            })
            .ok()?;

        let mut entries = Vec::new();
        for line in lines {
            if line.is_empty() {
                continue;
            }
            let entry: FrequencyCacheEntry = serde_json::from_str(line)
                .map_err(|e| {
                    wwarn!("Failed to deserialize frequency cache entry: {e}");
                    e
                })
                .ok()?;
            entries.push(entry);
        }

        // Validate cache args compatibility
        // flag_no_nulls affects what's stored in the FTable — mismatch means
        // cache has wrong null counts
        if metadata.flag_no_nulls != self.flag_no_nulls {
            winfo!(
                "Frequency cache incompatible: --no-nulls differs (cache={}, current={}). \
                 Recomputing.",
                metadata.flag_no_nulls,
                self.flag_no_nulls
            );
            return None;
        }
        // flag_no_headers affects column naming in the cache
        if metadata.flag_no_headers != self.flag_no_headers {
            winfo!(
                "Frequency cache incompatible: --no-headers differs (cache={}, current={}). \
                 Recomputing.",
                metadata.flag_no_headers,
                self.flag_no_headers
            );
            return None;
        }
        // flag_delimiter affects how values are parsed — mismatch means
        // cache has values split on different boundaries
        let current_delimiter = self
            .flag_delimiter
            .as_ref()
            .map_or_else(|| ",".to_string(), |d| (d.as_byte() as char).to_string());
        if metadata.flag_delimiter != current_delimiter {
            winfo!(
                "Frequency cache incompatible: --delimiter differs (cache={:?}, current={:?}). \
                 Recomputing.",
                metadata.flag_delimiter,
                current_delimiter
            );
            return None;
        }
        // Threshold differences don't invalidate the cache — the partial cache
        // mechanism handles the mismatch gracefully:
        //   - If the current threshold is MORE lenient (higher) than the cache, columns cached as
        //     HIGH_CARDINALITY will be recomputed via parallel computation.
        //   - If the current threshold is STRICTER (lower) than the cache, columns cached with full
        //     data will still be served from cache even though they would now be classified as
        //     HIGH_CARDINALITY. This is intentional: the cached data is correct and complete, just
        //     more detailed than the current threshold would produce on a fresh run. The threshold
        //     only controls which columns get full data vs a sentinel during cache *generation*,
        //     not reads.
        if metadata.flag_high_card_threshold != self.flag_high_card_threshold
            || metadata.flag_high_card_pct != self.flag_high_card_pct
        {
            log::info!(
                "Frequency cache threshold differs: cache=(threshold={}, pct={}), \
                 current=(threshold={}, pct={}). Partial cache still valid.",
                metadata.flag_high_card_threshold,
                metadata.flag_high_card_pct,
                self.flag_high_card_threshold,
                self.flag_high_card_pct,
            );
        }

        if entries.is_empty() {
            return None;
        }

        Some(entries)
    }

    /// Try to produce output directly from the frequency cache.
    /// Returns Ok(true) if output was produced from cache, Ok(false) if cache
    /// was not usable and normal computation should proceed.
    ///
    /// When all selected columns have cached data, FTables are reconstructed via
    /// `increment_by` and output is produced directly (full cache hit).
    ///
    /// When some columns have HIGH_CARDINALITY sentinels (no cached data), sets up a
    /// partial cache: pre-builds FTables for cached columns into FREQ_CACHE_FTABLES
    /// and marks them in FREQ_CACHE_SKIP. Returns Ok(false) so the normal parallel
    /// computation runs, but `ftables_unweighted` skips the cached columns (same
    /// pattern as ALL_UNIQUE skip). After computation, `run()` merges the cached
    /// FTables back into the result.
    #[allow(clippy::cast_precision_loss)]
    fn try_output_from_cache(&self, rconfig: &Config, is_json: bool) -> CliResult<bool> {
        // Read and validate the cache
        let Some(cache_entries) = self.read_frequency_cache(rconfig) else {
            return Ok(false);
        };

        // Read CSV headers to resolve --select
        let mut rdr = rconfig.reader()?;
        let full_headers = rdr.byte_headers()?.clone();

        // Safety net: can_use_freq_cache already guards flag_weight.is_none(),
        // but keep a runtime check because the selection below does not
        // exclude the weight column. If the guard in can_use_freq_cache is
        // ever loosened, this prevents silently including the weight column
        // in frequency output.
        if self.flag_weight.is_some() {
            return Ok(false);
        }
        let sel = self.rconfig().selection(&full_headers)?;
        let selected_headers: csv::ByteRecord = sel.select(&full_headers).collect();

        let selected_col_names: Vec<String> = selected_headers
            .iter()
            .map(|h| {
                if rconfig.no_headers {
                    String::new() // handled by index below
                } else {
                    String::from_utf8_lossy(h).to_string()
                }
            })
            .collect();

        // Build a map from field name to cache entry for quick lookup
        let cache_map: foldhash::HashMap<&str, &FrequencyCacheEntry> = cache_entries
            .iter()
            .map(|e| (e.field.as_str(), e))
            .collect();

        // Filter cache entries to selected columns, preserving selection order
        let mut selected_entries: Vec<&FrequencyCacheEntry> =
            Vec::with_capacity(selected_col_names.len());

        if rconfig.no_headers {
            // With no-headers, columns are 1-based indices
            for (i, _) in selected_headers.iter().enumerate() {
                let col_name = (i + 1).to_string();
                if let Some(entry) = cache_map.get(col_name.as_str()) {
                    selected_entries.push(entry);
                } else {
                    log::info!("Column '{col_name}' not found in frequency cache, falling back");
                    return Ok(false);
                }
            }
        } else {
            for col_name in &selected_col_names {
                if let Some(entry) = cache_map.get(col_name.as_str()) {
                    selected_entries.push(entry);
                } else {
                    log::info!("Column '{col_name}' not found in frequency cache, falling back");
                    return Ok(false);
                }
            }
        }

        // Check if any selected column has HIGH_CARDINALITY sentinel.
        // If so, set up a partial cache: pre-build FTables for columns with actual
        // cached data, and let the parallel computation handle only the
        // HIGH_CARDINALITY columns (which have no data in the cache).
        let has_high_cardinality = selected_entries.iter().any(|entry| {
            entry.frequencies.len() == 1 && entry.frequencies[0].value == "<HIGH_CARDINALITY>"
        });

        if has_high_cardinality {
            let mut skip_vec: Vec<bool> = Vec::with_capacity(selected_entries.len());
            let mut cached_ftables: FTables = Vec::with_capacity(selected_entries.len());

            for entry in &selected_entries {
                let is_sentinel = entry.frequencies.len() == 1
                    && (entry.frequencies[0].value == "<HIGH_CARDINALITY>"
                        || entry.frequencies[0].value == "<ALL_UNIQUE>");

                if is_sentinel {
                    // No actual data in cache — needs computation (or ALL_UNIQUE skip)
                    skip_vec.push(false);
                    cached_ftables.push(Frequencies::with_capacity(1));
                } else {
                    // Reconstruct FTable from cached data
                    skip_vec.push(true);
                    let mut ftab: FTable = Frequencies::with_capacity(entry.frequencies.len());
                    for freq_val in &entry.frequencies {
                        let key: Vec<u8> = if freq_val.value.is_empty() {
                            Vec::new()
                        } else {
                            freq_val.value.as_bytes().to_vec()
                        };
                        ftab.increment_by(key, freq_val.count);
                    }
                    cached_ftables.push(ftab);
                }
            }

            let cached_count = skip_vec.iter().filter(|&&s| s).count();
            winfo!(
                "Partial frequency cache hit: {cached_count}/{} columns from cache, {} need \
                 computation.",
                skip_vec.len(),
                skip_vec.len() - cached_count,
            );

            if FREQ_CACHE_SKIP.set(skip_vec).is_err() {
                log::warn!("FREQ_CACHE_SKIP already set — stale partial cache may be used");
            }
            if FREQ_CACHE_FTABLES.set(cached_ftables).is_err() {
                log::warn!("FREQ_CACHE_FTABLES already set — stale partial cache may be used");
            }
            return Ok(false);
        }

        // Derive row_count from cache: sum counts of first non-ALL_UNIQUE column,
        // or use cardinality of an ALL_UNIQUE column
        let row_count = selected_entries
            .iter()
            .find_map(|entry| {
                if entry.frequencies.len() == 1 && entry.frequencies[0].value == "<ALL_UNIQUE>" {
                    Some(entry.cardinality)
                } else {
                    let total: u64 = entry.frequencies.iter().map(|f| f.count).sum();
                    if total > 0 { Some(total) } else { None }
                }
            })
            .unwrap_or(0);

        if row_count == 0 {
            return Ok(false);
        }

        // Initialize OnceLocks that the output pipeline needs
        NULL_VAL
            .get()
            .expect("NULL_VAL should already be set in run()");

        if FREQ_ROW_COUNT.set(row_count).is_err() {
            log::warn!("FREQ_ROW_COUNT already set — stale row count may be used");
        }

        // Build unique columns vec: columns where cache has ALL_UNIQUE sentinel
        let unique_columns: Vec<usize> = selected_entries
            .iter()
            .enumerate()
            .filter(|(_, entry)| {
                entry.frequencies.len() == 1 && entry.frequencies[0].value == "<ALL_UNIQUE>"
            })
            .map(|(i, _)| i)
            .collect();
        if UNIQUE_COLUMNS_VEC.set(unique_columns).is_err() {
            log::warn!("UNIQUE_COLUMNS_VEC already set — stale unique columns may be used");
        }

        // Reconstruct FTables from cache using increment_by
        let mut tables: FTables = Vec::with_capacity(selected_entries.len());
        for entry in &selected_entries {
            if entry.frequencies.len() == 1 && entry.frequencies[0].value == "<ALL_UNIQUE>" {
                // ALL_UNIQUE: push empty FTable, process_frequencies handles the sentinel
                tables.push(Frequencies::with_capacity(1));
                continue;
            }
            let mut ftab: FTable = Frequencies::with_capacity(entry.frequencies.len());
            for freq_val in &entry.frequencies {
                // Convert empty string back to empty vec (null representation)
                let key: Vec<u8> = if freq_val.value.is_empty() {
                    Vec::new()
                } else {
                    freq_val.value.as_bytes().to_vec()
                };
                ftab.increment_by(key, freq_val.count);
            }
            tables.push(ftab);
        }

        // Now produce output using the existing pipeline
        // can_use_freq_cache already guards !is_json, so this is unreachable
        debug_assert!(!is_json, "try_output_from_cache called with JSON mode");

        // CSV output mode — reuse the existing output loop
        let abs_dec_places = self.flag_pct_dec_places.unsigned_abs() as u32;
        // safety: we just set UNIQUE_COLUMNS_VEC above
        let unique_headers_vec = UNIQUE_COLUMNS_VEC.get().unwrap();

        let mut wtr = Config::new(self.flag_output.as_ref()).writer()?;
        wtr.write_record(vec!["field", "value", "count", "percentage", "rank"])?;

        let mut header_vec: Vec<u8>;
        let mut itoa_buffer = itoa::Buffer::new();
        let mut zmij_buffer = zmij::Buffer::new();
        let mut rank_buffer = String::with_capacity(20);
        let mut row: Vec<&[u8]>;
        let mut processed_frequencies: Vec<ProcessedFrequency> =
            Vec::with_capacity(selected_entries.len());
        #[allow(unused_assignments)]
        let mut value_str = String::with_capacity(100);
        let vis_whitespace = self.flag_vis_whitespace;

        let head_ftables = selected_headers.iter().zip(tables);
        for (i, (header, ftab)) in head_ftables.enumerate() {
            header_vec = if rconfig.no_headers {
                (i + 1).to_string().into_bytes()
            } else {
                header.to_vec()
            };

            self.process_frequencies(
                unique_headers_vec.contains(&i),
                abs_dec_places,
                row_count,
                &ftab,
                &mut processed_frequencies,
            );

            for processed_freq in &processed_frequencies {
                rank_buffer.clear();
                if processed_freq.rank >= 0.0 {
                    if processed_freq.rank.fract() == 0.0 {
                        rank_buffer.push_str(itoa_buffer.format(processed_freq.rank as u64));
                    } else {
                        rank_buffer.push_str(zmij_buffer.format(processed_freq.rank));
                    }
                }

                row = vec![
                    &*header_vec,
                    if vis_whitespace {
                        value_str = util::visualize_whitespace(&String::from_utf8_lossy(
                            &processed_freq.value,
                        ));
                        value_str.as_bytes()
                    } else {
                        &processed_freq.value
                    },
                    itoa_buffer.format(processed_freq.count).as_bytes(),
                    processed_freq.formatted_percentage.as_bytes(),
                    rank_buffer.as_bytes(),
                ];
                wtr.write_record(row)?;
            }
            processed_frequencies.clear();
        }
        wtr.flush()?;

        winfo!("Frequency cache hit: output produced from cache.");
        Ok(true)
    }

    /// Helper to move "Other" category to end if not sorted
    fn move_other_to_end_if_needed<T>(&self, counts: &mut [(Vec<u8>, T, f64, f64)]) {
        let other_prefix = format!("{} (", self.flag_other_text);
        let other_prefix_bytes = other_prefix.as_bytes();
        if !self.flag_other_sorted
            && counts
                .first()
                .is_some_and(|(value, _, _, _)| value.starts_with(other_prefix_bytes))
        {
            counts.rotate_left(1);
        }
    }

    /// Helper to move NULL category to end if not sorted.
    /// Unlike `move_other_to_end_if_needed()` which only checks position 0 (since "Other" always
    /// has rank 0 and appears first in ascending sort), NULL can appear anywhere based on its
    /// count, so we need to search the entire list.
    /// This function handles multiple NULL entries (e.g., when literal "(NULL)" values exist
    /// in the data alongside empty strings that are converted to "(NULL)").
    fn move_null_to_end_if_needed<T: Copy>(&self, counts: &mut Vec<(Vec<u8>, T, f64, f64)>) {
        if self.flag_null_sorted {
            return;
        }
        // safety: NULL_VAL is set in run()
        let null_val = NULL_VAL.get().unwrap();
        // Collect all NULL entries
        let mut null_entries = Vec::new();
        let mut i = 0;
        while i < counts.len() {
            if counts[i].0 == *null_val {
                null_entries.push(counts.remove(i));
            } else {
                i += 1;
            }
        }
        // Append all NULL entries at the end
        counts.extend(null_entries);
    }

    /// Process weighted frequencies
    fn process_frequencies_weighted(
        &self,
        all_unique_header: bool, /* Indicates the column has all-unique values (e.g., an ID
                                  * column). For all-unique columns, show a single <ALL_UNIQUE>
                                  * entry with the sum of all weights. */
        abs_dec_places: u32,
        _row_count: u64,
        weighted_map: &HashMap<Vec<u8>, f64>,
        processed_frequencies: &mut Vec<ProcessedFrequency>,
    ) {
        if all_unique_header {
            // For all-unique headers with weighted frequencies, create a single entry
            // with the sum of all weights
            let total_weight: f64 = weighted_map.values().sum();
            // Skip emitting an all-unique entry if the total weight is non-finite (NaN or infinity)
            // to avoid producing a misleading count, consistent with the non-all-unique path
            // where non-finite weights are skipped entirely.
            if !total_weight.is_finite() {
                return;
            }
            #[allow(clippy::cast_precision_loss)]
            let count = total_weight.clamp(0.0, u64::MAX as f64).round() as u64;
            processed_frequencies.push(ProcessedFrequency {
                value: ALL_UNIQUE_TEXT.get().unwrap().clone(),
                count,
                percentage: 100.0,
                formatted_percentage: self.format_percentage(100.0, abs_dec_places),
                rank: 0.0, // Rank 0 for all-unique headers
            });
            return;
        }

        // For non-all-unique columns, process individual weighted values
        let mut counts_to_process = self.counts_weighted(weighted_map);
        self.move_other_to_end_if_needed(&mut counts_to_process);
        self.move_null_to_end_if_needed(&mut counts_to_process);

        // Convert to processed frequencies (count is f64, convert to u64 for display)
        for (value, weight, percentage, rank) in counts_to_process {
            // Skip non-finite weights (NaN or infinity) to avoid emitting misleading zero-count
            // rows.
            if !weight.is_finite() {
                continue;
            }
            #[allow(clippy::cast_precision_loss)]
            let count = weight.clamp(0.0, u64::MAX as f64).round() as u64;
            processed_frequencies.push(ProcessedFrequency {
                value,
                count,
                percentage,
                formatted_percentage: self.format_percentage(percentage, abs_dec_places),
                rank,
            });
        }
    }

    /// Shared frequency processing function used by both CSV and JSON output
    fn process_frequencies(
        &self,
        all_unique_header: bool,
        abs_dec_places: u32,
        row_count: u64,
        ftab: &FTable,
        processed_frequencies: &mut Vec<ProcessedFrequency>,
    ) {
        if all_unique_header {
            // For all-unique headers, create a single entry
            processed_frequencies.push(ProcessedFrequency {
                value:                ALL_UNIQUE_TEXT.get().unwrap().clone(),
                count:                row_count,
                percentage:           100.0,
                formatted_percentage: self.format_percentage(100.0, abs_dec_places),
                rank:                 0.0, // Rank 0 for all-unique headers
            });
        } else {
            // Process regular frequencies
            let mut counts_to_process = self.counts(ftab);
            self.move_other_to_end_if_needed(&mut counts_to_process);
            self.move_null_to_end_if_needed(&mut counts_to_process);

            // Convert to processed frequencies
            for (value, count, percentage, rank) in counts_to_process {
                processed_frequencies.push(ProcessedFrequency {
                    value,
                    count,
                    percentage,
                    formatted_percentage: self.format_percentage(percentage, abs_dec_places),
                    rank,
                });
            }
        }
    }

    /// Format percentage with proper decimal places
    fn format_percentage(&self, percentage: f64, abs_dec_places: u32) -> String {
        // Sentinel value -1.0 indicates NULL entry with --pct-nulls=false
        if percentage < 0.0 {
            return String::new();
        }
        let pct_decimal = Decimal::from_f64(percentage).unwrap_or_default();
        let pct_scale = if self.flag_pct_dec_places < 0 {
            let current_scale = pct_decimal.scale();
            current_scale.max(abs_dec_places)
        } else {
            abs_dec_places
        };
        let final_pct_decimal = pct_decimal
            .round_dp_with_strategy(
                pct_scale,
                rust_decimal::RoundingStrategy::MidpointAwayFromZero,
            )
            .normalize();
        // Optimize: Check scale directly instead of converting to string for length check
        if final_pct_decimal.scale() > abs_dec_places {
            final_pct_decimal
                .round_dp_with_strategy(abs_dec_places, RoundingStrategy::MidpointAwayFromZero)
                .normalize()
                .to_string()
        } else {
            final_pct_decimal.to_string()
        }
    }

    /// Process weighted frequencies from HashMap and return same format as counts()
    #[allow(clippy::cast_precision_loss)]
    fn counts_weighted(
        &self,
        weighted_map: &HashMap<Vec<u8>, f64>,
    ) -> Vec<(ByteString, f64, f64, f64)> {
        // Convert HashMap to Vec and sort
        let mut counts: Vec<(Vec<u8>, f64)> =
            weighted_map.iter().map(|(k, v)| (k.clone(), *v)).collect();

        // Sort by count (weight), breaking ties by value for deterministic output
        if self.flag_asc {
            counts.sort_unstable_by(|a, b| {
                a.1.partial_cmp(&b.1)
                    .unwrap_or(std::cmp::Ordering::Equal)
                    .then_with(|| a.0.cmp(&b.0))
            });
        } else {
            counts.sort_unstable_by(|a, b| {
                b.1.partial_cmp(&a.1)
                    .unwrap_or(std::cmp::Ordering::Equal)
                    .then_with(|| a.0.cmp(&b.0))
            });
        }

        // Calculate total weight (sum of all weights)
        let total_weight: f64 = weighted_map.values().sum();

        // When --pct-nulls is false, extract NULL entries before ranking
        // so that non-NULL values get correct ranks (excluding NULLs from ranking)
        let null_entry = if self.flag_pct_nulls {
            None
        } else {
            counts
                .iter()
                .position(|(k, _)| k.is_empty())
                .map(|pos| counts.remove(pos))
        };

        // Calculate NULL weight for adjusted percentage
        let null_weight = null_entry.as_ref().map_or(0.0, |(_, w)| *w);

        // Apply limits
        let unique_counts_len = counts.len();
        apply_limits_weighted(&mut counts, self.flag_limit, self.flag_lmt_threshold);

        // Calculate pct_factor: when --pct-nulls is false, exclude NULLs from denominator
        let adjusted_total = total_weight - null_weight;
        let pct_factor = if adjusted_total > 0.0 {
            100.0_f64 / adjusted_total
        } else {
            0.0_f64
        };

        // Compute tolerance once before the loop (outside hot path)
        // Use stats cache if available to determine weight scale for more accurate tolerance
        let weight_tolerance = if let Some(ref weight_col) = self.flag_weight {
            STATS_RECORDS
                .get()
                .and_then(|records| records.get(weight_col))
                .and_then(|stats| {
                    // Prefer stddev as it represents the scale of variation
                    // Fall back to range or mean if stddev not available
                    stats
                        .stddev
                        .or(stats.range)
                        .or(stats.mean)
                        .filter(|&s| s > 0.0)
                })
                // Use a scale-aware tolerance with a minimum absolute epsilon to handle
                // both small and large weight scales robustly.
                .map_or(f64::EPSILON, |scale| (scale * 1e-6).max(1e-10))
        } else {
            f64::EPSILON
        };

        // Group by weight to handle ties
        let weight_groups = group_by_weight(counts, weight_tolerance);

        // safety: NULL_VAL is set in the main function
        let null_val = NULL_VAL.get().unwrap();

        // Apply ranking strategy (NULLs already removed when pct_nulls is false)
        let (mut counts_final, count_sum, pct_sum) = apply_ranking_strategy_weighted(
            weight_groups,
            self.flag_rank_strategy,
            pct_factor,
            null_val,
            self.flag_pct_nulls,
        );

        // Add NULL entry back with sentinel values when --pct-nulls is false
        // Insert at the correct sorted position based on weight to preserve sort order
        if let Some((_, null_weight_val)) = null_entry {
            let null_entry_final = (null_val.to_vec(), null_weight_val, -1.0, -1.0);
            // Find the correct insertion position based on weight (descending or ascending)
            let insert_pos = if self.flag_asc {
                // Ascending: find first position where weight > null_weight
                counts_final
                    .iter()
                    .position(|(_, w, _, _)| *w > null_weight_val)
                    .unwrap_or(counts_final.len())
            } else {
                // Descending: find first position where weight < null_weight
                counts_final
                    .iter()
                    .position(|(_, w, _, _)| *w < null_weight_val)
                    .unwrap_or(counts_final.len())
            };
            counts_final.insert(insert_pos, null_entry_final);
        }

        // Calculate "Other" category
        // When NULL was extracted, adjust calculations to exclude it
        let (adjusted_other_weight, adjusted_unique_len) = if null_weight > 0.0 {
            // Subtract null_weight from other_weight since NULL is handled separately
            (
                total_weight - count_sum - null_weight,
                unique_counts_len.saturating_sub(1), // NULL was removed from counts
            )
        } else {
            (total_weight - count_sum, unique_counts_len)
        };

        // When NULL was extracted and re-added, don't count it as a "shown" entry
        // because it's separate from the top-k values
        let shown_count = if null_weight > 0.0 {
            counts_final.len().saturating_sub(1)
        } else {
            counts_final.len()
        };
        let other_unique_count = adjusted_unique_len.saturating_sub(shown_count);
        // Only create Other entry if there are actually remaining unique values
        // and the weight is positive. This prevents "Other (0)" entries when
        // --limit 0 is used and all values are included.
        // Use 100.0 - pct_sum to ensure percentages sum exactly to 100%,
        // handling floating-point precision issues consistently with unweighted case.
        if adjusted_other_weight > 0.0 && other_unique_count > 0 && self.flag_other_text != "<NONE>"
        {
            counts_final.push((
                format!(
                    "{} ({})",
                    self.flag_other_text,
                    HumanCount(other_unique_count as u64)
                )
                .as_bytes()
                .to_vec(),
                adjusted_other_weight,
                100.0_f64 - pct_sum,
                0.0,
            ));
        }

        counts_final
    }

    #[inline]
    fn counts(&self, ftab: &FTable) -> Vec<(ByteString, u64, f64, f64)> {
        let (counts_ref, total_count) = if self.flag_asc {
            // parallel sort in ascending order - least frequent values first
            ftab.par_frequent(true)
        } else {
            // parallel sort in descending order - most frequent values first
            ftab.par_frequent(false)
        };

        // Convert references to owned values
        let mut counts: Vec<(Vec<u8>, u64)> = counts_ref
            .into_iter()
            .map(|(k, v)| (k.clone(), v))
            .collect();

        // check if we need to apply limits
        let unique_counts_len = counts.len();
        let all_unique = if unique_counts_len > 0 {
            counts[if self.flag_asc {
                unique_counts_len - 1
            } else {
                0
            }]
            .1 == 1
        } else {
            false
        };

        // When --pct-nulls is false, extract NULL entries before ranking
        // so that non-NULL values get correct ranks (excluding NULLs from ranking)
        let null_entry = if self.flag_pct_nulls {
            None
        } else {
            // Find and remove NULL entry from counts
            counts
                .iter()
                .position(|(k, _)| k.is_empty())
                .map(|pos| counts.remove(pos))
        };

        // Calculate NULL count for adjusted percentage
        let null_count = null_entry.as_ref().map_or(0, |(_, c)| *c);

        // Apply limits (including unique limit logic for all-unique columns)
        apply_limits_unweighted(
            &mut counts,
            self.flag_limit,
            self.flag_unq_limit,
            self.flag_lmt_threshold,
            all_unique,
        );

        // Calculate pct_factor: when --pct-nulls is false, exclude NULLs from denominator
        let adjusted_total = total_count.saturating_sub(null_count);
        let pct_factor = if adjusted_total > 0 {
            100.0_f64 / adjusted_total.to_f64().unwrap_or(1.0_f64)
        } else {
            0.0_f64
        };

        // Group by count to handle ties
        let count_groups = group_by_count(counts);

        // safety: NULL_VAL is set in the main function
        let null_val = NULL_VAL.get().unwrap();

        // Apply ranking strategy (NULLs already removed when pct_nulls is false)
        let (mut counts_final, count_sum, pct_sum) = apply_ranking_strategy_unweighted(
            count_groups,
            self.flag_rank_strategy,
            pct_factor,
            null_val,
            self.flag_pct_nulls,
        );

        // Add NULL entry back with sentinel values when --pct-nulls is false
        // Insert at the correct sorted position based on count to preserve sort order
        if let Some((_, null_count_val)) = null_entry {
            let null_entry_final = (null_val.to_vec(), null_count_val, -1.0, -1.0);
            // Find the correct insertion position based on count (descending or ascending)
            let insert_pos = if self.flag_asc {
                // Ascending: find first position where count > null_count
                counts_final
                    .iter()
                    .position(|(_, c, _, _)| *c > null_count_val)
                    .unwrap_or(counts_final.len())
            } else {
                // Descending: find first position where count < null_count
                counts_final
                    .iter()
                    .position(|(_, c, _, _)| *c < null_count_val)
                    .unwrap_or(counts_final.len())
            };
            counts_final.insert(insert_pos, null_entry_final);
        }

        // Calculate "Other" category
        // When NULL was extracted, adjust calculations to exclude it
        let (adjusted_other_count, adjusted_unique_len) = if null_count > 0 {
            // Subtract null_count from other_count since NULL is handled separately
            (
                total_count
                    .saturating_sub(count_sum)
                    .saturating_sub(null_count),
                unique_counts_len.saturating_sub(1), // NULL was removed from counts
            )
        } else {
            (total_count - count_sum, unique_counts_len)
        };

        if adjusted_other_count > 0 && self.flag_other_text != "<NONE>" {
            // When NULL was extracted and re-added, don't count it as a "shown" entry
            // because it's separate from the top-k values
            let shown_count = if null_count > 0 {
                counts_final.len().saturating_sub(1)
            } else {
                counts_final.len()
            };
            let other_unique_count = adjusted_unique_len.saturating_sub(shown_count);
            counts_final.push((
                format!(
                    "{} ({})",
                    self.flag_other_text,
                    HumanCount(other_unique_count as u64)
                )
                .as_bytes()
                .to_vec(),
                adjusted_other_count,
                100.0_f64 - pct_sum,
                0.0, // Special rank for "Other" category
            ));
        }

        counts_final
    }

    pub fn sequential_ftables(&self) -> CliResult<(Headers, FTables, Option<WeightedFTables>)> {
        let mut rdr = self.rconfig().reader()?;
        let (headers, sel, weight_col_idx) = self.sel_headers(&mut rdr)?;
        if weight_col_idx.is_some() {
            let weighted =
                self.ftables_weighted_internal(&sel, rdr.byte_records(), 1, weight_col_idx);
            Ok((headers, vec![], Some(weighted)))
        } else {
            Ok((
                headers,
                self.ftables_unweighted(&sel, rdr.byte_records(), 1),
                None,
            ))
        }
    }

    pub fn parallel_ftables(
        &self,
        idx: &Indexed<fs::File, fs::File>,
    ) -> CliResult<(Headers, FTables, Option<WeightedFTables>)> {
        let mut rdr = self.rconfig().reader()?;
        let (headers, sel, weight_col_idx) = self.sel_headers(&mut rdr)?;

        let idx_count = idx.count() as usize;
        if idx_count == 0 {
            return Ok((headers, vec![], None));
        }

        let njobs = util::njobs(self.flag_jobs);

        // Read memory limit from environment variable

        // Read memory limit from environment variable
        // If QSV_FREQ_CHUNK_MEMORY_MB is set & valid, set max chunk memory
        // If QSV_FREQ_CHUNK_MEMORY_MB is not set, use 0 (dynamic sizing)
        // If QSV_FREQ_CHUNK_MEMORY_MB is set to a value that cannot be parsed as u64 (e.g., -1 or
        // any invalid/non-positive value), use CPU-based chunking
        let max_chunk_memory_mb = if let Ok(val) = std::env::var("QSV_FREQ_CHUNK_MEMORY_MB") {
            // if valid, set max chunk memory
            // if invalid (cannot be parsed as u64), use CPU-based chunking
            atoi_simd::parse::<u64>(val.as_bytes()).ok()
        } else {
            Some(0) // default to dynamic sizing
        };

        // Sample first 1000 records for memory estimation
        // Always sample when QSV_FREQ_CHUNK_MEMORY_MB is set to ANY value (including 0)
        // or when not set (to enable dynamic sizing)
        let sample_records = if max_chunk_memory_mb.is_some() {
            util::sample_records(&self.rconfig(), 1000)
        } else {
            None
        };

        let (chunking_mode, chunk_size) = if let Some(limit_mb) = max_chunk_memory_mb {
            // Calculate memory-aware chunk size
            let chunk_size = calculate_memory_aware_chunk_size_for_frequency(
                idx_count as u64,
                njobs,
                max_chunk_memory_mb,
                sample_records.as_deref(),
            );

            // Log chunk size and memory estimates for debugging
            // Log when memory-aware chunking is active (either explicitly set or automatically
            // enabled) Estimate average record size from samples if available
            let avg_record_size = if let Some(samples) = sample_records {
                calculate_avg_record_size_for_frequency(&samples)
            } else {
                1024 // Default: 1KB per record
            };

            let estimated_memory_mb =
                estimate_chunk_memory_for_frequency(chunk_size, avg_record_size, headers.len())
                    / (1024 * 1024);
            let chunking_mode = if limit_mb == 0 {
                "dynamic (auto)"
            } else {
                "fixed limit"
            };
            (
                format!(
                    "Memory-aware chunking ({chunking_mode}): chunk_size={chunk_size}, \
                     estimated_memory_mb={estimated_memory_mb:.2}"
                ),
                chunk_size,
            )
        } else {
            let chunk_size = util::chunk_size(idx_count, njobs);
            (
                format!("CPU-based chunking: chunk_size={chunk_size}"),
                chunk_size,
            )
        };

        let nchunks = util::num_of_chunks(idx_count, chunk_size);
        log::info!("({chunking_mode}) nchunks={nchunks}");

        if weight_col_idx.is_some() {
            // Parallel weighted frequencies
            let pool = ThreadPool::new(njobs);
            let (send, recv) = crossbeam_channel::bounded(nchunks);
            for i in 0..nchunks {
                let (send, args, sel, weight_idx) =
                    (send.clone(), self.clone(), sel.clone(), weight_col_idx);
                pool.execute(move || {
                    let mut idx = args.rconfig().indexed().unwrap().unwrap();
                    idx.seek((i * chunk_size) as u64).unwrap();
                    let it = idx.byte_records().take(chunk_size);
                    send.send(args.ftables_weighted_internal(&sel, it, nchunks, weight_idx))
                        .unwrap();
                });
            }
            drop(send);

            // Merge weighted frequencies
            let mut merged: WeightedFTables = Vec::new();
            for weighted_chunk in &recv {
                if merged.is_empty() {
                    merged = weighted_chunk;
                } else {
                    // Merge HashMaps
                    for (col_idx, weighted_map) in weighted_chunk.into_iter().enumerate() {
                        if col_idx < merged.len() {
                            for (value, weight) in weighted_map {
                                *merged[col_idx].entry(value).or_insert(0.0) += weight;
                            }
                        } else {
                            merged.push(weighted_map);
                        }
                    }
                }
            }
            Ok((headers, vec![], Some(merged)))
        } else {
            // Parallel unweighted frequencies
            let pool = ThreadPool::new(njobs);
            let (send, recv) = crossbeam_channel::bounded(nchunks);
            for i in 0..nchunks {
                let (send, args, sel) = (send.clone(), self.clone(), sel.clone());
                pool.execute(move || {
                    let mut idx = args.rconfig().indexed().unwrap().unwrap();
                    idx.seek((i * chunk_size) as u64).unwrap();
                    let it = idx.byte_records().take(chunk_size);
                    send.send(args.ftables_unweighted(&sel, it, nchunks))
                        .unwrap();
                });
            }
            drop(send);
            Ok((headers, merge_all(recv.iter()).unwrap(), None))
        }
    }

    #[inline]
    fn ftables_weighted_internal<I>(
        &self,
        sel: &Selection,
        it: I,
        nchunks: usize,
        weight_col_idx: Option<usize>,
    ) -> WeightedFTables
    where
        I: Iterator<Item = csv::Result<csv::ByteRecord>>,
    {
        // Extract the weighted HashMap implementation from ftables_weighted
        // This is a duplicate of the weighted logic but returns WeightedFTables
        let sel_len = sel.len();

        #[allow(unused_assignments)]
        let mut field_buffer: Vec<u8> = Vec::with_capacity(1024);
        let mut row_buffer: csv::ByteRecord = csv::ByteRecord::with_capacity(200, sel_len);
        let mut string_buf = String::with_capacity(512);

        // For weighted frequencies, we process all columns including all-unique ones
        // because the weights provide meaningful information, so we don't need to track
        // which columns are all-unique here (unlike unweighted frequencies where all-unique
        // columns are skipped for memory efficiency)
        let flag_no_nulls = self.flag_no_nulls;
        let flag_ignore_case = self.flag_ignore_case;
        let flag_no_trim = self.flag_no_trim;

        let col_cardinality_vec = COL_CARDINALITY_VEC.get().unwrap_or(&EMPTY_VEC);
        let mut weighted_freq_tables: Vec<HashMap<Vec<u8>, f64>> = if col_cardinality_vec.is_empty()
        {
            (0..sel_len).map(|_| HashMap::with_capacity(1000)).collect()
        } else {
            (0..sel_len)
                .map(|i| {
                    // For weighted frequencies, we process all columns including all-unique ones
                    // so we use the actual cardinality (or a reasonable default) rather than 1
                    let capacity = if nchunks == 1 {
                        col_cardinality_vec
                            .get(i)
                            .map_or(1000, |(_, cardinality)| *cardinality as usize)
                    } else {
                        let cardinality = col_cardinality_vec
                            .get(i)
                            .map_or(1000, |(_, cardinality)| *cardinality as usize);
                        cardinality / nchunks
                    };
                    HashMap::with_capacity(capacity)
                })
                .collect()
        };

        let process_field = if flag_ignore_case {
            if flag_no_trim {
                |field: &[u8], buf: &mut String| {
                    if let Ok(s) = simdutf8::basic::from_utf8(field) {
                        util::to_lowercase_into(s, buf);
                        buf.as_bytes().to_vec()
                    } else {
                        field.to_vec()
                    }
                }
            } else {
                |field: &[u8], buf: &mut String| {
                    if let Ok(s) = simdutf8::basic::from_utf8(field) {
                        util::to_lowercase_into(s.trim(), buf);
                        buf.as_bytes().to_vec()
                    } else {
                        trim_bs_whitespace(field).to_vec()
                    }
                }
            }
        } else if flag_no_trim {
            |field: &[u8], _buf: &mut String| field.to_vec()
        } else {
            #[inline]
            |field: &[u8], _buf: &mut String| trim_bs_whitespace(field).to_vec()
        };

        let mut row_result: csv::ByteRecord;
        for row in it {
            // safety: we know the row is valid because it comes from an iterator
            row_result = unsafe { row.unwrap_unchecked() };
            row_buffer.clone_from(&row_result);

            let weight = if let Some(widx) = weight_col_idx {
                if widx < row_result.len() {
                    // safety: widx < row_result.len() is checked above, so get(widx)
                    // will always return Some(&[u8])
                    fast_float2::parse::<f64, &[u8]>(row_result.get(widx).unwrap()).unwrap_or(1.0)
                } else {
                    1.0
                }
            } else {
                1.0
            };

            if !weight.is_finite() || weight <= 0.0 {
                continue;
            }

            for (i, field) in sel.select(&row_buffer).enumerate() {
                // For weighted frequencies, we process all columns including all-unique ones
                // because the weights provide meaningful information even when values are unique
                // (unlike unweighted frequencies where all-unique columns are skipped for memory
                // efficiency)

                // safety: weighted_freq_tables is pre-allocated with sel_len elements.
                // i will always be < sel_len as it comes from enumerate() over the selected cols
                if !field.is_empty() {
                    field_buffer = process_field(field, &mut string_buf);
                    unsafe {
                        *weighted_freq_tables
                            .get_unchecked_mut(i)
                            .entry(field_buffer)
                            .or_insert(0.0) += weight;
                    }
                } else if !flag_no_nulls {
                    unsafe {
                        *weighted_freq_tables
                            .get_unchecked_mut(i)
                            .entry(EMPTY_BYTE_VEC.clone())
                            .or_insert(0.0) += weight;
                    }
                }
            }
        }

        weighted_freq_tables
    }

    #[inline]
    fn ftables_unweighted<I>(&self, sel: &Selection, it: I, nchunks: usize) -> FTables
    where
        I: Iterator<Item = csv::Result<csv::ByteRecord>>,
    {
        let sel_len = sel.len();

        #[allow(unused_assignments)]
        // Optimize buffer allocations
        let mut field_buffer: Vec<u8> = Vec::with_capacity(1024);
        let mut row_buffer: csv::ByteRecord = csv::ByteRecord::with_capacity(200, sel_len);
        let mut string_buf = String::with_capacity(512);

        let unique_headers_vec = UNIQUE_COLUMNS_VEC.get().unwrap();

        // assign flags to local variables for faster access
        let flag_no_nulls = self.flag_no_nulls;
        let flag_ignore_case = self.flag_ignore_case;
        let flag_no_trim = self.flag_no_trim;

        // compile a vector of bool flags for columns to skip in the hot loop.
        // Includes ALL_UNIQUE columns and columns with pre-built FTables from
        // the frequency cache (partial cache hit — merged back in run()).
        let mut all_unique_flag_vec: Vec<bool> = (0..sel_len)
            .map(|i| unique_headers_vec.contains(&i))
            .collect();
        if let Some(cache_skip) = FREQ_CACHE_SKIP.get() {
            for (i, &is_cached) in cache_skip.iter().enumerate() {
                if is_cached && i < sel_len {
                    all_unique_flag_vec[i] = true;
                }
            }
        }

        // optimize the capacity of the freq_tables based on the cardinality of the columns
        // if sequential, use the cardinality from the stats cache
        // if parallel, use a default capacity of 1000 for non-unique columns
        let col_cardinality_vec = COL_CARDINALITY_VEC.get().unwrap_or(&EMPTY_VEC);
        let mut freq_tables: Vec<_> = if col_cardinality_vec.is_empty() {
            (0..sel_len)
                .map(|_| Frequencies::with_capacity(1000))
                .collect()
        } else {
            (0..sel_len)
                .map(|i| {
                    let capacity = if all_unique_flag_vec[i] {
                        1
                    } else if nchunks == 1 {
                        col_cardinality_vec
                            .get(i)
                            .map_or(1000, |(_, cardinality)| *cardinality as usize)
                    } else {
                        // use cardinality and number of jobs to set the capacity
                        let cardinality = col_cardinality_vec
                            .get(i)
                            .map_or(1000, |(_, cardinality)| *cardinality as usize);
                        cardinality / nchunks
                    };
                    Frequencies::with_capacity(capacity)
                })
                .collect()
        };

        // Pre-compute function pointers for the hot path
        // instead of doing if chains repeatedly in the hot loop
        let process_field = if flag_ignore_case {
            if flag_no_trim {
                |field: &[u8], buf: &mut String| {
                    if let Ok(s) = simdutf8::basic::from_utf8(field) {
                        util::to_lowercase_into(s, buf);
                        buf.as_bytes().to_vec()
                    } else {
                        field.to_vec()
                    }
                }
            } else {
                |field: &[u8], buf: &mut String| {
                    if let Ok(s) = simdutf8::basic::from_utf8(field) {
                        util::to_lowercase_into(s.trim(), buf);
                        buf.as_bytes().to_vec()
                    } else {
                        trim_bs_whitespace(field).to_vec()
                    }
                }
            }
        } else if flag_no_trim {
            |field: &[u8], _buf: &mut String| field.to_vec()
        } else {
            // this is the default hot path, so inline it
            #[inline]
            |field: &[u8], _buf: &mut String| trim_bs_whitespace(field).to_vec()
        };

        for row in it {
            // safety: we know the row is valid
            row_buffer.clone_from(&unsafe { row.unwrap_unchecked() });
            for (i, field) in sel.select(&row_buffer).enumerate() {
                // safety: all_unique_flag_vec is pre-computed to have exactly sel_len elements,
                // which matches the number of selected columns that we iterate over.
                // i will always be < sel_len as it comes from enumerate() over the selected cols
                if unsafe { *all_unique_flag_vec.get_unchecked(i) } {
                    continue;
                }

                // safety: freq_tables is pre-allocated with sel_len elements.
                // i will always be < sel_len as it comes from enumerate() over the selected cols
                if !field.is_empty() {
                    field_buffer = process_field(field, &mut string_buf);
                    unsafe {
                        freq_tables.get_unchecked_mut(i).add(field_buffer);
                    }
                } else if !flag_no_nulls {
                    // set to null (EMPTY_BYTES) as flag_no_nulls is false
                    unsafe {
                        freq_tables.get_unchecked_mut(i).add(EMPTY_BYTE_VEC);
                    }
                }
            }
        }
        // shrink the capacity of the freq_tables to the actual number of elements.
        // if sequential (nchunks == 1), we don't need to shrink the capacity as we
        // use cardinality to set the capacity of the freq_tables
        // if parallel (nchunks > 1), shrink the capacity to avoid over-allocating memory
        if nchunks > 1 {
            freq_tables.shrink_to_fit();
        }
        freq_tables
    }

    /// Compute indices of Float columns that should be skipped from frequency analysis.
    ///
    /// # Arguments
    /// * `headers` - The selected CSV headers
    /// * `col_type_map` - Map of column names to their data types from stats cache
    ///
    /// # Returns
    /// A vector of indices (into the selected headers) of Float columns to skip.
    /// Columns listed in the --no-float exception list are NOT included in the skip list.
    fn compute_float_columns_to_skip(
        &self,
        headers: &Headers,
        col_type_map: &HashMap<String, String>,
    ) -> Vec<usize> {
        // Parse exception columns from flag value
        // If value is "*", exclude ALL Float columns (empty exception list)
        // Otherwise, parse as comma-separated list of Float columns to INCLUDE
        let exception_cols: HashSet<String> = self
            .flag_no_float
            .as_ref()
            .map(|cols| {
                let trimmed = cols.trim();
                // "*" means exclude all floats (no exceptions)
                if trimmed == "*" {
                    HashSet::new()
                } else {
                    trimmed
                        .split(',')
                        .map(|s| s.trim().to_lowercase())
                        .filter(|s| !s.is_empty() && s != "*")
                        .collect()
                }
            })
            .unwrap_or_default();

        let mut float_columns_to_skip = Vec::new();

        for (i, header) in headers.iter().enumerate() {
            let header_str = simdutf8::basic::from_utf8(header)
                .unwrap_or(NON_UTF8_ERR)
                .to_string();

            // Check if column is Float type and not in exception list
            if let Some(col_type) = col_type_map.get(&header_str)
                && col_type == "Float"
                && !exception_cols.contains(&header_str.to_lowercase())
            {
                float_columns_to_skip.push(i);
            }
        }

        float_columns_to_skip
    }

    /// Compute indices of columns that should be skipped based on the --stats-filter expression.
    ///
    /// # Arguments
    /// * `headers` - The selected CSV headers
    /// * `stats_records` - Map of column names to their stats data from stats cache
    /// * `filter_expression` - The Luau expression to evaluate for each column
    ///
    /// # Returns
    /// A vector of indices (into the selected headers) of columns where the filter
    /// expression evaluated to `true` (meaning they should be excluded).
    #[allow(clippy::unused_self)]
    #[cfg(feature = "luau")]
    fn compute_stats_filter_columns_to_skip(
        &self,
        headers: &Headers,
        stats_records: &HashMap<String, StatsData>,
        filter_expression: &str,
    ) -> CliResult<Vec<usize>> {
        use mlua::Lua;

        // Create a single sandboxed Luau VM for all column evaluations
        let lua = Lua::new();
        lua.sandbox(true)
            .map_err(|e| format!("Failed to enable Luau sandbox: {e}"))?;

        let mut columns_to_skip = Vec::new();

        for (i, header) in headers.iter().enumerate() {
            let header_str = simdutf8::basic::from_utf8(header)
                .unwrap_or(NON_UTF8_ERR)
                .to_string();

            // Look up the stats record for this column
            if let Some(stats_data) = stats_records.get(&header_str) {
                // Evaluate the filter expression against this column's stats
                match evaluate_stats_filter(&lua, stats_data, filter_expression) {
                    Ok(should_exclude) => {
                        if should_exclude {
                            log::debug!(
                                "Column '{header_str}' excluded by --stats-filter expression"
                            );
                            columns_to_skip.push(i);
                        }
                    },
                    Err(e) => {
                        return fail_clierror!(
                            "Error evaluating --stats-filter expression for column \
                             '{header_str}': {e}"
                        );
                    },
                }
            } else {
                // No stats available for this column - skip filtering for it
                log::debug!(
                    "No stats available for column '{header_str}', skipping --stats-filter \
                     evaluation"
                );
            }
        }

        Ok(columns_to_skip)
    }

    /// return the names of headers/columns that are unique identifiers
    /// (i.e. where cardinality == rowcount)
    /// Also stores the stats records in a hashmap for use when producing JSON output
    fn get_unique_headers(&self, headers: &Headers) -> CliResult<Vec<usize>> {
        // get the stats records for the entire CSV
        let schema_args = util::SchemaArgs {
            flag_enum_threshold:  0,
            flag_ignore_case:     self.flag_ignore_case,
            flag_strict_dates:    false,
            flag_strict_formats:  false,
            // we still get all the stats columns so we can use the stats cache
            flag_pattern_columns: crate::select::SelectColumns::parse("").unwrap(),
            flag_dates_whitelist: String::new(),
            flag_prefer_dmy:      false,
            flag_force:           false,
            flag_stdout:          false,
            flag_jobs:            Some(util::njobs(self.flag_jobs)),
            flag_polars:          false,
            flag_no_headers:      self.flag_no_headers,
            flag_delimiter:       self.flag_delimiter,
            arg_input:            self.arg_input.clone(),
            flag_memcheck:        false,
            flag_output:          None,
        };
        let is_json = self.flag_json || self.flag_pretty_json || self.flag_toon;
        // Check if we need to populate stats_records_hashmap
        // We need it for JSON output and for --stats-filter
        #[cfg(feature = "luau")]
        let needs_stats_records = is_json || self.flag_stats_filter.is_some();
        #[cfg(not(feature = "luau"))]
        let needs_stats_records = is_json;

        // initialize the stats records hashmap
        let mut stats_records_hashmap = if needs_stats_records {
            HashMap::with_capacity(headers.len())
        } else {
            HashMap::new()
        };

        let (csv_fields, csv_stats) = get_stats_records(&schema_args, StatsMode::Frequency)?;

        if csv_fields.is_empty() || csv_stats.len() != csv_fields.len() {
            // the stats cache does not exist or the number of fields & stats records
            // do not match. Just return an empty vector.
            // we're not going to be able to get the cardinalities, so
            // this signals that we just compute frequencies for all columns
            return Ok(Vec::new());
        }

        // Build column name -> (cardinality, type) map for matching by name
        let mut col_type_map: HashMap<String, String> = HashMap::with_capacity(csv_stats.len());

        let col_cardinality_vec: Vec<(String, u64)> = csv_stats
            .iter()
            .enumerate()
            .map(|(i, stats_record)| {
                // get the column name and stats record
                // safety: we know that csv_fields and csv_stats have the same length
                let col_name = csv_fields.get(i).unwrap();
                let col_name_str = simdutf8::basic::from_utf8(col_name)
                    .unwrap_or(NON_UTF8_ERR)
                    .to_string();
                if needs_stats_records {
                    // Store the stats records hashmap for later use when producing JSON output
                    // or for --stats-filter evaluation
                    stats_records_hashmap.insert(col_name_str.clone(), stats_record.clone());
                }
                // Store type info for Float column detection
                col_type_map.insert(col_name_str.clone(), stats_record.r#type.clone());
                (col_name_str, stats_record.cardinality)
            })
            .collect();

        // now, get the unique headers, where cardinality == rowcount
        let row_count = util::count_rows(&self.rconfig()).unwrap_or_default();
        FREQ_ROW_COUNT.set(row_count).unwrap();

        // Most datasets have relatively few columns with all unique values (e.g. ID columns)
        // so pre-allocate space for 5 as a reasonable default capacity
        let mut all_unique_headers_vec: Vec<usize> = Vec::with_capacity(5);
        for (i, header) in headers.iter().enumerate() {
            // Look up cardinality by column name, not index, since headers may be a
            // user-selected subset in a different order than the original CSV columns
            let cardinality = col_cardinality_vec
                .iter()
                .find(|(name, _)| {
                    name == simdutf8::basic::from_utf8(header).unwrap_or(NON_UTF8_ERR)
                })
                .map_or(0, |(_, card)| *card);

            if cardinality == row_count {
                all_unique_headers_vec.push(i);
            }
        }

        // Compute Float columns to skip if --no-float is specified
        if self.flag_no_float.is_some() {
            let float_columns_to_skip = self.compute_float_columns_to_skip(headers, &col_type_map);
            if FLOAT_COLUMNS_TO_SKIP.set(float_columns_to_skip).is_err() {
                log::warn!("FLOAT_COLUMNS_TO_SKIP already set — stale float columns may be used");
            }
        }

        // Compute stats filter columns to skip if --stats-filter is specified
        #[cfg(feature = "luau")]
        if let Some(ref filter_expression) = self.flag_stats_filter {
            if stats_records_hashmap.is_empty() {
                log::warn!(
                    "Stats cache unavailable. Cannot apply --stats-filter. Run 'qsv stats \
                     --cardinality --stats-jsonl' first."
                );
            } else {
                let stats_filter_columns_to_skip = self.compute_stats_filter_columns_to_skip(
                    headers,
                    &stats_records_hashmap,
                    filter_expression,
                )?;
                if STATS_FILTER_COLUMNS_TO_SKIP
                    .set(stats_filter_columns_to_skip)
                    .is_err()
                {
                    log::warn!(
                        "STATS_FILTER_COLUMNS_TO_SKIP already set — stale filter columns may be \
                         used"
                    );
                }
            }
        }

        COL_CARDINALITY_VEC.get_or_init(|| col_cardinality_vec);

        if is_json {
            // Store the stats records hashmap for later use when producing JSON output
            STATS_RECORDS.set(stats_records_hashmap).unwrap();
        }

        Ok(all_unique_headers_vec)
    }

    #[allow(clippy::cast_precision_loss)]
    fn output_json(
        &self,
        headers: &Headers,
        tables: FTables,
        weighted_tables: Option<&WeightedFTables>,
        rconfig: &Config,
        argv: &[&str],
        is_stdin: bool,
    ) -> CliResult<()> {
        let fieldcount = headers.len();

        // init vars and amortize allocations
        let mut fields = Vec::with_capacity(fieldcount);
        let rowcount = *FREQ_ROW_COUNT.get().unwrap_or(&0);
        let unique_headers_vec = UNIQUE_COLUMNS_VEC.get().unwrap();
        let mut processed_frequencies = Vec::with_capacity(headers.len());
        let abs_dec_places = self.flag_pct_dec_places.unsigned_abs() as u32;
        // pre-allocate space for 17 field stats, see list below for details
        let mut field_stats: Vec<FieldStats> = Vec::with_capacity(17);

        // Helper function to build a frequency field for JSON output
        let build_frequency_field = |field_name: String,
                                     cardinality: u64,
                                     processed_frequencies: &mut Vec<ProcessedFrequency>,
                                     field_stats: &mut Vec<FieldStats>,
                                     skip_stats: bool| {
            // Sort frequencies by count if flag_other_sorted,
            // breaking ties by value for deterministic output
            if self.flag_other_sorted {
                if self.flag_asc {
                    processed_frequencies.sort_unstable_by(|a, b| {
                        a.count.cmp(&b.count).then_with(|| a.value.cmp(&b.value))
                    });
                } else {
                    processed_frequencies.sort_unstable_by(|a, b| {
                        b.count.cmp(&a.count).then_with(|| a.value.cmp(&b.value))
                    });
                }
            }

            // Get stats record for this field
            let stats_record = STATS_RECORDS
                .get()
                .and_then(|records| records.get(&field_name));

            // Get data type and nullcount from stats record
            let dtype = stats_record.map_or(String::new(), |sr| sr.r#type.clone());
            let nullcount = stats_record.map_or(0, |sr| sr.nullcount);
            let sparsity =
                fast_float2::parse(util::round_num(nullcount as f64 / rowcount as f64, 4))
                    .unwrap_or(0.0);
            let uniqueness_ratio =
                fast_float2::parse(util::round_num(cardinality as f64 / rowcount as f64, 4))
                    .unwrap_or(0.0);

            // Build stats vector from stats record if type is not empty and not NULL or Boolean
            // Skip stats when using weighted mode (stats would be misleading)
            if !self.flag_no_stats
                && !skip_stats
                && !dtype.is_empty()
                && dtype.as_str() != "NULL"
                && dtype.as_str() != "Boolean"
                && let Some(sr) = stats_record
            {
                // Add all available stats if some
                add_stat(field_stats, "sum", sr.sum);
                add_stat(field_stats, "min", sr.min.clone());
                add_stat(field_stats, "max", sr.max.clone());
                add_stat(field_stats, "range", sr.range);
                add_stat(field_stats, "sort_order", sr.sort_order.clone());

                // String-specific length stats
                add_stat(field_stats, "min_length", sr.min_length);
                add_stat(field_stats, "max_length", sr.max_length);
                add_stat(field_stats, "sum_length", sr.sum_length);
                add_stat(field_stats, "avg_length", sr.avg_length);
                add_stat(field_stats, "stddev_length", sr.stddev_length);
                add_stat(field_stats, "variance_length", sr.variance_length);
                add_stat(field_stats, "cv_length", sr.cv_length);

                // Numeric-specific stats
                add_stat(field_stats, "mean", sr.mean);
                add_stat(field_stats, "sem", sr.sem);
                add_stat(field_stats, "stddev", sr.stddev);
                add_stat(field_stats, "variance", sr.variance);
                add_stat(field_stats, "cv", sr.cv);
            }

            FrequencyField {
                field: field_name,
                r#type: dtype,
                cardinality,
                nullcount,
                sparsity,
                uniqueness_ratio,
                stats: std::mem::take(field_stats),
                frequencies: processed_frequencies
                    .iter()
                    .map(|pf| {
                        // Sentinel value -1.0 indicates NULL entry with --pct-nulls=false
                        let (pct_opt, rank_opt) = if pf.percentage < 0.0 {
                            (None, None)
                        } else {
                            (
                                Some(
                                    fast_float2::parse(&pf.formatted_percentage)
                                        .unwrap_or(pf.percentage),
                                ),
                                Some(pf.rank),
                            )
                        };
                        FrequencyEntry {
                            value:      if self.flag_vis_whitespace {
                                util::visualize_whitespace(&String::from_utf8_lossy(&pf.value))
                            } else {
                                String::from_utf8_lossy(&pf.value).into_owned()
                            },
                            count:      pf.count,
                            percentage: pct_opt,
                            rank:       rank_opt,
                        }
                    })
                    .collect(),
            }
        };

        if let Some(weighted) = weighted_tables {
            // Process weighted frequencies for JSON output
            for (i, header) in headers.iter().enumerate() {
                let field_name = if rconfig.no_headers {
                    (i + 1).to_string()
                } else {
                    String::from_utf8_lossy(header).to_string()
                };

                let all_unique_header = unique_headers_vec.contains(&i);
                if i < weighted.len() {
                    self.process_frequencies_weighted(
                        all_unique_header,
                        abs_dec_places,
                        rowcount,
                        &weighted[i],
                        &mut processed_frequencies,
                    );
                }

                // Calculate cardinality for this field
                let cardinality = if all_unique_header {
                    rowcount
                } else if i < weighted.len() {
                    weighted[i].len() as u64
                } else {
                    0
                };

                fields.push(build_frequency_field(
                    field_name,
                    cardinality,
                    &mut processed_frequencies,
                    &mut field_stats,
                    true, // Skip stats for weighted mode
                ));

                processed_frequencies.clear(); // clear for next field
            }
        } else {
            // Process unweighted frequencies for JSON output
            let head_ftables = headers.iter().zip(tables);
            for (i, (header, ftab)) in head_ftables.enumerate() {
                let field_name = if rconfig.no_headers {
                    (i + 1).to_string()
                } else {
                    String::from_utf8_lossy(header).to_string()
                };

                let all_unique_header = unique_headers_vec.contains(&i);
                self.process_frequencies(
                    all_unique_header,
                    abs_dec_places,
                    rowcount,
                    &ftab,
                    &mut processed_frequencies,
                );

                // Calculate cardinality for this field
                let cardinality = if all_unique_header {
                    rowcount // For all-unique fields, cardinality == rowcount
                } else {
                    ftab.len() as u64 // otherwise, cardinality == number of unique values
                };

                fields.push(build_frequency_field(
                    field_name,
                    cardinality,
                    &mut processed_frequencies,
                    &mut field_stats,
                    false, // Include stats for non-weighted mode
                ));

                processed_frequencies.clear(); // clear for next field
            }
        }

        let output = FrequencyOutput {
            input: if is_stdin {
                "stdin".to_string()
            } else {
                // safety: we know arg_input is not None
                self.arg_input.clone().unwrap()
            },
            description: format!("Generated with `qsv {}`", argv[1..].join(" ")),
            rowcount: if rowcount == 0 {
                // if rowcount == 0, derive the rowcount from first field's frequencies
                // by summing the counts for the first field
                fields
                    .first()
                    .map_or(0, |field| field.frequencies.iter().map(|f| f.count).sum())
            } else {
                rowcount
            },
            fieldcount,
            fields,
            rank_strategy: self.flag_rank_strategy,
        };

        if self.flag_toon {
            // TOON output - encode the JSON structure to TOON format
            // First serialize to JSON Value, then remove empty stats, then encode to TOON
            let mut json_value = serde_json::to_value(&output)?;

            // Remove empty stats arrays from each field (same as JSON output)
            if let Some(fields) = json_value.get_mut("fields").and_then(|f| f.as_array_mut()) {
                for field in fields {
                    if let Some(field_obj) = field.as_object_mut() {
                        // Remove empty stats
                        if let Some(stats) = field_obj.get("stats")
                            && let Some(stats_array) = stats.as_array()
                            && stats_array.is_empty()
                        {
                            field_obj.remove("stats");
                        }
                    }
                }
            }

            let opts = EncodeOptions::new();
            let toon_output = encode(&json_value, &opts)
                .map_err(|e| crate::CliError::Other(format!("Failed to encode to TOON: {e}")))?;
            if let Some(output_path) = &self.flag_output {
                std::fs::write(output_path, toon_output)?;
            } else {
                println!("{toon_output}");
            }
        } else {
            // JSON output
            let mut json_output = if self.flag_pretty_json {
                // pretty, with more whitespace
                serde_json::to_string_pretty(&output)?
            } else {
                // still pretty, but more compact and faster
                simd_json::to_string_pretty(&output)?
            };

            // remove all empty stats properties from the JSON output using regex
            // safety: regex pattern is a valid static string
            let re = regex::Regex::new(r#""stats": \[\],\n\s*"#).unwrap();
            json_output = re.replace_all(&json_output, "").to_string();

            if let Some(output_path) = &self.flag_output {
                std::fs::write(output_path, json_output)?;
            } else {
                println!("{json_output}");
            }
        }

        Ok(())
    }

    /// Processes headers and handles weight column exclusion if needed.
    ///
    /// This function handles the logic for excluding the weight column from frequency
    /// computation. It finds the weight column index, creates a modified selection that
    /// excludes it, and returns the selected headers.
    ///
    /// # Arguments
    ///
    /// * `full_headers` - The full CSV headers as a ByteRecord
    ///
    /// # Returns
    ///
    /// * `Ok((Option<usize>, Selection, csv::ByteRecord))` - Tuple containing:
    ///   - Weight column index (None if no weight column specified)
    ///   - Modified selection (excluding weight column if present)
    ///   - Selected headers (excluding weight column if present)
    /// * `Err(CliError)` - If weight column is not found or no columns remain after exclusion
    fn process_headers_with_weight_exclusion(
        &self,
        full_headers: &csv::ByteRecord,
    ) -> CliResult<(Option<usize>, Selection, csv::ByteRecord)> {
        if let Some(ref weight_col) = self.flag_weight {
            // Find weight column index in full headers
            let weight_idx = full_headers
                .iter()
                .position(|h| {
                    let h_str = String::from_utf8_lossy(h);
                    h_str.trim().eq_ignore_ascii_case(weight_col.trim())
                })
                .ok_or_else(|| {
                    crate::CliError::Other(format!(
                        "Weight column '{weight_col}' not found in CSV headers"
                    ))
                })?;

            // Create selection excluding weight column
            let sel = self.rconfig().selection(full_headers)?;
            // Remove weight column index from selection if present
            let sel_vec: Vec<usize> = sel
                .iter()
                .copied()
                .filter(|&idx| idx != weight_idx)
                .collect();

            // Validate that we still have columns after excluding the weight column
            if sel_vec.is_empty() {
                return Err(crate::CliError::Other(format!(
                    "After excluding weight column '{weight_col}', no columns remain for \
                     frequency computation"
                )));
            }

            // safety: We know Selection is a tuple struct with a Vec<usize> field
            // This is safe because we're creating it with valid indices
            let modified_sel = unsafe { std::mem::transmute::<Vec<usize>, Selection>(sel_vec) };

            // Get selected headers (excluding weight column)
            let selected_headers: csv::ByteRecord = modified_sel.select(full_headers).collect();

            Ok((Some(weight_idx), modified_sel, selected_headers))
        } else {
            // No weight column specified, use normal selection
            let sel = self.rconfig().selection(full_headers)?;
            let headers: csv::ByteRecord = sel.select(full_headers).collect();
            Ok((None, sel, headers))
        }
    }

    fn sel_headers<R: io::Read>(
        &self,
        rdr: &mut csv::Reader<R>,
    ) -> CliResult<(csv::ByteRecord, Selection, Option<usize>)> {
        let full_headers = rdr.byte_headers()?.clone();
        let (weight_col_idx, mut sel, selected_headers) =
            self.process_headers_with_weight_exclusion(&full_headers)?;

        let all_unique_headers_vec = self.get_unique_headers(&selected_headers)?;

        // Filter out Float columns if --no-float is specified
        let (final_sel, final_headers) = if self.flag_no_float.is_some() {
            if let Some(float_cols_to_skip) = FLOAT_COLUMNS_TO_SKIP.get() {
                if float_cols_to_skip.is_empty() {
                    (sel, selected_headers)
                } else {
                    // Filter selection to exclude Float columns
                    // float_cols_to_skip contains indices into selected_headers
                    let sel_vec: Vec<usize> = sel
                        .iter()
                        .copied()
                        .enumerate()
                        .filter(|(i, _)| !float_cols_to_skip.contains(i))
                        .map(|(_, idx)| idx)
                        .collect();

                    if sel_vec.is_empty() {
                        return Err(crate::CliError::Other(
                            "No columns remain after excluding Float columns. Use --no-float with \
                             exception columns to include specific Float columns."
                                .to_string(),
                        ));
                    }

                    // safety: We know Selection is a tuple struct with a Vec<usize> field
                    sel = unsafe { std::mem::transmute::<Vec<usize>, Selection>(sel_vec) };
                    let headers: csv::ByteRecord = sel.select(&full_headers).collect();
                    (sel, headers)
                }
            } else {
                // Stats cache unavailable for Float type detection
                log::warn!(
                    "Stats cache unavailable. Cannot detect Float columns for --no-float. \
                     Processing all columns. Run 'qsv stats --cardinality --stats-jsonl' first."
                );
                (sel, selected_headers)
            }
        } else {
            (sel, selected_headers)
        };

        // Filter out stats-filtered columns if --stats-filter is specified
        #[cfg(feature = "luau")]
        let (final_sel, final_headers) = if self.flag_stats_filter.is_some() {
            if let Some(stats_filter_cols_to_skip) = STATS_FILTER_COLUMNS_TO_SKIP.get() {
                if stats_filter_cols_to_skip.is_empty() {
                    (final_sel, final_headers)
                } else {
                    // Filter selection to exclude stats-filtered columns
                    // stats_filter_cols_to_skip contains indices into selected_headers
                    let sel_vec: Vec<usize> = final_sel
                        .iter()
                        .copied()
                        .enumerate()
                        .filter(|(i, _)| !stats_filter_cols_to_skip.contains(i))
                        .map(|(_, idx)| idx)
                        .collect();

                    if sel_vec.is_empty() {
                        return Err(crate::CliError::Other(
                            "No columns remain after applying --stats-filter. Adjust your filter \
                             expression to be less restrictive."
                                .to_string(),
                        ));
                    }

                    // safety: We know Selection is a tuple struct with a Vec<usize> field
                    let new_sel = unsafe { std::mem::transmute::<Vec<usize>, Selection>(sel_vec) };
                    let headers: csv::ByteRecord = new_sel.select(&full_headers).collect();
                    (new_sel, headers)
                }
            } else {
                // Stats cache unavailable for --stats-filter
                log::warn!(
                    "Stats cache unavailable. Cannot apply --stats-filter. Processing all \
                     columns. Run 'qsv stats --cardinality --stats-jsonl' first."
                );
                (final_sel, final_headers)
            }
        } else {
            (final_sel, final_headers)
        };

        // Map original column indices to selected column indices
        let mapped_unique_headers: Vec<usize> = all_unique_headers_vec
            .iter()
            .filter_map(|&original_idx| {
                // Find the position of this original index in the selection
                final_sel
                    .iter()
                    .position(|&sel_idx| sel_idx == original_idx)
            })
            .collect();

        UNIQUE_COLUMNS_VEC
            .set(mapped_unique_headers)
            .map_err(|_| "Cannot set UNIQUE_COLUMNS")?;

        Ok((final_headers, final_sel, weight_col_idx))
    }
}

/// Helper function to add a field to field_stats if it exists
/// Automatically converts any type to appropriate JSON value
fn add_stat<T: ToString>(field_stats: &mut Vec<FieldStats>, name: &str, value: Option<T>) {
    if let Some(val) = value {
        let val_string = val.to_string();

        // Try to parse as integer first
        let json_value = if let Ok(int_val) = atoi_simd::parse::<i64>(val_string.as_bytes()) {
            JsonValue::Number(int_val.into())
        } else if let Ok(float_val) = fast_float2::parse(&val_string) {
            JsonValue::Number(
                serde_json::Number::from_f64(float_val)
                    .unwrap_or_else(|| serde_json::Number::from(0)),
            )
        } else {
            // Fall back to string
            JsonValue::String(val_string)
        };

        field_stats.push(FieldStats {
            name:  name.to_string(),
            value: json_value,
        });
    }
}

/// trim leading and trailing whitespace from a byte slice
#[allow(clippy::inline_always)]
#[inline(always)]
fn trim_bs_whitespace(bytes: &[u8]) -> &[u8] {
    let mut start = 0;
    let mut end = bytes.len();

    // safety: use unchecked indexing since we're bounds checking with the while condition
    // Find start by scanning forward
    while start < end {
        let b = unsafe { *bytes.get_unchecked(start) };
        if !b.is_ascii_whitespace() {
            break;
        }
        start += 1;
    }

    // Find end by scanning backward
    while end > start {
        let b = unsafe { *bytes.get_unchecked(end - 1) };
        if !b.is_ascii_whitespace() {
            break;
        }
        end -= 1;
    }

    // safety: This slice is guaranteed to be in bounds due to our index calculations
    unsafe { bytes.get_unchecked(start..end) }
}

/// Evaluate a Luau expression against stats data for a column.
/// Returns `true` if the column should be EXCLUDED from frequency analysis.
/// The Lua VM is passed in to allow reuse across multiple column evaluations.
#[cfg(feature = "luau")]
fn evaluate_stats_filter(
    lua: &mlua::Lua,
    stats_data: &StatsData,
    filter_expression: &str,
) -> Result<bool, String> {
    use mlua::Value;

    // Set all StatsData fields as globals
    let globals = lua.globals();

    // Helper macros to reduce boilerplate
    macro_rules! set_string {
        ($name:ident) => {
            globals
                .set(stringify!($name), stats_data.$name.as_str())
                .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
        };
    }

    macro_rules! set_u64 {
        ($name:ident) => {
            globals
                .set(stringify!($name), stats_data.$name)
                .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
        };
    }

    macro_rules! set_bool {
        ($name:ident) => {
            globals
                .set(stringify!($name), stats_data.$name)
                .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
        };
    }

    macro_rules! set_optional_f64 {
        ($name:ident) => {
            if let Some(val) = stats_data.$name {
                globals
                    .set(stringify!($name), val)
                    .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
            } else {
                globals
                    .set(stringify!($name), Value::Nil)
                    .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
            }
        };
    }

    macro_rules! set_optional_u64 {
        ($name:ident) => {
            if let Some(val) = stats_data.$name {
                globals
                    .set(stringify!($name), val)
                    .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
            } else {
                globals
                    .set(stringify!($name), Value::Nil)
                    .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
            }
        };
    }

    macro_rules! set_optional_usize {
        ($name:ident) => {
            if let Some(val) = stats_data.$name {
                globals
                    .set(stringify!($name), val)
                    .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
            } else {
                globals
                    .set(stringify!($name), Value::Nil)
                    .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
            }
        };
    }

    macro_rules! set_optional_u32 {
        ($name:ident) => {
            if let Some(val) = stats_data.$name {
                globals
                    .set(stringify!($name), val)
                    .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
            } else {
                globals
                    .set(stringify!($name), Value::Nil)
                    .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
            }
        };
    }

    macro_rules! set_optional_string {
        ($name:ident) => {
            if let Some(ref val) = stats_data.$name {
                globals
                    .set(stringify!($name), val.as_str())
                    .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
            } else {
                globals
                    .set(stringify!($name), Value::Nil)
                    .map_err(|e| format!("Failed to set {}: {e}", stringify!($name)))?;
            }
        };
    }

    // Set all fields from StatsData
    // Basic fields
    set_string!(field);
    // 'type' is a reserved keyword in Rust, so we use r#type
    globals
        .set("type", stats_data.r#type.as_str())
        .map_err(|e| format!("Failed to set type: {e}"))?;
    set_bool!(is_ascii);

    // Counts (non-optional)
    set_u64!(cardinality);
    set_u64!(nullcount);

    // Optional numeric fields
    set_optional_f64!(sum);
    set_optional_string!(min);
    set_optional_string!(max);
    set_optional_f64!(range);
    set_optional_string!(sort_order);

    // String length stats
    set_optional_usize!(min_length);
    set_optional_usize!(max_length);
    set_optional_usize!(sum_length);
    set_optional_f64!(avg_length);
    set_optional_f64!(stddev_length);
    set_optional_f64!(variance_length);
    set_optional_f64!(cv_length);

    // Numeric stats
    set_optional_f64!(mean);
    set_optional_f64!(sem);
    set_optional_f64!(stddev);
    set_optional_f64!(variance);
    set_optional_f64!(cv);

    // Sign counts
    set_optional_u64!(n_negative);
    set_optional_u64!(n_zero);
    set_optional_u64!(n_positive);

    // Precision
    set_optional_u32!(max_precision);

    // Ratios
    set_optional_f64!(sparsity);
    set_optional_f64!(uniqueness_ratio);

    // Distribution stats
    set_optional_f64!(mad);
    set_optional_f64!(lower_outer_fence);
    set_optional_f64!(lower_inner_fence);
    set_optional_f64!(q1);
    set_optional_f64!(q2_median);
    set_optional_f64!(q3);
    set_optional_f64!(iqr);
    set_optional_f64!(upper_inner_fence);
    set_optional_f64!(upper_outer_fence);
    set_optional_f64!(skewness);

    // Mode/Antimode
    set_optional_string!(mode);
    set_optional_u64!(mode_count);
    set_optional_u64!(mode_occurrences);
    set_optional_string!(antimode);
    set_optional_u64!(antimode_count);
    set_optional_u64!(antimode_occurrences);

    // Wrap the expression in a return statement to get the result
    let wrapped_expr = format!("return {filter_expression}");

    // Evaluate the expression
    let result: Value = lua
        .load(&wrapped_expr)
        .eval()
        .map_err(|e| format!("Failed to evaluate filter expression: {e}"))?;

    // Convert result to boolean
    match result {
        Value::Boolean(b) => Ok(b),
        Value::Nil => Ok(false), // nil is treated as false (don't exclude)
        _ => Err(format!(
            "Filter expression must return a boolean, got: {result:?}"
        )),
    }
}