Stabilizing value changes, thresholding for both value and time

I am trying to ignore spikes in a control value: that is, changes that don’t last long and are not small fluctuations.

I’m sure there must be a simpler way… but I can’t find it. And since this function is using LocalIn/Out, I don’t want to make it a Pseudo-UGen. So, before I go on and make a proper UGen, can anyone suggest a better way to go?

Thaaaanks

{
    // test signals
    // var in = LFNoise0.kr(1).exprange(20,20000) 
    // *  LFNoise1.kr(10).range((-1).midiratio,1.midiratio);
    // var in = 100 * Env.perc(0.01,0.5).range(1,100).kr(gate:Impulse.kr(1));
    var in = LFNoise0.kr(0.2).exprange(20,20000)
    * Env.perc(0.1,0.1).range(1,2).kr(gate:Dust.kr(1));

    // a relative value thr
    var thr=(1.midiratio);
    var timeThr = 0.1;
		
    var local = LocalIn.kr(2);
    var stable = local[0], testStable = local[1];

    // a valid change needs to be both outside the stable range and inside the test range for long enough
	
    // check ranges	
    var inStableRange = InRange.kr( in / stable, thr.reciprocal, thr);
    var inTestRange = InRange.kr( in / testStable, thr.reciprocal, thr);
	
    // check durations
    var outsideLongEnough = Sweep.kr(Changed.kr(inStableRange)) > timeThr
    * (1 - inStableRange);
    var insideTestLongEnough = Sweep.kr(Changed.kr(inTestRange)) > timeThr
    * inTestRange;
	
    var validChange = outsideLongEnough * insideTestLongEnough;
    var out;

    // update testStable when exiting the testRange
    testStable = Latch.kr(in, 1 - inTestRange);
    stable = Latch.kr(testStable, validChange);
	
    LocalOut.kr( [stable, testStable] );
    // allow fluctuations within stable range
    out = Gate.kr(in, inStableRange);

    [in, out].poll
}.play