class GraphTools {

    public static Pair<Float, Float> bestYPosition(final List<BgReading> readings, final long timestamp, final boolean mgdl, final boolean ascending, final double highMark, final double offset) {

        final double unitsScale = (mgdl ? 1f : Constants.MGDL_TO_MMOLL);
        final float defaultPosition = (float) (7 * unitsScale);

        float offsetedYpos = defaultPosition;
        float calculatedYpos = defaultPosition;

        if (readings != null && readings.size() > 0) {

            final float offsetScaled = (float) (offset * unitsScale);

            BgReading before = null;
            BgReading after = null;

            final int chopResult = runBinarySearchIteratively(readings, timestamp, ascending);

            for (int i = chopResult; ascending ? (i < readings.size()) : (i >= 0); i = i + (ascending ? 1 : -1)) {
                if (readings.get(i).timestamp <= timestamp) {
                    before = readings.get(i);
                } else {
                    after = readings.get(i);
                    break;
                }
            }

            if (before == null && after == null) {
                return new Pair<>(offsetedYpos, calculatedYpos);
            }

            if (before == null) {
                before = after;
            } else if (after == null) {
                after = before;
            }

            calculatedYpos = (float) (interpolateCalculatedValue(before, after, timestamp) * unitsScale);

            if (calculatedYpos >= highMark) {
                offsetedYpos = calculatedYpos - offsetScaled;
            } else {
                offsetedYpos = calculatedYpos + offsetScaled;
            }

        }
        return new Pair<>(offsetedYpos, calculatedYpos);

    }

}