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
/*
 * Copyright (c) 2018-2021 Thomas Kramer.
 *
 * This file is part of LibrEDA 
 * (see https://codeberg.org/libreda/libreda-oasis).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
//! Defines functions to parse an OASIS data stream and populate a `Layout`.
//!
//! OASIS BNF Syntax:
//!
//! <oasis-file>: <magic-bytes> START { CBLOCK | PAD | PROPERTY | <cell> | <name> }* END
//! <name>: { CELLNAME | TEXTSTRING | LAYERNAME | PROPNAME | PROPSTRING | XNAME }
//! <cell>: { CELL { CBLOCK | PAD | PROPERTY | XYRELATIVE | XYABSOLUTE | <element> }* }
//! <element>: { <geometry> | PLACEMENT | TEXT | XELEMENT }
//! <geometry>: { RECTANGLE | POLYGON | PATH | TRAPEZOID | CTRAPEZOID | CIRCLE | XGEOMETRY }
//!

use num_traits::Zero;

use libreda_db as db;
use db::layout::prelude::*;
use db::prelude::WithProperties;

use std::io::Read;
use byteorder::{ReadBytesExt, LittleEndian};
use std::collections::{HashMap, HashSet};

use crate::base_types::*;
use crate::base_types::RegularRepetition;
use crate::base_types::Repetition;
use crate::{Modal, XYMode, NameOrRef};
use std::rc::Rc;

/// Collection of mutable state variables used in the OASIS reader/writer.
#[derive(Default, Debug)]
struct MutableState {
    m_expect_strict_mode: bool,
    m_table_cell_name: Option<UInt>,
    /// Mapping from cell IDs to cell names.
    m_cell_names: HashMap<UInt, String>,
    /// Remember the reference numbers of cell names that have been used as a forward reference
    /// where the name string was not known yet. The corresponding cell needs to be updated
    /// with the name once the cell name string is found.
    m_cell_names_forward_references: HashMap<UInt, CellIndex>,
    /// Unresolved property name forward references.
    /// Mapping from property name reference to property parents with value list.
    m_property_name_forward_references: HashMap<UInt, Vec<(PropertyParent, Vec<PropertyValue>)>>,
    /// Mapping from property IDs to property names.
    m_propnames: HashMap<UInt, String>,
    /// Mapping from property string IDs to property strings.
    m_propstrings: HashMap<UInt, Vec<u8>>,
    /// Mapping from text string IDs to text strings.
    m_textstrings: HashMap<UInt, String>,
}

/// Reference to the record which is parent for properties.
/// By default this is the OASIS file. Then this gets updated once other records are encountered:
/// CELL, CELLNAME, <element>
///
#[derive(Debug, Clone)]
enum PropertyParent {
    None,
    Cell(Rc<Cell<SInt>>),
    CellName(String),
    Geometry(Vec<Rc<Shape<SInt>>>),
    Placement(Vec<Rc<CellInstance<SInt>>>),
    //(Rc<CellInstance<SInt>>),
    // Text,
    XElement,
    XGeometry,
}


/// TODO
fn read_offset_table<R: Read>(reader: &mut R) -> Result<(), OASISReadError> {
    // For now this data is ignored.
    let _cellname_flag = read_unsigned_integer(reader)?;
    let _cellname_offset = read_unsigned_integer(reader)?;
    let _textstring_flag = read_unsigned_integer(reader)?;
    let _textstring_offset = read_unsigned_integer(reader)?;
    let _propname_flag = read_unsigned_integer(reader)?;
    let _propname_offset = read_unsigned_integer(reader)?;
    let _propstring_flag = read_unsigned_integer(reader)?;
    let _propstring_offset = read_unsigned_integer(reader)?;
    let _layername_flag = read_unsigned_integer(reader)?;
    let _layername_offset = read_unsigned_integer(reader)?;
    let _xname_flag = read_unsigned_integer(reader)?;
    let _xname_offset = read_unsigned_integer(reader)?;

    Ok(())
}

/// TODO
fn _read_properties<R: Read>(_reader: &mut R) -> Result<(), OASISReadError> {
    unimplemented!()
}


/// Read a `Repetition` if it is present, otherwise take it from the modal variables.
fn read_repetition_conditional<R: Read>(reader: &mut R,
                                        is_present: bool,
                                        modal_value: &mut Option<Repetition>) -> Result<Repetition, OASISReadError> {


    // Construct positions from a repetition if there is any.
    if is_present {
        let repetition = read_repetition(reader)?;

        // Get previous repetition if necessary.
        let repetition = match repetition {
            Repetition::ReusePrevious => {
                modal_value.as_ref().cloned().ok_or(OASISReadError::ModalRepetitionNotDefined)?
            }
            _ => repetition
        };

        assert_ne!(&repetition, &Repetition::ReusePrevious, "`modal.repetition` should never be set to `ReusePrevious`.");

        *modal_value = Some(repetition.clone()); // Remember the last repetition.

        Ok(repetition)
    } else {
        // Return single-element repetition.
        Ok(Repetition::Regular(
            RegularRepetition::new(Vector::zero(), Vector::zero(), 1, 1)
        ))
    }
}

/// Convert a repetition into explicit displacements.
fn repetition_to_offsets(rep: &Repetition, first_position: Vector<SInt>) -> Vec<Vector<SInt>> {
    match &rep {
        Repetition::ReusePrevious => {
            panic!("`modal.repetition` should never be set to `ReusePrevious`.")
        }
        Repetition::Regular(r) => {
            r.iter().map(|offset| first_position + offset).collect()
        }
        Repetition::Irregular(r) => {
            r.iter().map(|offset| first_position + *offset).collect()
        }
    }
}

/// Read a x/y coordinate if it is explicitly defined, otherwise use the modal variable.
/// Relative coordinates are resolved to absolute coordinates.
/// The `modal_value` is used if the coordinate is not present.
/// The `modal_value` is updated to the current coordinate value.
fn read_coordinate_conditional<R: Read>(reader: &mut R,
                                        is_present: bool,
                                        xy_mode: XYMode,
                                        modal_value: &mut SInt) -> Result<SInt, OASISReadError> {
    let c = if is_present {
        let c = read_signed_integer(reader)?;
        match xy_mode {
            XYMode::Absolute => c,
            XYMode::Relative => *modal_value + c
        }
    } else {
        *modal_value
    };
    *modal_value = c;
    Ok(c)
}


/// Read a (layer, datatype) pair.
fn read_layernum_datatype<R: Read>(reader: &mut R,
                                   is_layer_present: bool,
                                   is_datatype_present: bool,
                                   modal: &mut Modal) -> Result<(UInt, UInt), OASISReadError> {
    let layer = if is_layer_present {
        read_unsigned_integer(reader)?
    } else {
        modal.layer.ok_or(OASISReadError::NoImplicitLayerDefined)?
    };
    modal.layer = Some(layer);

    let datatype = if is_datatype_present {
        read_unsigned_integer(reader)?
    } else {
        modal.datatype.ok_or(OASISReadError::NoImplicitDataTypeDefined)?
    };
    modal.datatype = Some(datatype);

    Ok((layer, datatype))
}

/// Read an OASIS layout.
pub fn read_layout<R: Read>(reader: &mut R, layout: &mut Layout) -> Result<(), OASISReadError> {
    let mut modal = Modal::default();

    read_magic(reader)?;

    // Read START record.
    let record_id = read_unsigned_integer(reader)?;

    if record_id != 1 {
        return Err(OASISReadError::UnexpectedRecord(record_id)); // START record expected.
    }
    let version_string = read_ascii_string(reader)?;

    if !version_string.eq("1.0") {
        return Err(OASISReadError::WrongVersionString); // Wrong version string.
    }
    let resolution = read_real(reader)?; // Grid steps per micron.

    // If the resolution is negative, NaN or infinite return an error.
    {
        let r = resolution.to_f64();
        if f64::is_sign_negative(r) || f64::is_infinite(r) || f64::is_nan(r) {
            return Err(OASISReadError::InvalidResolution(resolution)); // Invalid resolution.
        }
    }

    let dbu = match resolution.try_to_int() {
        Some(r) if r > 0 => r as UInt,
        _ => unimplemented!("Resolution must be a positive non-zero integer.")
    };
    assert!(dbu >= 1);
    layout.dbu = dbu;

    // If the `offset_flag` is set to 0 then the table-offsets is stored in the START record.
    // Otherwise it is stored in the END record.
    let offset_flag = read_unsigned_integer(reader)?;
    debug!("offset flag = {}", offset_flag);
    let table_offsets_at_start = offset_flag == 0;
    if table_offsets_at_start {
        // table-offsets is stored in START record.
        read_offset_table(reader)?;
    }

    /// Tells if IDs are given implicitly by a counter or are explicitly written in the file.
    #[derive(Eq, PartialEq, Debug)]
    enum IdMode {
        /// ID mode is not known yet.
        Any,
        /// IDs are given based on a counter.
        Impl,
        /// IDs are given explicitely.
        Expl,
    }

    // Mutable state variables.
    let mut state = MutableState::default();
    let mut current_cell = None;

    // Remember cells that have been created as forward references in placement records.
    // They must be respected when afterwards a CELL record creates a cell with the same name.
    // TODO: This is not correctly used yet.
    // TODO: Put this into the mutable state struct.
    let mut placement_cell_forward_references = HashSet::new();

    // Remember with what to associate PROPERTY records.
    let mut property_parent = PropertyParent::None;

    // Define counters for implicit IDs.
    let mut cellname_id_mode = IdMode::Any;
    let mut cellname_id_counter = (0..).into_iter();
    let mut textstrings_id_mode = IdMode::Any;
    let mut textstrings_id_counter = (0..).into_iter();
    let mut propname_id_mode = IdMode::Any;
    let mut propname_id_counter = (0..).into_iter();
    let mut propstrings_id_mode = IdMode::Any;
    let mut propstrings_id_counter = (0..).into_iter();


    // Set properties of a certain object `property_parent`.
    let set_property = |layout: &Layout,
                        property_parent: &PropertyParent,
                        property_name: &String,
                        property_values: &Vec<PropertyValue>,
                        // Mapping from property string references to property strings.
                        property_strings: &HashMap<UInt, Vec<u8>>| {

        // Convert property values to data base types.
        let property_values: Vec<db::property_storage::PropertyValue> = property_values.iter()
            .map(|v| {
                use db::property_storage::PropertyValue as PV;
                match v {
                    PropertyValue::SInt(v) => (*v).into(),
                    PropertyValue::UInt(v) => (*v).into(),
                    PropertyValue::Real(v) => match v {
                        Real::IEEEFloat32(v) => PV::Float(*v as f64),
                        Real::IEEEFloat64(v) => PV::Float(*v),
                        Real::PositiveWholeNumber(v) => (*v).into(),
                        Real::NegativeWholeNumber(v) => (0 - *v as i32).into(),
                        x => {
                            dbg!(&property_name, x);
                            unimplemented!();
                        }
                    },
                    PropertyValue::AString(s) => s.clone().into(),
                    PropertyValue::NString(s) => s.clone().into(),
                    PropertyValue::BString(s) => s.clone().into(),
                    PropertyValue::NStringRef(propstring_id) => {
                        // Fetch property string.
                        let bstring = property_strings.get(propstring_id)
                            .expect("AString forward references are not supported yet."); // TODO

                        let s = bytes_to_name_string(bstring.clone())
                            .expect("Failed to convert bytes to name string.");
                        s.into()
                    }
                    PropertyValue::AStringRef(propstring_id) => {
                        // Fetch property string.
                        let bstring = property_strings.get(propstring_id)
                            .expect("NString forward references are not supported yet."); // TODO

                        let s = bytes_to_ascii_string(bstring.clone())
                            .expect("Failed to convert bytes to ascii string.");
                        s.into()
                    }
                    PropertyValue::BStringRef(propstring_id) => {
                        // Fetch property string.
                        let bstring = property_strings.get(propstring_id)
                            .expect("BString forward references are not supported yet."); // TODO
                        bstring.clone().into()
                    }
                }
            })
            .collect();

        match &property_parent {
            PropertyParent::None => {
                // Properties related to the whole layout.
                for v in &property_values {
                    layout.set_property(property_name.clone(),
                                        v.clone());
                }
            }
            PropertyParent::Geometry(shapes) => {
                for shape in shapes {
                    for v in &property_values {
                        shape.set_property(property_name.clone(),
                                           v.clone());
                    }
                }
            }
            PropertyParent::Cell(cell) => {
                for v in &property_values {
                    cell.set_property(property_name.clone(),
                                      v.clone());
                }
            }
            PropertyParent::CellName(cell_name) => {
                // Properties associated with a cell name.
                let cell = layout.cell_by_name(cell_name).expect("Cell name not found.");
                for v in &property_values {
                    cell.set_property(property_name.clone(),
                                      v.clone());
                }
            }
            PropertyParent::Placement(instances) => {
                for instance in instances {
                    for v in &property_values {
                        instance.set_property(property_name.clone(),
                                              v.clone());
                    }
                }
            }
            x => debug!("Storing properties to this type is not supported yet: {:?}", x)
        }
    };

    loop {
        let record_id = read_unsigned_integer(reader)?;
        debug!("record_id = {}", record_id);

        match record_id {
            0 => {
                // PAD record
                debug!("PAD record");
            }
            1 => {
                // START record
                debug!("START record");
                return Err(OASISReadError::UnexpectedRecord(record_id)); // No start record expected.
            }
            2 => {
                // END record.
                debug!("END record");
                // Finished reading file.

                if !table_offsets_at_start {
                    // table-offsets is stored in END record.
                    read_offset_table(reader)?;
                }

                // The padding string makes sure that the byte length of the END record inclusive record-ID is exactly 256.
                let _padding_string = read_byte_string(reader)?;

                // Type of integrity check: None, CRC32 or CHECKSUM32.
                let validation_scheme = read_unsigned_integer(reader)?;

                match validation_scheme {
                    0 => {
                        // No validation.
                        debug!("No integrity validation.");
                    }
                    1 => {
                        // CRC32, checksum length = 4
                        let crc32_expected = reader.read_u32::<LittleEndian>()?;
                        debug!("CRC32 (from file): {:x}", crc32_expected);
                        // TODO: Validate checksum
                    }
                    2 => {
                        // CHECKSUM32, checksum length = 4
                        // CHECKSUM32 is the simple arithmetic addition of all bytes from the first
                        // byte of the START record until the `validation_scheme` byte of this END record.
                        let checksum32_expected = reader.read_u32::<LittleEndian>()?;
                        debug!("CHECKSUM32 (from file): {:x}", checksum32_expected);
                        // TODO: Validate checksum
                    }
                    v => {
                        return Err(OASISReadError::UnknownValidationScheme(v)); // Invalid validation scheme.
                    }
                }

                break;
            }
            3 | 4 => {
                // CELLNAME record
                debug!("CELLNAME record");

                let cell_name = read_name_string(reader)?;
                debug!("cell name = {}", &cell_name);

                let id = if record_id == 3 {
                    // Implicit IDs.
                    if cellname_id_mode == IdMode::Expl {
                        return Err(OASISReadError::MixedImplExplCellnameModes); // Implicit and explicit CELLNAME modes cannot be mixed.
                    };
                    cellname_id_mode = IdMode::Impl; // Remember mode.
                    cellname_id_counter.next().unwrap() // Infinite sequence, unwrap does not fail.
                } else {
                    // Explicit IDs.
                    if cellname_id_mode == IdMode::Impl {
                        return Err(OASISReadError::MixedImplExplCellnameModes); // Implicit and explicit CELLNAME modes cannot be mixed.
                    };
                    cellname_id_mode = IdMode::Expl; // Remember mode.
                    read_unsigned_integer(reader)?
                };

                // Store cell name.
                // Return an error if the cell name already exists.
                if let Some(_) = state.m_cell_names.insert(id, cell_name.clone()) {
                    return Err(OASISReadError::CellnameIdAlreadyPresent(id));
                }
                modal.reset();


                // Resolve forward references.
                if let Some(idx) = state.m_cell_names_forward_references.remove(&id) {
                    layout.rename_cell(idx, Some(cell_name.clone()))?;
                }

                // Subsequent PROPERTY records may be associated with the cell with this name.
                property_parent = PropertyParent::CellName(cell_name);
            }
            5 | 6 => {
                // TEXTSTRING record, associates a text string with a unique reference number.
                debug!("TEXTSTRING record");
                let textstring = read_ascii_string(reader)?;

                let id = if record_id == 5 {
                    // Implicit IDs.
                    if textstrings_id_mode == IdMode::Expl {
                        return Err(OASISReadError::MixedImplExplTextstringModes); // Implicit and explicit TEXTSTRING modes cannot be mixed.
                    };
                    textstrings_id_mode = IdMode::Impl; // Remember mode.
                    textstrings_id_counter.next().unwrap()
                } else {
                    // Explicit IDs.
                    if textstrings_id_mode == IdMode::Impl {
                        return Err(OASISReadError::MixedImplExplTextstringModes); // Implicit and explicit TEXTSTRING modes cannot be mixed.
                    };
                    textstrings_id_mode = IdMode::Expl; // Remember mode.
                    read_unsigned_integer(reader)?
                };

                // Store text string.
                if let Some(_) = state.m_textstrings.insert(id, textstring) {
                    return Err(OASISReadError::TextStringAlreadyPresent(id));
                }

                modal.reset();
            }
            7 | 8 => {
                // PROPNAME record, associates property name with a unique reference number.
                debug!("PROPNAME record");

                let property_name = read_name_string(reader)?;
                debug!("property_name = {}", &property_name);

                let prop_name_id = if record_id == 7 {
                    // Implicit IDs.
                    if propname_id_mode == IdMode::Expl {
                        return Err(OASISReadError::MixedImplExplPropnameModes); // Implicit and explicit CELLNAME modes cannot be mixed.
                    };
                    propname_id_mode = IdMode::Impl; // Remember mode.
                    propname_id_counter.next().unwrap() // Infinite sequence, unwrap does not fail.
                } else {
                    // Explicit IDs.
                    if propname_id_mode == IdMode::Impl {
                        return Err(OASISReadError::MixedImplExplPropnameModes); // Implicit and explicit CELLNAME modes cannot be mixed.
                    };
                    propname_id_mode = IdMode::Expl; // Remember mode.
                    read_unsigned_integer(reader)?
                };
                debug!("prop_id = {}", prop_name_id);

                // TODO: Property forward references without property-string forward references could be resolved already.

                // Store property name by the reference number.
                if let Some(_existing_name) = state.m_propnames.insert(prop_name_id, property_name) {
                    return Err(OASISReadError::PropnameIdAlreadyPresent(prop_name_id));
                }

                modal.reset();
            }
            9 | 10 => {
                // PROPSTRING record, associates a property string with a unique reference number.
                // The property string can be an a-string, b-string or n-string depending on the
                // referencing property record (28).
                debug!("PROPSTRING record");
                // `propstring` is a a-string, n-string or b-string depending on the referencing
                // PROPERTY record.
                let propstring = read_byte_string(reader)?;
                debug!("propstring = {:?}", &propstring);

                let id = if record_id == 9 {
                    // Implicit IDs.
                    if propstrings_id_mode == IdMode::Expl {
                        return Err(OASISReadError::MixedImplExplPropstringModes); // Implicit and explicit PROPSTRING modes cannot be mixed.
                    };
                    propstrings_id_mode = IdMode::Impl; // Remember mode.
                    propstrings_id_counter.next().unwrap() // Infinite sequence, unwrap does not fail.
                } else {
                    // Explicit IDs.
                    if propstrings_id_mode == IdMode::Impl {
                        return Err(OASISReadError::MixedImplExplPropstringModes); // Implicit and explicit PROPSTRING modes cannot be mixed.
                    };
                    propstrings_id_mode = IdMode::Expl; // Remember mode.
                    read_unsigned_integer(reader)?
                };

                // Store text string.
                if let Some(_existing_name) = state.m_propstrings.insert(id, propstring) {
                    // Conflict: Property string ID is already used.
                    return Err(OASISReadError::PropStringAlreadyPresent(id));
                }

                modal.reset();
            }
            11 | 12 => {
                // LAYERNAME record
                debug!("LAYERNAME record");

                let layer_name = read_name_string(reader)?;
                debug!("layer_name = {}", &layer_name);

                let read_interval = |reader: &mut R| {
                    let interval_type = read_unsigned_integer(reader)?;
                    let max = UInt::MAX; // Maximum integer value. Used as a pseudo representation for infinity.
                    match interval_type {
                        0 => Ok((0, max)),
                        1 => Ok((0, read_unsigned_integer(reader)?)),
                        2 => Ok((read_unsigned_integer(reader)?, max)),
                        3 => {
                            let a = read_unsigned_integer(reader)?;
                            Ok((a, a))
                        }
                        4 => Ok((read_unsigned_integer(reader)?, read_unsigned_integer(reader)?)),
                        t => return Err(OASISReadError::IllegalIntervalType(t)) // Invalid interval type.
                    }
                };

                let (layer_start, layer_end) = read_interval(reader)?;
                let (dtype_start, dtype_end) = read_interval(reader)?;

                // Set the layer name in the layout.
                for l in layer_start..layer_end {
                    for d in dtype_start..dtype_end {
                        let idx = layout.find_or_create_layer(l, d);
                        layout.set_layer_name(idx, Some(layer_name.clone()));
                    }
                }

                // Reset modal variables.
                modal.reset();

                warn!("LAYERNAME record is not implemented: '{}'", &layer_name);
            }
            13 | 14 => {
                // 13: CELL record, with reference-number for the name.
                // 14: CELL record, with name string.
                debug!("CELL record");

                // All subsequent records in the file up to the next CELL, END, or <name> record
                // are considered to be part of that cell.


                let cell_name = if record_id == 13 {
                    // Name by reference.
                    let cell_name_reference = read_unsigned_integer(reader)?;
                    let cell_name = state.m_cell_names.get(&cell_name_reference);

                    // Return the name if it is present, other wise return the reference number.
                    if let Some(cell_name) = cell_name {
                        NameOrRef::Name(cell_name.clone())
                    } else {
                        NameOrRef::NameRef(cell_name_reference)
                    }
                } else {
                    NameOrRef::Name(read_name_string(reader)?)
                };
                debug!("cell_name = {:?}", &cell_name);

                // Set the cell name if it is already defined.
                // Otherwise remember the forward reference such that the name can be defined later.
                let cell_idx = match cell_name {
                    NameOrRef::Name(n) => {
                        if let Some(cell_idx) = layout.cell_index_by_name(&n) {
                            // Cell with this name already exists.
                            // This is fine if it has been created as a forward reference for a placement record.
                            // Check if it is a forward reference to a placement record.
                            if placement_cell_forward_references.remove(&cell_idx) {
                                // Cell has been created as a forward reference. No name clash.
                                cell_idx
                            } else {
                                // Cell has not been created as a forward reference. Name clash.
                                return Err(OASISReadError::CellnameAlreadyPresent(n));
                            }
                        } else {
                            layout.create_cell(Some(n))
                        }
                    }
                    NameOrRef::NameRef(r) => {
                        // Check if the reference does not already exist.
                        if let Some(&cell_idx) = state.m_cell_names_forward_references.get(&r) {
                            if placement_cell_forward_references.remove(&cell_idx) {
                                // Cell has been created as a forward reference. No name reference clash.
                                cell_idx
                            } else {
                                // Cell has not been created as a forward reference. Name reference clash.
                                return Err(OASISReadError::CellnameIdAlreadyPresent(r));
                            }
                        } else {
                            // The value of this reference has not yet been defined.
                            let cell_idx = layout.create_cell::<String>(None);
                            // Remember the forward reference.
                            state.m_cell_names_forward_references.insert(r, cell_idx);
                            cell_idx
                        }
                    }
                };

                // Remember this cell as the 'active' cell.
                current_cell = Some(layout.cell_by_index(cell_idx)
                                        .unwrap() // Cell index must exist. Unwrap should not fail.
                );

                // Associate following properties with this cell for now.
                property_parent = PropertyParent::Cell(current_cell.clone().unwrap());

                // Reset modal values.
                modal.reset();
            }
            15 => {
                // XYABSOLUTE record
                debug!("XYABSOLUTE record");
                modal.xy_mode = XYMode::Absolute;
            }
            16 => {
                // XYRELATIVE record
                debug!("XYRELATIVE record");
                modal.xy_mode = XYMode::Relative;
            }
            17 | 18 => {
                // PLACEMENT record
                // 17/18 are different in how the magnification and rotation are encoded.
                debug!("PLACEMENT record");

                let placement_info_byte = read_byte(reader)?;
                let b = |index| { (placement_info_byte >> index) & 1u8 == 1u8 };
                let is_cell_reference_explicit = b(7); // C
                let is_cell_reference_number_present = b(6); // N
                let is_x_present = b(5); // X
                let is_y_present = b(4); // Y
                let is_repetition_present = b(3); // R
                let is_flip = b(0); // F

                // Get either a reference to the cell to be instantiated or at least the name to it.
                // It is possible that this is a forward reference with the cell not yet defined.
                let instance_ref = if is_cell_reference_explicit {

                    // Read cell name.
                    let cell_name = if is_cell_reference_number_present {
                        // Cell name is given by reference number.
                        let cell_name_ref = read_unsigned_integer(reader)?;

                        // Get cell name if it is already defined.
                        if let Some(cell_name) = state.m_cell_names.get(&cell_name_ref) {
                            NameOrRef::Name(cell_name.clone())
                        } else {
                            NameOrRef::NameRef(cell_name_ref)
                        }
                    } else {
                        // Read explicit cell name.
                        NameOrRef::Name(read_name_string(reader)?)
                    };

                    // Get the cell by the name or create it if necessary.
                    // If the cell needs to be created but no name is defined yet
                    // an unnamed cell will be created.
                    // TODO: FIXME: What if a cell is placed once by name and once by reference before it is created and before the name is defined?
                    // "Use of a reference-number for which there is no corresponding CELLNAME
                    // record should be treated as a fatal error"
                    match cell_name {
                        NameOrRef::Name(n) => {
                            if let Some(cell) = layout.cell_by_name(&n) {
                                cell
                            } else {
                                let cell = layout.create_and_get_cell(Some(n));
                                // Remember that this cell has been created as a forward reference.
                                placement_cell_forward_references.insert(cell.index());
                                cell
                            }
                        }
                        NameOrRef::NameRef(r) => {
                            // Try to find the cell by forward reference (if the name is not yet defined).
                            state.m_cell_names_forward_references.get(&r)
                                .map(|&i| layout.cell_by_index(i)
                                    // If the cell index was found in the forward references,
                                    // then it should also exist in the layout.
                                    .expect("Could not find cell even tough it must have been created.")
                                )
                                // If no forward reference can be found, create a new cell
                                // and a new forward reference.
                                .unwrap_or_else(|| {
                                    // Create an unnamed cell.
                                    let cell = layout.create_and_get_cell::<String>(None);
                                    let idx = cell.index();
                                    state.m_cell_names_forward_references.insert(r, idx);
                                    // Remember that this cell has been created as a forward reference.
                                    placement_cell_forward_references.insert(idx);
                                    cell
                                })
                        }
                    }
                } else {
                    // Implicit cell.
                    // Use modal variable `placement_cell` which refers to the same cell as the placement record before.
                    modal.placement_cell.clone()
                        .ok_or(OASISReadError::ModalPlacementCellNotDefined)?
                };

                // Remember the last placement cell if any.
                modal.placement_cell = Some(instance_ref.clone());

                // Read magnification and angle or take default values.
                let (magnification, angle_degrees) = if record_id == 17 {
                    let aa = (placement_info_byte >> 1) & 3u8; // AA
                    let angle_degrees = 90 * (aa as u16);
                    let magnification = 1;
                    (Real::PositiveWholeNumber(magnification), Real::PositiveWholeNumber(angle_degrees.into()))
                } else {
                    // Magnification and rotation are reals.
                    let is_magnification_present = b(2); // M
                    let is_angle_present = b(1); // A
                    // Read magnification and angle (default are 1.0 and 0.0).
                    let magnification = if is_magnification_present {
                        read_real(reader)?
                    } else {
                        Real::PositiveWholeNumber(1)
                    };

                    // Read rotation angle default is 0.
                    let angle_degrees = if is_angle_present {
                        read_real(reader)?
                    } else {
                        Real::PositiveWholeNumber(0)
                    };

                    (magnification, angle_degrees)
                };

                // Read x.
                let x = read_coordinate_conditional(reader, is_x_present, modal.xy_mode, &mut modal.placement_x)?;

                // Read y.
                let y = read_coordinate_conditional(reader, is_y_present, modal.xy_mode, &mut modal.placement_y)?;

                // Construct placement offset.
                let displacement = Vector::new(x, y);

                // Construct positions from a repetition if there is any.
                let repetition = read_repetition_conditional(reader,
                                                             is_repetition_present,
                                                             &mut modal.repetition)?;

                // Convert angle back into a multiple of 90 degrees if possible.
                let angle90 = match angle_degrees.try_to_int() {
                    Some(0) => Some(Angle::R0),
                    Some(90) => Some(Angle::R90),
                    Some(180) => Some(Angle::R180),
                    Some(270) => Some(Angle::R270),
                    _ => None
                }.expect("Rotation angle must be a multiple of 90 degree."); // TODO: Support complex transforms here.

                // TODO: Support non-integer magnification.
                let magnification = magnification.try_to_int().expect("Magnification mut be an integer.");

                // Convert the repetition into actual offsets.
                let positions = repetition_to_offsets(&repetition, displacement);

                // Create cell instances.
                // TODO: Create cell instance arrays.
                let parent_cell = current_cell.as_ref().ok_or(OASISReadError::NoCellRecordPresent)?;

                let mut instances = Vec::new();
                for pos in positions {
                    let trans = SimpleTransform::new(is_flip, angle90,
                                                     magnification, pos);
                    let instance = parent_cell.create_instance(&instance_ref, trans);
                    instances.push(instance);
                }

                // Associate following properties with this instance for now.
                property_parent = PropertyParent::Placement(instances);
            }
            19 => {
                // TEXT record
                debug!("TEXT record");

                let text_info_byte = read_byte(reader)?;
                let b = |index| { (text_info_byte >> index) & 1u8 == 1u8 };
                let is_text_reference_explicit = b(6); // C

                let text_string = if is_text_reference_explicit {
                    let reference_number_present = b(5);
                    if reference_number_present {
                        let ref_number = read_unsigned_integer(reader)?;
                        let text_string = state.m_textstrings.get(&ref_number);
                        text_string.cloned().ok_or(OASISReadError::PropStringIdNotFound(ref_number))?
                    } else {
                        read_ascii_string(reader)?
                    }
                } else {
                    modal.text_string.as_ref().cloned().ok_or(OASISReadError::NoImplicitTextStringDefined)?
                };
                debug!("text_string = {}", &text_string);
                modal.text_string = Some(text_string.clone());

                let is_explicit_textlayer = b(0);
                let is_explicit_texttype = b(1);
                let is_repetition_present = b(2);
                let is_x_present = b(4);
                let is_y_present = b(3);

                let textlayer = if is_explicit_textlayer {
                    read_unsigned_integer(reader)?
                } else {
                    modal.textlayer.ok_or(OASISReadError::ModalTextLayerDefined)?
                };
                modal.textlayer = Some(textlayer);

                let texttype = if is_explicit_texttype {
                    read_unsigned_integer(reader)?
                } else {
                    modal.texttype.ok_or(OASISReadError::ModalTextTypeDefined)?
                };
                modal.texttype = Some(texttype);

                // Read x.
                let x = read_coordinate_conditional(reader, is_x_present, modal.xy_mode, &mut modal.text_x)?;

                // Read y.
                let y = read_coordinate_conditional(reader, is_y_present, modal.xy_mode, &mut modal.text_y)?;


                // Construct the coordinate of the first text instance (there might be a repetition).
                let pos = Vector::new(x, y);

                // Construct positions from a repetition if there is any.
                let repetition = read_repetition_conditional(reader,
                                                             is_repetition_present,
                                                             &mut modal.repetition)?;
                let positions = repetition_to_offsets(&repetition, pos);

                let parent_cell = current_cell.as_ref()
                    .ok_or(OASISReadError::NoCellRecordPresent)?;
                let layer = layout.find_or_create_layer(textlayer, texttype);
                let shapes = parent_cell.shapes_get_or_create(layer);

                let mut shape_instances = Vec::new();
                // Create rectangle instances.
                for pos in positions {
                    let text = Text::new(text_string.clone(), pos.into());
                    let shape = shapes.insert(text);
                    shape_instances.push(shape); // Remember all instances.
                }

                // Remember the shapes to associate upcoming properties with them.
                property_parent = PropertyParent::Geometry(shape_instances);
            }
            20 => {
                // RECTANGLE record.
                debug!("RECTANGLE record");

                let rectangle_info_byte = read_byte(reader)?;
                let b = |index| { (rectangle_info_byte >> index) & 1u8 == 1u8 };

                let is_layer_number_present = b(0);
                let is_datatype_number_present = b(1);
                let is_width_present = b(6); // W
                let is_height_present = b(5); // H
                let is_x_present = b(4); // X
                let is_y_present = b(3); // Y
                let is_repetition_present = b(2); // R
                let is_square = b(7); // S

                let (layer, datatype) = read_layernum_datatype(reader, is_layer_number_present,
                                                               is_datatype_number_present, &mut modal)?;

                let width = if is_width_present {
                    read_unsigned_integer(reader)?
                } else {
                    modal.geometry_w.ok_or(OASISReadError::ModalGeometryWNotDefined)?
                };
                modal.geometry_w = Some(width);

                let height = if is_square {
                    if is_height_present {
                        // `height` should not be present if S is 1.
                        return Err(OASISReadError::HeightIsPresentForSquare);
                    } else {
                        width
                    }
                } else {
                    if is_height_present {
                        read_unsigned_integer(reader)?
                    } else {
                        modal.geometry_h.ok_or(OASISReadError::ModalGeometryHNotDefined)?
                    }
                };
                modal.geometry_h = Some(height);

                // Read x.
                let x = read_coordinate_conditional(reader, is_x_present,
                                                    modal.xy_mode,
                                                    &mut modal.geometry_x)?;

                // Read y.
                let y = read_coordinate_conditional(reader,
                                                    is_y_present, modal.xy_mode,
                                                    &mut modal.geometry_y)?;

                // Construct the coordinate of the first text instance (there might be a repetition).
                let pos = Vector::new(x, y);

                // Construct positions from a repetition if there is any.
                let repetition = read_repetition_conditional(reader,
                                                             is_repetition_present,
                                                             &mut modal.repetition)?;

                let positions = repetition_to_offsets(&repetition, pos);

                let diagonal = Vector::new(width as SInt, height as SInt);

                let lower_left = Point::zero();
                let rect = Rect::new(lower_left, lower_left + diagonal);

                if let Some(parent_cell) = &current_cell {
                    let layer_id = layout.find_or_create_layer(layer, datatype);
                    let shapes = parent_cell.shapes_get_or_create(layer_id);
                    let mut shape_instances = Vec::new();
                    // Create rectangle instances.
                    for pos in positions {
                        let r = rect.translate(pos);
                        let shape = shapes.insert(r);
                        shape_instances.push(shape); // Remember all instances.
                    }

                    // Remember the shapes to associate upcoming properties with them.
                    property_parent = PropertyParent::Geometry(shape_instances);
                } else {
                    return Err(OASISReadError::NoCellRecordPresent);
                }
            }
            21 => {
                // POLYGON record.
                debug!("POLYGON record");

                let polygon_info_byte = read_byte(reader)?;
                let b = |index| { (polygon_info_byte >> index) & 1u8 == 1u8 };

                let is_layer_number_present = b(0); // L
                let is_datatype_number_present = b(1); // D
                let is_repetition_present = b(2); // R
                let is_y_present = b(3); // Y
                let is_x_present = b(4); // X
                let is_pointlist_present = b(5); // P

                let (layer, datatype) = read_layernum_datatype(reader, is_layer_number_present,
                                                               is_datatype_number_present, &mut modal)?;

                if is_pointlist_present {
                    let p = read_point_list(reader)?;
                    modal.polygon_point_list = Some(p);
                }

                // Read x.
                let x = read_coordinate_conditional(reader, is_x_present, modal.xy_mode, &mut modal.geometry_x)?;

                // Read y.
                let y = read_coordinate_conditional(reader, is_y_present, modal.xy_mode, &mut modal.geometry_y)?;

                let point0 = Vector::new(x, y);

                // Create coordinates.
                let points: Vec<_> = modal.polygon_point_list.as_ref()
                    .ok_or(OASISReadError::ModalPolygonPointListNotDefined)
                    .map(|pointlist| pointlist.points(Vector::zero(), true))?;

                // Construct positions from a repetition if there is any.
                let repetition = read_repetition_conditional(reader,
                                                             is_repetition_present,
                                                             &mut modal.repetition)?;
                let positions = repetition_to_offsets(&repetition, point0);

                let polygon = SimplePolygon::new(points);

                if let Some(parent_cell) = &current_cell {
                    let layer_id = layout.find_or_create_layer(layer, datatype);

                    let shapes = parent_cell.shapes_get_or_create(layer_id);

                    // Repeat polygon and add the repetitions to the current cell.
                    let mut shape_instances = Vec::new();
                    // Create polygon instances.
                    for pos in positions {
                        let p = polygon.translate(pos);
                        let shape = shapes.insert(p);
                        shape_instances.push(shape); // Remember all instances.
                    }

                    // Remember the shapes to associate upcoming properties with them.
                    property_parent = PropertyParent::Geometry(shape_instances);
                } else {
                    return Err(OASISReadError::NoCellRecordPresent);
                }
            }
            22 => {
                // PATH record.
                debug!("PATH record");

                let path_info_byte = read_byte(reader)?;
                let b = |index| { (path_info_byte >> index) & 1u8 == 1u8 };

                let is_layer_number_present = b(0); // L
                let is_datatype_number_present = b(1); // D
                let is_repetition_present = b(2); // R
                let is_y_present = b(3); // Y
                let is_x_present = b(4); // X
                let is_pointlist_present = b(5); // P
                let is_half_width_present = b(6); // W
                let is_extension_scheme_present = b(7); // E

                let (layer, datatype) = read_layernum_datatype(reader, is_layer_number_present,
                                                               is_datatype_number_present, &mut modal)?;

                let half_width = if is_half_width_present {
                    let hw = read_unsigned_integer(reader)?;
                    modal.path_halfwidth = Some(hw);
                    hw
                } else {
                    modal.path_halfwidth.ok_or(OASISReadError::ModalPathHalfWidthNotDefined)?
                };

                let (start_ext, end_ext) = if is_extension_scheme_present {
                    let ext_scheme = read_unsigned_integer(reader)?;
                    let ss = (ext_scheme >> 2) & 0b11; // Path start extension.
                    let ee = ext_scheme & 0b11; // Path end extension.

                    let start_ext = match ss {
                        0 => modal.path_start_extension.ok_or(OASISReadError::ModalPathStartExtensionNotDefined)?,
                        1 => 0, // 'Flush'
                        2 => half_width as SInt,
                        3 => read_signed_integer(reader)?,
                        _ => panic!() // This cannot happen.
                    };
                    let end_ext = match ee {
                        0 => modal.path_end_extension.ok_or(OASISReadError::ModalPathEndExtensionNotDefined)?,
                        1 => 0, // 'Flush'
                        2 => half_width as SInt,
                        3 => read_signed_integer(reader)?,
                        _ => panic!() // This cannot happen.
                    };

                    (start_ext, end_ext)
                } else {
                    let s = modal.path_start_extension.ok_or(OASISReadError::ModalPathStartExtensionNotDefined)?;
                    let e = modal.path_end_extension.ok_or(OASISReadError::ModalPathEndExtensionNotDefined)?;
                    (s, e)
                };
                modal.path_start_extension = Some(start_ext);
                modal.path_end_extension = Some(end_ext);

                if is_pointlist_present {
                    let p = read_point_list(reader)?;
                    modal.path_point_list = Some(p);
                }

                // Read x and set modal geometry_x.
                let x = read_coordinate_conditional(reader, is_x_present, modal.xy_mode, &mut modal.geometry_x)?;

                // Read y and set modal geometry_y.
                let y = read_coordinate_conditional(reader, is_y_present, modal.xy_mode, &mut modal.geometry_y)?;

                let point0 = Vector::new(x, y);

                // Construct positions from a repetition if there is any.
                let repetition = read_repetition_conditional(reader,
                                                             is_repetition_present,
                                                             &mut modal.repetition)?;
                let positions = repetition_to_offsets(&repetition, point0);


                // Create coordinates.
                let points: Vec<_> = modal.path_point_list.as_ref()
                    .ok_or(OASISReadError::ModalPathPointListNotDefined)
                    .map(|pointlist| pointlist.points(Vector::zero(), false))?;

                // Create untranslated path.
                let path = Path::new_extended(points, half_width as SInt * 2, start_ext, end_ext);

                if let Some(parent_cell) = &current_cell {
                    let layer_id = layout.find_or_create_layer(layer, datatype);

                    let shapes = parent_cell.shapes_get_or_create(layer_id);
                    // Repeat shape and add the repetitions to the current cell.
                    let mut shape_instances = Vec::new();
                    // Create path instances.
                    for pos in positions {
                        let p = path.translate(pos);
                        let shape = shapes.insert(p);
                        shape_instances.push(shape); // Remember all instances.
                    }

                    // Remember the shapes to associate upcoming properties with them.
                    property_parent = PropertyParent::Geometry(shape_instances);
                } else {
                    return Err(OASISReadError::NoCellRecordPresent);
                }
            }
            28 | 29 => {
                // PROPERTY record.
                // PROPERTY records follow the records they are associated with.
                // Updates `last_property_name` and `last_value_list` modal variables.

                // 29 specifies a duplicate of the most recently seen property.

                debug!("PROPERTY record");

                let (property_name_or_ref, property_values) = if record_id == 28 {
                    let prop_info_byte = read_byte(reader)?;
                    let b = |index| { (prop_info_byte >> index) & 1u8 == 1u8 };
                    let is_name_reference_explicit = b(2); // C
                    let use_last_value_list = b(3); // V
                    let _is_standard_property = b(0); // S, TODO: How to handle this?
                    let uuuu = ((prop_info_byte >> 4) & 0xF).into(); // Upper nibble.

                    let property_name_or_ref = if is_name_reference_explicit {
                        let is_ref_number_present = b(1);
                        if is_ref_number_present {
                            // Property name is defined by the reference number.
                            // This can be a forward reference.
                            let ref_number = read_unsigned_integer(reader)?; // Reference number to property name.
                            let property_name = state.m_propnames.get(&ref_number);
                            debug!("ref_number = {}", ref_number);
                            // property_name.cloned().ok_or(OASISReadError::PropStringIdNotFound(ref_number))?
                            match property_name {
                                Some(name) => NameOrRef::Name(name.clone()),
                                None => NameOrRef::NameRef(ref_number) // This is a forward reference.
                            }
                        } else {
                            NameOrRef::Name(read_name_string(reader)?)
                        }
                    } else {
                        // Implicit name: Modal variable `last_property_name` is used.
                        modal.last_property_name
                            .ok_or(OASISReadError::ModalLastPropertyNameNotDefined)?
                    };

                    let values = if !use_last_value_list {
                        let num_values = if uuuu == 15 {
                            read_unsigned_integer(reader)?
                        } else {
                            uuuu
                        };

                        // Read property values.
                        let mut prop_value_list = Vec::new();
                        for _i in 0..num_values {
                            let prop = read_property_value(reader)?;
                            prop_value_list.push(prop)
                        }
                        prop_value_list
                    } else {
                        // uuuu must be 0
                        if uuuu != 0 {
                            return Err(OASISReadError::FormatError); // TODO More specific error type: "uuuu must be 0".
                        }

                        modal.last_value_list.ok_or(OASISReadError::ModalLastValueListNotDefined)?
                    };

                    // Update modal variables.
                    modal.last_property_name = Some(property_name_or_ref.clone());
                    modal.last_value_list = Some(values.clone());

                    (property_name_or_ref, values)
                } else {
                    // Use the last property.
                    (
                        modal.last_property_name.clone().ok_or(OASISReadError::ModalLastPropertyNameNotDefined)?,
                        modal.last_value_list.clone().ok_or(OASISReadError::ModalLastValueListNotDefined)?
                    )
                };

                debug!("property name or reference = {:?}", &property_name_or_ref);
                debug!("property values = {:?}", &property_values);

                match property_name_or_ref {
                    NameOrRef::Name(property_name) => {
                        // Name is known.
                        debug!("property name = {}", &property_name);

                        // Store the properties!
                        set_property(&layout,
                                     &property_parent,
                                     &property_name,
                                     &property_values,
                                     &state.m_propstrings);
                    }
                    NameOrRef::NameRef(property_name_ref) => {
                        // Forward reference to a property name.
                        debug!("Property name is a forward reference = {}", &property_name_ref);

                        // Remember forward reference to be resolved later.
                        state.m_property_name_forward_references.entry(property_name_ref)
                            .or_insert(Vec::new())
                            .push((property_parent.clone(), property_values))
                    }
                }
            }
            30 | 31 => {
                // XNAME record
                debug!("XNAME record");

                let _xname_attribute = read_unsigned_integer(reader)?;
                let _xname_string = read_byte_string(reader)?;

                if record_id == 31 {
                    let _reference_number = read_unsigned_integer(reader)?;
                }

                modal.reset();

                // TODO: This is neither complete nor correct.

                unimplemented!("XNAME record is not supported yet.")
            }
            32 => {
                // XELEMENT record
                debug!("XELEMENT record");

                let _xelement_attribute = read_unsigned_integer(reader)?;
                let _xelement_string = read_byte_string(reader)?; // Contains user defined data.

                property_parent = PropertyParent::XElement;
            }
            33 => {
                // XGEOMETRY record
                debug!("XGEOMETRY record");

                // TODO: This is neither complete nor correct.

                property_parent = PropertyParent::XGeometry;
                
                unimplemented!("XGEOMETRY record is not supported yet.")
            }
            _ => unimplemented!("Unsupported record type.")
        }
    }

    // Resolve property forward references.
    // if let Some(forward_references) = state.m_property_name_forward_references.remove(&prop_name_id) {
    for (prop_name_id, forward_references) in state.m_property_name_forward_references.drain() {
        let property_name = state.m_propnames.get(&prop_name_id).unwrap();
        debug!("Resolve {} forward references '{}=>{}'.",
               forward_references.len(),
               prop_name_id,
               &property_name);
        for (property_parent, property_values) in forward_references {
            set_property(&layout, &property_parent, &property_name, &property_values,
                         &state.m_propstrings);
        }
    }

    // Check for cells that never had their name defined.
    if !state.m_cell_names_forward_references.is_empty() {
        error!("Some cell name forward references where not resolved.");
        return Err(OASISReadError::UnresolvedForwardReferences(
            state.m_cell_names_forward_references.keys().copied().collect()
        ));
    }

    debug_assert!(placement_cell_forward_references.is_empty(),
                  "Some forward references have never been resolved.");

    // Check that all property forward reference have been resolved.
    if !state.m_property_name_forward_references.is_empty() {
        error!("Some property name forward references where not resolved.");
        return Err(OASISReadError::UnresolvedForwardReferences(
            state.m_property_name_forward_references.keys().copied().collect()
        ));
    }

    Ok(())
}