function [i, y] = localmin(x, s)
    // This function finds local minima within vector x
    //
    // Usage:
    //        [i, y] = localmin(x) 
    // 
    // where  x: input vector
    //        s: strict (2), semistrict (1) or loose (0) local minima
    //        i: vector of indexes where x reaches local minima
    //        y: vector of values of x at such indexes   
    //
    // Local minima are defined as values smaller than or equal to the
    // immediately preceding and immediately following ones. Argument 
    // s is optional. If it is equal to 2, strict minima are found 
    // (i.e., the values are strictly smaller than the neighbouring 
    // ones); if it is equal to 1, semistrict minima are found (i.e.,
    // the values are strictly smaller than at least one neighbouring
    // value); if it is equal to 0, loose minima are found (i.e., the
    // values are smaller than or equal to the neighbouring ones). x 
    // may be either a row vector or a column vector. If x is complex,
    // abs(x) is used instead of x and given as the second output 
    // argument.
    // 
    // NOTE: In order to assess the first and last elements the vector
    //       x is extended with inf values 
    //
    // ------------------------------
    // Author: Federico Miyara
    // Dete:   2007-06-28
    //         2008-08-09
    //         2010-06-28
    //         2010-08-24 
    //         2020-01-24
    //         2020-04-22  

    // Default value for s (loose minima)
    if argn(2)<2
        s = 0;
    end

    // Ensure x is a column vector
    if size(x)(1)==1
        x = x(:);
        wasrow = 1;
    else 
        wasrow = 0;
    end

    // For complex signals, the minimum will be obtained for
    // the absolute value
    if isreal(x)==0
        x = abs(x);
    end

    // Compute a vector xdec that is positive on indexes where x
    // is decreasing. To that end, the next value is subtracted
    // from each value of x
    xdec = x - [x(2:$); %inf];

    // Compute a vector xinc that is positive on indexes where x
    // is increasing. To that end, the preceding value is subtracted
    // from each value of x
    xinc = x - [%inf; x(1:$-1)];

    // Obtain a vector whose components are 1 if both xdec and xinc
    // are negative or non-postive
    switch s
    case 2
        mini = (xdec<0).*(xinc<0);
    case 1
        mini =  (xdec<=0).*(xinc<0) + (xdec<0).*(xinc<=0);
    case 0
        mini = (xdec<=0).*(xinc<=0);
    end

    // Find the indexes corresponding to 1's
    i = find(mini); 

    // If x was a row vector, so must be i
    if wasrow== 1
        i = i(:).';
    else
        i = i(:);
    end

    // Provide the second output argument if requested 
    if argn(1)>1
        y = x(i);
        // If x was a row vector, so must be y
        if wasrow==1
            y = y(:).';
        else
            y = y(:);
        end
    end

endfunction   
