b = Buffer.read(s, "/home/lcoogan/snd/live/2025-04-26.Basic_City_Brewery/trax/01-Cantor_Samual_Malavsky_Shomea_Kol_Bichios.wav");

(
SynthDef(\layer0_struct0, {
	arg bufnum, fftSize = 1024, amp = 2,
	wipeFreq = 0.1, wipeDepth = 0.4,
	trigFreq = 2.0, threshold = 0.3, smoothAmt = 0.2,
	mix = 1.0, crf_1, rs_1, crf_2, rs_2, foldLo = -0.8, foldHi = 0.8,
    combDelay = 0.2, combDecay = 2.0,
    verbMix = 0.5, verbSize = 1.0,
    splayWidth = 1.0;




	var in, dry, sig, chain;
	var wipe, trig;

	var ir = Buffer.read(s, "/home/lcoogan/snd/ir/ForestScaleModel/ForestScaleModel/IR_ScaleModel/S1R1_ScaleModel.wav"); // Load an impulse response file


	in = PlayBuf.ar(1, bufnum, BufRateScale.kr(bufnum), loop: 1);
	dry = in;

	// FFT
	chain = FFT(LocalBuf(fftSize), in);

	// Modulated parameters
	wipe = LFSaw.kr(wipeFreq).range(wipeDepth, 0.9);
	trig = Impulse.kr(trigFreq);

	// Needs adjustment
	chain = PV_MagFreeze(chain);
	chain = PV_BrickWall(chain);


	sig = IFFT(chain);


	// Filtering -- needs adjustment
	// sig = RLPF.ar(sig, crf, rs_);
	sig = RHPF.ar(sig, crf_1, rs_1);
	sig = BLowShelf.ar(sig, crf_2, rs_2);


	sig = GlitchBPF.ar(sig, 440);


	// Effects
// Inside signal chain
sig = Fold.ar(sig, foldLo, foldHi);
sig = CombL.ar(sig, combDelay, combDelay, combDecay);
sig = Splay.ar(sig, spread: splayWidth);
sig = XFade2.ar(sig, Convolution2.ar(sig, ir, 512), verbMix);  // Mix dry and wet



	// Mix dry/wet
	sig = XFade2.ar(dry, sig, mix.linlin(0, 1, -1, 1));

	Out.ar(0, sig.dup * amp);
}).add;
)


(
~midiControlMap = (

	// Group 1

	// Mixing
	00: \amp,
	01: \mix,

	// Filtering
	04: \crf_1,
	05: \rs_1,
	06: \crf_2,
	07: \rs_2,

	// Modulation
	08: \wipeFreq,
	09: \wipeDepth,
	10: \trigFreq,
	11: \threshold,

	// Modulation ext
	12: \smoothAmt,



	// Group 2 — FX Modulation

	// Fold
	16: \fold,         // enable/fade
	17: \foldLo,       // lower bound
	18: \foldHi,       // upper bound
	// 19:

	// Comb
	20: \comb,         // enable/fade
	21: \combDelay,    // delay time
	22: \combDecay,    // decay time4
	// 23:

	// Verb
	24: \verb,         // enable/fade
	25: \verbMix,      // wet/dry
	26: \verbSize,     // scale IR/dry level
	// 27

	// Splay
	28: \splay,        // enable/fade
	29: \splayWidth    // stereo spread
);

// Replace this with your actual Synth instance
~layer0 = Synth(\layer0_struct0, [\bufnum, b]);

// Connect MIDI CCs on channel 2
~midiControlMap.keysValuesDo { |cc, param|
	MIDIFunc.cc({ |val, num, chan, src|
		if (chan == 2) {  // Channel 2 (zero-indexed)
			var mappedVal = val.linlin(0, 127, 0.0, 1.0);
			~layer0.set(param, mappedVal);
			("CC" ++ cc ++ " (" ++ param ++ ") → " ++ mappedVal).postln;
		}
	}, cc);
};
)
