~track = "/Users/lcoogan/Music/Musicians/Xiu Xiu/01-xiu_xiu-sad_pony_guerilla_girl-sge.opus".standardizePath;

~track = "/Users/lcoogan/Music/Musicians/Suicide/1977 - Suicide [1998 Reissue]/01 Ghost Rider.opus".standardizePath;
~bpm = 191;

~track = "/Users/lcoogan/Music/Musicians/My Bloody Valentine/Loveless/05 When You Sleep.opus".standardizePath;
~bpm = 90;

~bpm = 116.6;
~looplen = 480 / ~bpm;

~track = "/Users/lcoogan/Music/Musicians/Broadcast/broadcast - tender buttons (2005)/05 - Tears in the Typing Pool.opus".standardizePath; ~bpm=145.1;



b = Buffer.cueSoundFile(s, ~track, 0, 2);
x = { DiskIn.ar(2, b) }.play;

~loopbuf = Buffer.alloc(s, 1000, 513);  // Make sure loopbuf is allocated

(
y = { |which=1, active=1, thresh=1|
    var son = In.ar(0);
    var chain = FFT(LocalBuf(1024), son);
    chain.postln; // Debug: Check the FFT output
    chain = PV_ExtractRepeat(chain, ~loopbuf, ~looplen, memorytime:30, which:which, thresh:thresh);
    ReplaceOut.ar(0, Select.ar(active, [son, IFFT(chain)]).dup);
}.play(x, addAction: \addAfter);
)

y.set(\which, 0)  // Focus on non-repeating part
y.set(\which, 1)  // Focus on repeating part
y.set(\active, 0)  // Switch back to original signal
y.set(\active, 1)  // Apply filter
y.set(\which, 0, \thresh, 1.5)  // Try a higher threshold

y.free;
x.free;
b.close;
