]> git.cworth.org Git - scherzo/blobdiff - scherzo.c
Avoid duplicating notes within note_group_t and score_staff_t
[scherzo] / scherzo.c
index a13196e5b802563f7f8906e7cd42157e5c7ed7c0..3fcae5cfb9e3e291f367b9cac94726ad6c7f4b7a 100644 (file)
--- a/scherzo.c
+++ b/scherzo.c
@@ -407,13 +407,21 @@ typedef struct analyzed_note {
 } analyzed_note_t;
 
 static int
-_compare_analyzed_note (const void *va, const void *vb)
+_compare_analyzed_note_by_midi_pitch (const void *va, const void *vb)
 {
     const analyzed_note_t *a = va, *b = vb;
 
     return a->midi_pitch - b->midi_pitch;
 }
 
+static int
+_compare_analyzed_note_by_relative_pitch (const void *va, const void *vb)
+{
+    const analyzed_note_t *a = va, *b = vb;
+
+    return a->relative_pitch - b->relative_pitch;
+}
+
 static int
 _chord_signature_matches (analyzed_note_t *notes,
                          int num_notes,
@@ -461,6 +469,10 @@ scherzo_analyze_chord (scherzo_t *scherzo)
 
     num_notes = note_group->num_notes;
 
+    struct { int pitches[1]; const char *name; } octaves[] = {
+       { {0}, "Octave"}
+    };
+
     struct { int pitches[2]; const char *name; } intervals[] = {
        { {0, 1}, "Minor 2nd"},
        { {0, 2}, "Major 2nd"},
@@ -515,16 +527,28 @@ scherzo_analyze_chord (scherzo_t *scherzo)
        notes[i].relative_pitch = 0;
     }
 
-    qsort (notes, num_notes, sizeof (analyzed_note_t), _compare_analyzed_note);
+    /* First, sort by midi pitch to find the bass note. */
+    qsort (notes, num_notes, sizeof (analyzed_note_t),
+          _compare_analyzed_note_by_midi_pitch);
     
     bass_pitch = notes[0].midi_pitch;
 
+    /* With the bass note identified, we can find all relative pitches. */
     for (i = 0; i < num_notes; i++) {
        notes[i].relative_pitch = notes[i].midi_pitch - bass_pitch;
-       while (notes[i].relative_pitch > 12)
+       while (notes[i].relative_pitch >= 12)
            notes[i].relative_pitch -= 12;
     }
 
+    /* Now, sort again by relative pitch. */
+    qsort (notes, num_notes, sizeof (analyzed_note_t),
+          _compare_analyzed_note_by_relative_pitch);
+
+    for (i = 0; i < ARRAY_SIZE (octaves); i++) {
+       if (_chord_signature_matches (notes, num_notes, octaves[i].pitches, 1))
+           chord_name = octaves[i].name;
+    }
+
     for (i = 0; i < ARRAY_SIZE (intervals); i++) {
        if (_chord_signature_matches (notes, num_notes, intervals[i].pitches, 2))
            chord_name = intervals[i].name;
@@ -561,6 +585,17 @@ note_group_init (void *ctx, note_group_t *group)
 static void
 note_group_add_note (note_group_t *group, score_note_t *note)
 {
+    int i;
+
+    /* Do nothing if note is already in group. */
+    for (i = 0; i < group->num_notes; i++) {
+       if (group->notes[i]->pitch == note->pitch &&
+           group->notes[i]->octave == note->octave)
+       {
+           return;
+       }
+    }
+
     group->num_notes++;
 
     if (group->num_notes > group->size) {