(
// PARAMETERS
~musicalParams = (
    scale: Scale.minor,
    key: 0,
    progressionSeed: 0,
    bpm: 90
);

// BASIC CHORD PROGRESSION (Golden Age Cantorial Style with chaotic tunings)
~makeProgression = { |seed|
    var chords = [
        [0, 3, 7],     // I (minor)
        [2, 5, 9],     // ii (minor)
        [4, 8, 11],    // III (augmented)
        [5, 9, 0],     // IV (major)
        [7, 11, 2, 5], // V7 (dominant seventh)
        [9, 0, 4],     // vi (major)
        [11, 2, 5],    // vii° (diminished)
        [0, 4, 7, 10], // I augmented (dramatic effect)
        [3, 6, 10],    // iv (minor)
        [6, 9, 1, 4],  // V7 (dominant seventh)
        [0, 3, 7],     // Freygish I (minor)
        [2, 5, 9],     // Freygish ii (minor)
        [7, 10, 2, 5], // Freygish V7 (dominant seventh)
        [0, 4, 7],     // Double Harmonic I (major)
        [5, 9, 0],     // Double Harmonic IV (major)
        [7, 11, 2, 5], // Double Harmonic V7 (dominant seventh)
        [0, 2, 6, 9],  // Dissonant I chord (almost suspended, unstable)
        [3, 5, 8],     // Flat VI (minor)
        [7, 10, 1],    // Inverted V7
        [1, 4, 8],     // Added dissonance with suspended 2nd and 5th
        [5, 9, 12],    // Augmented 4th (tense)
        [1, 6, 10],    // Major 7th on a diminished scale (creates tension)
        [0, 7, 4],     // Unconventional I chord (doesn't resolve)
        [8, 11, 4]     // Diminished 5th (added dissonance)
    ];

    var prng = Pseed(seed, Pseq((0..6).scramble, inf)).asStream;
    var progression = Array.fill(4, { chords.wrapAt(prng.next) });

    // Some unpredictable modulations for more drama
    progression = progression.collect { |chord|
        chord.scramble
    };

    progression
};

// SYNTH DEF (Pad with chaotic organ-like sound)
SynthDef(\chaoticPad, {
    |out=0, freq=440, amp=0.2, gate=1, pan=0|
    var env = EnvGen.kr(Env.asr(2, 1, 2), gate, doneAction: 2);
    var sig = Mix.fill(4, {
        |i| VarSaw.ar(freq * (1 + Rand(-0.01, 0.01)), 0, 0.5)
    });
    sig = LPF.ar(sig, freq * 2);
    sig = Splay.ar(sig * env * amp, 0.3, center: pan);
    Out.ar(out, sig);
}).add;

// PATTERN (Cantorial-like progression and improvisation)
~pattern = Pbind(
    \instrument, \chaoticPad,
    \dur, 2,
    \amp, 0.1,
    \pan, Pwhite(-0.3, 0.3),
    \freq, Pfunc {
        var progression = ~makeProgression.(~musicalParams[\progressionSeed]);
        var chord = progression.choose;

        // Generate frequencies for each note in the chord
        chord.collect { |deg|
            ~musicalParams[\scale].degreeToFreq(deg + 1, ~musicalParams[\key].midicps, 4)
        }
    }
);

// PLAYBACK
~player = ~pattern.play(TempoClock.new(~musicalParams[\bpm] / 60));
)
