def matches_value_in_range(range_start, range_stop, range_step, value):
    """Helper function that matches the value with the nearest value in the
    given range.

    :param int range_start: The start of the range.
    :param int range_stop: The end of the range.
    :param int range_step: The gap between two value in the range.
    :param int value: The value to process.

    :rtype: int

    >>> matches_value_in_range(0, 100, 10, 40)
    40
    >>> matches_value_in_range(0, 100, 10, 42)
    40
    >>> matches_value_in_range(0, 1000, 100, 51)
    100
    >>> matches_value_in_range(42, 1000, 100, 150)
    142
    >>> matches_value_in_range(500, 1000, 100, 100)
    500
    >>> matches_value_in_range(500, 1000, 100, 4000)
    1000
    """
    if value <= range_start:
        return range_start

    if value >= range_stop:
        return range_stop

    delta = (value - range_start) % range_step
    if not delta:
        return value
    else:
        if delta < range_step / 2:
            return value - delta
        else:
            return value - delta + range_step