function [x,y] = compress_curve(x, y, mse)
    %COMPRESS_CURVE reduces the number of samples in a curve by LSE thresholding.
    
    arguments
        x (:,1) {mustBeNumeric}
        y (:,1) {mustBeNumeric}
        mse (1,1) {mustBePositive} = 0.1
    end

    % first normalize so error is consistent for different scalings
    X = (x - min(x)) / (max(x) - min(x));
    Y = (y - min(y)) / (max(y) - min(y));

    Z = [X, Y, zeros(length(X),1)];

    idx = 1;
    k = 1;
    
    e = 0;
    for i = 3:length(X)
        e = 0;
        for j = k+1:i-1
            e = e + p2l(Z(j,:), Z(k,:), Z(i,:));
        end
        e = e / length(e);
        if e > mse
            idx = [idx, i-1];
            k = i-1;
        end
    end

    idx = [idx, length(x)];

    x = x(idx);
    y = y(idx);

    if nargout == 1
        x = [x,y];
    end
end

function d = p2l(pt, v1, v2)
    a = v1 - v2;
    b = pt - v2;
    d = norm(cross(a,b)) / norm(a);
end