//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Base/Type/Span.cpp
//! @brief     Defines class Span.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "Base/Type/Span.h"
#include "Base/Util/Assert.h"
#include <algorithm>
#include <cmath>

//! Otherwise invalid interval (+1,-1) encodes empty span.
Span::Span()
    : m_low(+1.)
    , m_hig(-1.)
{
}

Span::Span(double low, double hig)
    : m_low(low)
    , m_hig(hig)
{
    ASSERT(low <= hig);
}

Span Span::operator+(double increment) const
{
    return {low() + increment, hig() + increment};
}

double Span::low() const
{
    ASSERT(!empty());
    return m_low;
}

double Span::hig() const
{
    ASSERT(!empty());
    return m_hig;
}

double Span::center() const
{
    ASSERT(!empty());
    return (m_low + m_hig) / 2;
}

double Span::extension() const
{
    if (empty())
        return 0;
    return hig() - low();
}

bool Span::empty() const
{
    return m_low > m_hig;
}

Span Span::unite(const Span& left, const Span& right)
{
    if (right.empty())
        return left;
    if (left.empty())
        return right;
    return {std::min(left.low(), right.low()), std::max(left.hig(), right.hig())};
}

Span Span::intersect(const Span& left, const Span& right)
{
    if (right.empty() || left.empty())
        return {};
    const double low = std::max(left.low(), right.low());
    const double hig = std::min(left.hig(), right.hig());
    if (hig <= low)
        return {};
    return {low, hig};
}
