oxiphysics-io 0.1.1

File I/O and serialization for the OxiPhysics engine
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
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
#![allow(clippy::needless_range_loop)]
// Copyright 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! AMBER molecular dynamics file format I/O (prmtop, rst7, mdcrd, mdinfo).
//!
//! Supports reading and writing the primary AMBER file formats used in
//! classical molecular dynamics simulations:
//!
//! - `prmtop` / `parm7` – topology + force-field parameters
//! - `rst7` / `inpcrd` – restart / initial-coordinate files
//! - `mdcrd` / `nc` – ASCII trajectory files
//! - `mdin` – MD input (namelist) files
//! - `mdinfo` – runtime energy/temperature summary files
//! - GAFF / ff14SB parameter files (MASS, BOND, ANGLE, DIHE sections)

use std::collections::HashMap;
use std::fmt;
use std::io::{BufRead, BufReader, BufWriter, Read, Write};
// ──────────────────────────────────────────────────────────────────────────────
// Shared error type
// ──────────────────────────────────────────────────────────────────────────────

/// Errors produced by the AMBER I/O module.
#[derive(Debug)]
pub enum AmberIoError {
    /// The file could not be parsed.
    ParseError(String),
    /// An I/O operation failed.
    IoError(String),
    /// A required section was not found.
    MissingSection(String),
    /// Unexpected end of data.
    UnexpectedEof,
}

impl fmt::Display for AmberIoError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AmberIoError::ParseError(s) => write!(f, "AMBER parse error: {s}"),
            AmberIoError::IoError(s) => write!(f, "AMBER I/O error: {s}"),
            AmberIoError::MissingSection(s) => write!(f, "AMBER missing section: {s}"),
            AmberIoError::UnexpectedEof => write!(f, "AMBER unexpected end of file"),
        }
    }
}

impl std::error::Error for AmberIoError {}

// ──────────────────────────────────────────────────────────────────────────────
// PrmtopAtom
// ──────────────────────────────────────────────────────────────────────────────

/// A single atom entry from an AMBER topology (`prmtop`) file.
#[derive(Debug, Clone, PartialEq)]
pub struct PrmtopAtom {
    /// AMBER atom name (up to 4 characters).
    pub name: String,
    /// Partial charge in AMBER internal units (e × 18.2223).
    pub charge: f64,
    /// Atomic mass in u (unified atomic mass units).
    pub mass: f64,
    /// AMBER atom-type string.
    pub atom_type: String,
}

impl PrmtopAtom {
    /// Create a new [`PrmtopAtom`].
    pub fn new(
        name: impl Into<String>,
        charge: f64,
        mass: f64,
        atom_type: impl Into<String>,
    ) -> Self {
        PrmtopAtom {
            name: name.into(),
            charge,
            mass,
            atom_type: atom_type.into(),
        }
    }

    /// Convert the stored AMBER charge to SI elementary charges (divide by 18.2223).
    pub fn charge_si(&self) -> f64 {
        self.charge / 18.2223
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// PrmtopBond
// ──────────────────────────────────────────────────────────────────────────────

/// Bond connectivity and force-field parameters from a prmtop file.
#[derive(Debug, Clone, PartialEq)]
pub struct PrmtopBond {
    /// Index of the first atom (0-based).
    pub atom_i: usize,
    /// Index of the second atom (0-based).
    pub atom_j: usize,
    /// Harmonic force constant k (kcal mol⁻¹ Å⁻²).
    pub force_constant: f64,
    /// Equilibrium bond length r₀ (Å).
    pub eq_length: f64,
}

impl PrmtopBond {
    /// Create a new [`PrmtopBond`].
    pub fn new(atom_i: usize, atom_j: usize, force_constant: f64, eq_length: f64) -> Self {
        PrmtopBond {
            atom_i,
            atom_j,
            force_constant,
            eq_length,
        }
    }

    /// Compute the harmonic potential energy for a given bond length.
    ///
    /// `E = k * (r - r0)^2`
    pub fn energy(&self, r: f64) -> f64 {
        self.force_constant * (r - self.eq_length).powi(2)
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// PrmtopAngle
// ──────────────────────────────────────────────────────────────────────────────

/// Angle connectivity and force-field parameters from a prmtop file.
#[derive(Debug, Clone, PartialEq)]
pub struct PrmtopAngle {
    /// Index of atom i (0-based).
    pub atom_i: usize,
    /// Index of the central atom j (0-based).
    pub atom_j: usize,
    /// Index of atom k (0-based).
    pub atom_k: usize,
    /// Harmonic force constant k_θ (kcal mol⁻¹ rad⁻²).
    pub force_constant: f64,
    /// Equilibrium angle θ₀ (radians).
    pub eq_angle: f64,
}

impl PrmtopAngle {
    /// Create a new [`PrmtopAngle`].
    pub fn new(
        atom_i: usize,
        atom_j: usize,
        atom_k: usize,
        force_constant: f64,
        eq_angle: f64,
    ) -> Self {
        PrmtopAngle {
            atom_i,
            atom_j,
            atom_k,
            force_constant,
            eq_angle,
        }
    }

    /// Compute the harmonic bending energy for a given angle.
    ///
    /// `E = k * (θ - θ0)^2`
    pub fn energy(&self, theta: f64) -> f64 {
        self.force_constant * (theta - self.eq_angle).powi(2)
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// PrmtopFile
// ──────────────────────────────────────────────────────────────────────────────

/// AMBER topology file (`prmtop` / `parm7`) representation.
///
/// Only the most commonly used sections are modelled here; raw section data
/// for every other `%FLAG` is preserved in `extra_sections`.
#[derive(Debug, Clone, Default)]
pub struct PrmtopFile {
    /// Version string from the `%VERSION` line.
    pub version: String,
    /// All atoms in topology order.
    pub atoms: Vec<PrmtopAtom>,
    /// All covalent bonds.
    pub bonds: Vec<PrmtopBond>,
    /// All valence angles.
    pub angles: Vec<PrmtopAngle>,
    /// Raw text for unrecognised `%FLAG` sections.
    pub extra_sections: HashMap<String, Vec<String>>,
}

impl PrmtopFile {
    /// Create an empty [`PrmtopFile`].
    pub fn new() -> Self {
        PrmtopFile::default()
    }

    /// Write the topology to any [`Write`] sink in a simplified prmtop-style
    /// text format.
    ///
    /// The output is intentionally human-readable rather than byte-perfect
    /// AMBER binary prmtop; it is suitable for round-trip testing.
    pub fn write<W: Write>(&self, writer: &mut W) -> Result<(), AmberIoError> {
        let mut bw = BufWriter::new(writer);
        writeln!(bw, "%VERSION  {}", self.version)
            .map_err(|e| AmberIoError::IoError(e.to_string()))?;
        writeln!(bw, "%FLAG ATOM_NAME").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        writeln!(bw, "%FORMAT(20a4)").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        for (i, atom) in self.atoms.iter().enumerate() {
            write!(bw, "{:<4}", &atom.name).map_err(|e| AmberIoError::IoError(e.to_string()))?;
            if (i + 1) % 20 == 0 {
                writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
            }
        }
        if !self.atoms.len().is_multiple_of(20) {
            writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
        }

        writeln!(bw, "%FLAG CHARGE").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        writeln!(bw, "%FORMAT(5E16.8)").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        for (i, atom) in self.atoms.iter().enumerate() {
            write!(bw, "{:16.8E}", atom.charge)
                .map_err(|e| AmberIoError::IoError(e.to_string()))?;
            if (i + 1) % 5 == 0 {
                writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
            }
        }
        if !self.atoms.len().is_multiple_of(5) {
            writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
        }

        writeln!(bw, "%FLAG MASS").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        writeln!(bw, "%FORMAT(5E16.8)").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        for (i, atom) in self.atoms.iter().enumerate() {
            write!(bw, "{:16.8E}", atom.mass).map_err(|e| AmberIoError::IoError(e.to_string()))?;
            if (i + 1) % 5 == 0 {
                writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
            }
        }
        if !self.atoms.len().is_multiple_of(5) {
            writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
        }

        writeln!(bw, "%FLAG ATOM_TYPE_INDEX").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        writeln!(bw, "%FORMAT(20a4)").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        for (i, atom) in self.atoms.iter().enumerate() {
            write!(bw, "{:<4}", &atom.atom_type)
                .map_err(|e| AmberIoError::IoError(e.to_string()))?;
            if (i + 1) % 20 == 0 {
                writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
            }
        }
        if !self.atoms.len().is_multiple_of(20) {
            writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
        }

        // Bonds
        writeln!(bw, "%FLAG BOND_FORCE_CONSTANT")
            .map_err(|e| AmberIoError::IoError(e.to_string()))?;
        writeln!(bw, "%FORMAT(5E16.8)").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        for (i, bond) in self.bonds.iter().enumerate() {
            write!(bw, "{:16.8E}", bond.force_constant)
                .map_err(|e| AmberIoError::IoError(e.to_string()))?;
            if (i + 1) % 5 == 0 {
                writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
            }
        }
        if !self.bonds.is_empty() && !self.bonds.len().is_multiple_of(5) {
            writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
        }

        writeln!(bw, "%FLAG BOND_EQUIL_VALUE").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        writeln!(bw, "%FORMAT(5E16.8)").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        for (i, bond) in self.bonds.iter().enumerate() {
            write!(bw, "{:16.8E}", bond.eq_length)
                .map_err(|e| AmberIoError::IoError(e.to_string()))?;
            if (i + 1) % 5 == 0 {
                writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
            }
        }
        if !self.bonds.is_empty() && !self.bonds.len().is_multiple_of(5) {
            writeln!(bw).map_err(|e| AmberIoError::IoError(e.to_string()))?;
        }

        writeln!(bw, "%END").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        Ok(())
    }

    /// Parse a simplified prmtop-style text produced by [`PrmtopFile::write`].
    pub fn read<R: Read>(reader: R) -> Result<Self, AmberIoError> {
        let br = BufReader::new(reader);
        let mut file = PrmtopFile::new();
        let lines: Vec<String> = br
            .lines()
            .map(|l| l.map_err(|e| AmberIoError::IoError(e.to_string())))
            .collect::<Result<_, _>>()?;

        let mut i = 0usize;
        let mut names: Vec<String> = Vec::new();
        let mut charges: Vec<f64> = Vec::new();
        let mut masses: Vec<f64> = Vec::new();
        let mut types: Vec<String> = Vec::new();
        let mut bond_kf: Vec<f64> = Vec::new();
        let mut bond_eq: Vec<f64> = Vec::new();

        while i < lines.len() {
            let line = lines[i].trim();
            if line.starts_with("%VERSION") {
                file.version = line.trim_start_matches("%VERSION").trim().to_string();
            } else if line == "%FLAG ATOM_NAME" {
                i += 1; // skip FORMAT
                i += 1;
                while i < lines.len() && !lines[i].starts_with('%') {
                    let row = &lines[i];
                    let mut pos = 0usize;
                    while pos + 4 <= row.len() {
                        names.push(row[pos..pos + 4].trim().to_string());
                        pos += 4;
                    }
                    i += 1;
                }
                continue;
            } else if line == "%FLAG CHARGE" {
                i += 1;
                i += 1;
                while i < lines.len() && !lines[i].starts_with('%') {
                    for tok in lines[i].split_whitespace() {
                        charges.push(
                            tok.parse::<f64>()
                                .map_err(|e| AmberIoError::ParseError(e.to_string()))?,
                        );
                    }
                    i += 1;
                }
                continue;
            } else if line == "%FLAG MASS" {
                i += 1;
                i += 1;
                while i < lines.len() && !lines[i].starts_with('%') {
                    for tok in lines[i].split_whitespace() {
                        masses.push(
                            tok.parse::<f64>()
                                .map_err(|e| AmberIoError::ParseError(e.to_string()))?,
                        );
                    }
                    i += 1;
                }
                continue;
            } else if line == "%FLAG ATOM_TYPE_INDEX" {
                i += 1;
                i += 1;
                while i < lines.len() && !lines[i].starts_with('%') {
                    let row = &lines[i];
                    let mut pos = 0usize;
                    while pos + 4 <= row.len() {
                        types.push(row[pos..pos + 4].trim().to_string());
                        pos += 4;
                    }
                    i += 1;
                }
                continue;
            } else if line == "%FLAG BOND_FORCE_CONSTANT" {
                i += 1;
                i += 1;
                while i < lines.len() && !lines[i].starts_with('%') {
                    for tok in lines[i].split_whitespace() {
                        bond_kf.push(
                            tok.parse::<f64>()
                                .map_err(|e| AmberIoError::ParseError(e.to_string()))?,
                        );
                    }
                    i += 1;
                }
                continue;
            } else if line == "%FLAG BOND_EQUIL_VALUE" {
                i += 1;
                i += 1;
                while i < lines.len() && !lines[i].starts_with('%') {
                    for tok in lines[i].split_whitespace() {
                        bond_eq.push(
                            tok.parse::<f64>()
                                .map_err(|e| AmberIoError::ParseError(e.to_string()))?,
                        );
                    }
                    i += 1;
                }
                continue;
            }
            i += 1;
        }

        let n = names.len();
        for idx in 0..n {
            file.atoms.push(PrmtopAtom {
                name: names.get(idx).cloned().unwrap_or_default(),
                charge: charges.get(idx).copied().unwrap_or(0.0),
                mass: masses.get(idx).copied().unwrap_or(0.0),
                atom_type: types.get(idx).cloned().unwrap_or_default(),
            });
        }

        for idx in 0..bond_kf.len() {
            file.bonds.push(PrmtopBond {
                atom_i: idx * 2,
                atom_j: idx * 2 + 1,
                force_constant: bond_kf[idx],
                eq_length: bond_eq.get(idx).copied().unwrap_or(0.0),
            });
        }

        Ok(file)
    }

    /// Return the number of atoms.
    pub fn natom(&self) -> usize {
        self.atoms.len()
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Rst7File
// ──────────────────────────────────────────────────────────────────────────────

/// AMBER restart / initial-coordinate file (`rst7` / `inpcrd`).
///
/// ASCII format:
/// ```text
/// title
/// natom [time]
/// x1 y1 z1 x2 y2 z2 ...   (10 per line, 12.7 format)
/// [velocities – same format]
/// [box: a b c alpha beta gamma]
/// ```
#[derive(Debug, Clone, Default)]
pub struct Rst7File {
    /// Title line.
    pub title: String,
    /// Simulation time (ps) from the header, if present.
    pub time: Option<f64>,
    /// Cartesian coordinates (Å) in x,y,z order, length = 3 × NATOM.
    pub coordinates: Vec<f64>,
    /// Velocities (Å ps⁻¹) in x,y,z order, same length as coordinates.
    pub velocities: Vec<f64>,
    /// Periodic box dimensions: `[a, b, c, alpha, beta, gamma]`.
    pub box_dimensions: Option<[f64; 6]>,
}

impl Rst7File {
    /// Create an empty [`Rst7File`].
    pub fn new() -> Self {
        Rst7File::default()
    }

    /// Return the number of atoms.
    pub fn natom(&self) -> usize {
        self.coordinates.len() / 3
    }

    /// Write the restart file to any [`Write`] sink.
    ///
    /// Coordinates are written in 12.7 fixed-point format, 6 values per line
    /// (= 2 atoms per line, matching the AMBER specification).
    pub fn write<W: Write>(&self, writer: &mut W) -> Result<(), AmberIoError> {
        let mut bw = BufWriter::new(writer);
        writeln!(bw, "{}", self.title).map_err(|e| AmberIoError::IoError(e.to_string()))?;
        if let Some(t) = self.time {
            writeln!(bw, "{:6}{:15.7e}", self.natom(), t)
                .map_err(|e| AmberIoError::IoError(e.to_string()))?;
        } else {
            writeln!(bw, "{:6}", self.natom()).map_err(|e| AmberIoError::IoError(e.to_string()))?;
        }

        write_f64_block(&mut bw, &self.coordinates, 6)?;

        if !self.velocities.is_empty() {
            write_f64_block(&mut bw, &self.velocities, 6)?;
        }

        if let Some(b) = self.box_dimensions {
            writeln!(
                bw,
                "{:12.7}{:12.7}{:12.7}{:12.7}{:12.7}{:12.7}",
                b[0], b[1], b[2], b[3], b[4], b[5]
            )
            .map_err(|e| AmberIoError::IoError(e.to_string()))?;
        }

        Ok(())
    }

    /// Parse an AMBER restart file from any [`Read`] source.
    pub fn read<R: Read>(reader: R) -> Result<Self, AmberIoError> {
        let br = BufReader::new(reader);
        let mut lines = br.lines();
        let mut rst = Rst7File::new();

        // title
        rst.title = lines
            .next()
            .ok_or(AmberIoError::UnexpectedEof)?
            .map_err(|e| AmberIoError::IoError(e.to_string()))?;

        // natom [time]
        let header = lines
            .next()
            .ok_or(AmberIoError::UnexpectedEof)?
            .map_err(|e| AmberIoError::IoError(e.to_string()))?;
        let mut hparts = header.split_whitespace();
        let natom: usize = hparts
            .next()
            .ok_or(AmberIoError::ParseError("missing natom".into()))?
            .parse()
            .map_err(|e: std::num::ParseIntError| AmberIoError::ParseError(e.to_string()))?;
        if let Some(t) = hparts.next() {
            rst.time = Some(
                t.parse::<f64>()
                    .map_err(|e| AmberIoError::ParseError(e.to_string()))?,
            );
        }

        let n_coord = natom * 3;
        let mut all_values: Vec<f64> = Vec::new();

        for line in lines {
            let l = line.map_err(|e| AmberIoError::IoError(e.to_string()))?;
            let trimmed = l.trim();
            if trimmed.is_empty() {
                continue;
            }
            // Check if this looks like a box line (6 values, reasonable floats)
            let parts: Vec<&str> = trimmed.split_whitespace().collect();
            // If we already have all coords + all vels, remainder is box
            if all_values.len() >= n_coord * 2 && parts.len() == 6 {
                let mut box_vals = [0f64; 6];
                for (i, p) in parts.iter().enumerate() {
                    box_vals[i] = p
                        .parse::<f64>()
                        .map_err(|e| AmberIoError::ParseError(e.to_string()))?;
                }
                rst.box_dimensions = Some(box_vals);
                break;
            }
            for p in parts {
                all_values.push(
                    p.parse::<f64>()
                        .map_err(|e| AmberIoError::ParseError(e.to_string()))?,
                );
            }
        }

        rst.coordinates = all_values[..n_coord.min(all_values.len())].to_vec();
        if all_values.len() > n_coord {
            rst.velocities = all_values[n_coord..].to_vec();
        }

        Ok(rst)
    }
}

/// Write a slice of `f64` values to a writer, `per_line` values per line,
/// using 12.7 fixed-point format.
fn write_f64_block<W: Write>(
    writer: &mut BufWriter<W>,
    values: &[f64],
    per_line: usize,
) -> Result<(), AmberIoError> {
    for (i, v) in values.iter().enumerate() {
        write!(writer, "{:12.7}", v).map_err(|e| AmberIoError::IoError(e.to_string()))?;
        if (i + 1) % per_line == 0 {
            writeln!(writer).map_err(|e| AmberIoError::IoError(e.to_string()))?;
        }
    }
    if !values.is_empty() && !values.len().is_multiple_of(per_line) {
        writeln!(writer).map_err(|e| AmberIoError::IoError(e.to_string()))?;
    }
    Ok(())
}

// ──────────────────────────────────────────────────────────────────────────────
// MdcrdReader
// ──────────────────────────────────────────────────────────────────────────────

/// Reader for AMBER ASCII trajectory files (`mdcrd`).
///
/// Format:
/// ```text
/// title
/// x1 y1 z1 x2 ... (10 values per line, 8.3 format)
/// [box a b c] (optional, if IFBOX > 0)
/// ```
pub struct MdcrdReader<R: BufRead> {
    reader: R,
    /// Number of atoms in each frame.
    pub natom: usize,
    /// Whether each frame includes a periodic box record.
    pub has_box: bool,
    title_consumed: bool,
}

impl<R: BufRead> MdcrdReader<R> {
    /// Create a new [`MdcrdReader`].
    ///
    /// - `natom`   – number of atoms per frame
    /// - `has_box` – set to `true` if the trajectory includes box records
    pub fn new(reader: R, natom: usize, has_box: bool) -> Self {
        MdcrdReader {
            reader,
            natom,
            has_box,
            title_consumed: false,
        }
    }

    /// Consume the title line.  Called automatically by the first `read_frame`.
    fn consume_title(&mut self) -> Result<String, AmberIoError> {
        let mut title = String::new();
        self.reader
            .read_line(&mut title)
            .map_err(|e| AmberIoError::IoError(e.to_string()))?;
        self.title_consumed = true;
        Ok(title.trim_end().to_string())
    }

    /// Read the next frame and return coordinates (and optionally box).
    ///
    /// Returns `Ok(None)` at end of file.
    pub fn read_frame(&mut self) -> Result<Option<MdcrdFrame>, AmberIoError> {
        if !self.title_consumed {
            self.consume_title()?;
        }

        let n_coords = self.natom * 3;
        let mut values: Vec<f64> = Vec::with_capacity(n_coords);

        loop {
            if values.len() >= n_coords {
                break;
            }
            let mut line = String::new();
            let bytes = self
                .reader
                .read_line(&mut line)
                .map_err(|e| AmberIoError::IoError(e.to_string()))?;
            if bytes == 0 {
                if values.is_empty() {
                    return Ok(None);
                }
                break;
            }
            for tok in line.split_whitespace() {
                values.push(
                    tok.parse::<f64>()
                        .map_err(|e| AmberIoError::ParseError(e.to_string()))?,
                );
                if values.len() >= n_coords {
                    break;
                }
            }
        }

        if values.is_empty() {
            return Ok(None);
        }

        let box_dims = if self.has_box {
            let mut line = String::new();
            self.reader
                .read_line(&mut line)
                .map_err(|e| AmberIoError::IoError(e.to_string()))?;
            let parts: Vec<f64> = line
                .split_whitespace()
                .filter_map(|t| t.parse::<f64>().ok())
                .collect();
            if parts.len() >= 3 {
                Some([parts[0], parts[1], parts[2]])
            } else {
                None
            }
        } else {
            None
        };

        Ok(Some(MdcrdFrame {
            coordinates: values,
            box_dims,
        }))
    }
}

/// A single frame from an AMBER trajectory file.
#[derive(Debug, Clone)]
pub struct MdcrdFrame {
    /// Cartesian coordinates (Å), x,y,z interleaved, length = 3 × NATOM.
    pub coordinates: Vec<f64>,
    /// Periodic box `[a, b, c]` (Å), if present.
    pub box_dims: Option<[f64; 3]>,
}

impl MdcrdFrame {
    /// Return the number of atoms in this frame.
    pub fn natom(&self) -> usize {
        self.coordinates.len() / 3
    }

    /// Return atom position as `(x, y, z)` tuple (0-based index).
    pub fn atom_pos(&self, idx: usize) -> Option<(f64, f64, f64)> {
        let base = idx * 3;
        if base + 2 < self.coordinates.len() {
            Some((
                self.coordinates[base],
                self.coordinates[base + 1],
                self.coordinates[base + 2],
            ))
        } else {
            None
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// MdinFile
// ──────────────────────────────────────────────────────────────────────────────

/// AMBER MD input (`mdin`) file representation.
///
/// Stores key-value pairs from the `&cntrl` (and optionally `&ewald`, `&pb`,
/// etc.) namelists as plain strings.
#[derive(Debug, Clone, Default)]
pub struct MdinFile {
    /// Title comment line.
    pub title: String,
    /// Parsed key/value entries from `&cntrl`.
    pub cntrl: HashMap<String, String>,
    /// Parsed key/value entries from `&ewald` (empty if absent).
    pub ewald: HashMap<String, String>,
}

impl MdinFile {
    /// Create an empty [`MdinFile`].
    pub fn new() -> Self {
        MdinFile::default()
    }

    /// Look up a `&cntrl` integer parameter with a default fallback.
    pub fn cntrl_int(&self, key: &str, default: i64) -> i64 {
        self.cntrl
            .get(key)
            .and_then(|v| v.trim().parse().ok())
            .unwrap_or(default)
    }

    /// Look up a `&cntrl` float parameter with a default fallback.
    pub fn cntrl_float(&self, key: &str, default: f64) -> f64 {
        self.cntrl
            .get(key)
            .and_then(|v| v.trim().parse().ok())
            .unwrap_or(default)
    }

    /// Write the `mdin` file to any [`Write`] sink.
    pub fn write<W: Write>(&self, writer: &mut W) -> Result<(), AmberIoError> {
        let mut bw = BufWriter::new(writer);
        writeln!(bw, "{}", self.title).map_err(|e| AmberIoError::IoError(e.to_string()))?;
        writeln!(bw, " &cntrl").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        let mut keys: Vec<&String> = self.cntrl.keys().collect();
        keys.sort();
        for k in &keys {
            writeln!(bw, "  {} = {},", k, self.cntrl[*k])
                .map_err(|e| AmberIoError::IoError(e.to_string()))?;
        }
        writeln!(bw, " /").map_err(|e| AmberIoError::IoError(e.to_string()))?;
        Ok(())
    }

    /// Parse an AMBER `mdin` file.
    pub fn read<R: Read>(reader: R) -> Result<Self, AmberIoError> {
        let br = BufReader::new(reader);
        let mut file = MdinFile::new();
        let mut lines = br.lines().peekable();

        // Title
        file.title = lines
            .next()
            .ok_or(AmberIoError::UnexpectedEof)?
            .map_err(|e| AmberIoError::IoError(e.to_string()))?;

        let mut current_nl: Option<&str> = None;
        for line_result in lines {
            let line = line_result.map_err(|e| AmberIoError::IoError(e.to_string()))?;
            let trimmed = line.trim();

            if trimmed.starts_with('&') {
                let nl_name = trimmed.trim_start_matches('&').to_lowercase();
                current_nl = match nl_name.as_str() {
                    "cntrl" => Some("cntrl"),
                    "ewald" => Some("ewald"),
                    _ => None,
                };
                continue;
            }

            if trimmed == "/" || trimmed == "&end" || trimmed.to_lowercase() == "end" {
                current_nl = None;
                continue;
            }

            if let Some(nl) = current_nl {
                // Each line may contain multiple key=value, pairs
                for entry in trimmed.split(',') {
                    let entry = entry.trim();
                    if entry.is_empty() {
                        continue;
                    }
                    if let Some(pos) = entry.find('=') {
                        let key = entry[..pos].trim().to_lowercase();
                        let val = entry[pos + 1..].trim().to_string();
                        if !key.is_empty() {
                            match nl {
                                "cntrl" => {
                                    file.cntrl.insert(key, val);
                                }
                                "ewald" => {
                                    file.ewald.insert(key, val);
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
        }

        Ok(file)
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// MdinfoParser
// ──────────────────────────────────────────────────────────────────────────────

/// Snapshot of energy/thermodynamic data from an AMBER `mdinfo` file.
#[derive(Debug, Clone, Default)]
pub struct MdinfoSnapshot {
    /// MD step number.
    pub nstep: i64,
    /// Simulation time (ps).
    pub time: f64,
    /// Instantaneous temperature (K).
    pub temp: f64,
    /// Pressure (bar).
    pub press: f64,
    /// Total energy (kcal mol⁻¹).
    pub etot: f64,
    /// Kinetic energy (kcal mol⁻¹).
    pub ektot: f64,
    /// Potential energy (kcal mol⁻¹).
    pub eptot: f64,
}

/// Parser for AMBER `mdinfo` runtime output files.
pub struct MdinfoParser;

impl MdinfoParser {
    /// Parse the first energy snapshot found in the mdinfo text.
    ///
    /// Handles lines of the form:
    /// ```text
    ///  NSTEP =      500   TIME(PS) =       1.000
    ///  TEMP(K) =   298.15  PRESS =     0.00
    ///  ETOT   =   -5000.0  EKTOT  =    1000.0  EPTOT  =  -6000.0
    /// ```
    pub fn parse<R: Read>(reader: R) -> Result<MdinfoSnapshot, AmberIoError> {
        let br = BufReader::new(reader);
        let mut snap = MdinfoSnapshot::default();

        for line_result in br.lines() {
            let line = line_result.map_err(|e| AmberIoError::IoError(e.to_string()))?;
            // Tokenise: split on '=' boundaries.
            // Strategy: find all '=' positions; everything between the previous
            // '=' value (a number token) and the next '=' is the key.
            let chars: Vec<char> = line.chars().collect();
            let mut i = 0usize;
            while i < chars.len() {
                // skip whitespace
                while i < chars.len() && chars[i].is_whitespace() {
                    i += 1;
                }
                // collect a key token up to '='
                let key_start = i;
                while i < chars.len() && chars[i] != '=' {
                    i += 1;
                }
                if i >= chars.len() {
                    break;
                }
                let key: String = chars[key_start..i]
                    .iter()
                    .collect::<String>()
                    .trim()
                    .to_uppercase();
                i += 1; // skip '='
                // collect value: skip whitespace then read non-whitespace
                while i < chars.len() && chars[i].is_whitespace() {
                    i += 1;
                }
                let val_start = i;
                while i < chars.len() && !chars[i].is_whitespace() {
                    i += 1;
                }
                let val_str: String = chars[val_start..i].iter().collect();
                let val: f64 = match val_str.parse() {
                    Ok(v) => v,
                    Err(_) => continue,
                };
                match key.as_str() {
                    "NSTEP" => snap.nstep = val as i64,
                    "TIME(PS)" => snap.time = val,
                    "TEMP(K)" => snap.temp = val,
                    "PRESS" => snap.press = val,
                    "ETOT" => snap.etot = val,
                    "EKTOT" => snap.ektot = val,
                    "EPTOT" => snap.eptot = val,
                    _ => {}
                }
            }
        }

        Ok(snap)
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// AmberForceFieldReader
// ──────────────────────────────────────────────────────────────────────────────

/// A single mass entry from a GAFF / ff14SB parameter file.
#[derive(Debug, Clone)]
pub struct FfMass {
    /// Atom type label.
    pub atom_type: String,
    /// Atomic mass (u).
    pub mass: f64,
    /// Polarisability (ų), optional.
    pub polarizability: f64,
}

/// A bond parameter entry from a GAFF / ff14SB parameter file.
#[derive(Debug, Clone)]
pub struct FfBond {
    /// First atom type.
    pub type_i: String,
    /// Second atom type.
    pub type_j: String,
    /// Force constant k (kcal mol⁻¹ Å⁻²).
    pub force_constant: f64,
    /// Equilibrium bond length (Å).
    pub eq_length: f64,
}

/// An angle parameter entry.
#[derive(Debug, Clone)]
pub struct FfAngle {
    /// Atom types i-j-k.
    pub type_i: String,
    /// Central atom type.
    pub type_j: String,
    /// Third atom type.
    pub type_k: String,
    /// Force constant (kcal mol⁻¹ rad⁻²).
    pub force_constant: f64,
    /// Equilibrium angle (degrees).
    pub eq_angle_deg: f64,
}

/// A dihedral parameter entry.
#[derive(Debug, Clone)]
pub struct FfDihedral {
    /// Atom types i-j-k-l.
    pub type_i: String,
    /// Second atom type.
    pub type_j: String,
    /// Third atom type.
    pub type_k: String,
    /// Fourth atom type.
    pub type_l: String,
    /// Periodicity N.
    pub periodicity: i32,
    /// Barrier height V/2 (kcal mol⁻¹).
    pub barrier: f64,
    /// Phase angle (degrees).
    pub phase_deg: f64,
}

/// Reader for GAFF / ff14SB force-field parameter files.
#[derive(Debug, Clone, Default)]
pub struct AmberForceFieldReader {
    /// Mass parameters.
    pub masses: Vec<FfMass>,
    /// Bond parameters.
    pub bonds: Vec<FfBond>,
    /// Angle parameters.
    pub angles: Vec<FfAngle>,
    /// Dihedral parameters.
    pub dihedrals: Vec<FfDihedral>,
}

impl AmberForceFieldReader {
    /// Create an empty reader.
    pub fn new() -> Self {
        AmberForceFieldReader::default()
    }

    /// Parse a GAFF/ff14SB parameter file.
    pub fn read<R: Read>(&mut self, reader: R) -> Result<(), AmberIoError> {
        let br = BufReader::new(reader);
        let lines: Vec<String> = br
            .lines()
            .map(|l| l.map_err(|e| AmberIoError::IoError(e.to_string())))
            .collect::<Result<_, _>>()?;

        #[derive(PartialEq)]
        enum Section {
            None,
            Mass,
            Bond,
            Angle,
            Dihe,
        }
        let mut section = Section::None;

        for line in &lines {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                section = Section::None;
                continue;
            }

            let upper = trimmed.to_uppercase();
            if upper.starts_with("MASS") {
                section = Section::Mass;
                continue;
            } else if upper.starts_with("BOND") {
                section = Section::Bond;
                continue;
            } else if upper.starts_with("ANGLE") || upper.starts_with("ANGL") {
                section = Section::Angle;
                continue;
            } else if upper.starts_with("DIHE") {
                section = Section::Dihe;
                continue;
            } else if upper.starts_with("NONB") || upper.starts_with("IMPR") {
                section = Section::None;
                continue;
            }

            match section {
                Section::Mass => {
                    // Format: AT  mass  polarizability  !comment
                    let clean = trimmed.split('!').next().unwrap_or("").trim();
                    let parts: Vec<&str> = clean.split_whitespace().collect();
                    if parts.len() >= 2 {
                        let mass = parts[1].parse::<f64>().unwrap_or(0.0);
                        let pol = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0.0);
                        self.masses.push(FfMass {
                            atom_type: parts[0].to_string(),
                            mass,
                            polarizability: pol,
                        });
                    }
                }
                Section::Bond => {
                    // Format: I1-I2  kf  r0  !comment
                    let clean = trimmed.split('!').next().unwrap_or("").trim();
                    let parts: Vec<&str> = clean.split_whitespace().collect();
                    if parts.len() >= 3 {
                        let types: Vec<&str> = parts[0].split('-').collect();
                        if types.len() >= 2 {
                            let kf = parts[1].parse::<f64>().unwrap_or(0.0);
                            let r0 = parts[2].parse::<f64>().unwrap_or(0.0);
                            self.bonds.push(FfBond {
                                type_i: types[0].trim().to_string(),
                                type_j: types[1].trim().to_string(),
                                force_constant: kf,
                                eq_length: r0,
                            });
                        }
                    }
                }
                Section::Angle => {
                    // Format: I1-I2-I3  kf  theta0  !comment
                    let clean = trimmed.split('!').next().unwrap_or("").trim();
                    let parts: Vec<&str> = clean.split_whitespace().collect();
                    if parts.len() >= 3 {
                        let types: Vec<&str> = parts[0].split('-').collect();
                        if types.len() >= 3 {
                            let kf = parts[1].parse::<f64>().unwrap_or(0.0);
                            let th0 = parts[2].parse::<f64>().unwrap_or(0.0);
                            self.angles.push(FfAngle {
                                type_i: types[0].trim().to_string(),
                                type_j: types[1].trim().to_string(),
                                type_k: types[2].trim().to_string(),
                                force_constant: kf,
                                eq_angle_deg: th0,
                            });
                        }
                    }
                }
                Section::Dihe => {
                    // AMBER dihedral format: "I1-I2-I3-I4  idivf  pk  phase  pn  !comment"
                    // Atom types are 2 chars each joined by '-'; wildcards use spaces, e.g.:
                    //   "c3-hc-n3-c3" or "X -c3-n3-X "
                    // Detect the type/number boundary: first whitespace run followed by a
                    // token that parses as f64 (the idivf integer).
                    let clean = trimmed.split('!').next().unwrap_or("").trim();
                    let mut split_at = clean.len();
                    let cbytes = clean.as_bytes();
                    let mut idx = 0usize;
                    while idx < cbytes.len() {
                        if cbytes[idx].is_ascii_whitespace() {
                            let ws_start = idx;
                            while idx < cbytes.len() && cbytes[idx].is_ascii_whitespace() {
                                idx += 1;
                            }
                            if idx < cbytes.len() {
                                let rest = &clean[idx..];
                                if rest
                                    .split_whitespace()
                                    .next()
                                    .map(|t| t.parse::<f64>().is_ok())
                                    .unwrap_or(false)
                                {
                                    split_at = ws_start;
                                    break;
                                }
                            }
                        } else {
                            idx += 1;
                        }
                    }
                    let type_field = clean[..split_at].trim();
                    let remainder = clean[split_at..].trim();
                    // Parse atom types: spaces are part of wildcard names → replace with '-'
                    let normalised = type_field.replace(' ', "-");
                    let types: Vec<&str> =
                        normalised.split('-').filter(|s| !s.is_empty()).collect();
                    let nums: Vec<&str> = remainder.split_whitespace().collect();
                    if types.len() >= 4 && nums.len() >= 4 {
                        let barrier = nums[1].parse::<f64>().unwrap_or(0.0);
                        let phase = nums[2].parse::<f64>().unwrap_or(0.0);
                        let pn = nums[3].parse::<f64>().unwrap_or(1.0).abs() as i32;
                        self.dihedrals.push(FfDihedral {
                            type_i: types[0].trim().to_string(),
                            type_j: types[1].trim().to_string(),
                            type_k: types[2].trim().to_string(),
                            type_l: types[3].trim().to_string(),
                            periodicity: pn,
                            barrier,
                            phase_deg: phase,
                        });
                    }
                }
                Section::None => {}
            }
        }

        Ok(())
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Utility: AMBER charge unit conversion
// ──────────────────────────────────────────────────────────────────────────────

/// AMBER internal charge unit factor.
///
/// AMBER stores partial charges as `q * 18.2223` where `q` is in elementary
/// charges.  Divide by this constant to recover the charge in elementary
/// charges (e).
pub const AMBER_CHARGE_UNIT: f64 = 18.2223;

/// Convert an AMBER internal charge value to elementary charges.
pub fn amber_charge_to_e(amber_q: f64) -> f64 {
    amber_q / AMBER_CHARGE_UNIT
}

/// Convert an elementary-charge value to AMBER internal units.
pub fn e_to_amber_charge(q_e: f64) -> f64 {
    q_e * AMBER_CHARGE_UNIT
}

// ──────────────────────────────────────────────────────────────────────────────
// Tests
// ──────────────────────────────────────────────────────────────────────────────

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

    // ── PrmtopAtom ────────────────────────────────────────────────────────────

    #[test]
    fn test_prmtop_atom_new() {
        let a = PrmtopAtom::new("CA", 0.0, 12.011, "CT");
        assert_eq!(a.name, "CA");
        assert_eq!(a.mass, 12.011);
    }

    #[test]
    fn test_prmtop_atom_charge_si() {
        let a = PrmtopAtom::new("N", 18.2223, 14.007, "N");
        let q = a.charge_si();
        assert!((q - 1.0).abs() < 1e-6, "expected ~1.0, got {q}");
    }

    #[test]
    fn test_prmtop_atom_charge_negative() {
        let a = PrmtopAtom::new("O", -0.8 * 18.2223, 15.999, "OS");
        assert!(a.charge_si() < 0.0);
    }

    // ── PrmtopBond ────────────────────────────────────────────────────────────

    #[test]
    fn test_prmtop_bond_new() {
        let b = PrmtopBond::new(0, 1, 340.0, 1.526);
        assert!(b.force_constant > 0.0);
        assert!(b.eq_length > 0.0);
    }

    #[test]
    fn test_prmtop_bond_energy_at_eq() {
        let b = PrmtopBond::new(0, 1, 340.0, 1.526);
        let e = b.energy(b.eq_length);
        assert!(e.abs() < 1e-12, "energy at eq length should be ~0, got {e}");
    }

    #[test]
    fn test_prmtop_bond_energy_positive() {
        let b = PrmtopBond::new(0, 1, 340.0, 1.526);
        let e = b.energy(1.7);
        assert!(e > 0.0);
    }

    #[test]
    fn test_prmtop_bond_energy_symmetric() {
        let b = PrmtopBond::new(0, 1, 340.0, 1.526);
        let e1 = b.energy(1.526 + 0.1);
        let e2 = b.energy(1.526 - 0.1);
        assert!((e1 - e2).abs() < 1e-10);
    }

    // ── PrmtopAngle ───────────────────────────────────────────────────────────

    #[test]
    fn test_prmtop_angle_new() {
        let a = PrmtopAngle::new(0, 1, 2, 50.0, std::f64::consts::PI * 109.5 / 180.0);
        assert_eq!(a.atom_j, 1);
    }

    #[test]
    fn test_prmtop_angle_energy_at_eq() {
        let theta0 = 109.5_f64.to_radians();
        let a = PrmtopAngle::new(0, 1, 2, 50.0, theta0);
        let e = a.energy(theta0);
        assert!(e.abs() < 1e-12);
    }

    #[test]
    fn test_prmtop_angle_energy_positive_deviation() {
        let theta0 = 109.5_f64.to_radians();
        let a = PrmtopAngle::new(0, 1, 2, 50.0, theta0);
        let e = a.energy(theta0 + 0.2);
        assert!(e > 0.0);
    }

    // ── PrmtopFile round-trip ─────────────────────────────────────────────────

    fn make_prmtop() -> PrmtopFile {
        let mut f = PrmtopFile::new();
        f.version = "V0001.000".to_string();
        f.atoms.push(PrmtopAtom::new(
            "N",
            -0.4157 * AMBER_CHARGE_UNIT,
            14.007,
            "N3",
        ));
        f.atoms.push(PrmtopAtom::new(
            "H1",
            0.2719 * AMBER_CHARGE_UNIT,
            1.008,
            "H",
        ));
        f.atoms.push(PrmtopAtom::new(
            "CA",
            -0.0249 * AMBER_CHARGE_UNIT,
            12.011,
            "CT",
        ));
        f.bonds.push(PrmtopBond::new(0, 1, 434.0, 1.01));
        f.bonds.push(PrmtopBond::new(1, 2, 317.0, 1.522));
        f
    }

    #[test]
    fn test_prmtop_roundtrip_natom() {
        let original = make_prmtop();
        let mut buf = Vec::new();
        original.write(&mut buf).unwrap();
        let restored = PrmtopFile::read(Cursor::new(&buf)).unwrap();
        assert_eq!(original.natom(), restored.natom());
    }

    #[test]
    fn test_prmtop_roundtrip_atom_names() {
        let original = make_prmtop();
        let mut buf = Vec::new();
        original.write(&mut buf).unwrap();
        let restored = PrmtopFile::read(Cursor::new(&buf)).unwrap();
        for (a, b) in original.atoms.iter().zip(restored.atoms.iter()) {
            assert_eq!(a.name, b.name);
        }
    }

    #[test]
    fn test_prmtop_roundtrip_charges() {
        let original = make_prmtop();
        let mut buf = Vec::new();
        original.write(&mut buf).unwrap();
        let restored = PrmtopFile::read(Cursor::new(&buf)).unwrap();
        for (a, b) in original.atoms.iter().zip(restored.atoms.iter()) {
            assert!(
                (a.charge - b.charge).abs() < 1e-4,
                "charge mismatch: {} vs {}",
                a.charge,
                b.charge
            );
        }
    }

    #[test]
    fn test_prmtop_roundtrip_masses() {
        let original = make_prmtop();
        let mut buf = Vec::new();
        original.write(&mut buf).unwrap();
        let restored = PrmtopFile::read(Cursor::new(&buf)).unwrap();
        for (a, b) in original.atoms.iter().zip(restored.atoms.iter()) {
            assert!((a.mass - b.mass).abs() < 1e-4);
        }
    }

    #[test]
    fn test_prmtop_roundtrip_bond_force_constants() {
        let original = make_prmtop();
        let mut buf = Vec::new();
        original.write(&mut buf).unwrap();
        let restored = PrmtopFile::read(Cursor::new(&buf)).unwrap();
        assert_eq!(original.bonds.len(), restored.bonds.len());
        for (a, b) in original.bonds.iter().zip(restored.bonds.iter()) {
            assert!(
                (a.force_constant - b.force_constant).abs() < 1e-3,
                "force_constant mismatch: {} vs {}",
                a.force_constant,
                b.force_constant
            );
        }
    }

    #[test]
    fn test_prmtop_bond_parameters_positive() {
        let f = make_prmtop();
        for bond in &f.bonds {
            assert!(bond.force_constant > 0.0, "force constant must be positive");
            assert!(bond.eq_length > 0.0, "eq length must be positive");
        }
    }

    #[test]
    fn test_prmtop_empty_roundtrip() {
        let original = PrmtopFile::new();
        let mut buf = Vec::new();
        original.write(&mut buf).unwrap();
        let restored = PrmtopFile::read(Cursor::new(&buf)).unwrap();
        assert_eq!(restored.natom(), 0);
    }

    // ── Rst7File ──────────────────────────────────────────────────────────────

    fn make_rst7(natom: usize) -> Rst7File {
        let mut r = Rst7File::new();
        r.title = "Test restart file".to_string();
        r.time = Some(0.5);
        r.coordinates = (0..natom * 3).map(|i| i as f64 * 0.1).collect();
        r.velocities = vec![0.01; natom * 3];
        r
    }

    #[test]
    fn test_rst7_natom() {
        let r = make_rst7(20);
        assert_eq!(r.natom(), 20);
    }

    #[test]
    fn test_rst7_coordinate_count_matches_natom() {
        let r = make_rst7(7);
        assert_eq!(r.coordinates.len(), r.natom() * 3);
    }

    #[test]
    fn test_rst7_write_read_roundtrip_natom() {
        let original = make_rst7(10);
        let mut buf = Vec::new();
        original.write(&mut buf).unwrap();
        let restored = Rst7File::read(Cursor::new(&buf)).unwrap();
        assert_eq!(original.natom(), restored.natom());
    }

    #[test]
    fn test_rst7_write_read_roundtrip_coordinates() {
        let original = make_rst7(5);
        let mut buf = Vec::new();
        original.write(&mut buf).unwrap();
        let restored = Rst7File::read(Cursor::new(&buf)).unwrap();
        for (a, b) in original.coordinates.iter().zip(restored.coordinates.iter()) {
            assert!((a - b).abs() < 1e-5, "coord mismatch: {a} vs {b}");
        }
    }

    #[test]
    fn test_rst7_coordinate_format_12_7() {
        // Verify the file actually contains 12.7 format numbers
        let r = make_rst7(1);
        let mut buf = Vec::new();
        r.write(&mut buf).unwrap();
        let text = String::from_utf8(buf).unwrap();
        // Each coordinate field should be 12 characters wide
        // Check at least one line after header (2 lines) has correct format
        let data_lines: Vec<&str> = text.lines().skip(2).collect();
        let first_data_line = data_lines[0];
        // At most 6 values × 12 chars = 72 chars per line
        assert!(first_data_line.len() <= 72 + 1); // +1 for newline
    }

    #[test]
    fn test_rst7_time_preserved() {
        let original = make_rst7(3);
        let mut buf = Vec::new();
        original.write(&mut buf).unwrap();
        let restored = Rst7File::read(Cursor::new(&buf)).unwrap();
        assert!(restored.time.is_some());
        assert!((restored.time.unwrap() - 0.5).abs() < 1e-3);
    }

    #[test]
    fn test_rst7_no_time() {
        let mut r = make_rst7(2);
        r.time = None;
        let mut buf = Vec::new();
        r.write(&mut buf).unwrap();
        let restored = Rst7File::read(Cursor::new(&buf)).unwrap();
        assert_eq!(restored.natom(), 2);
    }

    // ── MdcrdReader ───────────────────────────────────────────────────────────

    fn make_mdcrd_text(natom: usize, nframes: usize) -> String {
        let mut s = String::from("TITLE : mdcrd test\n");
        let n_coord = natom * 3;
        for frame in 0..nframes {
            let vals: Vec<f64> = (0..n_coord)
                .map(|i| (frame * 100 + i) as f64 * 0.1)
                .collect();
            let mut count = 0usize;
            for v in &vals {
                s.push_str(&format!("{:8.3}", v));
                count += 1;
                if count.is_multiple_of(10) {
                    s.push('\n');
                }
            }
            if !n_coord.is_multiple_of(10) {
                s.push('\n');
            }
        }
        s
    }

    #[test]
    fn test_mdcrd_read_frame_count() {
        let natom = 5;
        let nframes = 4;
        let text = make_mdcrd_text(natom, nframes);
        let mut reader = MdcrdReader::new(BufReader::new(Cursor::new(text)), natom, false);
        let mut count = 0usize;
        while let Some(_frame) = reader.read_frame().unwrap() {
            count += 1;
        }
        assert_eq!(count, nframes);
    }

    #[test]
    fn test_mdcrd_frame_natom() {
        let natom = 6;
        let text = make_mdcrd_text(natom, 1);
        let mut reader = MdcrdReader::new(BufReader::new(Cursor::new(text)), natom, false);
        let frame = reader.read_frame().unwrap().unwrap();
        assert_eq!(frame.natom(), natom);
    }

    #[test]
    fn test_mdcrd_frame_coord_len() {
        let natom = 3;
        let text = make_mdcrd_text(natom, 1);
        let mut reader = MdcrdReader::new(BufReader::new(Cursor::new(text)), natom, false);
        let frame = reader.read_frame().unwrap().unwrap();
        assert_eq!(frame.coordinates.len(), natom * 3);
    }

    #[test]
    fn test_mdcrd_atom_pos_valid() {
        let natom = 4;
        let text = make_mdcrd_text(natom, 1);
        let mut reader = MdcrdReader::new(BufReader::new(Cursor::new(text)), natom, false);
        let frame = reader.read_frame().unwrap().unwrap();
        assert!(frame.atom_pos(0).is_some());
        assert!(frame.atom_pos(natom - 1).is_some());
    }

    #[test]
    fn test_mdcrd_atom_pos_out_of_bounds() {
        let natom = 2;
        let text = make_mdcrd_text(natom, 1);
        let mut reader = MdcrdReader::new(BufReader::new(Cursor::new(text)), natom, false);
        let frame = reader.read_frame().unwrap().unwrap();
        // Index 2 is out of bounds for natom=2 (valid: 0,1)
        assert!(frame.atom_pos(100).is_none());
    }

    #[test]
    fn test_mdcrd_eof_returns_none() {
        let text = "TITLE\n";
        let mut reader = MdcrdReader::new(BufReader::new(Cursor::new(text)), 3, false);
        let result = reader.read_frame().unwrap();
        assert!(result.is_none());
    }

    // ── MdinFile ──────────────────────────────────────────────────────────────

    fn make_mdin_text() -> &'static str {
        "MD simulation test\n \
         &cntrl\n  \
           nstlim = 1000,\n  \
           dt = 0.002,\n  \
           temp0 = 300.0,\n  \
           ntpr = 100,\n  \
           ntwx = 100,\n  \
           ntb = 1,\n  \
         /\n"
    }

    #[test]
    fn test_mdin_parse_nstlim() {
        let f = MdinFile::read(Cursor::new(make_mdin_text())).unwrap();
        assert_eq!(f.cntrl_int("nstlim", 0), 1000);
    }

    #[test]
    fn test_mdin_parse_dt() {
        let f = MdinFile::read(Cursor::new(make_mdin_text())).unwrap();
        let dt = f.cntrl_float("dt", 0.0);
        assert!((dt - 0.002).abs() < 1e-6);
    }

    #[test]
    fn test_mdin_parse_temp0() {
        let f = MdinFile::read(Cursor::new(make_mdin_text())).unwrap();
        let temp = f.cntrl_float("temp0", 0.0);
        assert!((temp - 300.0).abs() < 1e-6);
    }

    #[test]
    fn test_mdin_parse_ntpr() {
        let f = MdinFile::read(Cursor::new(make_mdin_text())).unwrap();
        assert_eq!(f.cntrl_int("ntpr", 0), 100);
    }

    #[test]
    fn test_mdin_default_for_missing_key() {
        let f = MdinFile::read(Cursor::new(make_mdin_text())).unwrap();
        assert_eq!(f.cntrl_int("nonexistent", 42), 42);
    }

    #[test]
    fn test_mdin_write_read_roundtrip() {
        let original = MdinFile::read(Cursor::new(make_mdin_text())).unwrap();
        let mut buf = Vec::new();
        original.write(&mut buf).unwrap();
        let restored = MdinFile::read(Cursor::new(&buf)).unwrap();
        assert_eq!(
            original.cntrl_int("nstlim", 0),
            restored.cntrl_int("nstlim", 0)
        );
    }

    // ── MdinfoParser ──────────────────────────────────────────────────────────

    fn make_mdinfo_text() -> &'static str {
        " NSTEP =      500   TIME(PS) =       1.000\n \
          TEMP(K) =   298.15  PRESS =     0.00\n \
          ETOT   =   -5000.0  EKTOT  =    1000.0  EPTOT  =  -6000.0\n"
    }

    #[test]
    fn test_mdinfo_parse_nstep() {
        let s = MdinfoParser::parse(Cursor::new(make_mdinfo_text())).unwrap();
        assert_eq!(s.nstep, 500);
    }

    #[test]
    fn test_mdinfo_parse_time() {
        let s = MdinfoParser::parse(Cursor::new(make_mdinfo_text())).unwrap();
        assert!((s.time - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_mdinfo_parse_temp() {
        let s = MdinfoParser::parse(Cursor::new(make_mdinfo_text())).unwrap();
        assert!((s.temp - 298.15).abs() < 0.1);
    }

    #[test]
    fn test_mdinfo_parse_etot() {
        let s = MdinfoParser::parse(Cursor::new(make_mdinfo_text())).unwrap();
        assert!((s.etot - (-5000.0)).abs() < 1.0);
    }

    #[test]
    fn test_mdinfo_energy_conservation() {
        let s = MdinfoParser::parse(Cursor::new(make_mdinfo_text())).unwrap();
        // etot ≈ ektot + eptot
        let sum = s.ektot + s.eptot;
        assert!((s.etot - sum).abs() < 1.0);
    }

    // ── AmberForceFieldReader ─────────────────────────────────────────────────

    fn make_ff_text() -> &'static str {
        "AMBER force field parameters\n\
         MASS\n\
         c3  12.010  !sp3 carbon\n\
         hc   1.008  !H on aliphatic C\n\
         n3  14.010  !nitrogen sp3\n\
         \n\
         BOND\n\
         c3-hc  340.0  1.09  !C-H aliphatic\n\
         c3-n3  337.0  1.47  !C-N single\n\
         \n\
         ANGLE\n\
         hc-c3-hc  35.0  109.50  !tetrahedral H-C-H\n\
         hc-c3-n3  50.0  109.50  !H-C-N\n\
         \n\
         DIHE\n\
         X -c3-n3-X   1  1.40  180.0  2.0  !sp3 C-N dihedral\n\
         \n"
    }

    #[test]
    fn test_ff_mass_count() {
        let mut r = AmberForceFieldReader::new();
        r.read(Cursor::new(make_ff_text())).unwrap();
        assert_eq!(r.masses.len(), 3);
    }

    #[test]
    fn test_ff_bond_count() {
        let mut r = AmberForceFieldReader::new();
        r.read(Cursor::new(make_ff_text())).unwrap();
        assert_eq!(r.bonds.len(), 2);
    }

    #[test]
    fn test_ff_angle_count() {
        let mut r = AmberForceFieldReader::new();
        r.read(Cursor::new(make_ff_text())).unwrap();
        assert_eq!(r.angles.len(), 2);
    }

    #[test]
    fn test_ff_dihedral_count() {
        let mut r = AmberForceFieldReader::new();
        r.read(Cursor::new(make_ff_text())).unwrap();
        assert_eq!(r.dihedrals.len(), 1);
    }

    #[test]
    fn test_ff_bond_force_constants_positive() {
        let mut r = AmberForceFieldReader::new();
        r.read(Cursor::new(make_ff_text())).unwrap();
        for b in &r.bonds {
            assert!(
                b.force_constant > 0.0,
                "bond force constant must be positive, got {}",
                b.force_constant
            );
        }
    }

    #[test]
    fn test_ff_bond_eq_lengths_positive() {
        let mut r = AmberForceFieldReader::new();
        r.read(Cursor::new(make_ff_text())).unwrap();
        for b in &r.bonds {
            assert!(
                b.eq_length > 0.0,
                "bond eq length must be positive, got {}",
                b.eq_length
            );
        }
    }

    #[test]
    fn test_ff_angle_force_constants_positive() {
        let mut r = AmberForceFieldReader::new();
        r.read(Cursor::new(make_ff_text())).unwrap();
        for a in &r.angles {
            assert!(a.force_constant > 0.0);
        }
    }

    #[test]
    fn test_ff_mass_values() {
        let mut r = AmberForceFieldReader::new();
        r.read(Cursor::new(make_ff_text())).unwrap();
        let c3 = r.masses.iter().find(|m| m.atom_type == "c3").unwrap();
        assert!((c3.mass - 12.01).abs() < 0.1);
    }

    // ── Charge conversion utilities ───────────────────────────────────────────

    #[test]
    fn test_amber_charge_to_e_unit() {
        let q = amber_charge_to_e(AMBER_CHARGE_UNIT);
        assert!((q - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_e_to_amber_charge_unit() {
        let q = e_to_amber_charge(1.0);
        assert!((q - AMBER_CHARGE_UNIT).abs() < 1e-10);
    }

    #[test]
    fn test_amber_charge_roundtrip() {
        let original = 0.6;
        let roundtripped = amber_charge_to_e(e_to_amber_charge(original));
        assert!((original - roundtripped).abs() < 1e-12);
    }

    #[test]
    fn test_amber_charge_factor_value() {
        // AMBER factor must be close to 18.2223
        assert!((AMBER_CHARGE_UNIT - 18.2223).abs() < 1e-4);
    }

    #[test]
    fn test_amber_charge_negative() {
        let q_si = -0.5;
        let q_amber = e_to_amber_charge(q_si);
        assert!(q_amber < 0.0);
        assert!((amber_charge_to_e(q_amber) - q_si).abs() < 1e-12);
    }
}