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
#![deny(missing_docs)]
//! This crate (codenano) allows one to design DNA molecules.
//!
//! The following creates a strand zig-zagging between three helices,
//! and outputs it to a file:
//!
//! ```
//! use codenano::*;
//! let mut design: Design<(), ()> = Design::new();
//! for i in 0..3 {
//!    design.add_grid_helix(i, 0);
//! }
//! // Let's first design a strand.
//! design.strand(0, 0).to(31)
//!   .cross(1).to(10)
//!   .cross(2).to(21);
//! // Now its reverse complement:
//! design.strand(2, 21).to(10)
//!    .cross(1).to(31)
//!    .cross(0).to(0);
//! design.write_to("my_design.json").unwrap()
//! ```
//!
//! This library is compatible with the `codenano-server` crate, which
//! watches changes made to a file and shows the result in 3D in a web
//! browser. Additionally, the client part (also called codenano) of the the `codenano-server`crate can run
//! finite element simulations and display the secondary structure.

#[macro_use]
extern crate serde_derive;
extern crate failure;
extern crate serde;

pub use failure::Error;
use std::borrow::Cow;
use std::collections::HashMap;
use std::f64::consts::PI;

/// 3D points and vectors
pub mod geometry;
use crate::geometry::*;

/// Extra tools for sequences (random completions, etc.)
pub mod sequences;

/// Conversion to Cadnano format.
pub mod cadnano;

/// The main type of this crate, describing a DNA design.
#[derive(Serialize, Deserialize)]
pub struct Design<StrandLabel, DomainLabel> {
    /// Version of this format.
    pub version: String,
    /// The vector of all helices used in this design. Helices have a
    /// position and an orientation in 3D.
    pub helices: Vec<Helix>,
    /// The vector of strands.
    pub strands: Vec<Strand<StrandLabel, DomainLabel>>,
    /// Parameters of DNA geometry. This can be skipped (in JSON), or
    /// set to `None` in Rust, in which case a default set of
    /// parameters from the literature is used.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub parameters: Option<Parameters>,
}

fn is_false(x: &bool) -> bool {
    !*x
}

fn none<Label>() -> Option<Label> {
    None
}

/// A DNA strand.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Strand<Label, DomainLabel> {
    /// The (ordered) vector of domains, where each domain is a
    /// directed interval of a helix.
    pub domains: Vec<Domain<DomainLabel>>,
    /// The sequence of this strand, if any. If the sequence is longer
    /// than specified by the domains, a prefix is assumed. Can be
    /// skipped in the serialisation.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub sequence: Option<Cow<'static, str>>,
    /// Is this sequence cyclic? Can be skipped (and defaults to
    /// `false`) in the serialization.
    #[serde(skip_serializing_if = "is_false", default)]
    pub cyclic: bool,
    /// Colour of this strand. If skipped, a default colour will be
    /// chosen automatically.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub color: Option<u32>,
    /// An optional label for the strand. Can be
    /// `serde_json::Value::Null`, and skipped in the serialisation.
    #[serde(skip_serializing_if = "Option::is_none", default = "none")]
    pub label: Option<Label>,
}

impl<Label, DomainLabel> Strand<Label, DomainLabel> {
    /// Find the nucl-th nucleotide of the strand. Output is (h, x, b) so that the nucl-th nucleotide
    /// of the strand is on helix h at position x with orientation b.
    pub fn find_nucl(&self, nucl: isize) -> (isize, isize, bool) {
        let mut current = 0;
        let mut i = 0;
        while current + &self.domains[i].length() <= nucl {
            current += &self.domains[i].length();
            i += 1;
        }
        let position = if self.domains[i].right {
            self.domains[i].start + nucl - current
        } else {
            self.domains[i].end - 1 - nucl + current
        };
        (self.domains[i].helix, position, self.domains[i].right)
    }
}



/// A domain, i.e. an interval of a helix.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Domain<Label> {
    /// Index of the helix in the array of helices. Indices start at
    /// 0.
    pub helix: isize,
    /// Position of the leftmost base of this domain along the helix
    /// (this might be the first or last base of the domain, depending
    /// on the `orientation` parameter below).
    pub start: isize,
    /// Position of the first base after the rightmost base of the
    /// domain, along the helix. Domains must always be such that
    /// `domain.start < domain.end`.
    pub end: isize,
    /// If true, the "5' to 3'" direction of this domain runs in the
    /// same direction as the helix, i.e. "to the right" along the
    /// axis of the helix. Else, the 5' to 3' runs to the left along
    /// the axis.
    pub right: bool,
    /// An optional label that can be attached to strands.
    #[serde(skip_serializing_if = "Option::is_none", default = "none")]
    pub label: Option<Label>,
    /// In addition to the strand-level sequence, individual domains
    /// may have sequences too. The precedence has to be defined by
    /// the user of this library.
    pub sequence: Option<Cow<'static, str>>,
}

impl<Label> Domain<Label> {
    /// Iterate through the positions of this domain, in 5' to 3'
    /// order (meaning that the values produced by this iterator might
    /// be increasing or decreasing).
    pub fn iter(&self) -> DomainIter {
        DomainIter {
            start: self.start,
            end: self.end,
            right: self.right,
        }
    }
    /// Translate this domain. The first parameter is the translation
    /// along the helix, the second one is a translation across
    /// helices (probably most meaningful for a flat design).
    pub fn translate(self, dx: isize, dy: isize) -> Self {
        use std::convert::TryFrom;
        Domain {
            start: self.start + dx,
            end: self.end + dx,
            helix: usize::try_from(self.helix as isize + dy).unwrap() as isize,
            ..self
        }
    }
    /// Translate this domain along its helix.
    pub fn shift_x(self, dx: isize) -> Self {
        Domain {
            start: self.start + dx,
            end: self.end + dx,
            ..self
        }
    }
    /// Translate this domain to a different helix (probably most
    /// meaningful for a flat design).
    pub fn shift_y(self, dy: isize) -> Self {
        use std::convert::TryFrom;
        Domain {
            helix: usize::try_from(self.helix as isize + dy).unwrap() as isize,
            ..self
        }
    }

    /// Number of Nucleotides on the domain
    pub fn length(&self) -> isize {
        self.end - self.start
    }
}

/// An iterator over all positions of a domain.
pub struct DomainIter {
    start: isize,
    end: isize,
    right: bool,
}

impl Iterator for DomainIter {
    type Item = isize;
    fn next(&mut self) -> Option<Self::Item> {
        if self.start == self.end {
            None
        } else {
            if self.right {
                let s = self.start;
                self.start += 1;
                Some(s)
            } else {
                let s = self.end;
                self.end -= 1;
                Some(s - 1)
            }
        }
    }
}

/// The sequence of the M13 bacteriophage, used for example for DNA
/// Origami.
pub const M13_7249: &'static str = include_str!("m13");
/// A cut version of the M13, which can be obtained with enzymes from
/// the original genome (the `M13_7249` one).
pub const M13_594: &'static str = include_str!("m13_594");

/// DNA geometric parameters.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct Parameters {
    /// Distance between two consecutive bases along the axis of a
    /// helix, in nanometers.
    pub z_step: f64,
    /// Radius of a helix, in nanometers.
    pub helix_radius: f64,
    /// Number of bases per turn in nanometers.
    pub bases_per_turn: f64,
    /// Minor groove angle. DNA helices have a "minor groove" and a
    /// "major groove", meaning that two paired nucleotides are not at
    /// opposite positions around a double helix (i.e. at an angle of
    /// 180°), but instead have a different angle.
    ///
    /// Strands are directed. The "normal" direction is called "5' to
    /// 3'" (named after parts of the nucleotides). This parameter is
    /// the small angle, which is clockwise from the normal strand to
    /// the reverse strand.
    pub groove_angle: f64,

    /// Gap between two neighbouring helices.
    pub inter_helix_gap: f64,
}

impl Default for Parameters {
    fn default() -> Self {
        Parameters {
            // z-step and helix radius from:
            //
            // Single-molecule portrait of DNA and RNA double helices,
            // J. Ricardo Arias-Gonzalez, Integrative Biology, Royal
            // Society of Chemistry, 2014, vol. 6, p.904
            z_step: 0.332,
            helix_radius: 1.,
            // bases per turn from Wu Rothemund (Nature Chemistry).
            bases_per_turn: 10.44,
            groove_angle: -24. * PI / 34.,
            // From Paul's paper.
            inter_helix_gap: 1.,
        }
    }
}

/// A DNA helix. All bases of all strands must be on a helix.
///
/// The three angles are illustrated in the following image, from [the NASA website](https://www.grc.nasa.gov/www/k-12/airplane/rotations.html):
///
/// ![Aircraft angles](https://www.grc.nasa.gov/www/k-12/airplane/Images/rotations.gif)
#[derive(Serialize, Deserialize)]
pub struct Helix {
    /// Position of the origin of the helix axis.
    pub origin: Point<f64>,

    /// Angle around the axis of the helix.
    pub roll: f64,

    /// Horizontal rotation.
    pub yaw: f64,

    /// Vertical rotation.
    pub pitch: f64,
}

impl Helix {
    /// Angle of base number `n` around this helix.
    pub fn theta(&self, n: isize, right: bool, cst: &Parameters) -> f64 {
        let shift = if right {
            cst.groove_angle
        } else {
            0.
        };
        n as f64 * 2. * PI / cst.bases_per_turn + shift + self.roll
    }

    /*
    // Return `R(y,theta)*point` where `R(u,theta)` is the matrix of the rotation of axis u and
    // angle theta and `*` is a matrix,vector multiplication
    fn ry(point: &[f64], theta: f64) -> [f64; 3] {
        [
            point[0] * theta.cos() + point[2] * theta.sin(),
            point[1],
            point[0] * -theta.sin() + point[2] * theta.cos(),
        ]
    }

    // Return `R(z,theta)*point` where `R(u,theta)` is the matrix of the rotation of axis u and
    // angle theta and `*` is a matrix,vector multiplication
    fn rz(point: &[f64], theta: f64) -> [f64; 3] {
        [
            point[0] * theta.cos() + point[1] * -theta.sin(),
            point[0] * theta.sin() + point[1] * theta.cos(),
            point[2],
        ]
    }
    */

    /// 3D position of a nucleotide on this helix. `n` is the position along the axis, and `right` is true iff the 5' to 3' direction of the strand containing that nucleotide runs in the same direction as the axis of the helix.
    pub fn space_pos(&self, p: &Parameters, n: isize, right: bool) -> [f64; 3] {
        let theta = self.theta(n, right, p);
        let mut ret = [
            n as f64 * p.z_step,
            theta.cos() * p.helix_radius,
            theta.sin() * p.helix_radius,
        ];
        
        let forward = [self.yaw.cos() * self.pitch.cos(),
                       self.pitch.sin(),
                       -self.yaw.sin() * self.pitch.cos()];
        let right = [self.yaw.sin(),
                     0.,
                     self.yaw.cos()];
        let up = [ right[1] * forward[2] - right[2] * forward[1],
                   right[2] * forward[0] - right[0] * forward[2],
                   right[0] * forward[1] - right[1] * forward[0]];

        ret = [ret[0] * forward[0] + ret[1] * up[0] + ret[2] * right[0],
         ret[0] * forward[1] + ret[1] * up[1] + ret[2] * right[1],
         ret[0] * forward[2] + ret[1] * up[2] + ret[2] * right[2],
        ];
        /*
        ret = Helix::ry(&ret, self.yaw);
        ret = Helix::rz(&ret, self.pitch);
        */
        ret[0] += self.origin.x;
        ret[1] += self.origin.y;
        ret[2] += self.origin.z;
        ret
    }

    /// 3D position of the projection of the nucleotide on its helix.
    /// `n` is the position along the axis.
    pub fn axis_pos(&self, p: &Parameters, n:isize) -> [f64; 3] {
        let mut ret = [
            n as f64 * p.z_step,
            0.,
            0.,
        ];
        
        let forward = [self.yaw.cos() * self.pitch.cos(),
                       self.pitch.sin(),
                       -self.yaw.sin() * self.pitch.cos()];
        let right = [self.yaw.sin(),
                     0.,
                     self.yaw.cos()];
        let up = [ right[1] * forward[2] - right[2] * forward[1],
                   right[2] * forward[0] - right[0] * forward[2],
                   right[0] * forward[1] - right[1] * forward[0]];

        ret = [ret[0] * forward[0] + ret[1] * up[0] + ret[2] * right[0],
         ret[0] * forward[1] + ret[1] * up[1] + ret[2] * right[1],
         ret[0] * forward[2] + ret[1] * up[2] + ret[2] * right[2],
        ];

        ret[0] += self.origin.x;
        ret[1] += self.origin.y;
        ret[2] += self.origin.z;
        ret


    }
}

/// Identity of a helix, useful for referring to it.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HelixId(pub isize);

impl From<isize> for HelixId {
    fn from(e: isize) -> Self {
        HelixId(e)
    }
}

impl From<i32> for HelixId {
    fn from(e: i32) -> Self {
        HelixId(e as isize)
    }
}

impl From<usize> for HelixId {
    fn from(e: usize) -> Self {
        HelixId(e as isize)
    }
}

/// Identity of a strand, useful for referring to it.
pub struct StrandId(pub usize);

/// This is just a communication type between the server and the
/// client, serialisable in JSON. No need to really expose it.
#[doc(hidden)]
#[derive(Serialize, Deserialize)]
pub struct Res {
    pub out: String,
    pub err: String,
}

/// A pointer to a strand being built, containing a current domain and
/// position.
pub struct StrandRef<'a, StrandLabel, DomainLabel> {
    builder: &'a mut Design<StrandLabel, DomainLabel>,
    strand_id: usize,
    x: Option<isize>,
    x0: Option<isize>,
}

impl<StrandLabel: serde::Serialize, DomainLabel: serde::Serialize>
    Design<StrandLabel, DomainLabel>
{
    /// Initiates a design.
    pub fn new() -> Self {
        Design {
            version: env!("CARGO_PKG_VERSION").to_string(),
            helices: Vec::new(),
            strands: Vec::new(),
            parameters: Some(Parameters::default()),
        }
    }

    /// Creates a flat helix (in the `z = 0` plane).
    pub fn square_grid_helix(&self, h: isize, v: isize) -> Helix {
        Helix {
            origin: Point {
                x: 0.,
                y: h as f64
                    * (self.parameters.unwrap().helix_radius * 2.
                        + self.parameters.unwrap().inter_helix_gap),
                z: v as f64
                    * (self.parameters.unwrap().helix_radius * 2.
                        + self.parameters.unwrap().inter_helix_gap),
            },
            roll: 0.,
            pitch: 0.,
            yaw: 0.,
        }
    }

    /// Creates a flat helix in the `z = 0` plane with adjusted roll.
    pub fn adjusted_grid_helix(&self, h: isize, v: isize) -> Helix {
        let delta_roll = self.parameters.unwrap().groove_angle - PI;
        Helix {
            origin: Point {
                x: 0.,
                y: h as f64
                    * (self.parameters.unwrap().helix_radius * 2.
                        + self.parameters.unwrap().inter_helix_gap),
                z: v as f64
                    * (self.parameters.unwrap().helix_radius * 2.
                        + self.parameters.unwrap().inter_helix_gap),
            },
            roll: ((h + v) as f64) * delta_roll,
            pitch: 0.,
            yaw: 0.,
        }
    }

    /// Initiates a design with the given geometric parameters.
    pub fn with_parameters(parameters: Parameters) -> Self {
        let mut b = Design::new();
        b.parameters = Some(parameters);
        b
    }

    /// Add a helix created by `Self::square_grid_helix`.
    pub fn add_grid_helix(&mut self, h: isize, v: isize) -> HelixId {
        self.helices.push(self.square_grid_helix(h, v));
        HelixId((self.helices.len() - 1) as isize)
    }

    /// Add a helix created by `Self::add_grid_helix`.
    pub fn add_adjusted_grid_helix(&mut self, h: isize, v: isize) -> HelixId {
        self.helices.push(self.adjusted_grid_helix(h, v));
        HelixId((self.helices.len() - 1) as isize)
    }


    /// Add an arbitrary helix. Parameters x,y,z are in nanometers and are the 3D coordinates
    /// of the centre of the helix. roll,pitch,yaw are in radians.  
    pub fn add_helix(
        &mut self,
        x: f64,
        y: f64,
        z: f64,
        roll: f64,
        pitch: f64,
        yaw: f64,
    ) -> HelixId {
        self.helices.push(Helix {
            origin: Point { x, y, z },
            roll,
            pitch,
            yaw,
        });
        HelixId((self.helices.len() - 1) as isize)
    }

    /// Start a strand, placing the first base at the position given
    /// by `helix` and `start`.
    pub fn strand<H: Into<HelixId>>(
        &mut self,
        helix: H,
        start: isize,
    ) -> StrandRef<StrandLabel, DomainLabel> {
        let strand_id = self.strands.len();
        self.strands.push(Strand {
            domains: vec![Domain {
                helix: helix.into().0,
                start,
                end: start,
                right: true,
                label: None,
                sequence: None,
            }],
            label: None,
            sequence: None,
            cyclic: false,
            color: None,
        });
        StrandRef {
            strand_id,
            builder: self,
            x: Some(start),
            x0: Some(start),
        }
    }

    /// Create a strand with no initial domain. Useful for adding
    /// custom domains, for example domains obtained by geometric
    /// operations from other domains.
    pub fn empty_strand(&mut self) -> StrandRef<StrandLabel, DomainLabel> {
        let strand_id = self.strands.len();
        self.strands.push(Strand {
            domains: Vec::new(),
            cyclic: false,
            color: None,
            sequence: None,
            label: None,
        });
        StrandRef {
            strand_id,
            builder: self,
            x: None,
            x0: None,
        }
    }

    /// Return a StrandRef that can build the strand `strand_id`
    pub fn get_strand_ref(&mut self, strand_id: usize) -> StrandRef<StrandLabel, DomainLabel> {
        let strand = &self.strands[strand_id];
        if strand.cyclic {
            panic!("Attempt to keep building on a cyclic strand");
        }
        let domain = &strand.domains[strand.domains.len() - 1];
        let x0 = if domain.right {
            domain.start
        } else {
            domain.end - 1
        };
        let x = if domain.right {
            domain.end - 1
        } else {
            domain.start
        };
        StrandRef {
            strand_id,
            builder: self,
            x: Some(x),
            x0: Some(x0)
        }
    }

    /// Write this design to the standard output.
    pub fn write(&self) -> Result<(), Error> {
        serde_json::to_writer(std::io::stdout(), self)?;
        Ok(())
    }

    /// Write this design to a file. If the `REMOTE` environment
    /// variable is set, write it to the standard output instead.
    pub fn write_to<P: AsRef<std::path::Path>>(&self, p: P) -> Result<(), Error> {
        if std::env::var("REMOTE").is_ok() {
            serde_json::to_writer_pretty(std::io::stdout(), &self)?
        } else {
            serde_json::to_writer_pretty(std::fs::File::create(p)?, &self)?
        }
        Ok(())
    }

    /// Tests whether all bases have different positions, and returns
    /// an offending strand else. The return format is `(helix,
    /// position, orientation, i, j)`, where `i` and `j` are the indices of
    /// two strands sharing this position.
    /// Bases that are the start/end of a cycle are not detected and do not cause their
    /// strand to be offending
    pub fn unique_positions(&self) -> Option<(isize, isize, bool, usize, usize)> {
        let mut positions = HashMap::new();
        for (i, s) in self.strands.iter().enumerate() {
            for dom in s.domains.iter() {
                for pos in dom.iter() {
                    if let Some(prev) = positions.insert((dom.helix, pos, dom.right), i) {
                        if s.cyclic {
                            // unwrap OK because we know s.domain[0] has at least one nucl
                            let j = positions.get(&(s.domains[0].helix, s.domains[0].iter().next().unwrap(),
                                s.domains[0].right));
                            if let Some(x) = j {
                                if *x == prev {
                                    continue;
                                }
                            }
                        }
                            return Some((dom.helix, pos, dom.right, i, prev));
                    }
                }
            }
        }
        None
    }


    /// Tests whether all bases have different positions, and warns the user otherwise.
    /// Write this design to a file. If the `REMOTE` environment
    /// variable is set, write it to the standard output instead.
    pub fn check_and_write_to<P: AsRef<std::path::Path>>(&self, p: P) -> Result<(), Error> {
        if let Some((helix, pos, right, i, prev)) = self.unique_positions() {
            let sens = if right { "Sens" } else { "AntiSens" };
            println!("WARNING: SOME STRANDS ARE CONFLICTING");
            println!("First conflict found: On helix {}, at position {}, on the {} strand",
                helix,
                pos,
                sens);
            println!("Strands number {} and {} are in conflict", i, prev);
        }
        self.write_to(p)
    }

    fn get_cross_overs(&self) -> Vec<(isize, isize, bool, isize, isize, bool)> {
        let mut ret = Vec::new();
        for s in &self.strands {
            for i in 0..(s.domains.len() - 1) {
                if s.domains[i].helix != s.domains[i + 1].helix {
                    let origin = if s.domains[i].right {
                        s.domains[i].end - 1
                    } else {
                        s.domains[i].start
                    };
                    let destination = if s.domains[i + 1].right {
                        s.domains[i + 1].start
                    } else {
                        s.domains[i + 1].end - 1
                    };
                    ret.push((s.domains[i].helix,
                              origin,
                              s.domains[i].right,
                              s.domains[i + 1].helix,
                              destination,
                              s.domains[i + 1].right));
                }
            }
        }
        ret
    }

    fn get_cross_overs_helices(&self, h1: isize, h2:isize) -> Vec<(isize, bool, isize, bool)> {
        let cross_overs = self.get_cross_overs();
        let mut ret = Vec::new();
        for (g1, x1, b1, g2, x2, b2) in cross_overs {
            if g1 == h1 && g2 == h2 {
                ret.push((x1, b1, x2, b2));
            } else if g2 == h1 && g1 == h2 {
                ret.push((x2, b2, x1, b1));
            }
        }
        ret
    }

    fn get_total_dist_helices(&self, h1: isize, h2:isize, theta: f64, phi: f64) -> f64 {
        let cross_overs = self.get_cross_overs_helices(h1, h2);
        let helix1 = Helix {
            roll: theta,
            ..self.helices[h1 as usize]
        };
        let helix2 = Helix {
            roll: phi,
            ..self.helices[h2 as usize]
        };

        let mut ret = 0.;
        //println!("cross_overs: {:?}", cross_overs);

        for (x1, b1, x2, b2) in cross_overs {
            let pos_1 = helix1.space_pos(&self.parameters.unwrap(), x1, b1);
            let pos_2 = helix2.space_pos(&self.parameters.unwrap(), x2, b2);
            ret += (pos_1[0] - pos_2[0]) * (pos_1[0] - pos_2[0]);
            ret += (pos_1[1] - pos_2[1]) * (pos_1[1] - pos_2[1]);
            ret += (pos_1[2] - pos_2[2]) * (pos_1[2] - pos_2[2]);
        }
        ret
    }

    /// Adjust the roll of two helices to minimize the distance at crossing overs
    pub fn adjust_helix(&mut self, h1: usize, h2: usize) {
        let mut theta = self.helices[h1].roll;
        let mut phi = self.helices[h2].roll;

        loop {
            let best  = self.get_total_dist_helices(h1 as isize, h2 as isize, theta, phi);
            //println!("{}, {}, {}", best, theta, phi);
            if self.get_total_dist_helices(h1 as isize, h2 as isize, theta - 0.1, phi - 0.1) < best {
                theta -= 0.1;
                phi -= 0.1;
            } else if self.get_total_dist_helices(h1 as isize, h2 as isize, theta + 0.1, phi - 0.1) < best {
                theta += 0.1;
                phi -= 0.1;
            } else if self.get_total_dist_helices(h1 as isize, h2 as isize, theta - 0.1, phi + 0.1) < best {
                theta -= 0.1;
                phi += 0.1;
            } else if self.get_total_dist_helices(h1 as isize, h2 as isize, theta + 0.1, phi + 0.1) < best {
                theta += 0.1;
                phi += 0.1;
            } else if self.get_total_dist_helices(h1 as isize, h2 as isize, theta, phi + 0.1) < best {
                phi += 0.1;
            } else if self.get_total_dist_helices(h1 as isize, h2 as isize, theta, phi - 0.1) < best {
                phi -= 0.1;
            } else if self.get_total_dist_helices(h1 as isize, h2 as isize, theta - 0.1, phi) < best {
                theta -= 0.1;
            } else if self.get_total_dist_helices(h1 as isize, h2 as isize, theta + 0.1, phi) < best {
                theta += 0.1;
            } else {
                self.helices[h1].roll = theta;
                self.helices[h2].roll = phi;
                return;
            }
        }
    }

}

// http://eleanormaclure.files.wordpress.com/2011/03/colour-coding.pdf
const KELLY: [u32; 19] = [
    // 0xF2F3F4, // White
    // 0x222222, // Black,
    0xF3C300, 0x875692, // 0xF38400, // Orange, too close to others
    0xA1CAF1, 0xBE0032, 0xC2B280, 0x848482, 0x008856, 0xE68FAC, 0x0067A5, 0xF99379, 0x604E97,
    0xF6A600, 0xB3446C, 0xDCD300, 0x882D17, 0x8DB600, 0x654522, 0xE25822, 0x2B3D26,
];

impl<StrandLabel, DomainLabel> Strand<StrandLabel, DomainLabel> {
    /// Provide a default color to the strand.
    pub fn default_color(&self) -> u32 {
        for domain in self.domains.iter() {
            let x1 = if domain.right {
                domain.end - 1
            } else {
                domain.start
            };
            let h = domain.helix as isize;
            let x = x1 + (x1 % 11) + 5 * h;
            let n = KELLY.len() as isize;
            return KELLY[(((x % n) + n) % n) as usize];
        }
        0
    }

    /// Set the color of this strand to be Kelly's nth color.
    pub fn set_kelly_color(&mut self, n: usize) {
        self.color = Some(KELLY[n % KELLY.len()]);
    }
}

impl<'a:'b, 'b, StrandLabel, DomainLabel> StrandRef<'a, StrandLabel, DomainLabel> {
    /// Retrieve the identity of the strand currently being built.
    pub fn id(&self) -> StrandId {
        StrandId(self.strand_id)
    }

    /// Return self.builder
    pub fn design(&mut self) -> &mut Design<StrandLabel, DomainLabel> {
        self.builder
    }

    /// Total (current) length of the strand being created. Adding
    /// more points will increase the length.
    pub fn len(&self) -> usize {
        self.domains()
            .iter()
            .map(|d| (d.end - d.start) as usize)
            .sum()
    }

    /// Choose a color for this strand.
    pub fn with_color(self, color: u32) -> Self {
        self.builder.strands[self.strand_id].color = Some(color);
        self
    }

    /// Choose a color for this strand.
    pub fn with_kelly_color(self, color: usize) -> Self {
        self.builder.strands[self.strand_id].color = Some(KELLY[color]);
        self
    }

    /// List the current domains of this strand (more domains can be
    /// added later).
    pub fn domains(&self) -> &[Domain<DomainLabel>] {
        &self.builder.strands[self.strand_id].domains
    }

    /// Gives a mutable pointer to the vector of domains.
    pub fn domains_mut(&mut self) -> &mut Vec<Domain<DomainLabel>> {
        &mut self.builder.strands[self.strand_id].domains
    }

    /// Push a domain onto this strand.
    pub fn push_domain(&mut self, domain: Domain<DomainLabel>) {
        self.x = Some(if domain.right {
            domain.end - 1
        } else {
            domain.start
        });
        self.builder.strands[self.strand_id].domains.push(domain);
    }

    /// Extend this strand with multiple domains.
    pub fn extend<I: Iterator<Item = Domain<DomainLabel>>>(&mut self, i: I) {
        for i in i {
            self.push_domain(i)
        }
    }

    /// Sets the sequence of this strand.
    pub fn with_sequence<I: Into<Cow<'static, str>>>(self, sequence: I) -> Self {
        self.builder.strands[self.strand_id].sequence = Some(sequence.into());
        self
    }

    /// Sets the sequence of this strand.
    pub fn with_domain_sequence<I: Into<Cow<'static, str>>>(self, sequence: I) -> Self {
        self.builder.strands[self.strand_id]
            .domains
            .last_mut()
            .unwrap()
            .sequence = Some(sequence.into());
        self
    }

    /// Move along the helix. This method can be called multiple times
    /// consecutively, but the direction of the domain is set only on
    /// the first call, subsequent calls only change the 3' end of the
    /// domain (which is the rightmost point if `self.right` is true,
    /// and the leftmost point else).
    pub fn to(mut self, x: isize) -> Self {
        let strand = self.builder.strands[self.strand_id]
            .domains
            .last_mut()
            .unwrap();
        self.x = Some(x);
        let x0 = self.x0.unwrap();
        if x > x0 {
            strand.right = true;
            strand.start = x0;
            strand.end = x + 1;
        } else {
            strand.right = false;
            strand.start = x;
            strand.end = x0 + 1;
        }
        self
    }

    /// Remove the last domain of the strand.
    pub fn pop(mut self) -> Self {
        self.builder.strands[self.strand_id].domains.pop();
        if let Some(last) = self.builder.strands[self.strand_id].domains.last() {
            self.x = Some(if last.right {
                last.end - 1
            } else {
                last.start
            })
        } else {
            self.x = None
        }
        self
    }

    /// Change the initial point of the first domain of this strand.
    pub fn rev_to(mut self, x: isize) -> Self {
        if self.builder.strands[self.strand_id].domains.is_empty() {
            return self;
        }
        let ref mut strand = self.builder.strands[self.strand_id].domains[0];
        self.x = Some(x);
        let x0 = self.x0.unwrap();
        if x > x0 {
            strand.right = true;
            strand.start = x0;
            strand.end = x + 1;
        } else {
            strand.right = false;
            strand.start = x;
            strand.end = x0 + 1;
        }
        self
    }

    /// Give a label to this strand.
    pub fn with_label<L: Into<StrandLabel>>(self, label: L) -> Self {
        self.builder.strands[self.strand_id].label = Some(label.into());
        self
    }

    /// Give a label to the most recently produced domain on this strand.
    pub fn with_domain_label<L: Into<DomainLabel>>(self, label: L) -> Self {
        self.builder.strands[self.strand_id]
            .domains
            .last_mut()
            .unwrap()
            .label = Some(label.into());
        self
    }

    /// Finish a domain, and start a new one on the same helix and at
    /// the same position.
    pub fn next_domain_to(mut self, to: isize) -> Self {
        let helix = self.builder.strands[self.strand_id]
            .domains
            .last()
            .unwrap()
            .helix;
        // If the previous domain is on the same helix.
        let (start, end, right) = if to < self.x.unwrap() {
            let n = (to, self.x.unwrap(), false);
            self.x = Some(to);
            n
        } else {
            let n = (self.x.unwrap() + 1, to + 1, true);
            self.x = Some(to);
            n
        };
        let domain = Domain {
            helix,
            start,
            end,
            right,
            label: None,
            sequence: None,
        };
        self.builder.strands[self.strand_id].domains.push(domain);
        self
    }

    /// Move the cursor to a different helix, keeping the same current
    /// position along the axis of the helix (most meaningful when the helices are in the same plane).
    pub fn cross<H: Into<HelixId>>(self, h: H) -> Self {
        let x = self.x.unwrap();
        self.cross_to(h, x)
    }

    /// Move the cursor to a different helix, at the specified
    /// position.
    pub fn cross_to<H: Into<HelixId>>(mut self, h: H, start: isize) -> Self {
        let helix = h.into().0;
        if helix >= self.builder.helices.len() as isize {
            panic!("Crossing to an undefined helix")
        }
        self.builder.strands[self.strand_id].domains.push(Domain {
            helix,
            start,
            end: start,
            right: true,
            label: None,
            sequence: None,
        });
        self.x0 = Some(start);
        self.x = Some(start);
        self
    }

    /// Compute the horizontal symmetry of this strand with respect to
    /// x-coordinate `x`.
    pub fn hflip(self, x: isize) -> Self {
        for dom in self.builder.strands[self.strand_id].domains.iter_mut() {
            let start = dom.start;
            dom.start = x - dom.end;
            dom.end = x - start;
        }
        self.builder.strands[self.strand_id].domains.reverse();
        self
    }

    /// Compute the vertical symmetry of this strand with respect to
    /// y-coordinate `y`. Most meaningful in flat designs.
    pub fn vflip<H: Into<HelixId>>(self, y: H) -> Self {
        let y = y.into();
        for dom in self.builder.strands[self.strand_id].domains.iter_mut() {
            assert!(y.0 >= dom.helix);
            dom.helix = 2 * y.0 - dom.helix
        }
        self
    }

    /// Translate this strand (all domains) to a different
    /// position. `x` is the horizontal translation (along the axis of
    /// the helices), and `y` moves between helices. Most meaningful
    /// in a flat, on-grid design.
    pub fn translate(self, x: isize, y: isize) -> Self {
        use std::convert::TryFrom;
        for dom in self.builder.strands[self.strand_id].domains.iter_mut() {
            dom.helix = usize::try_from(dom.helix as isize + y).unwrap() as isize;
            dom.start += x;
            dom.end += x;
        }
        self
    }

    /// Ends a cyclic strands.
    /// Set `self.cycle` to `true` and link the end and the start of the strand.
    pub fn cycle(self) -> () {
        let helix = self.builder.strands[self.strand_id].domains[0].helix;
        let start = self.builder.strands[self.strand_id].domains[0].start;
        let id = self.strand_id;
        self.builder.strands[id].cyclic = true;
        self.cross(helix).to(start);
    }
}

fn sequence<StrandLabel, DomainLabel>(
    positions: &HashMap<(usize, isize, bool), char>,
    strand: &Strand<StrandLabel, DomainLabel>,
) -> String {
    let mut seq = String::new();
    // println!("label = {:?}", strand.label);
    for dom in strand.domains.iter() {
        if let Some(ref s) = dom.sequence {
            seq.push_str(s);
            continue;
        }
        assert!(dom.helix >= 0);
        for pos in dom.iter() {
            seq.push(sequences::complement(
                *positions
                    .get(&(dom.helix as usize, pos, !dom.right))
                    .unwrap(),
            ))
        }
    }
    seq
}

/// Common geometric transforms on domains (most useful when working
/// on grids or partial grids).
pub mod transforms {
    use super::Domain;

    /// Rotate all the domains provided as input by 180°. This can be
    /// used on domains obtained with
    /// [`StrandRef::domains()`](../struct.StrandRef.html#method.domains)
    /// method.
    pub fn rotate<Label>(domains: &mut [Domain<Label>]) {
        let max_helix = domains.iter().map(|x| x.helix).max().unwrap();
        for dom in domains.iter_mut() {
            let start = dom.start;
            dom.start = -dom.end;
            dom.end = -start;
            dom.helix = max_helix - dom.helix;
            dom.right = !dom.right;
        }
    }

    /// Flip all the domains provided as input vertically, i.e. relative
    /// to a horizontal axis. This can be used on domains obtained
    /// with
    /// [`StrandRef::domains()`](../struct.StrandRef.html#method.domains)
    /// method.
    pub fn v_flip<Label>(domains: &mut [Domain<Label>], max_helix: isize) {
        for dom in domains.iter_mut() {
            dom.helix = max_helix - dom.helix;
        }
    }

    /// Reverse the direction of the list of domains provided as
    /// input, starting from the very last base back to the first
    /// one. This can be used on domains obtained with
    /// [`StrandRef::domains()`](../struct.StrandRef.html#method.domains)
    /// method.
    pub fn reverse<Label>(domains: &mut [Domain<Label>]) {
        for dom in domains.iter_mut() {
            dom.right = !dom.right;
        }
    }

    /// Flip all the domains provided as input horizontally,
    /// i.e. relative to a vertical axis. This can be used on domains
    /// obtained with
    /// [`StrandRef::domains()`](../struct.StrandRef.html#method.domains)
    /// method.
    pub fn h_flip<Label>(domains: &mut [Domain<Label>]) {
        for dom in domains.iter_mut() {
            let start = dom.start;
            dom.start = -dom.end;
            dom.end = -start;
        }
    }

    /// Trnsalate all the domains provided as input by the specified
    /// number of helices (parameter `dh`) and bases (parameter
    /// `dx`). This can be used on domains obtained with
    /// [`StrandRef::domains()`](../struct.StrandRef.html#method.domains)
    /// method.
    pub fn translate<Label>(domains: &mut [Domain<Label>], dh: isize, dx: isize) {
        use std::convert::TryFrom;
        for dom in domains.iter_mut() {
            dom.helix = usize::try_from(dom.helix as isize + dh).unwrap() as isize;
            dom.start += dx;
            dom.end += dx;
        }
    }
}

impl<StrandLabel, DomainLabel> Design<StrandLabel, DomainLabel> {
    fn positions(&self) -> HashMap<(usize, isize, bool), char> {
        // First add sequences to all positions
        let mut positions = HashMap::new();
        for s in self.strands.iter() {
            if let Some(ref seq) = s.sequence {
                let mut seq = seq.chars();
                for dom in s.domains.iter() {
                    if dom.helix < 0 {
                        continue;
                    }
                    for pos in dom.iter() {
                        let c = seq.next().unwrap();
                        positions.insert((dom.helix as usize, pos, dom.right), c);
                    }
                }
            }
        }
        positions
    }

    /// Output all the sequences of the strands whose sequence has not
    /// been forced.
    pub fn sequences(&self) -> Vec<String> {
        let positions = self.positions();
        let mut sequences = Vec::new();
        for s in self.strands.iter() {
            if s.sequence.is_none() {
                sequences.push(sequence(&positions, s))
            }
        }
        sequences
    }
}

#[cfg(feature = "excel")]
impl<StrandLabel: Ord + std::fmt::Display, DomainLabel>
    Design<StrandLabel, DomainLabel>
{
    /// Output plates with the sequences, ordered by label, as an
    /// Excel spreadsheet that can be ordered from [the IDT
    /// website](https://idtdna.com).
    ///
    /// All strands `s` such that `filter(s).is_some()` are included,
    /// and only those. Moreover, if `filter(s) == Some(true)`, a new
    /// plate is started if the current plate is nonempty.
    ///
    /// Moreover, strands are ran through the `filter` function in the
    /// same order as they are in `self`.
    pub fn make_plates_96<
            H: FnMut(&Strand<StrandLabel, DomainLabel>) -> usize,
        F: FnMut(&Strand<StrandLabel, DomainLabel>) -> Option<bool>,
        G: FnMut(usize) -> String,
    >(
        &mut self,
        file: &str,
        mut seq_class: H,
        mut filter: F,
        mut format: G,
    ) {
        self.strands.sort_by(|a, b| seq_class(&a).cmp(&seq_class(b)));
        let mut current_plate = 0;
        let mut current_class = 0;

        let mut plate = Plate96::new();
        let mut plates = vec![Vec::new()];
        let positions = self.positions();
        for s in self.strands.iter() {
            let class = seq_class(s);
            if class != current_class && plate.row > 0 {
                plate.incr_col();
            }

            if plate.n != current_plate {
                plates.push(Vec::new());
                current_plate = plate.n;
            }
            if let Some(x) = filter(s) {
                // println!("{:?}", plate);
                if x && (plate.row != 0 || plate.column != 0) {
                    plate.incr_plate();
                    plates.push(Vec::new());
                    current_plate = plate.n;
                }
                plates.last_mut().unwrap().push((
                    plate.column,
                    plate.row,
                    &s.label,
                    sequence(&positions, s),
                ));
                plate.incr()
            }
            current_class = class;
        }
        use simple_excel_writer::*;
        let mut wb = Workbook::create(file);
        for (i, seqs) in plates.iter().enumerate() {
            let mut sheet = wb.create_sheet(&format(i));
            sheet.add_column(Column { width: 30.0 });
            sheet.add_column(Column { width: 30.0 });
            sheet.add_column(Column { width: 30.0 });
            wb.write_sheet(&mut sheet, |sw| {
                sw.append_row(row!["Well Position", "Name", "Sequence"])?;
                for &(col, row, label, ref seq) in seqs.iter() {
                    let row = (b'A' + row as u8) as char;
                    let label = if let Some(ref label) = label {
                        format!("{}", label)
                    } else {
                        format!("{}{}", row, col + 1)
                    };
                    sw.append_row(row![
                        format!("{}{}", row, col + 1).as_str(),
                        label.as_str(),
                        seq.as_str()
                    ])?
                }
                Ok(())
            })
            .unwrap()
        }
        wb.close().unwrap();
    }
}

#[cfg(feature = "excel")]
#[derive(Debug, Copy, Clone)]
/// Representation of a 96-well plate being filled. Plates are filled
/// from top to bottom (i.e. rows are incremented first), then from
/// left to right (columns are incremented).
pub struct Plate96 {
    /// Plate number.
    pub n: usize,
    /// Column number.
    pub column: usize,
    /// Row number.
    pub row: usize,
}

#[cfg(feature = "excel")]
impl Plate96 {
    /// Create a plate
    pub fn new() -> Self {
        Plate96 {
            n: 0,
            column: 0,
            row: 0,
        }
    }
    /// Move to the next well.
    pub fn incr(&mut self) {
        self.row += 1;
        if self.row >= 8 {
            self.incr_col()
        }
    }
    /// Move to the next column.
    pub fn incr_col(&mut self) {
        self.column += 1;
        self.row = 0;
        if self.column >= 12 {
            self.incr_plate()
        }
    }
    /// Move to the next plate.
    pub fn incr_plate(&mut self) {
        self.column = 0;
        self.row = 0;
        self.n += 1;
    }
}