xcp_registry 0.1.0

Measurement and Calibration registry for XCP - pure Rust, no C dependency
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
//-----------------------------------------------------------------------------
// Module a2l_writer
// Export an A2L file from super::registry

// Use log_level=Debug to track what exactly is written

use std::{collections::HashMap, io::Write};

use super::*;

trait GenerateA2l {
    fn write_a2l(&self, writer: &mut A2lWriter) -> std::io::Result<()>;
}

// Error for registry content which can not be represented in A2L
fn a2l_error(msg: String) -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::InvalidData, format!("A2L writer: {msg}"))
}

// Limits of an object, an error for value types which have none (Unknown, Blob, TypeDef)
fn get_limits(name: &str, mc_support_data: &McSupportData, value_type: McValueType) -> std::io::Result<(f64, f64)> {
    match (mc_support_data.get_min(value_type), mc_support_data.get_max(value_type)) {
        (Some(min), Some(max)) => Ok((min, max)),
        _ => Err(a2l_error(format!("{name}: value type {value_type:?} has no limits"))),
    }
}

// A2L types as str
impl McValueType {
    // Basic type
    fn get_type_str(&self) -> std::io::Result<&'static str> {
        Ok(match self {
            McValueType::Bool => "UBYTE",
            McValueType::Ubyte => "UBYTE",
            McValueType::Uword => "UWORD",
            McValueType::Ulong => "ULONG",
            McValueType::Ulonglong => "A_UINT64",
            McValueType::Sbyte => "SBYTE",
            McValueType::Sword => "SWORD",
            McValueType::Slong => "SLONG",
            McValueType::Slonglong => "A_INT64",
            McValueType::Float32Ieee => "FLOAT32_IEEE",
            McValueType::Float64Ieee => "FLOAT64_IEEE",
            McValueType::Blob(_) => "BLOB",
            McValueType::TypeDef(_) | McValueType::Unknown => return Err(a2l_error(format!("value type {self:?} is not a basic data type"))),
        })
    }

    // Get data type as str representing the A2L record_layout (all are predefined record layouts)
    // Used by A2L writer
    fn get_record_layout_str(&self) -> std::io::Result<&'static str> {
        Ok(match self {
            McValueType::Bool => "BOOL",
            McValueType::Ubyte => "U8",
            McValueType::Uword => "U16",
            McValueType::Ulong => "U32",
            McValueType::Ulonglong => "U64",
            McValueType::Sbyte => "I8",
            McValueType::Sword => "I16",
            McValueType::Slong => "I32",
            McValueType::Slonglong => "I64",
            McValueType::Float32Ieee => "F32",
            McValueType::Float64Ieee => "F64",
            McValueType::Blob(_) => "BLOB",
            McValueType::TypeDef(_) | McValueType::Unknown => return Err(a2l_error(format!("value type {self:?} has no record layout"))),
        })
    }
}

// Get the A2L object type of the calibration parameter
fn get_characteristic_subtype_str(dim_type: &McDimType, mc_support_data: &McSupportData) -> std::io::Result<&'static str> {
    Ok(match mc_support_data.object_type {
        McObjectType::Axis => "AXIS_PTS",
        McObjectType::Characteristic => {
            if dim_type.get_dim()[0] > 1
                && mc_support_data.x_axis_ref.is_none()
                && mc_support_data.y_axis_ref.is_none()
                && mc_support_data.x_axis_conv.is_none()
                && mc_support_data.y_axis_conv.is_none()
            {
                "VAL_BLK"
            } else if dim_type.get_dim()[0] > 1 && dim_type.get_dim()[1] > 1 {
                "MAP"
            } else if dim_type.get_dim()[0] > 1 || dim_type.get_dim()[1] > 1 {
                "CURVE"
            } else {
                "VALUE"
            }
        }
        _ => return Err(a2l_error(format!("object type {:?} is not a calibration object", mc_support_data.object_type))),
    })
}

//-------------------------------------------------------------------------------------------------

// Check if a unit string has the enum format and return the number of pairs.
// The unit string must be one or more pairs of <int> "<label>", without a leading count.
// Returns Some(count) if the format matches, None otherwise.
// Example: "0 "OFF" 1 "ON" 2 "STANDBY"" -> Some(3)
fn enum_pair_count(unit: &str) -> Option<usize> {
    let mut rest = unit.trim();
    if rest.is_empty() {
        return None;
    }
    let mut pairs = 0usize;
    while !rest.is_empty() {
        // expect an integer
        let sep = rest.find(' ').unwrap_or(rest.len());
        if rest[..sep].parse::<i64>().is_err() {
            return None;
        }
        rest = rest[sep..].trim_start();
        // expect a quoted string
        if !rest.starts_with('"') {
            return None;
        }
        rest = &rest[1..];
        let end = rest.find('"')?;
        rest = rest[end + 1..].trim_start();
        pairs += 1;
    }
    if pairs > 0 { Some(pairs) } else { None }
}

// The PHYS_UNIT string to emit for a unit. Enum-format units are encoded as a COMPU_VTAB
// conversion rule instead, so they must not be written as a (physical) PHYS_UNIT.
fn phys_unit(unit: &str) -> &str {
    if enum_pair_count(unit).is_some() { "" } else { unit }
}

// Write a conversion rule and return its name as string
fn write_conversion<'a>(writer: &mut A2lWriter, name: &'a str, instance_index: u16, dim_type: &McDimType, mc_support_data: &McSupportData) -> std::io::Result<&'a str> {
    let factor = mc_support_data.get_factor().unwrap_or(1.0);
    let offset = mc_support_data.get_offset().unwrap_or(0.0);
    let unit = mc_support_data.get_unit();

    // Bool: Use BOOL
    if dim_type.value_type == McValueType::Bool {
        Ok("BOOL")
    }
    // Conversion: Write a conversion rule and return its name
    else if (factor - 1.0).abs() > f64::EPSILON || offset.abs() > f64::EPSILON {
        // For measurements with multiple tli instances, the conversion name is created only once on index 1
        if instance_index > 1 {
            return Ok(name);
        }

        /*
        display format in %[<length>].<layout>
        <length> is an optional unsigned integer value, which indicates the overall length;
        <layout> is a mandatory unsigned integer value, which indicates the decimal places;
        The format string must always contain at least "%", "." and <layout>.
        */
        let layout: u8 = if dim_type.value_type == McValueType::Float32Ieee || dim_type.value_type == McValueType::Float64Ieee || factor < 0.001 {
            6
        } else if factor < 1.0 {
            3
        } else {
            0
        };

        writeln!(
            writer,
            r#"/begin COMPU_METHOD {name} "" LINEAR "%.{layout}" "{unit}" COEFFS_LINEAR {factor} {offset} /end COMPU_METHOD"#
        )?;
        Ok(name)
    }
    // No conversion
    else {
        // Float: Use NO_COMPU_METHOD
        if dim_type.value_type == McValueType::Float32Ieee || dim_type.value_type == McValueType::Float64Ieee {
            Ok("NO_COMPU_METHOD")
        }
        // Integer: Use predefined conversion rule identity with .0 display format
        else {
            // Create an enum conversion if the unit has enum format (pairs of <int> "<label>")
            // Example: "0 "OFF" 1 "ON" 2 "STANDBY"" -> COMPU_VTAB with count prepended: "3 0 "OFF" 1 "ON" 2 "STANDBY""
            if let Some(count) = enum_pair_count(unit) {
                writeln!(writer, r#"/begin COMPU_VTAB {name}.table "" TAB_VERB {count} {unit} /end COMPU_VTAB"#)?;
                writeln!(writer, r#"/begin COMPU_METHOD {name} "" TAB_VERB "%.0" "" COMPU_TAB_REF {name}.table /end COMPU_METHOD"#)?;
                Ok(name)
            } else {
                Ok("IDENTITY")
            }
        }
    }
}

// Write MATRIX_DIM if multi-dimensional VALUE
fn write_dimensions(dim_type: &McDimType, writer: &mut A2lWriter) -> std::io::Result<()> {
    let x_dim = dim_type.get_dim()[0];
    let y_dim = dim_type.get_dim()[1];
    if x_dim > 1 && y_dim > 1 {
        write!(writer, " MATRIX_DIM {} {}", x_dim, y_dim)?;
    } else if x_dim > 1 {
        write!(writer, " MATRIX_DIM {}", x_dim)?;
    }
    Ok(())
}

// Write AXIS_DESCR for MAP or CURVE or TYPEDEF_MAP, TYPEDEF_CURVE
fn write_axis_descr(_name: &str, dim_type: &McDimType, mc_support_data: &McSupportData, writer: &mut A2lWriter) -> std::io::Result<()> {
    let x_dim = dim_type.get_dim()[0];
    let y_dim = dim_type.get_dim()[1];

    let x_axis_input_quantity = if let Some(v) = &mc_support_data.x_axis_input_quantity {
        v.as_str()
    } else {
        "NO_INPUT_QUANTITY"
    };
    let y_axis_input_quantity = if let Some(v) = &mc_support_data.y_axis_input_quantity {
        v.as_str()
    } else {
        "NO_INPUT_QUANTITY"
    };

    // MAP
    if x_dim > 1 || y_dim > 1 {
        if x_dim > 1 && y_dim > 1 {
            // X
            if let Some(x_axis_conv) = &mc_support_data.x_axis_conv {
                write!(
                    writer,
                    r#" /begin AXIS_DESCR FIX_AXIS {} {} {} 0 {} FIX_AXIS_PAR_DIST 0 1 {} /end AXIS_DESCR"#,
                    x_axis_input_quantity,
                    x_axis_conv,
                    x_dim,     // MaxAxisPoints
                    x_dim - 1, // 0-UpperLimit
                    x_dim
                )?;
            } else if let Some(x_axis_ref) = &mc_support_data.x_axis_ref {
                write!(
                    writer,
                    r#" /begin AXIS_DESCR COM_AXIS {} NO_COMPU_METHOD {} 0.0 0.0 AXIS_PTS_REF {} /end AXIS_DESCR"#,
                    x_axis_input_quantity, x_dim, x_axis_ref
                )?;
            } else {
                write!(
                    writer,
                    r#" /begin AXIS_DESCR FIX_AXIS {} NO_COMPU_METHOD {} 0 {} FIX_AXIS_PAR_DIST 0 1 {} /end AXIS_DESCR"#,
                    x_axis_input_quantity,
                    x_dim,
                    x_dim - 1,
                    x_dim
                )?;
            }
            // Y
            if let Some(y_axis_conv) = &mc_support_data.y_axis_conv {
                write!(
                    writer,
                    r#" /begin AXIS_DESCR FIX_AXIS {} {} {} 0 {} FIX_AXIS_PAR_DIST 0 1 {} /end AXIS_DESCR"#,
                    y_axis_input_quantity,
                    y_axis_conv,
                    y_dim,
                    y_dim - 1,
                    y_dim
                )?;
            } else if let Some(y_axis_ref) = &mc_support_data.y_axis_ref {
                write!(
                    writer,
                    r#" /begin AXIS_DESCR COM_AXIS {} NO_COMPU_METHOD {} 0.0 0.0 AXIS_PTS_REF {} /end AXIS_DESCR"#,
                    y_axis_input_quantity, y_dim, y_axis_ref
                )?;
            } else {
                write!(
                    writer,
                    r#" /begin AXIS_DESCR FIX_AXIS {} NO_COMPU_METHOD {} 0 {} FIX_AXIS_PAR_DIST 0 1 {} /end AXIS_DESCR"#,
                    y_axis_input_quantity,
                    y_dim,
                    y_dim - 1,
                    y_dim
                )?;
            }
        }
        // CURVE
        else if x_dim > 1 {
            if let Some(x_axis_conv) = &mc_support_data.x_axis_conv {
                write!(
                    writer,
                    r#" /begin AXIS_DESCR FIX_AXIS {} {} {} 0 {} FIX_AXIS_PAR_DIST 0 1 {} /end AXIS_DESCR"#,
                    x_axis_input_quantity,
                    x_axis_conv,
                    x_dim,
                    x_dim - 1,
                    x_dim
                )?;
            } else if let Some(x_axis_ref) = &mc_support_data.x_axis_ref {
                write!(
                    writer,
                    r#" /begin AXIS_DESCR COM_AXIS {} NO_COMPU_METHOD {} 0.0 0.0 AXIS_PTS_REF {} /end AXIS_DESCR"#,
                    x_axis_input_quantity, x_dim, x_axis_ref
                )?;
            } else {
                write!(
                    writer,
                    r#" /begin AXIS_DESCR FIX_AXIS {} NO_COMPU_METHOD {} 0 {} FIX_AXIS_PAR_DIST 0 1 {} /end AXIS_DESCR"#,
                    x_axis_input_quantity,
                    x_dim,
                    x_dim - 1,
                    x_dim
                )?;
            }
        }
    }

    Ok(())
}

// Write instance IF_DATA with a single event, default or fixed
fn write_ifdata_event(event_id: u16, default: bool, writer: &mut A2lWriter) -> std::io::Result<()> {
    // Default event
    if default {
        write!(
            writer,
            " /begin IF_DATA XCP /begin DAQ_EVENT VARIABLE /begin DEFAULT_EVENT_LIST EVENT {event_id} /end DEFAULT_EVENT_LIST /end DAQ_EVENT /end IF_DATA"
        )?;
    }
    // Fixed event
    else {
        write!(writer, " /begin IF_DATA XCP /begin DAQ_EVENT FIXED_EVENT_LIST EVENT {event_id} /end DAQ_EVENT /end IF_DATA")?;
    }
    Ok(())
}

//-------------------------------------------------------------------------------------------------

impl GenerateA2l for McXcpTransportLayer {
    fn write_a2l(&self, writer: &mut A2lWriter) -> std::io::Result<()> {
        let protocol = self.protocol_name;

        // Ethernet
        // Example: /begin XCP_ON_UDP_IP 0x0104 5555 ADDRESS "127.0.0.1" /end XCP_ON_UDP_IP
        if protocol == "TCP" || protocol == "UDP" {
            let (Some(port), Some(addr)) = (self.port, self.addr) else {
                return Err(a2l_error(format!("transport layer {protocol}: address or port not set")));
            };
            log::info!("A2L writer: transport layer: {protocol} {addr}:{port}");
            writeln!(writer, "\n\t\t/begin XCP_ON_{protocol}_IP 0x0104 {port} ADDRESS \"{addr}\" /end XCP_ON_{protocol}_IP")
        }
        // CAN
        // Example: /begin XCP_ON_CAN 0x0100 CAN_ID_MASTER 0x0301 CAN_ID_SLAVE 0x01 BAUDRATE 0x0F4240 SAMPLE_POINT 0x4B SAMPLE_RATE SINGLE BTL_CYCLES 0x08 SJW 0x02 SYNC_EDGE SINGLE end XCP_ON_CAN
        else if protocol == "CAN" {
            // @@@@ TODO: Implement (CAN and CANFD)
            log::info!("A2L writer: transport layer: {protocol} ");
            Err(a2l_error("transport layer CAN is not supported".to_string()))
            // writeln!(
            //     writer,
            //     "\n\t\t/begin XCP_ON_CAN 0x0100 CAN_ID_MASTER 0x0301 CAN_ID_SLAVE 0x01 BAUDRATE 0x0F4240 SAMPLE_POINT 0x4B SAMPLE_RATE SINGLE BTL_CYCLES 0x08 SJW 0x02 SYNC_EDGE SINGLE /end XCP_ON_CAN"
            // )
        }
        // SxI
        else if protocol == "SxI" {
            /* Example (CANape default SLIP framingconfiguration):
                /begin XCP_ON_SxI
                    0x0100 115200
                    ASYNCH_FULL_DUPLEX_MODE PARITY_NONE ONE_STOP_BIT
                    FRAMING 0x9A 0x9B
                    HEADER_LEN_BYTE CHECKSUM_BYTE
                /end XCP_ON_SxI
            */
            let Some(baud_rate) = self.baud_rate else {
                return Err(a2l_error("transport layer SxI: baud rate not set".to_string()));
            };
            log::info!("A2L writer: transport layer: SxI baud_rate={baud_rate}");
            writeln!(
                writer,
                "\n\t\t/begin XCP_ON_SxI 0x0100 {baud_rate} ASYNCH_FULL_DUPLEX_MODE PARITY_NONE ONE_STOP_BIT FRAMING 0x9A 0x9B HEADER_LEN_BYTE CHECKSUM_BYTE /end XCP_ON_SxI",
            )
        } else {
            log::warn!("A2L writer: transport layer: {} not supported", protocol);
            Ok(())
        }
    }
}

//-------------------------------------------------------------------------------------------------

impl GenerateA2l for McEvent {
    fn write_a2l(&self, writer: &mut A2lWriter) -> std::io::Result<()> {
        let name = &self.name;
        let index = self.index;
        let id = self.id;

        log::debug!("A2L writer: event {} index={} id={}", name, index, id);

        let priority = 0; // Priority is always set to normal priority

        // Convert cycle time to ASAM coding timeCycle and timeUnit
        // "UNIT_1NS" = 0, "UNIT_10NS" = 1, ...
        // @@@@ TODO Create warning that not all cycle times can be represented in ASAM timeCycle and timeUnit
        let mut time_unit: u8 = 0;
        let mut time_cycle = self.target_cycle_time_ns;
        while time_cycle >= 256 {
            time_cycle /= 10;
            time_unit += 1;
        }

        // Write comment with function name, unit and CFA offset if available
        if let Some(function) = self.function.as_ref() {
            writeln!(
                writer,
                "\t\t\t/* compilation unit = {}, function = {}, CFA = {} */",
                self.unit.unwrap_or(0),
                function,
                self.cfa
            )?;
        }

        // long name 100+1 characters
        // short name 8+1 characters
        // TimeCycle 0
        // TimeUnit 0
        // Priority 0
        // @@@@ TODO CANape does not accept CONSISTENCY EVENT for serialized data types !!!!!!!!!!
        if index > 0 {
            let name = format!("{}_{}", name, index);
            let short_name = if name.len() > 8 { &name[name.len() - 8..] } else { &name };
            write!(writer, "\t\t\t/begin EVENT \"{:.100}\" \"{}\" ", name, short_name)?;
        } else {
            let short_name = if name.len() > 8 { &name[name.len() - 8..] } else { name };
            write!(writer, "\t\t\t/begin EVENT \"{:.100}\" \"{}\" ", name, short_name)?;
        }
        writeln!(writer, "{} DAQ 0xFF {} {} {} CONSISTENCY DAQ /end EVENT", id, time_cycle, time_unit, priority)
    }
}

//-------------------------------------------------------------------------------------------------

impl GenerateA2l for McApplication {
    fn write_a2l(&self, writer: &mut A2lWriter) -> std::io::Result<()> {
        // Add EPK if available
        if self.has_epk() {
            log::debug!("A2L writer: epk={} version_addr=0x{:08X}", self.version.epk, self.version.epk_addr);
            writeln!(writer, "EPK \"{}\" ADDR_EPK 0x{:08X}", self.version.epk, self.version.epk_addr)?;
        }

        Ok(())
    }
}

//-------------------------------------------------------------------------------------------------
// CalibrationSegment
// A2L MEMORY_SEGMENT

impl GenerateA2l for McCalibrationSegment {
    fn write_a2l(&self, writer: &mut A2lWriter) -> std::io::Result<()> {
        log::debug!(
            "A2L writer: memory segment {}:{}  {}:0x{:X} size={}",
            self.index,
            self.name,
            self.addr_ext,
            self.addr,
            self.size
        );

        writeln!(
            writer,
            r#"/begin MEMORY_SEGMENT {} "" DATA FLASH INTERN 0x{:X} {} -1 -1 -1 -1 -1"#,
            self.name, self.addr, self.size,
        )?;

        writeln!(
            writer,
            r#"/begin IF_DATA XCP
    /begin SEGMENT {} /*number*/ 2 /*pages*/ {} /* addr_ext*/ 0 0
    /begin CHECKSUM XCP_ADD_44 MAX_BLOCK_SIZE 0xFFFF EXTERNAL_FUNCTION "" /end CHECKSUM
    /begin PAGE 0x0 ECU_ACCESS_DONT_CARE XCP_READ_ACCESS_DONT_CARE XCP_WRITE_ACCESS_DONT_CARE /end PAGE
    /begin PAGE 0x1 ECU_ACCESS_DONT_CARE XCP_READ_ACCESS_DONT_CARE XCP_WRITE_ACCESS_NOT_ALLOWED /end PAGE
    /end SEGMENT
/end IF_DATA"#,
            self.index, self.addr_ext,
        )?;

        writeln!(writer, r#"/end MEMORY_SEGMENT"#,)?;
        //}
        Ok(())
    }
}

//-------------------------------------------------------------------------------------------------
// TYPEDEF_STRUCTURE

impl McTypeDef {
    pub(crate) fn write_typedef(&self, writer: &mut A2lWriter, level: usize) -> std::io::Result<()> {
        let type_length = self.size;
        let type_name = self.name.as_str();

        log::debug!("A2L writer: typedef {level} {type_name} len={type_length} ");

        // Names of the field typedefs (None for fields which are typedef structures), used for the STRUCTURE_COMPONENT references below
        let mut field_typedef_names: Vec<Option<String>> = Vec::with_capacity(self.fields.len());

        // Recurse or generate measurement typedefs for all TypeDefFields of this TypeDef
        for field in &self.fields {
            //
            // Field is a typedef, recursion here
            if let McValueType::TypeDef(field_type_name) = &field.dim_type.value_type {
                if let Some(typedef) = writer.registry.typedef_list.find_typedef(field_type_name.as_str()) {
                    typedef.write_typedef(writer, level + 1)?;
                } else {
                    log::error!("a2l_writer: TypeDef for {} not found", field_type_name.as_str());
                }
                field_typedef_names.push(None);
            } else {
                //
                // Field is a basic type

                // Generate TYPEDEF_MEASUREMENT, TYPEDEF_CHARACTERISTIC or TYPEDEF_AXIS for basic types in STRUCTURE_COMPONENT
                // TYPEDEF_MEASUREMENT, TYPEDEF_CHARACTERISTIC or TYPEDEF_AXIS share one name space, so the typedef is named after the field
                // as long as no other field with the same name but a different type or metadata has been written, otherwise the name is
                // qualified with the structure name (type_name.field_name).
                // TYPEDEF_MEASUREMENT, TYPEDEF_CHARACTERISTIC or TYPEDEF_AXIS do not support DISPLAY_IDENTIFIER, which would have been a solution
                let field_name = field.name.as_str();
                let field_dim_type = &field.dim_type;
                let mc_support_data = field.get_mc_support_data();
                let value_type = field_dim_type.value_type;

                // Content signature of the typedef: fields with the same name must not share a typedef if type or metadata differ
                let signature = format!("{field_dim_type:?} {mc_support_data:?}");
                let (typedef_name, exists) = writer.field_typedef_name(type_name, field_name, &signature);
                let ext_field_name = typedef_name.as_str();

                // Skip typedefs which have already been written (recursion, or same field name and content in another structure)
                if !exists {
                    let conversion_name = write_conversion(writer, ext_field_name, 0, field_dim_type, mc_support_data)?;
                    let unit = phys_unit(mc_support_data.get_unit());
                    // Field access, not get_object_type(), which panics on Unspecified
                    match mc_support_data.object_type {
                        McObjectType::Measurement => {
                            let type_str = value_type.get_type_str()?; // UWORD, SWORD, ULONG, SLONG, FLOAT32_IEEE, FLOAT64_IEEE, ...
                            let (min, max) = get_limits(ext_field_name, mc_support_data, value_type)?;
                            write!(
                                writer,
                                r#"/begin TYPEDEF_MEASUREMENT {ext_field_name} "{}" {type_str} {conversion_name} 0 0 {} {}"#, // 0 0 = resolution accuracy
                                mc_support_data.get_comment(),
                                min,
                                max
                            )?;
                            if !unit.is_empty() {
                                write!(writer, r#" PHYS_UNIT "{unit}""#)?;
                            }
                            write_dimensions(field_dim_type, writer)?;
                            writeln!(writer, r#" /end TYPEDEF_MEASUREMENT"#,)?;
                        }
                        McObjectType::Characteristic => {
                            let type_str = field_dim_type.value_type.get_record_layout_str()?;
                            let sub_type_str = get_characteristic_subtype_str(field_dim_type, field.get_mc_support_data())?;
                            let (min, max) = get_limits(ext_field_name, mc_support_data, value_type)?;
                            write!(
                                writer,
                                r#"/begin TYPEDEF_CHARACTERISTIC {ext_field_name} "{}" {sub_type_str} {type_str} 0 {conversion_name} {} {}"#,
                                mc_support_data.get_comment(),
                                min,
                                max
                            )?;
                            if !unit.is_empty() {
                                write!(writer, r#" PHYS_UNIT "{unit}""#)?;
                            }
                            // VAL_BLK (no x_axis and no y_axis)
                            if sub_type_str == "VAL_BLK" {
                                write_dimensions(field_dim_type, writer)?;
                            }
                            // else if it is MAP or CURVE type
                            else if sub_type_str == "MAP" || sub_type_str == "CURVE" {
                                write_axis_descr(ext_field_name, field_dim_type, mc_support_data, writer)?;
                            }
                            writeln!(writer, r#" /end TYPEDEF_CHARACTERISTIC"#,)?;
                        }
                        McObjectType::Axis => {
                            let type_str = value_type.get_record_layout_str()?; // + A_ prefix for AXIS_PTR record layouts
                            let (min, max) = get_limits(ext_field_name, mc_support_data, value_type)?;
                            write!(
                                writer,
                                r#"/begin TYPEDEF_AXIS {ext_field_name} "{}" NO_INPUT_QUANTITY A_{type_str} 0 {conversion_name} {} {} {}"#,
                                mc_support_data.get_comment(),
                                field_dim_type.get_dim()[0],
                                min,
                                max
                            )?;
                            if !unit.is_empty() {
                                write!(writer, r#" PHYS_UNIT "{unit}""#)?;
                            }
                            writeln!(writer, r#" /end TYPEDEF_AXIS"#,)?;
                        }
                        McObjectType::Unspecified => {
                            // A2L needs objects type specified in typedef field leafs
                            return Err(a2l_error(format!(
                                "typedef {type_name} field {field_name}: unspecified object type can not be represented in A2L"
                            )));
                        }
                    }
                }
                field_typedef_names.push(Some(typedef_name));
            }
        }

        // Skip duplicate TYPEDEF_STRUCTURE during recursion
        if !writer.check_duplicate(type_name) {
            // Generate structure definition which fields referencing the above field typedefs TYPEDEF_MEASUREMENT, TYPEDEF_CHARACTERISTIC or other TYPEDEF_STRUCTURE
            writeln!(writer, r#"/begin TYPEDEF_STRUCTURE {type_name} "" {type_length}"#)?;
            for (field, field_typedef_name) in self.fields.iter().zip(&field_typedef_names) {
                let field_dim_type = &field.dim_type;
                // Type of the field is another struct (then its a TYPEDEF)
                if let McValueType::TypeDef(type_name) = &field_dim_type.value_type {
                    write!(writer, "\t/begin STRUCTURE_COMPONENT {} {type_name} {}", field.name.as_str(), field.offset)?;
                }
                // Type of the field is basic (then its a TYPEDEF_CHARACTERISTIC, TYPEDEF_MEASUREMENT, TYPEDEF_AXIS), named as determined above
                else {
                    let field_typedef_name = field_typedef_name.as_deref().unwrap_or(field.name.as_str());
                    write!(writer, "\t/begin STRUCTURE_COMPONENT {} {field_typedef_name} {}", field.name.as_str(), field.offset)?;
                }

                // Write dimensions if the field is a typedef, otherwise the TYPEDEF_MEASUREMENT, TYPEDEF_CHARACTERISTIC or TYPEDEF_AXIS has the dimensions
                if field_dim_type.is_typedef() {
                    write_dimensions(field_dim_type, writer)?;
                }
                writeln!(writer, " /end STRUCTURE_COMPONENT")?;
            }
            writeln!(writer, r#"/end TYPEDEF_STRUCTURE"#)?;
        }
        Ok(())
    }
}

impl GenerateA2l for McTypeDef {
    fn write_a2l(&self, writer: &mut A2lWriter) -> std::io::Result<()> {
        self.write_typedef(writer, 0)
    }
}

//-------------------------------------------------------------------------------------------------
// Generate MEASUREMENT or INSTANCE
// Depending on RegistryMeasurement type

impl McInstance {
    fn write_measurement(&self, writer: &mut A2lWriter) -> std::io::Result<()> {
        let name = &self.name;

        // Addressing
        let event_id = self.address.get_event_id();
        let (ext, addr) = self.address.get_a2l_addr(writer.registry);

        // McSupportData
        let mc_support_data = self.get_mc_support_data();
        let dim_type = &self.dim_type;
        let unit = phys_unit(mc_support_data.get_unit());
        let comment = mc_support_data.get_comment();

        log::debug!("A2L writer: measurement {} {:?} {}:0x{:08X} event={:?}", name, dim_type.value_type, ext, addr, event_id);

        //
        // BLOB used for dynamic objects
        // With CANape specific IDL annotation
        if let McValueType::Blob(annotation) = &self.dim_type.value_type {
            let buffer_size = dim_type.get_dim()[0];
            if !(dim_type.get_dim()[0] > 0 && dim_type.get_dim()[1] == 1) {
                return Err(a2l_error(format!("blob {name}: must have x_dim > 0 and y_dim == 1")));
            }

            // As BLOB string (new representation)
            write!(writer, r#"/begin BLOB {name} "{comment}" 0x{addr:X} {buffer_size} ECU_ADDRESS_EXTENSION {ext} "#)?;
            let annotation_str = annotation.as_str();
            write!(
                writer,
                r#"
{annotation_str}
/begin ANNOTATION ANNOTATION_LABEL "IsVlsd" ANNOTATION_ORIGIN "" /begin ANNOTATION_TEXT  "true" /end ANNOTATION_TEXT /end ANNOTATION
/begin ANNOTATION ANNOTATION_LABEL "MaxBufferNeeded" ANNOTATION_ORIGIN "" /begin ANNOTATION_TEXT "{buffer_size}" /end ANNOTATION_TEXT /end ANNOTATION
 "#
            )?;
            if let Some(id) = event_id {
                write_ifdata_event(id, false, writer)?; // Fixed event
            }
            writeln!(writer, r#" /end BLOB"#)?;
        }
        //
        // INSTANCE used for measurement structures
        else if let McValueType::TypeDef(type_name) = &self.dim_type.value_type {
            let instance_name = self.get_unique_name(writer.registry);
            write!(writer, r#"/begin INSTANCE {instance_name} "{comment}" {type_name} 0x{addr:X} ECU_ADDRESS_EXTENSION {ext}"#)?;
            write_dimensions(dim_type, writer)?;
            if let Some(id) = event_id {
                // Instances in absolute addressing mode allow the tool, in the user's responsibility, to choose a different event
                write_ifdata_event(id, self.address.is_absolute(), writer)?;
            }
            writeln!(writer, r#" /end INSTANCE"#)?;
        }
        //
        // MEASUREMENT used for basic types
        else {
            let instance_name = self.get_unique_name(writer.registry);
            let instance_index = self.get_index(writer.registry);
            let mc_support_data = self.get_mc_support_data();
            let (min, max) = get_limits(name.as_str(), mc_support_data, dim_type.value_type)?;
            let step = mc_support_data.get_step();
            let type_str = self.dim_type.value_type.get_type_str()?; // UWORD, SWORD, ULONG, SLONG, FLOAT32_IEEE, FLOAT64_IEEE, ...
            let conversion_name = write_conversion(writer, self.name.as_str(), instance_index, dim_type, mc_support_data)?;
            let x_fix_axis = dim_type.get_dim()[0] > 1 && mc_support_data.get_x_axis_conv().is_some();
            let y_fix_axis = dim_type.get_dim()[1] > 1 && mc_support_data.get_y_axis_conv().is_some();
            // MEASUREMENT with multiple dimensions and fix axis is not supported !!!
            // In this special case, write a READ_ONLY CHARACTERISTIC MAP or CURVE, with fixed axis and an event
            if x_fix_axis || y_fix_axis {
                log::debug!("A2L writer: MEASUREMENT {} has multiple dimensions with fix axis", instance_name);
                let record_layout = dim_type.value_type.get_record_layout_str()?;
                let sub_type_str = if x_fix_axis && y_fix_axis { "MAP" } else { "CURVE" };
                write!(
                    writer,
                    r#"/begin CHARACTERISTIC {} "{}" {} 0x{:X} {} 0 {} {} {} READ_ONLY"#,
                    instance_name, comment, sub_type_str, addr, record_layout, conversion_name, min, max
                )?;
                if !unit.is_empty() {
                    write!(writer, r#" PHYS_UNIT "{}""#, unit)?;
                }
                if let Some(step) = step {
                    write!(writer, r#" STEP_SIZE {}"#, step)?;
                }
                write_axis_descr(name, dim_type, mc_support_data, writer)?;
                if ext != 0 {
                    write!(writer, " ECU_ADDRESS_EXTENSION {}", ext)?;
                }
                if let Some(id) = event_id {
                    write_ifdata_event(id, false, writer)?;
                }
                writeln!(writer, " /end CHARACTERISTIC")?;
            } else {
                if dim_type.get_dim()[0] > 1 && mc_support_data.get_x_axis_ref().is_some() {
                    log::warn!("A2L writer: MEASUREMENT {} has multiple dimensions", instance_name);
                }
                write!(
                    writer,
                    r#"/begin MEASUREMENT {instance_name} "{comment}" {type_str} {conversion_name} 0 0 {min} {max} ECU_ADDRESS 0x{addr:X}"#
                )?;
                if ext != 0 {
                    write!(writer, " ECU_ADDRESS_EXTENSION {ext}")?;
                }
                // Dynamic or absolute addressing mode makes it possible to write a measurement object
                if self.mc_support_data.qualifier == McObjectQualifier::ReadWrite && (self.address.is_event_relative() || self.address.is_absolute()) {
                    write!(writer, " READ_WRITE")?;
                }
                if !unit.is_empty() {
                    write!(writer, r#" PHYS_UNIT "{unit}""#)?;
                }
                if let Some(step) = step {
                    write!(writer, r#" STEP_SIZE {}"#, step)?;
                }
                write_dimensions(dim_type, writer)?;
                if let Some(id) = event_id {
                    // Measurements in absolute addressing mode allow the tool, in the user's responsibility, to choose a different event
                    write_ifdata_event(id, self.address.is_absolute(), writer)?;
                }
                writeln!(writer, r#" /end MEASUREMENT"#)?;
            }
        }

        Ok(())
    }
}

//-------------------------------------------------------------------------------------------------
// CHARACTERISTIC and AXIS_PTS
impl McInstance {
    fn write_axis(&self, writer: &mut A2lWriter) -> std::io::Result<()> {
        let name = &self.name;

        // Addressing
        let (ext, addr) = self.address.get_a2l_addr(writer.registry);

        // McSupportData
        let mc_support_data = self.get_mc_support_data();
        let dim_type = &self.dim_type;
        let unit = phys_unit(mc_support_data.get_unit());
        let comment = mc_support_data.get_comment();
        let record_layout = dim_type.value_type.get_record_layout_str()?;
        let (min, max) = get_limits(name.as_str(), mc_support_data, dim_type.value_type)?;
        let step = mc_support_data.get_step();
        let conversion_name = write_conversion(writer, name.as_str(), 0, dim_type, mc_support_data)?;
        write!(
            writer,
            r#"/begin AXIS_PTS {} "{}" 0x{:X} NO_INPUT_QUANTITY A_{} 0 {conversion_name} {}"#,
            name,
            comment,
            addr,
            record_layout,
            self.dim_type.get_dim()[0]
        )?;
        write!(writer, r#" {}"#, min)?;
        write!(writer, r#" {}"#, max)?;
        if let Some(step) = step {
            write!(writer, r#" STEP_SIZE {}"#, step)?;
        }
        if !unit.is_empty() {
            write!(writer, r#" PHYS_UNIT "{}""#, unit)?;
        }
        if ext != 0 {
            write!(writer, " ECU_ADDRESS_EXTENSION {}", ext)?;
        }
        writeln!(writer, " /end AXIS_PTS")?;
        Ok(())
    }

    fn write_characteristic(&self, writer: &mut A2lWriter) -> std::io::Result<()> {
        let name = &self.name;

        // Addressing
        let (ext, addr) = self.address.get_a2l_addr(writer.registry);

        // McSupportData
        let mc_support_data = self.get_mc_support_data();
        let dim_type = &self.dim_type;
        let unit = phys_unit(mc_support_data.get_unit());
        let comment = mc_support_data.get_comment();

        log::debug!("A2L writer: characteristic or instance {} {:?} {}:0x{:08X}", self.name, self.dim_type.value_type, ext, addr);

        // Special case when value type is instance: -> INSTANCE
        if let McValueType::TypeDef(type_name) = &self.dim_type.value_type {
            write!(writer, r#"/begin INSTANCE {} "{}" {type_name} 0x{:X}"#, name, comment, addr)?;
            write_dimensions(dim_type, writer)?;
            writeln!(writer, r#" /end INSTANCE"#)?;
        }
        // All other value types: -> CHARACTERISTIC
        else {
            let mc_support_data = self.get_mc_support_data();
            if !mc_support_data.is_calibration_object() {
                return Err(a2l_error(format!("{name}: not a calibration object")));
            }
            let (min, max) = get_limits(name.as_str(), mc_support_data, self.dim_type.value_type)?;
            let step = mc_support_data.get_step();
            let sub_type_str = get_characteristic_subtype_str(&self.dim_type, mc_support_data)?; // VAL_BLK, VALUE, MAP, CURVE
            let record_layout = self.dim_type.value_type.get_record_layout_str()?;

            // Bool: Use BOOL
            if self.dim_type.value_type == McValueType::Bool {
                write!(writer, r#"/begin CHARACTERISTIC {} "{}" VALUE 0x{:X} BOOL 0 BOOL 0 1"#, self.name, comment, addr)?;
            }
            // Other type: Use NO_COMPU_METHOD, not supported yet for CHARACTERISTIC
            else {
                let conversion_name = write_conversion(writer, name.as_str(), 0, dim_type, mc_support_data)?;
                write!(
                    writer,
                    r#"/begin CHARACTERISTIC {} "{}" {} 0x{:X} {} 0 {conversion_name} {} {}"#,
                    name, comment, sub_type_str, addr, record_layout, min, max
                )?;
            }

            // VAL_BLK (no x_axis and no y_axis)
            if sub_type_str == "VAL_BLK" {
                write_dimensions(dim_type, writer)?;
            }
            // else it is MAP or CURVE type
            else if sub_type_str == "MAP" || sub_type_str == "CURVE" {
                write_axis_descr(name, dim_type, mc_support_data, writer)?;
            }

            if !unit.is_empty() {
                write!(writer, r#" PHYS_UNIT "{}""#, unit)?;
            }

            if let Some(step) = step {
                write!(writer, r#" STEP_SIZE {}"#, step)?;
            }
            if ext != 0 {
                write!(writer, " ECU_ADDRESS_EXTENSION {}", ext)?;
            }

            // @@@@ TODO: Support the read only qualifier for CHARACTERISTIC self.mc_support_data.qualifier == "read_only"

            writeln!(writer, " /end CHARACTERISTIC")?;
        }
        Ok(())
    }
}

//-------------------------------------------------------------------------------------------------

pub struct A2lWriter<'a> {
    writer: &'a mut dyn Write,
    registry: &'a Registry,
    // Names of all TYPEDEF_* objects written so far, each with a signature of its content.
    // Used to skip duplicates during recursion and to detect field typedefs which share a name but differ in type or metadata.
    typedef_list: HashMap<String, String>,
}

impl Write for A2lWriter<'_> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.writer.write(buf)
    }
    fn flush(&mut self) -> std::io::Result<()> {
        self.writer.flush()
    }
}

impl<'a> A2lWriter<'a> {
    pub fn new(writer: &'a mut dyn Write, registry: &'a Registry) -> A2lWriter<'a> {
        A2lWriter {
            writer,
            registry,
            typedef_list: HashMap::new(),
        }
    }

    /// Check if a TYPEDEF_STRUCTURE with this name has already been written, register it otherwise
    fn check_duplicate(&mut self, ident: &str) -> bool {
        const STRUCTURE_SIGNATURE: &str = "TYPEDEF_STRUCTURE";
        if let Some(existing) = self.typedef_list.get(ident) {
            if existing != STRUCTURE_SIGNATURE {
                log::warn!("A2L writer: TYPEDEF_STRUCTURE {ident} has the same name as a field typedef, skipped");
            }
            return true;
        }
        self.typedef_list.insert(ident.to_string(), STRUCTURE_SIGNATURE.to_string());
        false
    }

    /// Get the name of the TYPEDEF_MEASUREMENT, TYPEDEF_CHARACTERISTIC or TYPEDEF_AXIS for a basic typed field of a TYPEDEF_STRUCTURE
    /// Returns the name to use and whether a typedef with this name and content has already been written.
    /// TYPEDEF_* names share one name space, but fields of different structures may have the same name with a different type or metadata.
    /// The plain field name is used as long as it is free or already used for a typedef with identical content,
    /// otherwise the name is qualified with the structure name (type_name.field_name)
    fn field_typedef_name(&mut self, type_name: &str, field_name: &str, signature: &str) -> (String, bool) {
        if let Some(existing) = self.typedef_list.get(field_name) {
            if existing == signature {
                return (field_name.to_string(), true);
            }
            let qualified = format!("{type_name}.{field_name}");
            if let Some(existing) = self.typedef_list.get(&qualified) {
                if existing != signature {
                    log::warn!("A2L writer: typedef {qualified} already exists with different content");
                }
                return (qualified, true);
            }
            log::debug!("A2L writer: field typedef {field_name} already exists with different content, using {qualified}");
            self.typedef_list.insert(qualified.clone(), signature.to_string());
            (qualified, false)
        } else {
            self.typedef_list.insert(field_name.to_string(), signature.to_string());
            (field_name.to_string(), false)
        }
    }

    fn write_a2l_head(&mut self, title_comment: &str, project_name: &str, project_description: &str, module_name: &str, project_no: &str) -> std::io::Result<()> {
        let a2ml = match self.registry.get_a2ml_mode() {
            McA2mlMode::Include => "/include \"XCP_104.aml\"",
            McA2mlMode::Embed => crate::XCP_104_AML.trim_end(),
            McA2mlMode::None => "",
        };
        writeln!(
            self,
            r#"
/* {title_comment} */
ASAP2_VERSION 1 71
/begin PROJECT {project_name} "{project_description}"
/begin HEADER "" VERSION "1.0" PROJECT_NO {project_no} /end HEADER

/begin MODULE {module_name} ""
        
    {a2ml}
    
    /begin MOD_COMMON ""
    BYTE_ORDER MSB_LAST
    ALIGNMENT_BYTE 1
    ALIGNMENT_WORD 1
    ALIGNMENT_LONG 1
    ALIGNMENT_FLOAT16_IEEE 1
    ALIGNMENT_FLOAT32_IEEE 1
    ALIGNMENT_FLOAT64_IEEE 1
    ALIGNMENT_INT64 1
    /end MOD_COMMON
    
    /* Predefined conversion rule for bool */
    /begin COMPU_METHOD BOOL ""
        TAB_VERB "%.0" "" COMPU_TAB_REF BOOL.table
    /end COMPU_METHOD
    /begin COMPU_VTAB BOOL.table "" TAB_VERB 2
        0 "false" 1 "true"
    /end COMPU_VTAB

    /* Predefined conversion rule identity with no phys unit and zero decimal places */
    /begin COMPU_METHOD IDENTITY ""
        IDENTICAL "%.0" "" 
    /end COMPU_METHOD

    /* Predefined characteristic record layouts for standard types */
    /begin RECORD_LAYOUT BOOL FNC_VALUES 1 UBYTE ROW_DIR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT U8 FNC_VALUES 1 UBYTE ROW_DIR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT U16 FNC_VALUES 1 UWORD ROW_DIR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT U32 FNC_VALUES 1 ULONG ROW_DIR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT U64 FNC_VALUES 1 A_UINT64 ROW_DIR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT I8 FNC_VALUES 1 SBYTE ROW_DIR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT I16 FNC_VALUES 1 SWORD ROW_DIR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT I32 FNC_VALUES 1 SLONG ROW_DIR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT I64 FNC_VALUES 1 A_INT64 ROW_DIR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT F32 FNC_VALUES 1 FLOAT32_IEEE ROW_DIR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT F64 FNC_VALUES 1 FLOAT64_IEEE ROW_DIR DIRECT /end RECORD_LAYOUT

    /* Predefined axis record layouts for standard types */
    /begin RECORD_LAYOUT A_U8 AXIS_PTS_X 1 UBYTE INDEX_INCR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT A_U16 AXIS_PTS_X 1 UWORD INDEX_INCR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT A_U32 AXIS_PTS_X 1 ULONG INDEX_INCR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT A_U64 AXIS_PTS_X 1 A_UINT64 INDEX_INCR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT A_I8 AXIS_PTS_X 1 SBYTE INDEX_INCR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT A_I16 AXIS_PTS_X 1 SWORD INDEX_INCR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT A_I32 AXIS_PTS_X 1 SLONG INDEX_INCR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT A_I64 AXIS_PTS_X 1 A_INT64 INDEX_INCR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT A_F32 AXIS_PTS_X 1 FLOAT32_IEEE INDEX_INCR DIRECT /end RECORD_LAYOUT
    /begin RECORD_LAYOUT A_F64 AXIS_PTS_X 1 FLOAT64_IEEE INDEX_INCR DIRECT /end RECORD_LAYOUT

    /* Predefined measurement and characteristic typedefs for standard types */
    /begin TYPEDEF_MEASUREMENT M_BOOL "" UBYTE BOOL 0 0 0 1 /end TYPEDEF_MEASUREMENT
    /begin TYPEDEF_MEASUREMENT M_U8 "" UBYTE NO_COMPU_METHOD 0 0 0 255 /end TYPEDEF_MEASUREMENT
    /begin TYPEDEF_MEASUREMENT M_U16 "" UWORD NO_COMPU_METHOD 0 0 0 65535 /end TYPEDEF_MEASUREMENT
    /begin TYPEDEF_MEASUREMENT M_U32 "" ULONG NO_COMPU_METHOD 0 0 0 4294967295 /end TYPEDEF_MEASUREMENT
    /begin TYPEDEF_MEASUREMENT M_U64 "" A_UINT64 NO_COMPU_METHOD 0 0 0 1e12 /end TYPEDEF_MEASUREMENT
    /begin TYPEDEF_MEASUREMENT M_I8 "" SBYTE NO_COMPU_METHOD 0 0 -128 127 /end TYPEDEF_MEASUREMENT
    /begin TYPEDEF_MEASUREMENT M_I16 "" SWORD NO_COMPU_METHOD 0 0 -32768 32767 /end TYPEDEF_MEASUREMENT
    /begin TYPEDEF_MEASUREMENT M_I32 "" SLONG NO_COMPU_METHOD 0 0 -2147483648 2147483647 /end TYPEDEF_MEASUREMENT
    /begin TYPEDEF_MEASUREMENT M_I64 "" A_INT64 NO_COMPU_METHOD 0 0 -1e12 1e12 /end TYPEDEF_MEASUREMENT
    /begin TYPEDEF_MEASUREMENT M_F32 "" FLOAT32_IEEE NO_COMPU_METHOD 0 0 -1e12 1e12 /end TYPEDEF_MEASUREMENT
    /begin TYPEDEF_MEASUREMENT M_F64 "" FLOAT64_IEEE NO_COMPU_METHOD 0 0 -1e12 1e12 /end TYPEDEF_MEASUREMENT
    /begin TYPEDEF_CHARACTERISTIC C_BOOL "" VALUE U8 0 BOOL 0 1 /end TYPEDEF_CHARACTERISTIC
    /begin TYPEDEF_CHARACTERISTIC C_U8 "" VALUE U8 0 NO_COMPU_METHOD 0 255 /end TYPEDEF_CHARACTERISTIC
    /begin TYPEDEF_CHARACTERISTIC C_U16 "" VALUE U16 0 NO_COMPU_METHOD 0 65535 /end TYPEDEF_CHARACTERISTIC
    /begin TYPEDEF_CHARACTERISTIC C_U32 "" VALUE U32 0 NO_COMPU_METHOD 0 4294967295 /end TYPEDEF_CHARACTERISTIC
    /begin TYPEDEF_CHARACTERISTIC C_U64 "" VALUE U64 0 NO_COMPU_METHOD 0 1e12 /end TYPEDEF_CHARACTERISTIC
    /begin TYPEDEF_CHARACTERISTIC C_I8 "" VALUE I8 0 NO_COMPU_METHOD -128 127 /end TYPEDEF_CHARACTERISTIC
    /begin TYPEDEF_CHARACTERISTIC C_I16 "" VALUE I16 0 NO_COMPU_METHOD -32768 32767 /end TYPEDEF_CHARACTERISTIC
    /begin TYPEDEF_CHARACTERISTIC C_I32 "" VALUE I32 0 NO_COMPU_METHOD -2147483648 2147483647 /end TYPEDEF_CHARACTERISTIC
    /begin TYPEDEF_CHARACTERISTIC C_I64 "" VALUE I64 0 NO_COMPU_METHOD -1e12 1e12 /end TYPEDEF_CHARACTERISTIC
    /begin TYPEDEF_CHARACTERISTIC C_F64 "" VALUE F64 0 NO_COMPU_METHOD -1e12 1e12 /end TYPEDEF_CHARACTERISTIC
    /begin TYPEDEF_CHARACTERISTIC C_F32 "" VALUE F32 0 NO_COMPU_METHOD -1e12 1e12 /end TYPEDEF_CHARACTERISTIC
    "#,
        )
    }

    // MOD_PAR
    fn write_a2l_modpar(&mut self) -> std::io::Result<()> {
        writeln!(self, "/begin MOD_PAR \"\" ")?;

        // EPK
        {
            let application = &self.registry.application;
            application.write_a2l(self)?;
        }

        // Calibration segments
        for s in &self.registry.cal_seg_list {
            if s.number.is_some() {
                // Skip calibration block (number is None)
                s.write_a2l(self)?;
            }
        }
        writeln!(self, "/end MOD_PAR\n")
    }

    // IF_DATA XCP
    // IF_DATA XCP with protocol layer, DAQ events and, if set, the transport layer
    // Without protocol layer parameters (set_xcp_eth_params, set_xcp_sxi_params), the XCPlite defaults for XCP on Ethernet are used
    fn write_a2l_if_data(&mut self) -> std::io::Result<()> {
        let max_cto: u8 = self.registry.xcp_params.map_or(248, |p| p.max_cto);
        let max_dto: u16 = self.registry.xcp_params.map_or(1024, |p| p.max_dto);

        write!(
            self,
            r#"/begin IF_DATA XCP
        /begin PROTOCOL_LAYER
        0x0104 1000 2000 0 0 0 0 0 {max_cto} {max_dto} BYTE_ORDER_MSB_LAST ADDRESS_GRANULARITY_BYTE
        OPTIONAL_CMD GET_COMM_MODE_INFO
        OPTIONAL_CMD GET_ID
        OPTIONAL_CMD SET_REQUEST
        OPTIONAL_CMD SET_MTA
        OPTIONAL_CMD UPLOAD
        OPTIONAL_CMD SHORT_UPLOAD
        OPTIONAL_CMD DOWNLOAD
        OPTIONAL_CMD SHORT_DOWNLOAD
        OPTIONAL_CMD GET_CAL_PAGE
        OPTIONAL_CMD SET_CAL_PAGE
        OPTIONAL_CMD COPY_CAL_PAGE
        OPTIONAL_CMD BUILD_CHECKSUM
        OPTIONAL_CMD GET_DAQ_RESOLUTION_INFO
        OPTIONAL_CMD GET_DAQ_PROCESSOR_INFO
        OPTIONAL_CMD FREE_DAQ
        OPTIONAL_CMD ALLOC_DAQ
        OPTIONAL_CMD ALLOC_ODT
        OPTIONAL_CMD ALLOC_ODT_ENTRY
        OPTIONAL_CMD SET_DAQ_PTR
        OPTIONAL_CMD WRITE_DAQ
        OPTIONAL_CMD GET_DAQ_LIST_MODE
        OPTIONAL_CMD SET_DAQ_LIST_MODE
        OPTIONAL_CMD START_STOP_SYNCH
        OPTIONAL_CMD START_STOP_DAQ_LIST
        OPTIONAL_CMD GET_DAQ_CLOCK
        OPTIONAL_CMD WRITE_DAQ_MULTIPLE
        OPTIONAL_CMD TIME_CORRELATION_PROPERTIES
        OPTIONAL_CMD USER_CMD
        OPTIONAL_LEVEL1_CMD GET_VERSION
        /end PROTOCOL_LAYER"#
        )?;

        let event_count = self.registry.event_list.len();
        writeln!(
            self,
            "\n\n\t\t/begin DAQ
            DYNAMIC 0 {event_count} 0 OPTIMISATION_TYPE_DEFAULT ADDRESS_EXTENSION_FREE IDENTIFICATION_FIELD_TYPE_RELATIVE_BYTE GRANULARITY_ODT_ENTRY_SIZE_DAQ_BYTE 0xF8 OVERLOAD_INDICATION_PID
            /begin TIMESTAMP_SUPPORTED
                0x1 SIZE_DWORD UNIT_1US TIMESTAMP_FIXED
            /end TIMESTAMP_SUPPORTED
            "
        )?;

        // Eventlist
        for e in &self.registry.event_list {
            e.write_a2l(self)?;
        }

        write!(self, "\n\t\t/end DAQ\n")?;

        // Transport layer parameters in IF_DATA
        if let Some(xcp_tl_params) = self.registry.xcp_tl_params {
            xcp_tl_params.write_a2l(self)?;
        }

        write!(self, "\n/end IF_DATA\n\n")?;
        Ok(())
    }

    fn write_a2l_typedefs(&mut self) -> std::io::Result<()> {
        writeln!(self, "\n/* TypeDefs */")?;

        for m in &self.registry.typedef_list {
            m.write_a2l(self)?;
        }
        writeln!(self)?;
        Ok(())
    }

    fn write_a2l_measurements(&mut self) -> std::io::Result<()> {
        writeln!(self, "\n/* Measurements */")?;

        // Measurable objects with event_id
        for e in &self.registry.event_list {
            writeln!(self, "\n/* Measurements for event '{}' */", e.name)?;
            for m in self.registry.instance_list.into_iter() {
                // If with event or explicitly a measurement object
                if m.is_measurement_object() && m.address.get_event_id() == Some(e.id) {
                    m.write_measurement(self)?;
                }
            }
        }

        // Measurable objects without event_id
        writeln!(self, "\n/* Measurements without fixed event */")?;
        for m in self.registry.instance_list.into_iter() {
            // If without event and not explicitly a measurement object
            if m.is_measurement_object() && m.address.get_event_id().is_none() {
                m.write_measurement(self)?;
            }
        }

        // GROUP
        // Group root measurement
        write!(self, "\n/begin GROUP Measurements \"\" ROOT /begin SUB_GROUP")?;
        for e in &self.registry.event_list {
            // Ignore all but the first event instance
            if e.index > 1 {
                continue;
            }
            write!(self, " {}", e.name)?;
        }
        writeln!(self, " /end SUB_GROUP /end GROUP")?;

        // Sub group for each event with event name as group name
        for event in &self.registry.event_list {
            // Ignore all but the first event instance, and compare events by name
            if event.index > 1 {
                continue;
            }
            let event_name = &event.name;
            write!(self, "/begin GROUP {} \"\" /begin REF_MEASUREMENT", event_name)?;
            for instance in self.registry.instance_list.into_iter().filter(|i| i.is_measurement_object()) {
                if let Some(instance_event_id) = instance.address.get_event_id() {
                    if let Some(instance_event) = self.registry.event_list.find_event_id(instance_event_id) {
                        if *event_name == instance_event.name {
                            let name = instance.get_unique_name(self.registry);
                            write!(self, " {name}")?;
                        }
                    }
                }
            }
            writeln!(self, " /end REF_MEASUREMENT /end GROUP")?;
        }

        Ok(())
    }

    fn write_a2l_characteristics(&mut self) -> std::io::Result<()> {
        // Write all Axis
        writeln!(self, "\n/* Axis */")?;
        for a in self.registry.instance_list.into_iter() {
            // If axis
            if a.is_axis() {
                if !a.address.is_segment_relative() || a.is_measurement_object() {
                    return Err(a2l_error(format!("axis {}: must be a calibration object in a calibration segment", a.name)));
                }
                a.write_axis(self)?;
            }
        }

        // Write all Characteristics
        writeln!(self, "\n/* Characteristics */")?;
        for c in self.registry.instance_list.into_iter() {
            // If not an axis, to be sure to catch all instances and assert on inconsistencies
            if !c.is_axis() {
                // This is the inverse condition of the one in write_a2l_measurements
                if !(c.is_measurement_object() || c.address.get_event_id().is_some()) {
                    c.write_characteristic(self)?;
                }
            }
        }

        Ok(())
    }

    fn write_a2l_groups(&mut self) -> std::io::Result<()> {
        // Write ROOT GROUP "Characteristics" with subgroups for all calibration segments
        writeln!(self, "\n/* Characteristic and Axis Groups */")?;
        if self.registry.cal_seg_list.len() > 0 {
            write!(self, "/begin GROUP Characteristics \"\" ROOT /begin SUB_GROUP")?;
            for s in &self.registry.cal_seg_list {
                if s.name == crate::EPK_SEG_NAME {
                    continue;
                }
                write!(self, " {}", s.name)?;
            }
            writeln!(self, " /end SUB_GROUP /end GROUP")?;
        }

        // Write GROUPs for each calibration segment
        for s in &self.registry.cal_seg_list {
            let mut n = 0;
            for c in self.registry.instance_list.into_iter() {
                if c.is_calibration_object() {
                    // Check if the calibration object (characteristics or axis) belongs to the calibration segment by comparing the a2l address of the characteristic with the address range of the calibration segment
                    // @@@@ TODO: Improve this hack
                    let a2l_addr = c.address.get_a2l_addr(self.registry);
                    if a2l_addr.0 == 0u8 && a2l_addr.1 >= s.addr && a2l_addr.1 < s.addr + s.size {
                        n += 1;
                        if n == 1 {
                            write!(self, "/begin GROUP {} \"\" /begin REF_CHARACTERISTIC ", s.name)?;
                        }
                        write!(self, " {} ", c.name)?;
                    }
                }
            }
            if n > 0 {
                writeln!(self, "/end REF_CHARACTERISTIC /end GROUP")?;
            }
        }

        Ok(())
    }

    fn write_a2l_tail(&mut self) -> std::io::Result<()> {
        self.write_all("\n/end MODULE\n/end PROJECT\n".as_bytes())
    }

    pub fn write_a2l(&mut self, title_comment: &str, project_name: &str, project_description: &str, module_name: &str, project_no: &str) -> Result<(), std::io::Error> {
        if project_name.is_empty() || module_name.is_empty() || project_no.is_empty() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "A2L writer: project name, module name and project number must not be empty",
            ));
        }
        self.write_a2l_head(title_comment, project_name, project_description, module_name, project_no)?;
        self.write_a2l_modpar()?;
        self.write_a2l_if_data()?; // Always, the transport layer block only if set
        self.write_a2l_typedefs()?;
        self.write_a2l_measurements()?;
        self.write_a2l_characteristics()?;
        self.write_a2l_groups()?;
        self.write_a2l_tail()?;
        Ok(())
    }
}

//-------------------------------------------------------------------------------------------------
// Tests

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

    // Write only the typedef section of a registry into a string
    fn write_typedefs(reg: &Registry) -> String {
        let mut buf: Vec<u8> = Vec::new();
        {
            let writer: &mut dyn Write = &mut buf;
            let mut a2l_writer = A2lWriter::new(writer, reg);
            a2l_writer.write_a2l_typedefs().unwrap();
        }
        String::from_utf8(buf).unwrap()
    }

    fn add_field(reg: &mut Registry, type_name: &'static str, value_type: McValueType, mc_support_data: McSupportData) {
        reg.add_typedef(type_name, 4).unwrap();
        reg.add_typedef_field(type_name, "value", McDimType::new(value_type, 1, 1), mc_support_data, 0).unwrap();
    }

    // Fields with the same name in different structures share a typedef only if type and metadata are identical,
    // otherwise the typedef name is qualified with the structure name
    #[test]
    fn test_field_typedef_name_collision() {
        let mut reg = Registry::new();
        add_field(&mut reg, "A", McValueType::Uword, McSupportData::new(McObjectType::Measurement));
        add_field(&mut reg, "B", McValueType::Float32Ieee, McSupportData::new(McObjectType::Measurement));
        add_field(&mut reg, "C", McValueType::Uword, McSupportData::new(McObjectType::Measurement));
        add_field(&mut reg, "D", McValueType::Uword, McSupportData::new(McObjectType::Measurement).set_unit("V"));
        add_field(&mut reg, "E", McValueType::Uword, McSupportData::new(McObjectType::Characteristic));
        let a2l = write_typedefs(&reg);
        println!("{a2l}");

        // A and C share one UWORD typedef named after the field
        assert_eq!(
            a2l.matches(r#"/begin TYPEDEF_MEASUREMENT value "" UWORD IDENTITY 0 0 0 65535 /end TYPEDEF_MEASUREMENT"#)
                .count(),
            1
        );
        assert_eq!(a2l.matches("/begin STRUCTURE_COMPONENT value value 0 /end STRUCTURE_COMPONENT").count(), 2);
        // B has a different type, D a different unit, E a different object type: qualified names
        assert!(a2l.contains(r#"/begin TYPEDEF_MEASUREMENT B.value "" FLOAT32_IEEE NO_COMPU_METHOD"#));
        assert!(a2l.contains("/begin STRUCTURE_COMPONENT value B.value 0 /end STRUCTURE_COMPONENT"));
        assert!(a2l.contains(r#"/begin TYPEDEF_MEASUREMENT D.value "" UWORD IDENTITY 0 0 0 65535 PHYS_UNIT "V" /end TYPEDEF_MEASUREMENT"#));
        assert!(a2l.contains("/begin STRUCTURE_COMPONENT value D.value 0 /end STRUCTURE_COMPONENT"));
        assert!(a2l.contains(r#"/begin TYPEDEF_CHARACTERISTIC E.value "" VALUE U16 0 IDENTITY 0 65535 /end TYPEDEF_CHARACTERISTIC"#));
        assert!(a2l.contains("/begin STRUCTURE_COMPONENT value E.value 0 /end STRUCTURE_COMPONENT"));
        // every typedef name is defined exactly once
        for name in ["value", "B.value", "D.value", "E.value"] {
            assert_eq!(
                a2l.matches(&format!("/begin TYPEDEF_MEASUREMENT {name} ")).count() + a2l.matches(&format!("/begin TYPEDEF_CHARACTERISTIC {name} ")).count(),
                1,
                "{name}"
            );
        }
    }

    // The same typedef referenced several times (nested and by several instances) is written once and keeps plain field names
    #[test]
    fn test_nested_typedef_written_once() {
        let mut reg = Registry::new();
        add_field(&mut reg, "Inner", McValueType::Ulong, McSupportData::new(McObjectType::Measurement));
        reg.add_typedef("Outer", 8).unwrap();
        reg.add_typedef_field(
            "Outer",
            "first",
            McDimType::new(McValueType::new_typedef("Inner"), 1, 1),
            McSupportData::new(McObjectType::Measurement),
            0,
        )
        .unwrap();
        reg.add_typedef_field(
            "Outer",
            "second",
            McDimType::new(McValueType::new_typedef("Inner"), 1, 1),
            McSupportData::new(McObjectType::Measurement),
            4,
        )
        .unwrap();
        let a2l = write_typedefs(&reg);
        println!("{a2l}");

        assert_eq!(a2l.matches("/begin TYPEDEF_STRUCTURE Inner ").count(), 1);
        assert_eq!(a2l.matches(r#"/begin TYPEDEF_MEASUREMENT value "" ULONG"#).count(), 1);
        assert!(a2l.contains("/begin STRUCTURE_COMPONENT first Inner 0 /end STRUCTURE_COMPONENT"));
        assert!(a2l.contains("/begin STRUCTURE_COMPONENT second Inner 4 /end STRUCTURE_COMPONENT"));
    }
}