neopdf_capi 0.3.2

C language interface to NeoPDF
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
//! The C-language interface for `NeoPDF`

use std::ffi::CStr;
use std::os::raw::{c_char, c_double, c_int};
use std::slice;

use neopdf::gridpdf::{ForcePositive, GridArray};
use neopdf::metadata::{InterpolatorType, MetaData, SetType};
use neopdf::parser::SubgridData;
use neopdf::pdf::PDF;
use neopdf::writer::GridArrayCollection;

const DEFAULT_PIDS: [i32; 14] = [21, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 22];

/// Result codes for `NeoPDF` operations
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NeopdfResult {
    /// Operation completed successfully.
    Success = 0,
    /// A null pointer was encountered where a valid pointer was expected.
    ErrorNullPointer = -1,
    /// The provided data was invalid or could not be processed.
    ErrorInvalidData = -2,
    /// A memory allocation or deallocation error occurred.
    ErrorMemoryError = -3,
    /// The provided length or size argument was invalid.
    ErrorInvalidLength = -4,
}

impl From<NeopdfResult> for c_int {
    fn from(result: NeopdfResult) -> Self {
        result as Self
    }
}

/// Opaque pointer to a PDF object.
pub struct NeoPDFWrapper(PDF);

/// Structure to hold an array of PDF pointers and its length.
#[repr(C)]
pub struct NeoPDFMembers {
    /// Pointers to the `NeoPDF` objects.
    pub pdfs: *mut *mut NeoPDFWrapper,
    /// The number of PDF members.
    pub size: usize,
}

/// Loads a given member of the PDF set.
///
/// # Panics
///
/// This function will panic if the provided C string is not valid UTF-8.
///
/// # Safety
///
/// The `pdf_name` C string must be null-terminated and valid UTF-8.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_load(
    pdf_name: *const c_char,
    member: usize,
) -> *mut NeoPDFWrapper {
    let c_str = unsafe { CStr::from_ptr(pdf_name) };
    let pdf_name = c_str.to_str().expect("Invalid UTF-8 string");
    let pdf = PDF::load(pdf_name, member);
    Box::into_raw(Box::new(NeoPDFWrapper(pdf)))
}

/// Loads a PDF member by its LHAPDF ID (LHAID).
///
/// The set name and member index are resolved by fetching the LHAPDF set index
/// from `https://lhapdfsets.web.cern.ch/current/pdfsets.index`.
///
/// # Panics
///
/// Panics if the index cannot be fetched or `lhaid` is not found in the index.
#[no_mangle]
pub extern "C" fn neopdf_pdf_load_by_lhaid(lhaid: u32) -> *mut NeoPDFWrapper {
    let pdf = PDF::load_by_lhaid(lhaid);
    Box::into_raw(Box::new(NeoPDFWrapper(pdf)))
}

/// Loads a PDF member from a specific LHAPDF `.dat` file path.
///
/// # Panics
///
/// This function will panic if the provided C string is not valid UTF-8
/// or if the file cannot be loaded.
///
/// # Safety
///
/// The `path` C string must be null-terminated and valid UTF-8.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_load_lhapdf_by_file(path: *const c_char) -> *mut NeoPDFWrapper {
    let c_str = unsafe { CStr::from_ptr(path) };
    let path_str = c_str.to_str().expect("Invalid UTF-8 string for path");
    let pdf = PDF::load_lhapdf_by_file(path_str);
    Box::into_raw(Box::new(NeoPDFWrapper(pdf)))
}

/// Loads all members of the PDF set.
///
/// Returns a `NeoPDFMembers` containing pointers to all PDF objects in the set.
/// The caller is responsible for freeing the memory using `neopdf_pdf_array_free`.
///
/// # Panics
///
/// This function will panic if the provided C string is not valid UTF-8.
///
/// # Safety
///
/// The `pdf_name` C string must be null-terminated and valid UTF-8.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_load_all(pdf_name: *const c_char) -> NeoPDFMembers {
    let c_str = unsafe { CStr::from_ptr(pdf_name) };
    let pdf_name = c_str.to_str().expect("Invalid UTF-8 string");

    let pdfs = PDF::load_pdfs(pdf_name);
    let length = pdfs.len();

    let mut pdf_pointers: Vec<*mut NeoPDFWrapper> = pdfs
        .into_iter()
        .map(|pdf| Box::into_raw(Box::new(NeoPDFWrapper(pdf))))
        .collect();

    let pdfs_ptr = pdf_pointers.as_mut_ptr();
    std::mem::forget(pdf_pointers); // Prevent Vec from being dropped

    NeoPDFMembers {
        pdfs: pdfs_ptr,
        size: length,
    }
}

/// Frees a PDF object.
///
/// # Panics
///
/// This function does not panic.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object previously
/// allocated by `neopdf_pdf_load`.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_free(pdf: *mut NeoPDFWrapper) {
    if pdf.is_null() {
        return;
    }
    unsafe { drop(Box::from_raw(pdf)) };
}

/// Frees the memory allocated for a `NeoPDFMembers`.
///
/// # Safety
///
/// The `array` must be a valid `NeoPDFMembers` returned by `neopdf_pdf_load_all`.
/// After calling this function, the array and all PDF objects it contains
/// become invalid and must not be used.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_array_free(pdfs: NeoPDFMembers) {
    if pdfs.pdfs.is_null() {
        return;
    }

    let pdf_pointers = unsafe { Vec::from_raw_parts(pdfs.pdfs, pdfs.size, pdfs.size) };

    for pdf_ptr in pdf_pointers {
        if !pdf_ptr.is_null() {
            unsafe { drop(Box::from_raw(pdf_ptr)) };
        }
    }
}

/// Opaque pointer to a lazy PDF iterator object.
pub struct NeoPDFLazyIterator(Box<dyn Iterator<Item = Result<PDF, Box<dyn std::error::Error>>>>);

/// Loads a PDF set for lazy iteration.
///
/// This function is only supported for `.neopdf.lz4` files.
/// Returns a pointer to a `NeoPDFLazyIterator`. The caller is responsible for
/// freeing the memory using `neopdf_lazy_iterator_free`.
///
/// # Panics
///
/// This function will panic if the provided C string is not valid UTF-8.
///
/// # Safety
///
/// The `pdf_name` C string must be null-terminated and valid UTF-8.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_load_lazy(pdf_name: *const c_char) -> *mut NeoPDFLazyIterator {
    let c_str = unsafe { CStr::from_ptr(pdf_name) };
    let pdf_name = c_str.to_str().expect("Invalid UTF-8 string");

    if !pdf_name.ends_with(".neopdf.lz4") {
        return std::ptr::null_mut();
    }

    let lazy_iter = PDF::load_pdfs_lazy(pdf_name);
    let boxed_iter: Box<dyn Iterator<Item = Result<PDF, Box<dyn std::error::Error>>>> =
        Box::new(lazy_iter);

    Box::into_raw(Box::new(NeoPDFLazyIterator(boxed_iter)))
}

/// Retrieves the next PDF member from the lazy iterator.
///
/// Returns a pointer to a `NeoPDFWrapper` for the next member, or `NULL` if the
/// iterator is exhausted or an error occurs. The caller is responsible for freeing
/// the returned `NeoPDFWrapper` with `neopdf_pdf_free`.
///
/// # Safety
///
/// The `iter` pointer must be a valid pointer to a `NeoPDFLazyIterator` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_lazy_iterator_next(
    iter: *mut NeoPDFLazyIterator,
) -> *mut NeoPDFWrapper {
    if iter.is_null() {
        return std::ptr::null_mut();
    }
    let iter_wrapper = unsafe { &mut (*iter).0 };

    match iter_wrapper.next() {
        Some(Ok(pdf)) => Box::into_raw(Box::new(NeoPDFWrapper(pdf))),
        Some(Err(_)) | None => std::ptr::null_mut(),
    }
}

/// Frees a lazy PDF iterator object.
///
/// # Safety
///
/// The `iter` pointer must be a valid pointer to a `NeoPDFLazyIterator` object
/// previously allocated by `neopdf_pdf_load_lazy`.
#[no_mangle]
pub unsafe extern "C" fn neopdf_lazy_iterator_free(iter: *mut NeoPDFLazyIterator) {
    if !iter.is_null() {
        unsafe { drop(Box::from_raw(iter)) };
    }
}

/// Retrieves the `x_min` for this PDF set.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_x_min(pdf: *mut NeoPDFWrapper) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.param_ranges().x.min
}

/// Retrieves the `x_max` for this PDF set.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_x_max(pdf: *mut NeoPDFWrapper) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.param_ranges().x.max
}

/// Retrieves the `q2_min` for this PDF set.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_q2_min(pdf: *mut NeoPDFWrapper) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.param_ranges().q2.min
}

/// Retrieves the `q2_max` for this PDF set.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_q2_max(pdf: *mut NeoPDFWrapper) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.param_ranges().q2.max
}

/// Interpolates the PDF value (xf) for a given flavor, x, and Q2.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_xfxq2(
    pdf: *mut NeoPDFWrapper,
    id: i32,
    x: f64,
    q2: f64,
) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.xfxq2(id, &[x, q2])
}

/// Interpolates the PDF value (xf) for a generic set of parameters.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_xfxq2_nd(
    pdf: *mut NeoPDFWrapper,
    id: i32,
    params: *mut f64,
    num_params: usize,
) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    let params = unsafe { slice::from_raw_parts(params, num_params) };

    pdf_obj.xfxq2(id, params)
}

/// Interpolates PDF values for multiple points in parallel using Chebyshev batch interpolation.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
/// The `points` pointer must be a valid pointer to an array of pointers to `c_double`.
/// The `lengths` pointer must be a valid pointer to an array of `usize`.
/// `num_points` must be the correct number of points.
/// The `results` pointer must be valid for writing `num_points` elements.
///
/// # Panics
///
/// TODO
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_xfxq2_cheby_batch(
    pdf: *mut NeoPDFWrapper,
    pid: i32,
    points: *const *const c_double,
    lengths: *const usize,
    num_points: usize,
    results: *mut c_double,
) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };

    let points_slices: &[*const c_double] = unsafe { slice::from_raw_parts(points, num_points) };
    let lengths_slice: &[usize] = unsafe { slice::from_raw_parts(lengths, num_points) };

    let rust_points: Vec<&[f64]> = points_slices
        .iter()
        .zip(lengths_slice)
        .map(|(&p, &l)| unsafe { slice::from_raw_parts(p, l) })
        .collect();

    let res_vec = pdf_obj.xfxq2_cheby_batch(pid, &rust_points);

    let results_slice = unsafe { slice::from_raw_parts_mut(results, res_vec.len()) };
    results_slice.copy_from_slice(&res_vec);
}

/// Evaluates all requested flavors at a single kinematic point.
///
/// Performs the subgrid lookup and log transform once, then loops over PIDs.
/// The `results` buffer must be pre-allocated to hold `num_pids` elements.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// - The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
/// - `pids` must be valid for reading `num_pids` elements.
/// - `points` must be valid for reading `num_points` elements.
/// - `results` must be valid for writing `num_pids` elements.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_xfxq2_pids(
    pdf: *mut NeoPDFWrapper,
    pids: *const c_int,
    num_pids: usize,
    points: *const c_double,
    num_points: usize,
    results: *mut c_double,
) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };

    let pids_slice = unsafe { slice::from_raw_parts(pids, num_pids) };
    let points_slice = unsafe { slice::from_raw_parts(points, num_points) };
    let results_slice = unsafe { slice::from_raw_parts_mut(results, num_pids) };

    pdf_obj.xfxq2_allpids(pids_slice, points_slice, results_slice);
}

/// Interpolates PDF values for multiple PIDs at multiple kinematic points.
///
/// The results are written into a flat row-major buffer of shape `[num_pids, num_points]`.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// - The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
/// - `pids` must be valid for reading `num_pids` elements.
/// - `points` must be a valid pointer to an array of `num_points` pointers to `c_double` arrays.
/// - `lengths` must be a valid pointer to an array of `num_points` `usize` values.
/// - `results` must be valid for writing `num_pids * num_points` elements.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_xfxq2s(
    pdf: *mut NeoPDFWrapper,
    pids: *const c_int,
    num_pids: usize,
    points: *const *const c_double,
    lengths: *const usize,
    num_points: usize,
    results: *mut c_double,
) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };

    let pids_slice = unsafe { slice::from_raw_parts(pids, num_pids) };
    let points_slices = unsafe { slice::from_raw_parts(points, num_points) };
    let lengths_slice = unsafe { slice::from_raw_parts(lengths, num_points) };

    let rust_points: Vec<&[f64]> = points_slices
        .iter()
        .zip(lengths_slice)
        .map(|(&p, &l)| unsafe { slice::from_raw_parts(p, l) })
        .collect();

    let result_array = pdf_obj.xfxq2s(pids_slice.to_vec(), &rust_points);

    let results_slice = unsafe { slice::from_raw_parts_mut(results, num_pids * num_points) };
    results_slice.copy_from_slice(result_array.as_slice().unwrap());
}

/// Clip the interpolated values if they turned out negatives.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_set_force_positive(
    pdf: *mut NeoPDFWrapper,
    option: ForcePositive,
) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &mut (*pdf).0 };

    pdf_obj.set_force_positive(option);
}

/// Clip the interpolated values if they turned out negatives for all members.
///
/// # Panics
///
/// This function will panic if the `pdfs` pointer is null.
///
/// # Safety
///
/// The `pdfs` pointer must be a valid pointer to a `NeoPDFMembers` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_set_force_positive_members(
    pdfs: *mut NeoPDFMembers,
    option: ForcePositive,
) {
    assert!(!pdfs.is_null());
    let members = unsafe { &mut *pdfs };
    let pdf_slice = unsafe { slice::from_raw_parts_mut(members.pdfs, members.size) };

    for pdf_ptr in pdf_slice {
        let pdf_obj = unsafe { &mut (**pdf_ptr).0 };
        pdf_obj.set_force_positive(option.clone());
    }
}

/// Returns the value of `ForcePositive` defining the PDF grid.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_is_force_positive(pdf: *mut NeoPDFWrapper) -> ForcePositive {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &mut (*pdf).0 };

    pdf_obj.is_force_positive().clone()
}

/// Computes the `alpha_s` value at a given Q2.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_alphas_q2(pdf: *mut NeoPDFWrapper, q2: f64) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.alphas_q2(q2)
}

/// Returns the number of PIDs.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_num_pids(pdf: *mut NeoPDFWrapper) -> usize {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.pids().len()
}

/// Returns the PID representation of the PDF Grid.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object, and the `pids` pointer
/// must be valid for writing `num_pids` elements.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_pids(pdf: *mut NeoPDFWrapper, pids: *mut i32, num_pids: usize) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };

    let pids = unsafe { slice::from_raw_parts_mut(pids, num_pids) };
    let pid_values = pdf_obj.pids();

    pids.copy_from_slice(pid_values.as_slice().unwrap());
}

/// Parameters for subgrids in the PDF grid.
#[repr(C)]
pub enum NeopdfSubgridParams {
    /// Parameters for subgrids in the PDF grid.
    Nucleons,
    /// The strong coupling constant (`alpha_s`) parameter.
    Alphas,
    /// The xi parameter.
    Xi,
    /// The delta parameter.
    Delta,
    /// The transverse momentum `kT` parameter.
    Kt,
    /// The momentum fraction (x) parameter.
    Momentum,
    /// The energy scale (Q^2) parameter.
    Scale,
}

/// Returns the number of subgrids in the PDF Grid.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_num_subgrids(pdf: *mut NeoPDFWrapper) -> usize {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.num_subgrids()
}

/// Returns the minimum and maximum value for a given parameter.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object, and the `param_range` pointer
/// must be valid for writing two `f64` values.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_param_range(
    pdf: *mut NeoPDFWrapper,
    param: NeopdfSubgridParams,
    param_range: *mut f64,
) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };

    let param_range = unsafe { slice::from_raw_parts_mut(param_range, 2) };
    let range_params = match param {
        NeopdfSubgridParams::Nucleons => &[
            pdf_obj.param_ranges().nucleons.min,
            pdf_obj.param_ranges().nucleons.max,
        ],
        NeopdfSubgridParams::Alphas => &[
            pdf_obj.param_ranges().alphas.min,
            pdf_obj.param_ranges().alphas.max,
        ],
        NeopdfSubgridParams::Xi => &[pdf_obj.param_ranges().xi.min, pdf_obj.param_ranges().xi.max],
        NeopdfSubgridParams::Delta => &[
            pdf_obj.param_ranges().delta.min,
            pdf_obj.param_ranges().delta.max,
        ],
        NeopdfSubgridParams::Kt => &[pdf_obj.param_ranges().kt.min, pdf_obj.param_ranges().kt.max],
        NeopdfSubgridParams::Momentum => {
            &[pdf_obj.param_ranges().x.min, pdf_obj.param_ranges().x.max]
        }
        NeopdfSubgridParams::Scale => {
            &[pdf_obj.param_ranges().q2.min, pdf_obj.param_ranges().q2.max]
        }
    };

    param_range.copy_from_slice(range_params);
}

/// Returns the shape of the subgrids in the order of their index for a given parameter.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object, and the `subgrid_shape` pointer
/// must be valid for writing `num_subgrid` elements.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_subgrids_shape_for_param(
    pdf: *mut NeoPDFWrapper,
    subgrid_shape: *mut usize,
    num_subgrid: usize,
    subgrid_param: NeopdfSubgridParams,
) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };

    let subgrid_shape = unsafe { slice::from_raw_parts_mut(subgrid_shape, num_subgrid) };
    let shape_subgrids: Vec<usize> = pdf_obj
        .subgrids()
        .iter()
        .map(|sub| match subgrid_param {
            NeopdfSubgridParams::Nucleons => sub.nucleons.len(),
            NeopdfSubgridParams::Alphas => sub.alphas.len(),
            NeopdfSubgridParams::Xi => sub.xis.len(),
            NeopdfSubgridParams::Delta => sub.deltas.len(),
            NeopdfSubgridParams::Kt => sub.kts.len(),
            NeopdfSubgridParams::Momentum => sub.xs.len(),
            NeopdfSubgridParams::Scale => sub.q2s.len(),
        })
        .collect();

    subgrid_shape.copy_from_slice(&shape_subgrids);
}

/// Returns the grid values of a parameter for a given subgrid.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object. The `subgrid` pointer must be
/// valid for writing the number of elements specified by `subgrid_shape[subgrid_index]`.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_subgrids_for_param(
    pdf: *mut NeoPDFWrapper,
    subgrid: *mut f64,
    subgrid_param: NeopdfSubgridParams,
    num_subgrid: usize,
    subgrid_shape: *mut usize,
    subgrid_index: usize,
) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };

    let subgrid_shape = unsafe { slice::from_raw_parts(subgrid_shape, num_subgrid) };
    let subgrid = unsafe { slice::from_raw_parts_mut(subgrid, subgrid_shape[subgrid_index]) };
    let subgrid_knots = match subgrid_param {
        NeopdfSubgridParams::Nucleons => &pdf_obj.subgrids()[subgrid_index].nucleons,
        NeopdfSubgridParams::Alphas => &pdf_obj.subgrids()[subgrid_index].alphas,
        NeopdfSubgridParams::Xi => &pdf_obj.subgrids()[subgrid_index].xis,
        NeopdfSubgridParams::Delta => &pdf_obj.subgrids()[subgrid_index].deltas,
        NeopdfSubgridParams::Kt => &pdf_obj.subgrids()[subgrid_index].kts,
        NeopdfSubgridParams::Momentum => &pdf_obj.subgrids()[subgrid_index].xs,
        NeopdfSubgridParams::Scale => &pdf_obj.subgrids()[subgrid_index].q2s,
    };

    subgrid.copy_from_slice(subgrid_knots.as_slice().unwrap());
}

/// An opaque struct holding the data for a single grid, including its subgrids and flavors.
/// C code should not access its fields directly.
pub struct NeoPDFGrid {
    subgrids: Vec<SubgridData>,
    flavors: Vec<i32>,
}

impl NeoPDFGrid {
    /// Creates a new, empty grid
    const fn new() -> Self {
        Self {
            subgrids: Vec::new(),
            flavors: Vec::new(),
        }
    }

    /// Adds a subgrid to the grid
    #[allow(clippy::too_many_arguments)]
    unsafe fn add_subgrid(
        &mut self,
        nucleons: *const c_double,
        num_nucleons: usize,
        alphas: *const c_double,
        num_alphas: usize,
        kts: *const c_double,
        num_kts: usize,
        xs: *const c_double,
        num_xs: usize,
        q2s: *const c_double,
        num_q2s: usize,
        grid_data: *const c_double,
        grid_data_len: usize,
    ) -> NeopdfResult {
        // Check for null pointers
        if nucleons.is_null()
            || alphas.is_null()
            || kts.is_null()
            || xs.is_null()
            || q2s.is_null()
            || grid_data.is_null()
        {
            return NeopdfResult::ErrorNullPointer;
        }

        let subgrid = unsafe {
            SubgridData {
                nucleons: slice::from_raw_parts(nucleons, num_nucleons).to_vec(),
                alphas: slice::from_raw_parts(alphas, num_alphas).to_vec(),
                xis: vec![0.0],
                deltas: vec![0.0],
                kts: slice::from_raw_parts(kts, num_kts).to_vec(),
                xs: slice::from_raw_parts(xs, num_xs).to_vec(),
                q2s: slice::from_raw_parts(q2s, num_q2s).to_vec(),
                grid_data: slice::from_raw_parts(grid_data, grid_data_len).to_vec(),
            }
        };
        self.subgrids.push(subgrid);

        NeopdfResult::Success
    }

    /// Sets the flavor IDs for the grid
    unsafe fn set_flavors(&mut self, flavors: *const c_int, num_flavors: usize) -> NeopdfResult {
        if flavors.is_null() {
            return NeopdfResult::ErrorNullPointer;
        }
        self.flavors = unsafe { slice::from_raw_parts(flavors, num_flavors).to_vec() };

        NeopdfResult::Success
    }

    /// Adds a subgrid to the grid (v2 for 8D)
    #[allow(clippy::too_many_arguments, clippy::similar_names)]
    unsafe fn add_subgrid_v2(
        &mut self,
        nucleons: *const c_double,
        num_nucleons: usize,
        alphas: *const c_double,
        num_alphas: usize,
        xis: *const c_double,
        num_xis: usize,
        deltas: *const c_double,
        num_deltas: usize,
        kts: *const c_double,
        num_kts: usize,
        xs: *const c_double,
        num_xs: usize,
        q2s: *const c_double,
        num_q2s: usize,
        grid_data: *const c_double,
        grid_data_len: usize,
    ) -> NeopdfResult {
        // Check for null pointers
        if nucleons.is_null()
            || alphas.is_null()
            || xis.is_null()
            || deltas.is_null()
            || kts.is_null()
            || xs.is_null()
            || q2s.is_null()
            || grid_data.is_null()
        {
            return NeopdfResult::ErrorNullPointer;
        }

        let subgrid = unsafe {
            SubgridData {
                nucleons: slice::from_raw_parts(nucleons, num_nucleons).to_vec(),
                alphas: slice::from_raw_parts(alphas, num_alphas).to_vec(),
                xis: slice::from_raw_parts(xis, num_xis).to_vec(),
                deltas: slice::from_raw_parts(deltas, num_deltas).to_vec(),
                kts: slice::from_raw_parts(kts, num_kts).to_vec(),
                xs: slice::from_raw_parts(xs, num_xs).to_vec(),
                q2s: slice::from_raw_parts(q2s, num_q2s).to_vec(),
                grid_data: slice::from_raw_parts(grid_data, grid_data_len).to_vec(),
            }
        };
        self.subgrids.push(subgrid);

        NeopdfResult::Success
    }
}

/// Creates a new, empty `NeoPDFGrid`.
///
/// The caller is responsible for freeing the returned grid using `neopdf_grid_free`.
#[no_mangle]
pub extern "C" fn neopdf_grid_new() -> *mut NeoPDFGrid {
    Box::into_raw(Box::new(NeoPDFGrid::new()))
}

/// Adds a subgrid to an existing `NeoPDFGrid`.
///
/// This function takes ownership of the provided data arrays and resizes them as needed.
///
/// # Safety
/// - `grid` must be a valid pointer to a `NeoPDFGrid` created by `neopdf_grid_new`.
/// - The data pointers must be valid for the specified lengths.
#[no_mangle]
pub unsafe extern "C" fn neopdf_grid_add_subgrid(
    grid: *mut NeoPDFGrid,
    nucleons: *const c_double,
    num_nucleons: usize,
    alphas: *const c_double,
    num_alphas: usize,
    kts: *const c_double,
    num_kts: usize,
    xs: *const c_double,
    num_xs: usize,
    q2s: *const c_double,
    num_q2s: usize,
    grid_data: *const c_double,
    grid_data_len: usize,
) -> NeopdfResult {
    unsafe {
        grid.as_mut()
            .map_or(NeopdfResult::ErrorNullPointer, |grid| {
                grid.add_subgrid(
                    nucleons,
                    num_nucleons,
                    alphas,
                    num_alphas,
                    kts,
                    num_kts,
                    xs,
                    num_xs,
                    q2s,
                    num_q2s,
                    grid_data,
                    grid_data_len,
                )
            })
    }
}

/// Adds a subgrid to an existing `NeoPDFGrid` (v2 for 8D).
///
/// This function takes ownership of the provided data arrays and resizes them as needed.
///
/// # Safety
/// - `grid` must be a valid pointer to a `NeoPDFGrid` created by `neopdf_grid_new`.
/// - The data pointers must be valid for the specified lengths.
#[allow(clippy::similar_names)]
#[no_mangle]
pub unsafe extern "C" fn neopdf_grid_add_subgridv2(
    grid: *mut NeoPDFGrid,
    nucleons: *const c_double,
    num_nucleons: usize,
    alphas: *const c_double,
    num_alphas: usize,
    xis: *const c_double,
    num_xis: usize,
    deltas: *const c_double,
    num_deltas: usize,
    kts: *const c_double,
    num_kts: usize,
    xs: *const c_double,
    num_xs: usize,
    q2s: *const c_double,
    num_q2s: usize,
    grid_data: *const c_double,
    grid_data_len: usize,
) -> NeopdfResult {
    unsafe {
        grid.as_mut()
            .map_or(NeopdfResult::ErrorNullPointer, |grid| {
                grid.add_subgrid_v2(
                    nucleons,
                    num_nucleons,
                    alphas,
                    num_alphas,
                    xis,
                    num_xis,
                    deltas,
                    num_deltas,
                    kts,
                    num_kts,
                    xs,
                    num_xs,
                    q2s,
                    num_q2s,
                    grid_data,
                    grid_data_len,
                )
            })
    }
}

/// Sets the flavor IDs for a `NeoPDFGrid`.
///
/// # Safety
/// - `grid` must be a valid pointer to a `NeoPDFGrid`.
/// - `flavors` must be a valid pointer to an array of integers of size `num_flavors`.
#[no_mangle]
pub unsafe extern "C" fn neopdf_grid_set_flavors(
    grid: *mut NeoPDFGrid,
    flavors: *const c_int,
    num_flavors: usize,
) -> NeopdfResult {
    unsafe {
        grid.as_mut()
            .map_or(NeopdfResult::ErrorNullPointer, |grid| {
                grid.set_flavors(flavors, num_flavors)
            })
    }
}

/// Frees the memory allocated for a `NeoPDFGrid`.
///
/// # Safety
/// `grid` must be a valid pointer to a `NeoPDFGrid` created by `neopdf_grid_new`.
#[no_mangle]
pub unsafe extern "C" fn neopdf_grid_free(grid: *mut NeoPDFGrid) {
    if !grid.is_null() {
        unsafe { drop(Box::from_raw(grid)) };
    }
}

/// Physical Parameters of the PDF set.
#[repr(C)]
pub struct NeoPDFPhysicsParameters {
    /// The flavor scheme used for the PDF set.
    pub flavor_scheme: *const c_char,
    /// Number of QCD loops in the calculation of PDF evolution.
    pub order_qcd: u32,
    /// Number of QCD loops in the calculation of `alpha_s`.
    pub alphas_order_qcd: u32,
    /// Value of the W boson mass.
    pub m_w: f64,
    /// Value of the Z boson mass.
    pub m_z: f64,
    /// Value of the `u` quark mass.
    pub m_up: f64,
    /// Value of the `d` quark mass.
    pub m_down: f64,
    /// Value of the `s` quark mass.
    pub m_strange: f64,
    /// Value of the `c` quark mass.
    pub m_charm: f64,
    /// Value of the `b` quark mass.
    pub m_bottom: f64,
    /// Value of the `t` quark mass.
    pub m_top: f64,
    /// Method to compute strong coupling.
    pub alphas_type: *const c_char,
    /// Number of active flavors.
    pub number_flavors: u32,
}

/// Metadata for PDF grids
#[repr(C)]
pub struct NeoPDFMetaData {
    set_desc: *const c_char,
    set_index: u32,
    num_members: u32,
    x_min: c_double,
    x_max: c_double,
    q_min: c_double,
    q_max: c_double,
    flavors: *const c_int,
    num_flavors: usize,
    format: *const c_char,
    alphas_q_values: *const c_double,
    num_alphas_q: usize,
    alphas_vals: *const c_double,
    num_alphas_vals: usize,
    polarised: bool,
    set_type: SetType,
    interpolator_type: InterpolatorType,
    error_type: *const c_char,
    hadron_pid: c_int,
    phys_params: NeoPDFPhysicsParameters,
}

/// Metadata for PDF grids (V2 with extended fields)
#[repr(C)]
pub struct NeoPDFMetaDataV2 {
    set_desc: *const c_char,
    set_index: u32,
    num_members: u32,
    x_min: c_double,
    x_max: c_double,
    q_min: c_double,
    q_max: c_double,
    flavors: *const c_int,
    num_flavors: usize,
    format: *const c_char,
    alphas_q_values: *const c_double,
    num_alphas_q: usize,
    alphas_vals: *const c_double,
    num_alphas_vals: usize,
    polarised: bool,
    set_type: SetType,
    interpolator_type: InterpolatorType,
    error_type: *const c_char,
    hadron_pid: c_int,
    phys_params: NeoPDFPhysicsParameters,
    xi_min: c_double,
    xi_max: c_double,
    delta_min: c_double,
    delta_max: c_double,
}

/// Safely converts C string to Rust string
unsafe fn cstr_to_string(ptr: *const c_char) -> Option<String> {
    if ptr.is_null() {
        None
    } else {
        unsafe { Some(CStr::from_ptr(ptr).to_string_lossy().into_owned()) }
    }
}

/// Safely converts C array to Rust Vec
unsafe fn carray_to_vec<T: Copy>(ptr: *const T, len: usize) -> Option<Vec<T>> {
    if ptr.is_null() {
        None
    } else {
        unsafe { Some(slice::from_raw_parts(ptr, len).to_vec()) }
    }
}

/// Processes metadata from C struct to Rust struct
fn process_metadata(meta: *const NeoPDFMetaData) -> Option<MetaData> {
    if meta.is_null() {
        return None;
    }

    let meta = unsafe { &*meta };

    let set_desc = unsafe { cstr_to_string(meta.set_desc) }?;
    let format = unsafe { cstr_to_string(meta.format) }?;
    let flavors = unsafe { carray_to_vec(meta.flavors, meta.num_flavors) }?;
    let alphas_q_values = unsafe { carray_to_vec(meta.alphas_q_values, meta.num_alphas_q) }?;
    let alphas_vals = unsafe { carray_to_vec(meta.alphas_vals, meta.num_alphas_vals) }?;
    let error_type = unsafe { cstr_to_string(meta.error_type) }?;
    let flavor_scheme = unsafe { cstr_to_string(meta.phys_params.flavor_scheme) }?;
    let alphas_type = unsafe { cstr_to_string(meta.phys_params.alphas_type) }?;

    // Create MetaData (now MetaDataV2) directly
    let metadata = MetaData {
        set_desc,
        set_index: meta.set_index,
        num_members: meta.num_members,
        x_min: meta.x_min,
        x_max: meta.x_max,
        q_min: meta.q_min,
        q_max: meta.q_max,
        flavors,
        format,
        alphas_q_values,
        alphas_vals,
        polarised: meta.polarised,
        set_type: meta.set_type.clone(),
        interpolator_type: meta.interpolator_type.clone(),
        error_type,
        hadron_pid: meta.hadron_pid,
        git_version: String::new(),  // placeholder to be overwritten
        code_version: String::new(), // placeholder to be overwritten
        flavor_scheme,
        order_qcd: meta.phys_params.order_qcd,
        alphas_order_qcd: meta.phys_params.alphas_order_qcd,
        m_w: meta.phys_params.m_w,
        m_z: meta.phys_params.m_z,
        m_up: meta.phys_params.m_up,
        m_down: meta.phys_params.m_down,
        m_strange: meta.phys_params.m_strange,
        m_charm: meta.phys_params.m_charm,
        m_bottom: meta.phys_params.m_bottom,
        m_top: meta.phys_params.m_top,
        alphas_type,
        number_flavors: meta.phys_params.number_flavors,
        // New V2 fields with defaults
        xi_min: 1.0,
        xi_max: 1.0,
        delta_min: 0.0,
        delta_max: 0.0,
    };

    Some(metadata)
}

/// Processes metadata from C struct to Rust struct (V2)
fn process_metadata_v2(meta: *const NeoPDFMetaDataV2) -> Option<MetaData> {
    if meta.is_null() {
        return None;
    }

    let meta = unsafe { &*meta };

    let set_desc = unsafe { cstr_to_string(meta.set_desc) }?;
    let format = unsafe { cstr_to_string(meta.format) }?;
    let flavors = unsafe { carray_to_vec(meta.flavors, meta.num_flavors) }?;
    let alphas_q_values = unsafe { carray_to_vec(meta.alphas_q_values, meta.num_alphas_q) }?;
    let alphas_vals = unsafe { carray_to_vec(meta.alphas_vals, meta.num_alphas_vals) }?;
    let error_type = unsafe { cstr_to_string(meta.error_type) }?;
    let flavor_scheme = unsafe { cstr_to_string(meta.phys_params.flavor_scheme) }?;
    let alphas_type = unsafe { cstr_to_string(meta.phys_params.alphas_type) }?;

    // Create MetaData directly from V2 struct
    let metadata = MetaData {
        set_desc,
        set_index: meta.set_index,
        num_members: meta.num_members,
        x_min: meta.x_min,
        x_max: meta.x_max,
        q_min: meta.q_min,
        q_max: meta.q_max,
        flavors,
        format,
        alphas_q_values,
        alphas_vals,
        polarised: meta.polarised,
        set_type: meta.set_type.clone(),
        interpolator_type: meta.interpolator_type.clone(),
        error_type,
        hadron_pid: meta.hadron_pid,
        git_version: String::new(),  // placeholder to be overwritten
        code_version: String::new(), // placeholder to be overwritten
        flavor_scheme,
        order_qcd: meta.phys_params.order_qcd,
        alphas_order_qcd: meta.phys_params.alphas_order_qcd,
        m_w: meta.phys_params.m_w,
        m_z: meta.phys_params.m_z,
        m_up: meta.phys_params.m_up,
        m_down: meta.phys_params.m_down,
        m_strange: meta.phys_params.m_strange,
        m_charm: meta.phys_params.m_charm,
        m_bottom: meta.phys_params.m_bottom,
        m_top: meta.phys_params.m_top,
        alphas_type,
        number_flavors: meta.phys_params.number_flavors,
        // New V2 fields
        xi_min: meta.xi_min,
        xi_max: meta.xi_max,
        delta_min: meta.delta_min,
        delta_max: meta.delta_max,
    };

    Some(metadata)
}

/// Represents a dynamically-sized collection of `NeoPDFGrid` pointers.
/// This struct is exposed to C and manages memory for the array of pointers.
#[repr(C)]
pub struct NeoPDFGridArrayCollection {
    /// A raw pointer to a C-style array of `NeoPDFGrid` pointers.
    /// This array holds the pointers to the individual grids added to the collection.
    grids: *mut *mut NeoPDFGrid,
    /// The current number of `NeoPDFGrid` pointers stored in the `grids` array.
    num_grids: usize,
    /// The total allocated capacity of the `grids` array.
    /// When `num_grids` reaches `capacity`, the array is reallocated to a larger size.
    capacity: usize,
}

impl NeoPDFGridArrayCollection {
    /// Creates a new, empty `NeoPDFGridArrayCollection`.
    /// Initializes the collection with no grids and zero capacity.
    const fn new() -> Self {
        Self {
            grids: std::ptr::null_mut(),
            num_grids: 0,
            capacity: 0,
        }
    }

    /// Adds a `NeoPDFGrid` pointer to the collection.
    /// This function handles dynamic resizing of the underlying array if needed.
    ///
    /// # Arguments
    /// * `grid` - A raw pointer to the `NeoPDFGrid` to be added.
    ///
    /// # Returns
    /// `NeoPDFResult::Success` if the grid was added successfully, or an error code
    /// (`ErrorNullPointer`, `ErrorMemoryError`) if an issue occurred.
    fn add_grid(&mut self, grid: *mut NeoPDFGrid) -> NeopdfResult {
        // Ensure the provided grid pointer is not null.
        if grid.is_null() {
            return NeopdfResult::ErrorNullPointer;
        }

        if self.num_grids == self.capacity {
            let new_capacity = if self.capacity == 0 {
                4
            } else {
                self.capacity * 2
            };

            let new_ptr = if self.grids.is_null() {
                unsafe {
                    std::alloc::alloc(
                        std::alloc::Layout::array::<*mut NeoPDFGrid>(new_capacity).unwrap(),
                    )
                    // TODO: Would using `libc` better? See commit `54b3044`.
                    .cast::<()>()
                    .cast::<*mut NeoPDFGrid>()
                }
            } else {
                unsafe {
                    std::alloc::realloc(
                        self.grids.cast::<u8>(),
                        std::alloc::Layout::array::<*mut NeoPDFGrid>(self.capacity).unwrap(),
                        new_capacity * std::mem::size_of::<*mut NeoPDFGrid>(),
                    )
                    // TODO: Would using `libc` better? See commit `54b3044`.
                    .cast::<()>()
                    .cast::<*mut NeoPDFGrid>()
                }
            };

            if new_ptr.is_null() {
                return NeopdfResult::ErrorMemoryError;
            }

            self.grids = new_ptr;
            self.capacity = new_capacity;
        }

        unsafe {
            *self.grids.add(self.num_grids) = grid;
        }
        self.num_grids += 1;

        NeopdfResult::Success
    }

    /// Returns the number of grids currently in the collection.
    const fn len(&self) -> usize {
        self.num_grids
    }

    /// Retrieves a reference to the `NeoPDFGrid` at the specified index.
    ///
    /// # Arguments
    /// * `index` - The zero-based index of the grid to retrieve.
    ///
    /// # Returns
    /// An `Option<&NeoPDFGrid>`: `Some` if the index is valid, `None` otherwise.
    fn get(&self, index: usize) -> Option<&NeoPDFGrid> {
        if index >= self.num_grids {
            return None;
        }
        unsafe { (*self.grids.add(index)).as_ref() }
    }
}

impl Drop for NeoPDFGridArrayCollection {
    fn drop(&mut self) {
        if self.grids.is_null() {
            return;
        }
        let grids_slice = unsafe { slice::from_raw_parts(self.grids, self.num_grids) };
        for &grid_ptr in grids_slice {
            if !grid_ptr.is_null() {
                unsafe { drop(Box::from_raw(grid_ptr)) };
            }
        }

        unsafe {
            std::alloc::dealloc(
                self.grids.cast::<u8>(),
                std::alloc::Layout::array::<*mut NeoPDFGrid>(self.capacity).unwrap(),
            );
        }
    }
}

/// Creates a new, empty `NeoPDFGridArrayCollection`.
///
/// # Safety
/// The caller is responsible for freeing the returned collection using
/// `neopdf_gridarray_collection_free` to prevent memory leaks.
#[no_mangle]
pub extern "C" fn neopdf_gridarray_collection_new() -> *mut NeoPDFGridArrayCollection {
    Box::into_raw(Box::new(NeoPDFGridArrayCollection::new()))
}

/// Adds a `NeoPDFGrid` to a `NeoPDFGridArrayCollection`.
///
/// # Safety
/// - `collection` must be a valid, non-null pointer to a `NeoPDFGridArrayCollection`.
/// - `grid` must be a valid, non-null pointer to a `NeoPDFGrid`.
/// - The `grid` pointer is taken ownership of by the collection; it should not be freed separately
///   until the collection itself is freed or the grid is removed from the collection.
#[no_mangle]
pub unsafe extern "C" fn neopdf_gridarray_collection_add_grid(
    collection: *mut NeoPDFGridArrayCollection,
    grid: *mut NeoPDFGrid,
) -> NeopdfResult {
    unsafe {
        collection
            .as_mut()
            .map_or(NeopdfResult::ErrorNullPointer, |collection| {
                collection.add_grid(grid)
            })
    }
}

/// Frees the memory of a `NeoPDFGridArrayCollection` and all the grids it contains.
///
/// # Safety
/// - `collection` must be a valid, non-null pointer to a `NeoPDFGridArrayCollection`
///   that was previously created by `neopdf_gridarray_collection_new`.
/// - After this call, the `collection` pointer and all grids it contained become invalid
///   and should not be used.
#[no_mangle]
pub unsafe extern "C" fn neopdf_gridarray_collection_free(
    collection: *mut NeoPDFGridArrayCollection,
) {
    if !collection.is_null() {
        unsafe { drop(Box::from_raw(collection)) };
    }
}

/// Compresses a collection of `NeoPDFGrid` objects and writes them to a file.
///
/// This function iterates through the grids in the collection, converts them to `GridArray`s,
/// and then uses the `neopdf::writer::GridArrayCollection::compress` function to write them.
///
/// # Safety
/// - `collection` must be a valid, non-null pointer to a `NeoPDFGridArrayCollection`.
/// - `metadata` must be a valid, non-null pointer to a `NeoPDFMetaData` struct.
/// - `output_path` must be a valid, null-terminated C string representing the output file path.
#[no_mangle]
pub unsafe extern "C" fn neopdf_grid_compress(
    collection: *const NeoPDFGridArrayCollection,
    metadata: *const NeoPDFMetaData,
    output_path: *const c_char,
) -> NeopdfResult {
    if collection.is_null() || metadata.is_null() || output_path.is_null() {
        return NeopdfResult::ErrorNullPointer;
    }

    let collection = unsafe { &*collection };

    let Some(meta) = process_metadata(metadata) else {
        return NeopdfResult::ErrorInvalidData;
    };

    let out_path = unsafe { CStr::from_ptr(output_path).to_str() };
    let Ok(out_path) = out_path else {
        return NeopdfResult::ErrorInvalidData;
    };

    let mut grid_arrays = Vec::with_capacity(collection.len());

    for i in 0..collection.len() {
        let Some(grid) = collection.get(i) else {
            return NeopdfResult::ErrorInvalidData;
        };
        let grid_array = GridArray::new(grid.subgrids.clone(), grid.flavors.clone());
        grid_arrays.push(grid_array);
    }

    let grid_refs: Vec<&GridArray> = grid_arrays.iter().collect();

    match GridArrayCollection::compress(&grid_refs, &meta, out_path) {
        Ok(()) => NeopdfResult::Success,
        Err(_) => NeopdfResult::ErrorMemoryError,
    }
}

/// Compresses a collection of `NeoPDFGrid` objects and writes them to a file (V2).
///
/// This function iterates through the grids in the collection, converts them to `GridArray`s,
/// and then uses the `neopdf::writer::GridArrayCollection::compress` function to write them.
///
/// # Safety
/// - `collection` must be a valid, non-null pointer to a `NeoPDFGridArrayCollection`.
/// - `metadata` must be a valid, non-null pointer to a `NeoPDFMetaDataV2` struct.
/// - `output_path` must be a valid, null-terminated C string representing the output file path.
#[no_mangle]
pub unsafe extern "C" fn neopdf_grid_compress_v2(
    collection: *const NeoPDFGridArrayCollection,
    metadata: *const NeoPDFMetaDataV2,
    output_path: *const c_char,
) -> NeopdfResult {
    if collection.is_null() || metadata.is_null() || output_path.is_null() {
        return NeopdfResult::ErrorNullPointer;
    }

    let collection = unsafe { &*collection };

    let Some(meta) = process_metadata_v2(metadata) else {
        return NeopdfResult::ErrorInvalidData;
    };

    let out_path = unsafe { CStr::from_ptr(output_path).to_str() };
    let Ok(out_path) = out_path else {
        return NeopdfResult::ErrorInvalidData;
    };

    let mut grid_arrays = Vec::with_capacity(collection.len());

    for i in 0..collection.len() {
        let Some(grid) = collection.get(i) else {
            return NeopdfResult::ErrorInvalidData;
        };
        let grid_array = GridArray::new(grid.subgrids.clone(), grid.flavors.clone());
        grid_arrays.push(grid_array);
    }

    let grid_refs: Vec<&GridArray> = grid_arrays.iter().collect();

    match GridArrayCollection::compress(&grid_refs, &meta, out_path) {
        Ok(()) => NeopdfResult::Success,
        Err(_) => NeopdfResult::ErrorMemoryError,
    }
}

// LHAPDF C-API drop-in compatibility layer.
///
/// This global state stores the loaded PDF set and the currently selected
/// member index. It is not thread-safe and mirrors the behavior of legacy
/// LHAPDF interfaces.
struct LhapdfState {
    pdf_set: Option<Vec<PDF>>,
    member: usize,
}

static mut LHAPDF_STATE: LhapdfState = LhapdfState {
    pdf_set: None,
    member: 0,
};

/// Sets LHAPDF runtime parameters from a string (no-op).
///
/// This function is provided for compatibility with the LHAPDF C API and does
/// nothing in this implementation.
///
/// # Safety
///
/// The pointer `line` must be a valid, null-terminated C string if non-null.
#[no_mangle]
pub const unsafe extern "C" fn setlhaparm(_line: *const c_char) {}

/// Fortran name-mangled variant of `setlhaparm` (no-op).
///
/// This function is provided for compatibility with the LHAPDF Fortran API and
/// does nothing in this implementation.
///
/// # Safety
///
/// The pointer `line` must be valid for reads of `len` bytes if non-null.
#[no_mangle]
pub const unsafe extern "C" fn setlhaparm_(_line: *const c_char, _len: isize) {}

/// Initializes a PDF set by its name/path and loads all members.
///
/// The loaded set is stored in a global state used by the other LHAPDF-compatible
/// functions, with the current member index reset to 0.
///
/// # Panics
///
/// Panics if `name` is not valid UTF-8 or is not a valid, null-terminated C string.
///
/// # Safety
///
/// `name` must be a valid, null-terminated C string pointing to a UTF-8 path or set name.
#[no_mangle]
pub unsafe extern "C" fn initpdfsetbyname(name: *const c_char) {
    unsafe {
        let c_str = CStr::from_ptr(name);
        let pdf_name = c_str.to_str().expect("Invalid UTF-8 string");
        let pdfs = PDF::load_pdfs(pdf_name);
        LHAPDF_STATE.pdf_set = Some(pdfs);
        LHAPDF_STATE.member = 0;
    }
}

/// Fortran name-mangled variant of `initpdfsetbyname`.
///
/// Reads a fixed-length Fortran character buffer, trims trailing spaces, and loads
/// the corresponding PDF set into the global state. The current member index is
/// reset to 0.
///
/// # Panics
///
/// TODO
///
/// # Safety
///
/// `name` must be valid for reads of `len` bytes. The buffer may not be
/// null-terminated; trailing spaces are trimmed.
#[no_mangle]
#[allow(clippy::cast_sign_loss)]
pub unsafe extern "C" fn initpdfsetbyname_(name: *const c_char, len: c_int) {
    unsafe {
        let name_slice = slice::from_raw_parts(name.cast::<u8>(), len as usize);
        let pdf_name = std::str::from_utf8(name_slice).unwrap().trim_end();
        let pdfs = PDF::load_pdfs(pdf_name);
        LHAPDF_STATE.pdf_set = Some(pdfs);
        LHAPDF_STATE.member = 0;
    }
}

/// Selects the active member of the currently loaded PDF set.
///
/// # Safety
///
/// This function does not perform bounds checking here; subsequent calls that
/// use the member will return early if the index is out of range.
#[no_mangle]
#[allow(clippy::cast_sign_loss)]
pub unsafe extern "C" fn initpdf(member: c_int) {
    unsafe { LHAPDF_STATE.member = member as usize };
}

/// Fortran name-mangled variant of `initpdf`.
///
/// # Safety
///
/// `member` must be a valid pointer to an integer.
#[no_mangle]
#[allow(clippy::cast_sign_loss)]
pub unsafe extern "C" fn initpdf_(member: *const c_int) {
    unsafe { LHAPDF_STATE.member = *member as usize };
}

/// Evaluates parton distribution functions at given `(x, q)` for the active member.
///
/// # Safety
///
/// - `f` must point to writable memory for at least 13 `c_double` values.
/// - Requires that a PDF set has been initialized via `initpdfsetbyname` or its
///   Fortran variant. If no set is loaded or the member index is out of range,
///   the function returns without writing.
#[no_mangle]
pub unsafe extern "C" fn evolvepdf(x: c_double, q: c_double, f: *mut c_double) {
    unsafe {
        let state_ptr = &raw const LHAPDF_STATE;
        let pdf_set_ptr = &raw const (*state_ptr).pdf_set;

        if let Some(pdfs) = &*pdf_set_ptr {
            let member = (*state_ptr).member;
            if member >= pdfs.len() {
                return;
            }
            let pdf = &pdfs[member];
            let q2 = q * q;

            let out_slice = slice::from_raw_parts_mut(f, 14);
            pdf.xfxq2_allpids(&DEFAULT_PIDS, &[x, q2], out_slice);
        }
    }
}

/// Fortran name-mangled variant of `evolvepdf`.
///
/// # Safety
///
/// - `x`, `q` must be valid pointers to `c_double` values.
/// - `f` must point to writable memory for at least 13 `c_double` values.
/// - A PDF set must have been initialized and the member index must be valid or
///   the function will return without writing.
#[no_mangle]
pub unsafe extern "C" fn evolvepdf_(x: *const c_double, q: *const c_double, f: *mut c_double) {
    unsafe {
        let pdf_set_ptr = &raw const LHAPDF_STATE.pdf_set;

        if let Some(pdfs) = &*pdf_set_ptr {
            let member = (&raw const LHAPDF_STATE.member).read();
            if member >= pdfs.len() {
                return;
            }
            let pdf = &pdfs[member];
            let q2 = (*q) * (*q);

            let out_slice = slice::from_raw_parts_mut(f, 14);
            pdf.xfxq2_allpids(&DEFAULT_PIDS, &[*x, q2], out_slice);
        }
    }
}

/// Evaluates the strong coupling `alpha_s` at scale `q` for the active member.
///
/// # Safety
///
/// - Requires that a PDF set has been initialized via `initpdfsetbyname` or its
///   Fortran variant. If no set is loaded or the member index is out of range,
///   the function returns 0.0.
#[no_mangle]
pub unsafe extern "C" fn alphaspdf(q: c_double) -> c_double {
    unsafe {
        let state_ptr = &raw const LHAPDF_STATE;
        let pdf_set_ptr = &raw const (*state_ptr).pdf_set;

        if let Some(pdfs) = &*pdf_set_ptr {
            let member = (*state_ptr).member;
            if member >= pdfs.len() {
                return 0.0;
            }
            let pdf = &pdfs[member];
            let q2 = q * q;
            pdf.alphas_q2(q2)
        } else {
            0.0
        }
    }
}

/// Fortran name-mangled variant of `alphaspdf`.
///
/// # Safety
///
/// - `q` must be a valid pointer to a `c_double` value.
/// - A PDF set must have been initialized and the member index must be valid or
///   the function will return 0.0.
#[no_mangle]
pub unsafe extern "C" fn alphaspdf_(q: *const c_double) -> c_double {
    unsafe {
        let state_ptr = &raw const LHAPDF_STATE;
        let pdf_set_ptr = &raw const (*state_ptr).pdf_set;

        if let Some(pdfs) = &*pdf_set_ptr {
            let member = (*state_ptr).member;
            if member >= pdfs.len() {
                return 0.0;
            }
            let pdf = &pdfs[member];
            let q2 = (*q) * (*q);
            pdf.alphas_q2(q2)
        } else {
            0.0
        }
    }
}