classdef Interval < handle
% An Interval has a left endpoint and a right endpoint.

properties (GetAccess=private, SetAccess=private)
left=0;
right=0;
end

methods
function Inter = Interval(lt, rt)
% Constructor: construct an Interval object
if nargin==2
if rt>lt
Inter.setLeft(lt)
Inter.setRight(rt)
else
disp('At instantiation arguments incorrect: left>right')
end
end
end

function lt = getLeft(self)
% lt is self's left
lt= self.left;
end

function rt = getRight(self)
% rt is self's right
rt= self.right;
end

function w = getWidth(self)
% w is the width of self
w= self.right - self.getLeft();
end

function scale(self, f)
% Scale self by a factor f
w= self.getWidth();
self.setRight(self.getLeft() + w*f)
end

function shift(self, s)
% Shift self by s
self.setLeft(self.getLeft() + s)
self.setRight(self.getRight() + s)
end

function tf = isIn(self, other)
% tf is true (1) if self is in the other Interval
tf= self.getLeft()>=other.getLeft() && self.getRight()<=other.getRight();
end

function Inter = add(self, other)
% Inter is the resulting Interval formed by adding self and the
% the other Interval
newLeft= self.getLeft() + other.getLeft();
newRight= self.getRight() + other.getRight();
Inter= Interval(newLeft, newRight);
end

function Inter = overlap(self, other)
% If self and the other Interval overlap, then Inter is the
% overlapped Interval; otherwise Inter is empty.
Inter= Interval.empty();
left= max(self.getLeft(), other.getLeft());
right= min(self.getRight(), other.getRight());
if right-left > 0
Inter= Interval(left, right);
end
end

function disp(self)
% Display self, if not empty, in this format: (left,right)
% If empty, display 'Empty <classname>'
if isempty(self)
fprintf('Empty %s\n', class(self))
elseif length(self)>1
disp@handle(self)
else
fprintf('(%f,%f)\n', self.getLeft(), self.getRight())
end
end

end %methods (Access=public)

methods (Access=private)
function setLeft(self, lt)
self.left= lt;
end

function setRight(self, rt)
self.right= rt;
end
end % methods (Access=private)

end %classdef