function [y, t, z] = trim_audio(x, Fs, tlow, thr)
    // Trim out low-level portions of audio signal
    //
    // Usage:
    //       [y, t, z] = trim_audio(x, Fs, sil, thr)
    // where
    //       x:    audio signal
    //       Fs:   sample rate in Hz
    //       tlow: maximum low-level duration in s
    //       thr:  low-level signal threshold
    //       y:    signal with excess low-level parts 
    //             trimmed out
    //       t:    time vector of same duration as y
    //       z:    energy envelope of y
    //
    // Fs, Tlow and thr are optional, being the default
    // values 44100, 1 and 1/100 of the maximum signal
    // energy.
    //       
    // -----------------------------
    // Author: Federico Miyara
    // Date:   2021-01-20
    
    // Load envelope()
    exec envelope.sci;    
    
    // Output arguments
    rhs = argn(2);

    // Provide default values to missing arguments
    if rhs<3
        // Default maximum low-level duration is 1 s
        tlow = 1;
    end
    if rhs<2
        // Default sample rate is 44100 Hz
        Fs = 44100;
    end
    
    // Compute signal energy envelope
    z = envelope(x, 0.01, Fs, 1);
    
    if rhs<4 
        // Default threshold is 40 dB below energy
        // peak
        thr = max(z)/100;
    end    
    
    // Compute a signal that is 1 if the envelope is 
    // below the threshold
    u = bool2s(z<thr);
    // Find instants in which the envelope crosses
    // the threshold 
    v = [0, find(diff(u)), length(u)];

    // Maximum length of low-level portions of the 
    // signal, in samples 
    L = floor(tlow*Fs);
    
    // Vector I contains the índices of samples to 
    // trim out. They correspond to the low-level 
    // part immediately before a high-level one with
    // a duration such that the rest of low-level
    // interval has at most a duration tlow. 
    
    // Initialize index vector
    I = [];
    // Choose where to start depending on whether 
    // the signal starts at low-level or high level 
    io = 3 - u(1);
    for i=io:2:length(v)
        if v(i) - v(i-1) > L
            // Add range of indices to remove
            I = [I, v(i-1)+L+1:v(i)];
        end
    end

    // From each low-level interval remove all 
    // samples except at most the first L ones 
    y = x;
    y(I) = [];
    
    if argn(1)>1
        // If required provide time vector
        t = [0:length(y)-1]/Fs;
    end
    if argn(1)>2
        // If required provide envelope vector
        z(I) = [];
    end


endfunction
