namecase 0.1.0

A tool for converting names to proper case with intelligent handling of special naming conventions.
Documentation
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
use once_cell::sync::Lazy;
use regex::{Captures, Regex};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};

/// Options for the namecase function
#[derive(Debug, Clone, Copy)]
pub struct NamecaseOptions {
    /// Allow lowercase at start of name (preserves prefixes like "von", "van", "de") (default: false)
    pub enable_lowercase_start: bool,
    /// Disable Hebrew "ben"/"bat" prefix handling (default: true)
    pub disable_hebrew: bool,
    /// Disable Spanish capitalization for "El"/"La" (default: true)
    pub disable_spanish: bool,
    /// Disable Roman numeral uppercasing (default: true)
    pub disable_roman_numerals: bool,
    /// Disable post-nominal initials preservation (PhD, MD, etc.) (default: true)
    pub disable_postnominal: bool,
    /// Preserve mixed case input (skip processing) (default: false)
    pub enable_preserve_mixed: bool,
}

impl Default for NamecaseOptions {
    fn default() -> Self {
        Self {
            enable_preserve_mixed: false,
            enable_lowercase_start: false,
            disable_hebrew: false,
            disable_spanish: false,
            disable_roman_numerals: false,
            disable_postnominal: false,
        }
    }
}

/// Don't change capitalization unless capitalization isn't set
fn check_name(name: &str) -> bool {
    name == name.to_lowercase() || name == name.to_uppercase()
}

// Precompiled regexes
static RE_SPACES: Lazy<Regex> = Lazy::new(|| Regex::new(r"\s{2,}").expect("RE_SPACES"));
static RE_WORD: Lazy<Regex> = Lazy::new(|| Regex::new(r#"([^\s\-'",./()]+)"#).expect("RE_WORD"));
static RE_MAC_PATTERN: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"\bMac[A-Za-z]{2,}[^aciozj]\b").expect("RE_MAC_PATTERN"));
static RE_MC_PATTERN: Lazy<Regex> = Lazy::new(|| Regex::new(r"\bMc").expect("RE_MC_PATTERN"));
static RE_SPECIAL_MAC: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?i)\b(MacMurdo|MacIsaac)\b").expect("RE_SPECIAL_MAC"));
static RE_MAC_PREFIX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"\b(Ma?c)([A-Za-z]+)").expect("RE_MAC_PREFIX"));
// Roman numeral pattern - matches at end of string
// Limitations: Only supports I (1), V (5), X (10) characters, not L (50), C (100), D (500), M (1000)
// Therefore can only match Roman numerals 1-39 (I through XXXIX)
// This is so as to not match Chinese names -- e.g. Li
static RE_ROMAN_NUMERAL: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"(?i)\b(?:[IVX])(?:X{0,3}I{0,3}|X{0,2}VI{0,3}|X{0,2}I?[VX])$")
        .expect("RE_ROMAN_NUMERAL")
});
static RE_NOI: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\b[0-9](x)\b").expect("RE_NOI"));
static RE_CONSONANT_PAIR: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?i)\b([bcdfghjklmnpqrstvwxz]{2})(\s)").expect("RE_CONSONANT_PAIR"));
static RE_TITLE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?i)\b(mr|ms|dr|st|jr|sr|lt)\.?\b").expect("RE_TITLE"));
static RE_LOWERCASE_WORDS: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"\b(the|of|and)\b").expect("RE_LOWERCASE_WORDS"));

// Honorific/title abbreviations
static TITLES: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
    let mut m = HashMap::new();
    m.insert("mr", "Mr");
    m.insert("ms", "Ms");
    m.insert("dr", "Dr");
    m.insert("st", "St");
    m.insert("jr", "Jr");
    m.insert("sr", "Sr");
    m.insert("lt", "Lt");
    m
});

// Common lowercase words in names
static LOWERCASE_WORDS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
    let mut s = HashSet::new();
    s.insert("the");
    s.insert("of");
    s.insert("and");
    s
});

// Mac exceptions as a list of (Regex, Replacement)
static MAC_EXCEPTIONS: Lazy<Vec<(Regex, &'static str)>> = Lazy::new(|| {
    vec![
        (Regex::new(r"(\bMacEvicius\b)").unwrap(), "Macevicius"),
        (Regex::new(r"(\bMacHado\b)").unwrap(), "Machado"),
        (Regex::new(r"(\bMacHar\b)").unwrap(), "Machar"),
        (Regex::new(r"(\bMacHin\b)").unwrap(), "Machin"),
        (Regex::new(r"(\bMacHlin\b)").unwrap(), "Machlin"),
        (Regex::new(r"(\bMacIas\b)").unwrap(), "Macias"),
        (Regex::new(r"(\bMacIulis\b)").unwrap(), "Maciulis"),
        (Regex::new(r"(\bMacKie\b)").unwrap(), "Mackie"),
        (Regex::new(r"(\bMacKle\b)").unwrap(), "Mackle"),
        (Regex::new(r"(\bMacKlin\b)").unwrap(), "Macklin"),
        (Regex::new(r"(\bMacQuarie\b)").unwrap(), "Macquarie"),
        (Regex::new(r"(\bMacOmber\b)").unwrap(), "Macomber"),
        (Regex::new(r"(\bMacIn\b)").unwrap(), "Macin"),
        (Regex::new(r"(\bMacKintosh\b)").unwrap(), "Mackintosh"),
        (Regex::new(r"(\bMacKen\b)").unwrap(), "Macken"),
        (Regex::new(r"(\bMacHen\b)").unwrap(), "Machen"),
        (Regex::new(r"(\bMacHiel\b)").unwrap(), "Machiel"),
        (Regex::new(r"(\bMacIol\b)").unwrap(), "Maciol"),
        (Regex::new(r"(\bMacKell\b)").unwrap(), "Mackell"),
        (Regex::new(r"(\bMacKlem\b)").unwrap(), "Macklem"),
        (Regex::new(r"(\bMacKrell\b)").unwrap(), "Mackrell"),
        (Regex::new(r"(\bMacLin\b)").unwrap(), "Maclin"),
        (Regex::new(r"(\bMacKey\b)").unwrap(), "Mackey"),
        (Regex::new(r"(\bMacKley\b)").unwrap(), "Mackley"),
        (Regex::new(r"(\bMacHell\b)").unwrap(), "Machell"),
        (Regex::new(r"(\bMacHon\b)").unwrap(), "Machon"),
        (Regex::new(r"(\bMacAyla\b)").unwrap(), "Macayla"),
        (Regex::new(r"(?i)(\bMacmurdo\b)").unwrap(), "MacMurdo"),
        (Regex::new(r"(?i)(\bMacisaac\b)").unwrap(), "MacIsaac"),
    ]
});

// Linguistic prefix rules
static PREFIX_RULES: Lazy<Vec<(Regex, &'static str)>> = Lazy::new(|| {
    vec![
        (Regex::new(r"\b(Al)(\s+\w)").unwrap(), "al$2"),
        (Regex::new(r"\bAp\b").unwrap(), "ap"),
        (Regex::new(r"\bDell([ae])\b").unwrap(), "dell$1"),
        (Regex::new(r"\bD([aeiu])\b").unwrap(), "d$1"),
        (Regex::new(r"\bDe([lr])\b").unwrap(), "de$1"),
        (Regex::new(r"\b(Le)(\s+\w)").unwrap(), "le$2"),
        (Regex::new(r"\bLo\b").unwrap(), "lo"),
        (Regex::new(r"\b(Van)(\s+\w)").unwrap(), "van$2"),
        (Regex::new(r"\bVon\b").unwrap(), "von"),
    ]
});

static PREFIX_RULES_SPANISH: Lazy<Vec<(Regex, &'static str)>> = Lazy::new(|| {
    vec![
        (Regex::new(r"\bEl\b").unwrap(), "el"),
        (Regex::new(r"\bLa\b").unwrap(), "la"),
        (Regex::new(r"\bY\b").unwrap(), "y"),
    ]
});

static PREFIX_RULES_HEBREW: Lazy<Vec<(Regex, &'static str)>> = Lazy::new(|| {
    vec![
        (Regex::new(r"\b(Ben)(\s+\w)").unwrap(), "ben$2"),
        (Regex::new(r"\bBat\b").unwrap(), "bat"),
    ]
});

// Post-nominal initials (degrees, titles, certifications)
static POST_NOMINAL_INITIALS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
    HashSet::from([
        // Honours and decorations
        "VC",
        "GC",
        "KG",
        "LG",
        "KT",
        "LT",
        "KP",
        "GCB",
        "OM",
        "GCSI",
        "GCMG",
        "GCIE",
        "GCVO",
        "GBE",
        "CH",
        "KCB",
        "DCB",
        "KCSI",
        "KCMG",
        "DCMG",
        "KCIE",
        "KCVO",
        "DCVO",
        "KBE",
        "DBE",
        "CB",
        "CSI",
        "CMG",
        "CIE",
        "CVO",
        "CBE",
        "DSO",
        "LVO",
        "OBE",
        "ISO",
        "MVO",
        "MBE",
        "IOM",
        "CGC",
        "RRC",
        "DSC",
        "MC",
        "DFC",
        "AFC",
        "ARRC",
        "OBI",
        "DCM",
        "CGM",
        "GM",
        "IDSM",
        "DSM",
        "MM",
        "DFM",
        "AFM",
        "SGM",
        "CPM",
        "QGM",
        "RVM",
        "BEM",
        "QPM",
        "QFSM",
        "QAM",
        "MSM",
        "ERD",
        "VD",
        "TD",
        "UD",
        "ED",
        "RD",
        "VRD",
        "AE",
        // Appointments
        "PC",
        "ADC",
        "QHP",
        "QHS",
        "QHDS",
        "QHNS",
        "QHC",
        "SCJ",
        "J",
        "LJ",
        "QS",
        "SL",
        "QC",
        "KC",
        "JP",
        "DL",
        "MP",
        "MSP",
        "MSYP",
        "AM",
        "MLA",
        "MEP",
        // Doctorates
        "DBEnv",
        "DConstMgt",
        "DREst",
        "EdD",
        "DPhil",
        "PhD",
        "DLitt",
        "DSocSci",
        "MD",
        "EngD",
        "DD",
        "LLD",
        "DProf",
        // Masters
        "MA",
        "MArch",
        "MAnth",
        "MSc",
        "MMORSE",
        "MMath",
        "MMathStat",
        "MPharm",
        "MPhil",
        "MSci",
        "MSt",
        "MRes",
        "MEng",
        "MChem",
        "MBiochem",
        "MSocSc",
        "MMus",
        "LLM",
        "BCL",
        "MPhys",
        "MComp",
        "MAcc",
        "MFin",
        "MBA",
        "MPA",
        "MEd",
        "MEP",
        "MEnt",
        "MCGI",
        "MGeol",
        "MLitt",
        "MEarthSc",
        "MClinRes",
        // Bachelors
        "BA",
        "BSc",
        "LLB",
        "BEng",
        "MBChB",
        "FdA",
        "FdSc",
        "FdEng",
        // Postgraduate diplomas
        "PgDip",
        "PgD",
        "PgCert",
        "PgC",
        "PgCLTHE",
        // Other qualifications
        "AUH",
        "AKC",
        "AUS",
        "HNC",
        "HNCert",
        "HND",
        "HNDip",
        "DipHE",
        "Dip",
        "OND",
        "CertHE",
        "ACSM",
        "MCSM",
        "DIC",
        "AICSM",
        "ARSM",
        "ARCS",
        "MJur",
        "DipLP",
        // Professional - Legal
        "FCILEx",
        "GCILEx",
        "ACILEx",
        // Professional - Social work
        "CQSW",
        "DipSW",
        "BSW",
        "MSW",
        // Professional - Transport
        "FCILT",
        "CMILT",
        "MILT",
        "CPL",
        "CTP",
        "CML",
        "PLS",
        "CTL",
        "DLP",
        "PLog",
        "EJLog",
        "ESLog",
        "EMLog",
        "JrLog",
        "Log",
        "SrLog",
        // Professional - Architecture
        "BArch",
        "ARB",
        "RIBA",
        "RIAS",
        "RIAI",
        "RSAW",
        // Medical qualifications
        "MB",
        "BM",
        "BS",
        "BCh",
        "BChir",
        "MRCS",
        "FRCS",
        "MS",
        "MCh",
        "MRCP",
        "FRCP",
        "MRCPCH",
        "FRCPCH",
        "MRCPath",
        "MFPM",
        "FFPM",
        "BDS",
        "MRCPsych",
        "FRCPsych",
        "MRCOG",
        "FRCOG",
        "MCEM",
        "FCEM",
        "FRCA",
        "FFPMRCA",
        "MRCGP",
        "FRCGP",
        "MScChiro",
        "MChiro",
        "DC",
        "LFHOM",
        "MFHOM",
        "FFHOM",
        "FADO",
        "FBDO",
        "FCOptom",
        "MCOptom",
        "MOst",
        "DPT",
        "MCSP",
        "FCSP",
        "SROT",
        "MSCR",
        "FSCR",
        "CPhT",
        // Veterinary
        "RN",
        "VN",
        "RVN",
        "BVSc",
        "BVetMed",
        "VetMB",
        "MRCVS",
        "FRCVS",
        "FAWM",
        // Teaching
        "PGCAP",
        "PGCHE",
        "PGCE",
        "PGDE",
        "BEd",
        "NPQH",
        "QTS",
        "CSci",
        "CSciTeach",
        "RSci",
        "RSciTech",
        // Engineering
        "CEng",
        "IEng",
        "EngTech",
        "ICTTech",
        "DEM",
        "CMarEng",
        "CMarSci",
        "CMarTech",
        "IMarEng",
        "MarEngTech",
        // Nursing - UK
        "RGN",
        "SRN",
        "RMN",
        "RSCN",
        "SEN",
        "EN",
        "RNMH",
        "RM",
        "RN1",
        "RNA",
        "RN2",
        "RN3",
        "RN4",
        "RN5",
        "RNLD",
        "RN6",
        "RN8",
        "RNC",
        "RN7",
        "RN9",
        "RHV",
        "RSN",
        "ROH",
        "RFHN",
        "SPAN",
        "SPMH",
        "SPCN",
        "SPLD",
        "SPHP",
        "SCHM",
        "SCLD",
        "SPCC",
        "SPDN",
        "V100",
        "V200",
        "V300",
        "LPE",
    ])
});

fn capitalize(word: &str) -> String {
    let mut chars = word.chars();
    match chars.next() {
        None => String::new(),
        Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
    }
}

fn capitalize_split_words<'a>(text: &'a str) -> Cow<'a, str> {
    RE_WORD.replace_all(text, |caps: &Captures| capitalize(&caps[0]))
}

pub fn normalize<'a>(name: &'a str) -> Cow<'a, str> {
    RE_SPACES.replace_all(name, " ")
}

fn handle_mac_names<'a>(text: &'a str) -> Cow<'a, str> {
    if !RE_MAC_PATTERN.is_match(text)
        && !RE_MC_PATTERN.is_match(text)
        && !RE_SPECIAL_MAC.is_match(text)
    {
        return Cow::Borrowed(text);
    }

    let mut result = RE_MAC_PREFIX
        .replace_all(text, |caps: &Captures| {
            let prefix = &caps[1];
            let suffix = &caps[2];
            format!("{}{}", prefix, capitalize(suffix))
        })
        .into_owned();

    for (regex, replacement) in MAC_EXCEPTIONS.iter() {
        result = regex.replace_all(&result, *replacement).into_owned();
    }
    Cow::Owned(result)
}

fn handle_linguistic_prefixes<'a>(text: &'a str, opt: NamecaseOptions) -> Cow<'a, str> {
    let mut result = text.to_string();

    for (regex, replacement) in PREFIX_RULES.iter() {
        result = regex.replace_all(&result, *replacement).into_owned();
    }

    // handle Spanish El/La if Spanish mode is ENABLED
    if !opt.disable_spanish {
        for (regex, replacement) in PREFIX_RULES_SPANISH.iter() {
            result = regex.replace_all(&result, *replacement).into_owned();
        }
    }

    // Handle Hebrew ben/bat if Hebrew mode enabled
    if !opt.disable_hebrew {
        for (regex, replacement) in PREFIX_RULES_HEBREW.iter() {
            result = regex.replace_all(&result, *replacement).into_owned();
        }
    }

    Cow::Owned(result)
}

fn handle_special_cases<'a>(text: &'a str, opt: NamecaseOptions) -> Cow<'a, str> {
    let mut result = text.to_string();

    // Roman numerals (conditional on opt.roman_numerals)
    if !opt.disable_roman_numerals {
        result = RE_ROMAN_NUMERAL
            .replace_all(&result, |caps: &Captures| caps[0].to_uppercase())
            .into_owned();
    }

    result = RE_NOI
        .replace_all(&result, |caps: &Captures| caps[0].to_uppercase())
        .into_owned();

    result = RE_CONSONANT_PAIR
        .replace_all(&result, |caps: &Captures| {
            format!("{}{}", caps[1].to_uppercase(), &caps[2])
        })
        .into_owned();

    result = RE_TITLE
        .replace_all(&result, |caps: &Captures| {
            let title = &caps[1];
            let full_match = &caps[0];
            if let Some(replacement) = TITLES.get(title.to_lowercase().as_str()) {
                replacement.to_string()
            } else {
                full_match.to_string()
            }
        })
        .into_owned();

    result = RE_LOWERCASE_WORDS
        .replace_all(&result, |caps: &Captures| {
            let word = &caps[1];
            if LOWERCASE_WORDS.contains(word.to_lowercase().as_str()) {
                word.to_lowercase()
            } else {
                word.to_string()
            }
        })
        .into_owned();

    // Post-nominal initials (conditional on opt.postnominal)
    if !opt.disable_postnominal {
        // Post-nominals only appear at the END of names
        // Check the last 1-3 words for potential post-nominals
        let words: Vec<&str> = result.split_whitespace().collect();
        let word_count = words.len();

        if word_count > 0 {
            // Only check up to the last 3 words for post-nominals
            let check_start = if word_count > 3 {
                word_count - 3
            } else {
                word_count - word_count.min(1) // Start from first word if 1-3 words total
            };

            let mut processed_words: Vec<String> = words[..check_start]
                .iter()
                .map(|&w| w.to_string())
                .collect();

            // Check the last few words for post-nominals
            for &word in &words[check_start..] {
                let upper = word.to_uppercase();
                // Find the matching post-nominal (case-insensitive comparison)
                let replacement = POST_NOMINAL_INITIALS
                    .iter()
                    .find(|&pn| pn.to_uppercase() == upper)
                    .map(|&pn| pn.to_string())
                    .unwrap_or_else(|| word.to_string());
                processed_words.push(replacement);
            }

            result = processed_words.join(" ");
        }
    }

    Cow::Owned(result)
}

pub fn namecase(input: &str, opt: NamecaseOptions) -> String {
    if input.trim().is_empty() {
        return input.to_string();
    }

    // Preserve mixed case if input is already mixed case and enable_preserve_mixed is enabled
    if opt.enable_preserve_mixed && !check_name(input.trim()) {
        return input.trim().to_string();
    }

    let lowercased = input.trim().to_lowercase();
    let normalized = normalize(&lowercased);
    let capitalized = capitalize_split_words(&normalized);
    let mac_handled = handle_mac_names(&capitalized);
    let prefix_handled = handle_linguistic_prefixes(&mac_handled, opt);
    let special_handled = handle_special_cases(&prefix_handled, opt);
    let result = normalize(&special_handled);

    if opt.enable_lowercase_start {
        // Allow lowercase start - return without capitalizing first letter
        return result.into_owned();
    }

    // Always capitalize first letter
    capitalize(&result)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_capitalization() {
        let opt = NamecaseOptions::default();
        assert_eq!(namecase("GEORGE WASHINGTON", opt), "George Washington");
        assert_eq!(namecase("george washington", opt), "George Washington");
        assert_eq!(namecase("gEoRgE wAsHiNgToN", opt), "George Washington");
        assert_eq!(namecase("george", opt), "George");
        assert_eq!(namecase("", opt), "");
    }

    #[test]
    fn test_preserve_mixed() {
        let opt = NamecaseOptions {
            enable_preserve_mixed: true,
            ..NamecaseOptions::default()
        };
        assert_eq!(namecase("GEORGE WASHINGTON", opt), "George Washington");
        assert_eq!(namecase("george washington", opt), "George Washington");
        assert_eq!(namecase("gEoRgE wAsHiNgToN", opt), "gEoRgE wAsHiNgToN");
    }

    #[test]
    fn test_spanish_capitalization() {
        let opt = NamecaseOptions {
            enable_lowercase_start: true,
            ..NamecaseOptions::default()
        };
        let no_spanish_opt = NamecaseOptions {
            disable_spanish: true,
            enable_lowercase_start: true,
            ..NamecaseOptions::default()
        };

        assert_eq!(namecase("el nino", no_spanish_opt), "El Nino");
        assert_eq!(namecase("la niña", no_spanish_opt), "La Niña");
        assert_eq!(namecase("el niño", opt), "el Niño");
        assert_eq!(namecase("la niña", opt), "la Niña");
    }

    #[test]
    fn test_hebrew_capitalization() {
        let opt = NamecaseOptions::default();
        let no_hebrew_opt = NamecaseOptions {
            disable_hebrew: true,
            ..NamecaseOptions::default()
        };

        assert_eq!(
            namecase("Aharon BEN Amram Ha-Kohein", opt),
            "Aharon ben Amram Ha-Kohein"
        );
        assert_eq!(
            namecase("Aharon BEN Amram Ha-Kohein", no_hebrew_opt),
            "Aharon Ben Amram Ha-Kohein"
        );
    }

    #[test]
    fn test_postnominal_initials() {
        let opt = NamecaseOptions::default();
        let no_postnominal_opt = NamecaseOptions {
            disable_postnominal: true,
            ..NamecaseOptions::default()
        };

        assert_eq!(namecase("Barbie PHD", opt), "Barbie PhD");
        assert_eq!(namecase("Barbie PHD", no_postnominal_opt), "Barbie Phd");
        assert_eq!(namecase("John Smith MD", opt), "John Smith MD");
        assert_eq!(namecase("Jane Doe MBA", opt), "Jane Doe MBA");
        assert_eq!(namecase("Dr. Smith PhD MD", opt), "Dr. Smith PhD MD");
    }

    #[test]
    fn test_roman_numerals() {
        let opt = NamecaseOptions::default();
        let no_roman_opt = NamecaseOptions {
            disable_roman_numerals: true,
            ..NamecaseOptions::default()
        };

        // Test Roman numerals are uppercased when enabled
        assert_eq!(namecase("henry viii", opt), "Henry VIII");
        assert_eq!(namecase("louis xiv", opt), "Louis XIV");
        assert_eq!(namecase("charles ii", opt), "Charles II");

        // Test that Roman numerals are NOT uppercased when disabled
        assert_eq!(namecase("henry viii", no_roman_opt), "Henry Viii");
        assert_eq!(namecase("louis xiv", no_roman_opt), "Louis Xiv");
        assert_eq!(namecase("charles ii", no_roman_opt), "Charles Ii");
    }

    #[test]
    fn test_allow_lowercase_start() {
        let opt = NamecaseOptions {
            enable_lowercase_start: true, // Allow lowercase prefixes
            ..Default::default()
        };
        let names = vec![
            "Keith",
            "Leigh-Williams",
            "McCarthy",
            "O'Callaghan",
            "St. John",
            "von Streit",
            "van Dyke",
            "Van",
            "ap Llwyd Dafydd",
            "al Fahd",
            "Al",
            "el Grecco",
            "ben Gurion",
            "Ben",
            "da Vinci",
            "di Caprio",
            "du Pont",
            "de Legate",
            "del Crond",
            "der Sind",
            "van der Post",
            "von Trapp",
            "la Poisson",
            "le Figaro",
            "Mack Knife",
            "Dougal MacDonald",
            "Machin",
            "Machlin",
            "Machar",
            "Mackle",
            "Macklin",
            "Mackie",
            "Macquarie",
            "Machado",
            "Macevicius",
            "Maciulis",
            "Macias",
            "MacMurdo",
            "Mackrell",
            "Maclin",
            "McConnachie",
            "Henry VIII",
            "Louis III",
            "Louis XIV",
            "Charles II",
        ];

        for name in names {
            assert_eq!(namecase(name, opt), name, "Failed on {}", name);
        }
    }

    #[test]
    fn test_combined_fields() {
        let opt = NamecaseOptions {
            enable_lowercase_start: false, // Always capitalize first letter
            ..Default::default()
        };
        let names = vec![
            "Michael Abrash",
            "Scott Adams",
            "Leonard Adleman",
            "Alfred Aho",
            "JJ Allaire",
            "Andrei Alexandrescu",
            "Paul Allen",
            "Eric Allman",
            "Marc Andreessen",
            "Bill Atkinson",
            "John Backus",
            "Richard Bartle",
            "Brian Behlendorf",
            "Kent Beck",
            "Donald Becker",
            "Doug Bell",
            "Fabrice Bellard",
            "Tim Berners-Lee",
            "Daniel J. Bernstein",
            "Sabeer Bhatia",
            "Eric Bina",
            "Marc Blank",
            "Joshua Bloch",
            "Grady Booch",
            "Bert Bos",
            "Stephen Richard Bourne",
            "David Bradley",
            "Andrew Braybrook",
            "Lawrence M. Breed",
            "Jack E. Bresenham",
            "Dan Bricklin",
            "Walter Bright",
            "Richard Brodie",
            "Andries Brouwer",
            "Danielle Bunten Berry",
            "Dries Buytaert",
            "Steve Capps",
            "John D. Carmack",
            "Vinton Cerf",
            "Ward Christensen",
            "Edgar F. Codd",
            "Bram Cohen",
            "Alain Colmerauer",
            "Alan Cooper",
            "Alan Cox",
            "Brad Cox",
            "Mike Cowlishaw",
            "Mark Crispin",
            "Ward Cunningham",
            "William Crowther",
            "Dave Cutler",
            "Ole-Johan Dahl",
            "James Duncan Davidson",
            "L. Peter Deutsch",
            "Edsger Dijkstra",
            "Matt Dillon",
            "Jack Dorsey",
            "Martin Dougiamas",
            "Adam Dunkels",
            "Les Earnest",
            "Brendan Eich",
            "Larry Ellison",
            "Marc Ewing",
            "Dan Farmer",
            "Stuart Feldman",
            "David Filo",
            "Brad Fitzpatrick",
            "Andrew Fluegelman",
            "Brian Fox",
            "Martin Fowler",
            "Jim Fruchterman",
            "Elon Gasper",
            "Bill Gates",
            "Steve Gibson",
            "John Gilmore",
            "Adele Goldberg",
            "Ryan C. Gordon",
            "James Gosling",
            "Bill Gosper",
            "Andrew Gower",
            "Paul Gower",
            "Paul Graham",
            "John Graham-Cumming",
            "Ralph Griswold",
            "Richard Greenblatt",
            "Scott Guthrie",
            "Andi Gutmans",
            "Jim Hall",
            "David Heinemeier Hansson",
            "David Albert Huffman",
            "Rebecca Heineman",
            "Anders Hejlsberg",
            "Ted Henter",
            "Andy Hertzfeld",
            "Rich Hickey",
            "D. Richard Hipp",
            "C. A. R. Hoare",
            "James Holmes",
            "Grace Hopper",
            "Dave Hyatt",
            "Miguel de Icaza",
            "Roberto Ierusalimschy",
            "Dan Ingalls",
            "Geir Ivarsøy",
            "Kenneth E. Iverson",
            "Toru Iwatani",
            "Bo Jangeborg",
            "Paul Jardetzky",
            "Lynne Jolitz",
            "William Jolitz",
            "Stephen C. Johnson",
            "Bill Joy",
            "Robert K. Jung",
            "Poul-Henning Kamp",
            "Mitch Kapor",
            "Phil Katz",
            "Alan Kay",
            "Mel Kaye",
            "John George Kemeny",
            "Stan Kelly-Bootle",
            "Brian Kernighan",
            "Gary Kildall",
            "Tom Knight",
            "Jim Knopf",
            "Donald E. Knuth",
            "Andrew Koenig",
            "Tom Lane",
            "Leslie Lamport",
            "Butler Lampson",
            "Sam Lantinga",
            "Richard H. Lathwell",
            "Chris Lattner",
            "Samuel J Leffler",
            "Rasmus Lerdorf",
            "Michael Lesk",
            "Gordon Letwin",
            "Rockford Lhotka",
            "HÃ¥kon Wium Lie",
            "Robert Love",
            "Ada Lovelace",
            "Al Lowe",
            "Raphael Manfredi",
            "Khaled Mardam-Bey",
            "Yukihiro Matsumoto",
            "John McCarthy",
            "Craig McClanahan",
            "Daniel D. McCracken",
            "Douglas McIlroy",
            "Shawn McKenzie",
            "Marshall Kirk McKusick",
            "Bertrand Meyer",
            "Scott Meyers",
            "Bob Miner",
            "Jeff Minter",
            "Lou Montulli",
            "Bram Moolenaar",
            "David Moon",
            "Charles H. Moore",
            "Roger Moore",
            "Mike Muuss",
            "Patrick Naughton",
            "Peter Naur",
            "Fredrik Neij",
            "Graham Nelson",
            "Peter Norton",
            "Kristen Nygaard",
            "Ed Oates",
            "Martin Odersky",
            "Jarkko Oikarinen",
            "Oliver Twins",
            "John Ousterhout",
            "Onel de Guzman",
            "Larry Page",
            "Alexey Pajitnov",
            "Seymour Papert",
            "Tim Paterson",
            "Markus Persson",
            "Jeffrey Peterson",
            "Charles Petzold",
            "Rob Pike",
            "Kent Pitman",
            "Theo de Raadt",
            "Jef Raskin",
            "Eric S. Raymond",
            "Hans Reiser",
            "John Resig",
            "Craig Reynolds",
            "Dennis Ritchie",
            "Ron Rivest",
            "John Romero",
            "Blake Ross",
            "Guido van Rossum",
            "Jeff Rulifson",
            "Rusty Russell",
            "Steve Russell",
            "Mark Russinovich",
            "Bob Sabiston",
            "Muni Sakya",
            "Carl Sassenrath",
            "Chris Sawyer",
            "Bill Schelter",
            "Randal L. Schwartz",
            "Adi Shamir",
            "Mike Shaver",
            "Cliff Shaw",
            "Zed Shaw",
            "Emily Short",
            "Jacek Sieka",
            "Ken Silverman",
            "Charles Simonyi",
            "Colin Simpson",
            "Rich Skrenta",
            "Matthew Smith",
            "Henry Spencer",
            "Joel Spolsky",
            "Quentin Stafford-Fraser",
            "Richard Stallman",
            "Guy Steele",
            "Alexander Stepanov",
            "Ludvig Strigeus",
            "Bjarne Stroustrup",
            "Zeev Suraski",
            "Gerald Jay Sussman",
            "Herb Sutter",
            "Gottfrid Svartholm",
            "Tim Sweeney",
            "Andrew S. Tanenbaum",
            "Audrey Tang",
            "Simon Tatham",
            "Larry Tesler",
            "Jon Stephenson von Tetzchner",
            "Avie Tevanian",
            "Ken Thompson",
            "Michael Tiemann",
            "Linus Torvalds",
            "Andrew Tridgell",
            "Roy Trubshaw",
            "Bob Truel",
            "Wietse Venema",
            "Pat Villani",
            "Paul Vixie",
            "Patrick Volkerding",
            "Larry Wall",
            "Bob Wallace",
            "John Walker",
            "John Warnock",
            "Joseph Weizenbaum",
            "Robert Watson",
            "Pei-Yuan Wei",
            "Peter J. Weinberger",
            "Andrew Welch",
            "David Wheeler",
            "Arthur Whitney",
            "Bruce Wilcox",
            "Evan Williams",
            "Roberta Williams",
            "Sophie Wilson",
            "Dave Winer",
            "Niklaus Wirth",
            "Stephen Wolfram",
            "Don Woods",
            "Steve Wozniak",
            "Will Wright",
            "Jerry Yang",
            "Victor Yngve",
            "Jamie Zawinski",
            "Philip Zimmermann",
            "Mark Zuckerberg",
            "Khiem Le",
            "Macayla Carrns",
            "Dr Carmen Balzano",
            "Dr. Carmen Balzano",
            "Dr Robert & Ann Leitz",
            "Thao & Hy Nguyen",
            "Ty Cobb",
            "Eugene L. Nath,Jr.",
            "Lori & Leslie Cotton/Smith",
            "Ron/Alejandra Brown",
            "Derrick/Sandra Jackson",
        ];

        for name in names {
            assert_eq!(namecase(name, opt), name, "Failed on {}", name);
        }
    }
}