guitarpro 0.3.0

Rust library and command line interface (CLI) for guitar tab files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
use std::collections::HashMap;

use crate::error::{GpError, GpResult, ToPrimitiveGp};
use crate::{
    io::primitive::*,
    model::{enums::*, key_signature::*, song::*},
};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Version {
    pub data: String,
    pub number: (u8, u8, u8),
    pub clipboard: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Clipboard {
    pub start_measure: i32,
    pub stop_measure: i32,
    pub start_track: i32,
    pub stop_track: i32,
    pub start_beat: i32,
    pub stop_beat: i32,
    pub sub_bar_copy: bool,
}
impl Default for Clipboard {
    fn default() -> Self {
        Clipboard {
            start_measure: 1,
            stop_measure: 1,
            start_track: 1,
            stop_track: 1,
            start_beat: 1,
            stop_beat: 1,
            sub_bar_copy: false,
        }
    }
}

#[derive(Debug, Clone)]
pub struct MeasureHeader {
    pub number: u16,
    pub start: i64,
    pub time_signature: TimeSignature,
    pub tempo: i32,
    pub marker: Option<Marker>,
    pub repeat_open: bool,
    pub repeat_alternative: u8,
    pub repeat_close: i8,
    pub triplet_feel: TripletFeel,
    pub direction: Option<DirectionSign>,
    /// Tonality of the measure
    pub key_signature: KeySignature,
    pub double_bar: bool,
    /// Fermatas from GPIF (GP6/GP7)
    pub fermatas: Vec<(String, String)>,
    /// Free time (no metronome) from GPIF (GP6/GP7)
    pub free_time: bool,
}
impl Default for MeasureHeader {
    fn default() -> Self {
        MeasureHeader {
            number: 1,
            start: DURATION_QUARTER_TIME,
            tempo: 0,
            repeat_open: false,
            repeat_alternative: 0,
            repeat_close: -1,
            triplet_feel: TripletFeel::None,
            direction: None,
            key_signature: KeySignature::default(),
            double_bar: false,
            marker: None,
            time_signature: TimeSignature {
                numerator: 4,
                denominator: Duration::default(),
                beams: vec![2, 2, 2, 2],
            },
            fermatas: Vec::new(),
            free_time: false,
        }
    }
}
impl MeasureHeader {
    #[allow(dead_code)]
    pub(crate) fn length(&self) -> GpResult<i64> {
        Ok(self
            .time_signature
            .numerator
            .to_i64_gp("time_signature.numerator")?
            * crate::model::key_signature::DURATION_QUARTER_TIME
            * 4
            / self
                .time_signature
                .denominator
                .value
                .to_i64_gp("time_signature.denominator.value")?)
    }
    pub(crate) fn _end(&self) -> GpResult<i64> {
        Ok(self.start + self.length()?)
    }
}

/// A marker annotation for beats.
#[derive(Debug, Clone)]
pub struct Marker {
    pub title: String,
    pub color: i32,
}
impl Default for Marker {
    fn default() -> Self {
        Marker {
            title: "Section".to_owned(),
            color: 0xff0000,
        }
    }
}
/// Read a marker. The markers are written in two steps:
/// - first is written an integer equal to the marker's name length + 1
/// - then a string containing the marker's name. Finally the marker's color is written.
fn read_marker(data: &[u8], seek: &mut usize) -> GpResult<Marker> {
    let mut marker = Marker {
        title: read_int_size_string(data, seek)?,
        ..Default::default()
    };
    marker.color = read_color(data, seek)?;
    Ok(marker)
}

/// This class can store the information about a group of measures which are repeated.
#[derive(Debug, Clone, Default)]
pub struct RepeatGroup {
    /// List of measure header indexes.
    pub measure_headers: Vec<usize>,
    pub closings: Vec<usize>,
    pub openings: Vec<usize>,
    pub is_closed: bool,
}

pub trait SongHeaderOps {
    fn _add_measure_header(&mut self, header: MeasureHeader);
    fn read_clipboard(&mut self, data: &[u8], seek: &mut usize) -> GpResult<Option<Clipboard>>;
    fn read_measure_headers(
        &mut self,
        data: &[u8],
        seek: &mut usize,
        measure_count: usize,
    ) -> GpResult<()>;
    fn read_measure_headers_v5(
        &mut self,
        data: &[u8],
        seek: &mut usize,
        measure_count: usize,
        directions: &(HashMap<DirectionSign, i16>, HashMap<DirectionSign, i16>),
    ) -> GpResult<()>;
    fn read_measure_header(
        &mut self,
        data: &[u8],
        seek: &mut usize,
        number: usize,
        previous: Option<MeasureHeader>,
    ) -> GpResult<(MeasureHeader, u8)>;
    fn read_measure_header_v5(
        &mut self,
        data: &[u8],
        seek: &mut usize,
        number: usize,
        previous: Option<MeasureHeader>,
    ) -> GpResult<(MeasureHeader, u8)>;
    fn read_repeat_alternative(&mut self, data: &[u8], seek: &mut usize) -> GpResult<u8>;
    fn read_repeat_alternative_v5(&mut self, data: &[u8], seek: &mut usize) -> GpResult<u8>;
    fn read_directions(
        &self,
        data: &[u8],
        seek: &mut usize,
    ) -> GpResult<(HashMap<DirectionSign, i16>, HashMap<DirectionSign, i16>)>;
    fn write_measure_headers(&self, data: &mut Vec<u8>, version: &(u8, u8, u8)) -> GpResult<()>;
    fn write_measure_header(
        &self,
        data: &mut Vec<u8>,
        header: usize,
        previous: Option<usize>,
        version: &(u8, u8, u8),
    ) -> GpResult<()>;
    fn write_clipboard(&self, data: &mut Vec<u8>, version: &(u8, u8, u8)) -> GpResult<()>;
    fn write_directions(&self, data: &mut Vec<u8>) -> GpResult<()>;
}

impl SongHeaderOps for Song {
    fn _add_measure_header(&mut self, header: MeasureHeader) {
        // if the group is closed only the next upcoming header can reopen the group in case of a repeat alternative, so we remove the current group
        //TODO: if header.repeat_open or self.current_repeat_group.is_closed && header.repeat_alternative <= 0 {self.current_repeat_group = RepeatGroup::default();}
        self.measure_headers.push(header);
    }

    fn read_clipboard(&mut self, data: &[u8], seek: &mut usize) -> GpResult<Option<Clipboard>> {
        if !self.version.clipboard {
            return Ok(None);
        }
        let mut c = Clipboard {
            start_measure: read_int(data, seek)?,
            ..Default::default()
        };
        c.stop_measure = read_int(data, seek)?;
        c.start_track = read_int(data, seek)?;
        c.stop_track = read_int(data, seek)?;
        if self.version.number.0 == 5 {
            c.start_beat = read_int(data, seek)?;
            c.stop_beat = read_int(data, seek)?;
            c.sub_bar_copy = read_int(data, seek)? != 0;
        }
        println!("read_clipboard(): {:?}", c);
        Ok(Some(c))
    }

    /// Read measure headers. The *measures* are written one after another, their number have been specified previously.
    /// * `measure_count`: number of measures to expect.
    fn read_measure_headers(
        &mut self,
        data: &[u8],
        seek: &mut usize,
        measure_count: usize,
    ) -> GpResult<()> {
        //println!("read_measure_headers()");
        let mut previous: Option<MeasureHeader> = None;
        for i in 1..measure_count + 1 {
            let r: (MeasureHeader, u8) = self.read_measure_header(data, seek, i, previous)?;
            previous = Some(r.0.clone());
            self.measure_headers.push(r.0); //TODO: use add_measure_header
        }
        Ok(())
    }

    fn read_measure_headers_v5(
        &mut self,
        data: &[u8],
        seek: &mut usize,
        measure_count: usize,
        directions: &(HashMap<DirectionSign, i16>, HashMap<DirectionSign, i16>),
    ) -> GpResult<()> {
        //println!("read_measure_headers_v5()");
        let mut previous: Option<MeasureHeader> = None;
        for i in 1..measure_count + 1 {
            let r: (MeasureHeader, u8) = self.read_measure_header_v5(data, seek, i, previous)?;
            previous = Some(r.0.clone());
            self.measure_headers.push(r.0); //TODO: use add_measure_header
        }
        for s in &directions.0 {
            if s.1 > &-1 {
                self.measure_headers[s.1.to_usize_gp("direction measure index")? - 1].direction =
                    Some(s.0.clone());
            }
        }
        for s in &directions.1 {
            if s.1 > &-1 {
                self.measure_headers[s.1.to_usize_gp("direction measure index")? - 1].direction =
                    Some(s.0.clone());
            }
        }
        Ok(())
    }

    /// Read measure header. The first byte is the measure's flags. It lists the data given in the current measure.
    ///
    /// | **Bit 7** | **Bit 6** | **Bit 5** | **Bit 4** | **Bit 3** | **Bit 2** | **Bit 1** | **Bit 0** |
    /// |-----------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|
    /// | Presence of a double bar  | Tonality of the measure  | Presence of a marker  | Number of alternate ending | End of repeat | Beginning of repeat | Denominator of the (key) signature | Numerator of the (key) signature |
    ///
    /// Each of these elements is present only if the corresponding bit is a 1. The different elements are written (if they are present) from lowest to highest bit.
    /// Exceptions are made for the double bar and the beginning of repeat whose sole presence is enough, complementary data is not necessary.
    ///
    /// * **Numerator of the (key) signature**: `byte`. Numerator of the (key) signature of the piece
    /// * **Denominator of the (key) signature**: `byte`. Denominator of the (key) signature of the piece
    /// * **End of repeat**: `byte`. Number of repeats until the previous Beginning of repeat. Nombre de renvoi jusqu'au début de renvoi précédent.
    /// * **Number of alternate ending**: `byte`. The number of alternate ending.
    /// * **Marker**: The markers are written in two steps:
    /// 1) First is written an `integer` equal to the marker's name length + 1
    /// 2) a string containing the marker's name. Finally the marker's color is written.
    /// * **Tonality of the measure**: `byte`. This value encodes a key (signature) change on the current piece. It is encoded as: `0: C`, `1: G (#)`, `2: D (##)`, `-1: F (b)`, ...
    fn read_measure_header(
        &mut self,
        data: &[u8],
        seek: &mut usize,
        number: usize,
        previous: Option<MeasureHeader>,
    ) -> GpResult<(MeasureHeader, u8)> {
        let flag = read_byte(data, seek)?;
        //println!("read_measure_header(), flags: {} \t N: {} \t Measure header count: {}", flag, number, self.measure_headers.len());
        let mut mh = MeasureHeader {
            number: number.to_u16_gp("measure number")?,
            ..Default::default()
        };
        mh.start = 0;
        mh.triplet_feel = self.triplet_feel.clone(); //TODO: use ref & lifetime
        //we need a previous header for the next 2 flags
        //Numerator of the (key) signature
        if (flag & 0x01) == 0x01 {
            mh.time_signature.numerator = read_signed_byte(data, seek)?;
        } else if number > 1 {
            mh.time_signature.numerator = previous
                .clone()
                .ok_or(GpError::MissingState {
                    field: "previous_measure_header",
                })?
                .time_signature
                .numerator;
        }
        //Denominator of the (key) signature
        if (flag & 0x02) == 0x02 {
            mh.time_signature.denominator.value =
                read_signed_byte(data, seek)?.to_u16_gp("time_signature denominator value")?;
        } else if number > 1 {
            mh.time_signature.denominator = previous
                .clone()
                .ok_or(GpError::MissingState {
                    field: "previous_measure_header",
                })?
                .time_signature
                .denominator;
        }

        mh.repeat_open = (flag & 0x04) == 0x04; //Beginning of repeat
        if (flag & 0x08) == 0x08 {
            mh.repeat_close = read_signed_byte(data, seek)?;
        } //End of repeat
        if (flag & 0x10) == 0x10 {
            mh.repeat_alternative = if self.version.number.0 == 5 {
                self.read_repeat_alternative_v5(data, seek)?
            } else {
                self.read_repeat_alternative(data, seek)?
            };
        } //Number of alternate ending
        if (flag & 0x20) == 0x20 {
            mh.marker = Some(read_marker(data, seek)?);
        } //Presence of a marker
        if (flag & 0x40) == 0x40 {
            //Tonality of the measure
            mh.key_signature.key = read_signed_byte(data, seek)?;
            mh.key_signature.is_minor = read_signed_byte(data, seek)? != 0;
        } else if mh.number > 1 {
            mh.key_signature = previous
                .ok_or(GpError::MissingState {
                    field: "previous_measure_header",
                })?
                .key_signature;
        }
        mh.double_bar = (flag & 0x80) == 0x80; //presence of a double bar
        Ok((mh, flag))
    }
    /// Read measure header. Measure header format in Guitar Pro 5 differs from one if Guitar Pro 3.
    ///
    /// First, there is a blank byte if measure is not first. Then measure header is read as in GP3's `read_measure_header_v3()`. Then measure header is read as follows:
    /// - Time signature beams: 4 `Bytes <byte>`. Appears If time signature was set, i.e. flags *0x01* and *0x02* are both set.
    /// - Blank `byte` if flag at *0x10* is set.
    /// - Triplet feel: `byte`. See `TripletFeel`.
    fn read_measure_header_v5(
        &mut self,
        data: &[u8],
        seek: &mut usize,
        number: usize,
        previous: Option<MeasureHeader>,
    ) -> GpResult<(MeasureHeader, u8)> {
        if previous.is_some() {
            *seek += 1;
        } //always
        let r = self.read_measure_header(data, seek, number, previous.clone())?;
        let mut mh = r.0;
        let flags = r.1;
        //println!("read_measure_header_v5(), flags: {}", flags);
        if mh.repeat_close > -1 {
            mh.repeat_close -= 1;
        }
        if (flags & 0x03) == 0x03 {
            for i in 0..4 {
                mh.time_signature.beams[i] = read_byte(data, seek)?;
            }
        } else {
            mh.time_signature.beams = previous
                .ok_or(GpError::MissingState {
                    field: "previous_measure_header",
                })?
                .time_signature
                .beams;
        };
        if (flags & 0x10) == 0 {
            *seek += 1;
        } //always 0
        mh.triplet_feel = get_triplet_feel(read_byte(data, seek)?.to_i8_gp("triplet feel byte")?)?;
        //println!("################################### {:?}", mh.triplet_feel);
        Ok((mh, flags))
    }

    fn read_repeat_alternative(&mut self, data: &[u8], seek: &mut usize) -> GpResult<u8> {
        //println!("read_repeat_alternative()");
        let value = read_byte(data, seek)?.to_u16_gp("repeat alternative value")?;
        let mut existing_alternative = 0u16;
        for i in (0..self.measure_headers.len()).rev() {
            if self.measure_headers[i].repeat_open {
                break;
            }
            existing_alternative |= self.measure_headers[i]
                .repeat_alternative
                .to_u16_gp("repeat_alternative")?;
        }
        //println!("read_repeat_alternative(), value:  {}, existing_alternative: {}", value, existing_alternative);
        //println!("read_repeat_alternative(), return: {}", ((1 << value) - 1) ^ existing_alternative);
        (((1 << value) - 1) ^ existing_alternative).to_u8_gp("repeat alternative result")
    }
    fn read_repeat_alternative_v5(&mut self, data: &[u8], seek: &mut usize) -> GpResult<u8> {
        read_byte(data, seek)
    }

    /// Read directions.  Directions is a list of 19 `ShortInts <short>` each pointing at the number of measure.
    ///
    /// Directions are read in the following order:
    /// - Coda
    /// - Double Coda
    /// - Segno
    /// - Segno Segno
    /// - Fine
    /// - Da Capo
    /// - Da Capo al Coda
    /// - Da Capo al Double Coda
    /// - Da Capo al Fine
    /// - Da Segno
    /// - Da Segno al Coda
    /// - Da Segno al Double Coda
    /// - Da Segno al Fine
    /// - Da Segno Segno
    /// - Da Segno Segno al Coda
    /// - Da Segno Segno al Double Coda
    /// - Da Segno Segno al Fine
    /// - Da Coda
    /// - Da Double Coda
    fn read_directions(
        &self,
        data: &[u8],
        seek: &mut usize,
    ) -> GpResult<(HashMap<DirectionSign, i16>, HashMap<DirectionSign, i16>)> {
        let mut signs: HashMap<DirectionSign, i16> = HashMap::with_capacity(4);
        let mut from_signs: HashMap<DirectionSign, i16> = HashMap::with_capacity(15);
        //signs
        signs.insert(DirectionSign::Coda, read_short(data, seek)?);
        signs.insert(DirectionSign::DoubleCoda, read_short(data, seek)?);
        signs.insert(DirectionSign::Segno, read_short(data, seek)?);
        signs.insert(DirectionSign::SegnoSegno, read_short(data, seek)?);
        signs.insert(DirectionSign::Fine, read_short(data, seek)?);
        //from signs
        from_signs.insert(DirectionSign::DaCapo, read_short(data, seek)?);
        from_signs.insert(DirectionSign::DaCapoAlCoda, read_short(data, seek)?);
        from_signs.insert(DirectionSign::DaCapoAlDoubleCoda, read_short(data, seek)?);
        from_signs.insert(DirectionSign::DaCapoAlFine, read_short(data, seek)?);
        from_signs.insert(DirectionSign::DaSegno, read_short(data, seek)?);
        from_signs.insert(DirectionSign::DaSegnoAlCoda, read_short(data, seek)?);
        from_signs.insert(DirectionSign::DaSegnoAlDoubleCoda, read_short(data, seek)?);
        from_signs.insert(DirectionSign::DaSegnoAlFine, read_short(data, seek)?);
        from_signs.insert(DirectionSign::DaSegnoSegno, read_short(data, seek)?);
        from_signs.insert(DirectionSign::DaSegnoSegnoAlCoda, read_short(data, seek)?);
        from_signs.insert(
            DirectionSign::DaSegnoSegnoAlDoubleCoda,
            read_short(data, seek)?,
        );
        from_signs.insert(DirectionSign::DaSegnoSegnoAlFine, read_short(data, seek)?);
        from_signs.insert(DirectionSign::DaCoda, read_short(data, seek)?);
        from_signs.insert(DirectionSign::DaDoubleCoda, read_short(data, seek)?);
        Ok((signs, from_signs))
    }

    fn write_measure_headers(&self, data: &mut Vec<u8>, version: &(u8, u8, u8)) -> GpResult<()> {
        let mut previous: Option<usize> = None;
        for i in 0..self.measure_headers.len() {
            //self.current_measure_number = Some(self.tracks[0].measures[i].number);
            self.write_measure_header(data, i, previous, version)?;
            previous = Some(i);
        }
        Ok(())
    }

    fn write_measure_header(
        &self,
        data: &mut Vec<u8>,
        header: usize,
        previous: Option<usize>,
        version: &(u8, u8, u8),
    ) -> GpResult<()> {
        //pack measure header flags
        let mut flags: u8 = 0x00;
        if let Some(p) = previous {
            if self.measure_headers[header].time_signature.numerator
                != self.measure_headers[p].time_signature.numerator
            {
                flags |= 0x01;
            }
            if self.measure_headers[header]
                .time_signature
                .denominator
                .value
                != self.measure_headers[p].time_signature.denominator.value
            {
                flags |= 0x02;
            }
        } else {
            flags |= 0x01;
            flags |= 0x02;
        }
        if self.measure_headers[header].repeat_open {
            flags |= 0x04;
        }
        if self.measure_headers[header].repeat_close > -1 {
            flags |= 0x08;
        }
        if self.measure_headers[header].repeat_alternative > 0 {
            flags |= 0x10;
        }
        if self.measure_headers[header].marker.is_some() {
            flags |= 0x20;
        }
        if self.measure_headers[header].double_bar {
            flags |= 0x80;
        }
        if version.0 >= 4 {
            if previous.is_none() {
                flags |= 0x40;
            } else if let Some(p) = previous {
                if self.measure_headers[header].key_signature
                    != self.measure_headers[p].key_signature
                {
                    flags |= 0x40;
                }
            }
        }
        if version.0 >= 5 {
            if let Some(p) = previous {
                if self.measure_headers[header].time_signature
                    != self.measure_headers[p].time_signature
                {
                    flags |= 0x03;
                }
                write_placeholder_default(data, 1);
            }
        }
        //end pack
        //write measure header values
        write_byte(data, flags);
        if (flags & 0x01) == 0x01 {
            write_signed_byte(data, self.measure_headers[header].time_signature.numerator);
        }
        if (flags & 0x02) == 0x02 {
            write_signed_byte(
                data,
                self.measure_headers[header]
                    .time_signature
                    .denominator
                    .value
                    .to_i8_gp("denominator value")?,
            );
        }
        if (flags & 0x08) == 0x08 {
            write_signed_byte(
                data,
                if version.0 < 5 {
                    self.measure_headers[header].repeat_close
                } else {
                    self.measure_headers[header].repeat_close + 1
                },
            );
        }
        if (flags & 0x10) == 0x10 {
            //write repeat alternative
            if version.0 == 5 {
                write_byte(data, self.measure_headers[header].repeat_alternative);
            } else {
                let ra = self.measure_headers[header].repeat_alternative;
                let mut first_one = false;
                let mut out: u8 = 0;
                for i in 0u8..9 - ra.leading_zeros().to_u8_gp("leading zeros")? {
                    out = i;
                    if (ra as u16 & (1u16 << i)) > 0 {
                        first_one = true;
                    } else if first_one {
                        break;
                    }
                }
                write_byte(data, out);
            }
        }
        if (flags & 0x20) == 0x20 {
            //write marker
            if let Some(marker) = &self.measure_headers[header].marker {
                write_int_size_string(data, &marker.title);
                write_color(data, marker.color);
            }
        }
        if version.0 >= 4 && (flags & 0x40) == 0x40 {
            write_signed_byte(data, self.measure_headers[header].key_signature.key);
            write_signed_byte(
                data,
                i8::from(self.measure_headers[header].key_signature.is_minor),
            );
        }
        if version.0 >= 5 {
            if (flags & 0x03) == 0x03 {
                for i in 0..self.measure_headers[header].time_signature.beams.len() {
                    write_byte(data, self.measure_headers[header].time_signature.beams[i]);
                }
            }
            if (flags & 0x10) == 0 {
                write_placeholder_default(data, 1);
            }
            write_byte(
                data,
                from_triplet_feel(&self.measure_headers[header].triplet_feel),
            );
        }
        Ok(())
    }

    fn write_clipboard(&self, data: &mut Vec<u8>, version: &(u8, u8, u8)) -> GpResult<()> {
        if let Some(c) = &self.clipboard {
            write_i32(data, c.start_measure.to_i32_gp("clipboard start_measure")?);
            write_i32(data, c.stop_measure.to_i32_gp("clipboard stop_measure")?);
            write_i32(data, c.start_track.to_i32_gp("clipboard start_track")?);
            write_i32(data, c.stop_track.to_i32_gp("clipboard stop_track")?);
            if version.0 == 5 {
                write_i32(data, c.start_beat.to_i32_gp("clipboard start_beat")?);
                write_i32(data, c.stop_beat.to_i32_gp("clipboard stop_beat")?);
                write_i32(data, i32::from(c.sub_bar_copy));
            }
        }
        Ok(())
    }
    fn write_directions(&self, data: &mut Vec<u8>) -> GpResult<()> {
        let mut map: HashMap<DirectionSign, i16> = HashMap::with_capacity(19);
        for i in 0..self.measure_headers.len() {
            if let Some(d) = &self.measure_headers[i].direction {
                map.insert(d.clone(), (i + 1).to_i16_gp("direction measure index")?);
            }
        }
        let order: Vec<DirectionSign> = vec![
            DirectionSign::Coda,
            DirectionSign::DoubleCoda,
            DirectionSign::Segno,
            DirectionSign::SegnoSegno,
            DirectionSign::Fine,
            DirectionSign::DaCapo,
            DirectionSign::DaCapoAlCoda,
            DirectionSign::DaCapoAlDoubleCoda,
            DirectionSign::DaCapoAlFine,
            DirectionSign::DaSegno,
            DirectionSign::DaSegnoAlCoda,
            DirectionSign::DaSegnoAlDoubleCoda,
            DirectionSign::DaSegnoAlFine,
            DirectionSign::DaSegnoSegno,
            DirectionSign::DaSegnoSegnoAlCoda,
            DirectionSign::DaSegnoSegnoAlDoubleCoda,
            DirectionSign::DaSegnoSegnoAlFine,
            DirectionSign::DaCoda,
            DirectionSign::DaDoubleCoda,
        ];
        for d in order {
            let x = map.get(&d);
            if let Some(dir) = x {
                write_i16(data, *dir);
            } else {
                write_i16(data, -1);
            }
        }
        Ok(())
    }
}