import arb.soundcipher.*;

SoundCipher sc = new SoundCipher(this);
SCScore score = new SCScore();
int cycles = 8;
int keyOffset = 9;

float modeQuantize(float pitch, float[] mode, int keyOffset) {
  pitch = round(pitch);
  boolean inScale = false;
  while(!inScale) {
    for(int i=0; i<mode.length; i++) {
      if ((pitch - keyOffset)%12 == mode[i]) inScale = true;
      if(!inScale) pitch++;
    }
  }
  return pitch;
}

void setup() {
  background(100);
  textSize(112);
  text(cycles, 15, 90);
  score.addCallbackListener(this);
  makeMusic();
  score.play();
}

void makeMusic() {
  score.stop();
  score.empty();
  float dur = 0.5;
  for (int i=0; i<8; i += dur*2) {
    float pitch = modeQuantize(random(60, 80), sc.MINOR, keyOffset);
    dur = 0.5 * random(1, 3);
    score.addNote(i * 0.5, pitch, random(60, 110), dur);
    score.addNote(i * 0.5 + 4, pitch, random(60, 110), dur);
  }
  score.addCallback(8, 0);
}

void draw() {}

void handleCallbacks(int callbackID) {
  if (cycles > 0) {
    makeMusic();
    score.play();
    cycles--;
    background(100);
    text(cycles, 15, 90);
  } else sc.playNote(72 + keyOffset, 100, 2);
}