/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.collection.maps;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.ranides.assira.collection.iterators.AListIterator;
import java.util.Comparator;
import java.util.ListIterator;
import java.util.Map;
import java.util.NoSuchElementException;
import net.ranides.assira.generic.CompareUtils;

/**
 * A type-specific red-black tree map implementation for primitive int keys.
 * 
 * <P>The iterators can be safely cast end a {@linkplain java.util.ListIterator list iterator}.
 */
@SuppressWarnings({
    "PMD.AvoidReassigningParameters"
})
public class AIntRBTreeMap<V> extends AIntSortedMap<V> implements java.io.Serializable {

    private static final long serialVersionUID = 2L;
    
    protected final boolean unique;
    
    /**
     * A reference to the root entry.
     */
    protected transient Entry<V> tree;
    /**
     * Number of entries in this map.
     */
    protected int count;
    /**
     * The first key in this map.
     */
    protected transient Entry<V> firstEntry;
    /**
     * The last key in this map.
     */
    protected transient Entry<V> lastEntry;
    
    /**
     * This vector remembers the path and the direction followed during the
     * current insertion. It suffices for about 2<sup>32</sup> entries.
     */
    protected transient boolean dirPath[];
    
    protected transient Entry<V> nodePath[];

    /**
     * Creates a new empty tree map with the given comparator.
     *
     * @param comparator a (possibly type-specific) comparator.
     */
    protected AIntRBTreeMap(Comparator<? super Integer> comparator, boolean unique) {
        super(comparator);
        this.tree = null;
        this.count = 0;
        this.unique = unique;
        allocatePaths();
    }

    @SuppressWarnings("unchecked")
    private void allocatePaths() {
        dirPath = new boolean[64];
        nodePath = new Entry[64];
    }

    @Override
    protected Entry<V> findEntry(int key) {
        Entry<V> entry = tree;
        int cmp;
        while (entry != null && (cmp = compare(key, entry.key)) != 0) {
            entry = cmp < 0 ? entry.left() : entry.right();
        }
        return entry;
    }

    @Override
    protected Entry<V> locateEntry(int k) {
        Entry<V> current = tree, last = tree;
        int cmp = 0;
        while (current != null && (cmp = compare(k, current.key)) != 0) {
            last = current;
            current = cmp < 0 ? current.left() : current.right();
        }
        return rewind(cmp == 0 ? current : last, k);
    }
    
    private Entry<V> rewind(Entry<V> current, int value) {
        if(unique || current==null) {
            return current;
        }
        Entry<V> last;
        do {
            last = current;
            current = current.prev();
        } while(current!=null && compare(value, current.key) == 0);
        
        return last;
    }
    
    
    @Override
    protected Entry<V> firstEntry() {
        if (tree == null) {
            throw new NoSuchElementException();
        }
        return firstEntry;
    }

    @Override
    protected Entry<V> lastEntry() {
        if (tree == null) {
            throw new NoSuchElementException();
        }
        return lastEntry;
    }

    @Override
    protected ListIterator<IntEntry<V>> entryIterator() {
        return new TreeIterator();
    }

    @Override
    protected ListIterator<IntEntry<V>> entryIterator(int key) {
        return new TreeIterator(key);
    }

    @Override
    protected IntSortedMap<V> submap(int begin, boolean bottom, int end, boolean top) {
        return new Submap(begin, bottom, end, top);
    }
    
    @Override
    public int size() {
        return count;
    }

    @Override
    public boolean isEmpty() {
        return count == 0;
    }

    @SuppressWarnings("PMD")
    @Override
    public V put(int key, V value) {
        modified = false;
        int maxDepth = 0;
        if (tree == null) { // The case of the empty tree is treated separately.
            count++;
            tree = lastEntry = firstEntry = new Entry<>(key, value);
        } else {
            Entry<V> p = tree, e;
            int cmp, i = 0;
            while (true) {
                cmp = compare(key, p.key);
                if (cmp == 0 && (unique || CompareUtils.equals(p.value, value))) {
                    final V oldValue = p.value;
                    p.value = value;
                    // We clean up the node path, or we could have stale references later.
                    while (i-- != 0) {
                        nodePath[ i] = null;
                    }
                    return oldValue;
                }
                nodePath[ i] = p;
                if (dirPath[ i++] = cmp > 0) {
                    if (p.succ()) {
                        count++;
                        e = new Entry<>(key, value);
                        if (p.right == null) {
                            lastEntry = e;
                        }
                        e.left = p;
                        e.right = p.right;
                        p.right(e);
                        break;
                    }
                    p = p.right;
                } else {
                    if (p.pred()) {
                        count++;
                        e = new Entry<>(key, value);
                        if (p.left == null) {
                            firstEntry = e;
                        }
                        e.right = p;
                        e.left = p.left;
                        p.left(e);
                        break;
                    }
                    p = p.left;
                }
            }
            modified = true;
            maxDepth = i--;
            while (i > 0 && !nodePath[ i].black()) {
                if (!dirPath[ i - 1]) {
                    Entry<V> y = nodePath[ i - 1].right;
                    if (!nodePath[ i - 1].succ() && !y.black()) {
                        nodePath[ i].black(true);
                        y.black(true);
                        nodePath[ i - 1].black(false);
                        i -= 2;
                    } else {
                        Entry<V> x;
                        if (!dirPath[ i]) {
                            y = nodePath[ i];
                        } else {
                            x = nodePath[ i];
                            y = x.right;
                            x.right = y.left;
                            y.left = x;
                            nodePath[ i - 1].left = y;
                            if (y.pred()) {
                                y.pred(false);
                                x.succ(y);
                            }
                        }
                        x = nodePath[ i - 1];
                        x.black(false);
                        y.black(true);
                        x.left = y.right;
                        y.right = x;
                        if (i < 2) {
                            tree = y;
                        } else {
                            if (dirPath[ i - 2]) {
                                nodePath[ i - 2].right = y;
                            } else {
                                nodePath[ i - 2].left = y;
                            }
                        }
                        if (y.succ()) {
                            y.succ(false);
                            x.pred(y);
                        }
                        break;
                    }
                } else {
                    Entry<V> y = nodePath[ i - 1].left;
                    if (!nodePath[ i - 1].pred() && !y.black()) {
                        nodePath[ i].black(true);
                        y.black(true);
                        nodePath[ i - 1].black(false);
                        i -= 2;
                    } else {
                        Entry<V> x;
                        if (dirPath[ i]) {
                            y = nodePath[ i];
                        } else {
                            x = nodePath[ i];
                            y = x.left;
                            x.left = y.right;
                            y.right = x;
                            nodePath[ i - 1].right = y;
                            if (y.succ()) {
                                y.succ(false);
                                x.pred(y);
                            }
                        }
                        x = nodePath[ i - 1];
                        x.black(false);
                        y.black(true);
                        x.right = y.left;
                        y.left = x;
                        if (i < 2) {
                            tree = y;
                        } else {
                            if (dirPath[ i - 2]) {
                                nodePath[ i - 2].right = y;
                            } else {
                                nodePath[ i - 2].left = y;
                            }
                        }
                        if (y.pred()) {
                            y.pred(false);
                            x.succ(y);
                        }
                        break;
                    }
                }
            }
        }
        tree.black(true);
        // We clean up the node path, or we could have stale references later.
        while (maxDepth-- != 0) {
            nodePath[ maxDepth] = null;
        }
        return null;
    }

    @SuppressWarnings({"PMD","unchecked"})
    @Override
    public V remove(int key) {
        modified = false;
        if (tree == null) {
            return null;
        }
        Entry<V> p = tree;
        int cmp;
        int i = 0;
        final int kk = key;
        while (true) {
            if ((cmp = compare(kk, p.key)) == 0) {
                break;
            }
            dirPath[ i] = cmp > 0;
            nodePath[ i] = p;
            if (dirPath[ i++]) {
                if ((p = p.right()) == null) {
                    // We clean up the node path, or we could have stale references later.
                    while (i-- != 0) {
                        nodePath[ i] = null;
                    }
                    return null;
                }
            } else {
                if ((p = p.left()) == null) {
                    // We clean up the node path, or we could have stale references later.
                    while (i-- != 0) {
                        nodePath[ i] = null;
                    }
                    return null;
                }
            }
        }
        if (p.left == null) {
            firstEntry = p.next();
        }
        if (p.right == null) {
            lastEntry = p.prev();
        }
        if (p.succ()) {
            if (p.pred()) {
                if (i == 0) {
                    tree = p.left;
                } else {
                    if (dirPath[ i - 1]) {
                        nodePath[ i - 1].succ(p.right);
                    } else {
                        nodePath[ i - 1].pred(p.left);
                    }
                }
            } else {
                p.prev().right = p.right;
                if (i == 0) {
                    tree = p.left;
                } else {
                    if (dirPath[ i - 1]) {
                        nodePath[ i - 1].right = p.left;
                    } else {
                        nodePath[ i - 1].left = p.left;
                    }
                }
            }
        } else {
            boolean color;
            Entry<V> r = p.right;
            if (r.pred()) {
                r.left = p.left;
                r.pred(p.pred());
                if (!r.pred()) {
                    r.prev().right = r;
                }
                if (i == 0) {
                    tree = r;
                } else {
                    if (dirPath[ i - 1]) {
                        nodePath[ i - 1].right = r;
                    } else {
                        nodePath[ i - 1].left = r;
                    }
                }
                color = r.black();
                r.black(p.black());
                p.black(color);
                dirPath[ i] = true;
                nodePath[ i++] = r;
            } else {
                Entry<V> s;
                int j = i++;
                while (true) {
                    dirPath[ i] = false;
                    nodePath[ i++] = r;
                    s = r.left;
                    if (s.pred()) {
                        break;
                    }
                    r = s;
                }
                dirPath[ j] = true;
                nodePath[ j] = s;
                if (s.succ()) {
                    r.pred(s);
                } else {
                    r.left = s.right;
                }
                s.left = p.left;
                if (!p.pred()) {
                    p.prev().right = s;
                    s.pred(false);
                }
                s.right(p.right);
                color = s.black();
                s.black(p.black());
                p.black(color);
                if (j == 0) {
                    tree = s;
                } else {
                    if (dirPath[ j - 1]) {
                        nodePath[ j - 1].right = s;
                    } else {
                        nodePath[ j - 1].left = s;
                    }
                }
            }
        }
        int maxDepth = i;
        if (p.black()) {
            for (; i > 0; i--) {
                if (dirPath[ i - 1] && !nodePath[ i - 1].succ()
                        || !dirPath[ i - 1] && !nodePath[ i - 1].pred()) {
                    Entry<V> x = dirPath[ i - 1] ? nodePath[ i - 1].right : nodePath[ i - 1].left;
                    if (!x.black()) {
                        x.black(true);
                        break;
                    }
                }
                if (!dirPath[ i - 1]) {
                    Entry<V> w = nodePath[ i - 1].right;
                    if (!w.black()) {
                        w.black(true);
                        nodePath[ i - 1].black(false);
                        nodePath[ i - 1].right = w.left;
                        w.left = nodePath[ i - 1];
                        if (i < 2) {
                            tree = w;
                        } else {
                            if (dirPath[ i - 2]) {
                                nodePath[ i - 2].right = w;
                            } else {
                                nodePath[ i - 2].left = w;
                            }
                        }
                        nodePath[ i] = nodePath[ i - 1];
                        dirPath[ i] = false;
                        nodePath[ i - 1] = w;
                        if (maxDepth == i++) {
                            maxDepth++;
                        }
                        w = nodePath[ i - 1].right;
                    }
                    if ((w.pred() || w.left.black())
                            && (w.succ() || w.right.black())) {
                        w.black(false);
                    } else {
                        if (w.succ() || w.right.black()) {
                            Entry<V> y = w.left;
                            y.black(true);
                            w.black(false);
                            w.left = y.right;
                            y.right = w;
                            w = nodePath[ i - 1].right = y;
                            if (w.succ()) {
                                w.succ(false);
                                w.right.pred(w);
                            }
                        }
                        w.black(nodePath[ i - 1].black());
                        nodePath[ i - 1].black(true);
                        w.right.black(true);
                        nodePath[ i - 1].right = w.left;
                        w.left = nodePath[ i - 1];
                        if (i < 2) {
                            tree = w;
                        } else {
                            if (dirPath[ i - 2]) {
                                nodePath[ i - 2].right = w;
                            } else {
                                nodePath[ i - 2].left = w;
                            }
                        }
                        if (w.pred()) {
                            w.pred(false);
                            nodePath[ i - 1].succ(w);
                        }
                        break;
                    }
                } else {
                    Entry<V> w = nodePath[ i - 1].left;
                    if (!w.black()) {
                        w.black(true);
                        nodePath[ i - 1].black(false);
                        nodePath[ i - 1].left = w.right;
                        w.right = nodePath[ i - 1];
                        if (i < 2) {
                            tree = w;
                        } else {
                            if (dirPath[ i - 2]) {
                                nodePath[ i - 2].right = w;
                            } else {
                                nodePath[ i - 2].left = w;
                            }
                        }
                        nodePath[ i] = nodePath[ i - 1];
                        dirPath[ i] = true;
                        nodePath[ i - 1] = w;
                        if (maxDepth == i++) {
                            maxDepth++;
                        }
                        w = nodePath[ i - 1].left;
                    }
                    if ((w.pred() || w.left.black())
                            && (w.succ() || w.right.black())) {
                        w.black(false);
                    } else {
                        if (w.pred() || w.left.black()) {
                            Entry<V> y = w.right;
                            y.black(true);
                            w.black(false);
                            w.right = y.left;
                            y.left = w;
                            w = nodePath[ i - 1].left = y;
                            if (w.pred()) {
                                w.pred(false);
                                w.left.succ(w);
                            }
                        }
                        w.black(nodePath[ i - 1].black());
                        nodePath[ i - 1].black(true);
                        w.left.black(true);
                        nodePath[ i - 1].left = w.right;
                        w.right = nodePath[ i - 1];
                        if (i < 2) {
                            tree = w;
                        } else {
                            if (dirPath[ i - 2]) {
                                nodePath[ i - 2].right = w;
                            } else {
                                nodePath[ i - 2].left = w;
                            }
                        }
                        if (w.succ()) {
                            w.succ(false);
                            nodePath[ i - 1].pred(w);
                        }
                        break;
                    }
                }
            }
            if (tree != null) {
                tree.black(true);
            }
        }
        modified = true;
        count--;
        // We clean up the node path, or we could have stale references later.
        while (maxDepth-- != 0) {
            nodePath[ maxDepth] = null;
        }
        return p.value;
    }

    @Override
    public void clear() {
        count = 0;
        tree = null;
        firstEntry = null;
        lastEntry = null;
    }
    
    private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException {
        int n = count;
        TreeIterator iterator = new TreeIterator();
        IntEntry<V> entry;
        stream.defaultWriteObject();
        while (n-- != 0) {
            entry = iterator.next();
            stream.writeInt(entry.getIntKey());
            stream.writeObject(entry.getValue());
        }
    }

    /**
     * Reads the given number of entries from the input stream, returning the
     * corresponding tree.istream@param s the input stream.
     * @param n the (positive) number of entries to read.
     * @param pred the entry containing the key that preceeds the first key in
     * the tree.
     * @param succ the entry containing the key that follows the last key in the
     * tree.
     */
    @SuppressWarnings("unchecked")
    private Entry<V> readTree(java.io.ObjectInputStream istream, int n, Entry<V> pred, Entry<V> succ) throws java.io.IOException, ClassNotFoundException {
        if (n == 1) {
            final Entry<V> top = new Entry<>(istream.readInt(), (V) istream.readObject());
            top.pred(pred);
            top.succ(succ);
            top.black(true);
            return top;
        }
        if (n == 2) {
            /* We handle separately this case so that recursion will
             *always* be on nonempty subtrees. */
            final Entry<V> top = new Entry<>(istream.readInt(), (V) istream.readObject());
            top.black(true);
            top.right(new Entry<>(istream.readInt(), (V) istream.readObject()));
            top.right.pred(top);
            top.pred(pred);
            top.right.succ(succ);
            return top;
        }
        // The right subtree is the largest one.
        final int rightN = n / 2, leftN = n - rightN - 1;
        final Entry<V> top = new Entry<>();
        top.left(readTree(istream, leftN, pred, top));
        top.key = istream.readInt();
        top.value = (V) istream.readObject();
        top.black(true);
        top.right(readTree(istream, rightN, top, succ));
        if (n + 2 == ((n + 2) & -(n + 2))) {
            top.right.black(false); // Quick test for determining whether n + 2 is a power of 2.
        }
        return top;
    }

    private void readObject(java.io.ObjectInputStream istream) throws java.io.IOException, ClassNotFoundException {
        istream.defaultReadObject();
        allocatePaths();
        if (count != 0) {
            tree = readTree(istream, count, null, null);
            Entry<V> entry;
            entry = tree;
            while (entry.left() != null) {
                entry = entry.left();
            }
            firstEntry = entry;
            entry = tree;
            while (entry.right() != null) {
                entry = entry.right();
            }
            lastEntry = entry;
        }
    }

    /**
     * This class represent an entry in a tree map.
     *
     * <P>We use the only "metadata", i.e., {@link Entry#info}, to store
     * information about color, predecessor status and successor status.
     *
     * <P>Note that since the class is recursive, it can be considered
     * equivalently a tree.
     */
    protected static final class Entry<V> implements IntEntry<V> {

        /**
         * The the bit in this mask is true, the node is black.
         */
        private final static int BLACK_MASK = 1;
        /**
         * If the bit in this mask is true, {@link #right} points to a
         * successor.
         */
        private final static int SUCC_MASK = 1 << 31;
        /**
         * If the bit in this mask is true, {@link #left} points to a
         * predecessor.
         */
        private final static int PRED_MASK = 1 << 30;
        /**
         * The key of this entry.
         */
        int key;
        /**
         * The value of this entry.
         */
        V value;
        /**
         * The pointers to the left and right subtrees.
         */
        Entry<V> left, right;
        /**
         * This integers holds different information in different bits (see
         * {@link #SUCC_MASK} and {@link #PRED_MASK}.
         */
        int info;

        Entry() {
        }

        /**
         * Creates a new entry with the given key and value.
         *
         * @param key a key.
         * @param value a value.
         */
        Entry(int key, V value) {
            this.key = key;
            this.value = value;
            info = SUCC_MASK | PRED_MASK;
        }

        /**
         * Returns the left subtree.
         *
         * @return the left subtree (<code>null</code> if the left subtree is
         * empty).
         */
        Entry<V> left() {
            return (info & PRED_MASK) != 0 ? null : left;
        }

        /**
         * Returns the right subtree.
         *
         * @return the right subtree (<code>null</code> if the right subtree is
         * empty).
         */
        Entry<V> right() {
            return (info & SUCC_MASK) != 0 ? null : right;
        }

        /**
         * Checks whether the left pointer is really a predecessor.
         *
         * @return true if the left pointer is a predecessor.
         */
        boolean pred() {
            return (info & PRED_MASK) != 0;
        }

        /**
         * Checks whether the right pointer is really a successor.
         *
         * @return true if the right pointer is a successor.
         */
        boolean succ() {
            return (info & SUCC_MASK) != 0;
        }

        /**
         * Sets whether the left pointer is really a predecessor.
         *
         * @param pred if true then the left pointer will be considered a
         * predecessor.
         */
        void pred(boolean pred) {
            if (pred) {
                info |= PRED_MASK;
            } else {
                info &= ~PRED_MASK;
            }
        }

        /**
         * Sets whether the right pointer is really a successor.
         *
         * @param succ if true then the right pointer will be considered a
         * successor.
         */
        void succ(boolean succ) {
            if (succ) {
                info |= SUCC_MASK;
            } else {
                info &= ~SUCC_MASK;
            }
        }

        /**
         * Sets the left pointer to a predecessor.
         *
         * @param pred the predecessr.
         */
        void pred(Entry<V> pred) {
            info |= PRED_MASK;
            left = pred;
        }

        /**
         * Sets the right pointer to a successor.
         *
         * @param succ the successor.
         */
        void succ(Entry<V> succ) {
            info |= SUCC_MASK;
            right = succ;
        }

        /**
         * Sets the left pointer to the given subtree.
         *
         * @param left the new left subtree.
         */
        void left(Entry<V> left) {
            info &= ~PRED_MASK;
            this.left = left;
        }

        /**
         * Sets the right pointer to the given subtree.
         *
         * @param right the new right subtree.
         */
        void right(Entry<V> right) {
            info &= ~SUCC_MASK;
            this.right = right;
        }

        /**
         * Returns whether this node is black.
         *
         * @return true iff this node is black.
         */
        boolean black() {
            return (info & BLACK_MASK) != 0;
        }

        /**
         * Sets whether this node is black.
         *
         * @param black if true, then this node becomes black; otherwise, it
         * becomes red..
         */
        void black(boolean black) {
            if (black) {
                info |= BLACK_MASK;
            } else {
                info &= ~BLACK_MASK;
            }
        }

        /**
         * Computes the next entry in the set order.
         *
         * @return the next entry (<code>null</code>) if this is the last
         * entry).
         */
        Entry<V> next() {
            Entry<V> next = this.right;
            if ((info & SUCC_MASK) == 0) {
                while ((next.info & PRED_MASK) == 0) {
                    next = next.left;
                }
            }
            return next;
        }

        /**
         * Computes the previous entry in the set order.
         *
         * @return the previous entry (<code>null</code>) if this is the first
         * entry).
         */
        Entry<V> prev() {
            Entry<V> prev = this.left;
            if ((info & PRED_MASK) == 0) {
                while ((prev.info & SUCC_MASK) == 0) {
                    prev = prev.right;
                }
            }
            return prev;
        }

        @Override
        public Integer getKey() {
            return key;
        }

        @Override
        public int getIntKey() {
            return key;
        }

        @Override
        public V getValue() {
            return value;
        }

        @Override
        public V setValue(V value) {
            final V oldValue = this.value;
            this.value = value;
            return oldValue;
        }
        
        @SuppressWarnings("unchecked")
        @Override
        public boolean equals(Object object) {
            if (!(object instanceof Map.Entry)) {
                return false;
            }
            Map.Entry<Integer, V> entry = (Map.Entry<Integer, V>) object;
            return (key == entry.getKey()) && CompareUtils.equals(value, entry.getValue());
        }

        @Override
        public int hashCode() {
            return (key) ^ ((value) == null ? 0 : (value).hashCode());
        }

        @Override
        public String toString() {
            return key + "=>" + value;
        }

    }

    

    
    
    /**
     * An abstract iterator on the whole range.
     *
     * <P>This class can iterate in both directions on a threaded tree.
     */
    private class TreeIterator extends AListIterator<IntEntry<V>> {

        /**
         * The entry that will be returned by the next call to
         * {@link java.util.ListIterator#previous()} (or
         * <code>null</code> if no previous entry exists).
         */
        Entry<V> prev;
        /**
         * The entry that will be returned by the next call to
         * {@link java.util.ListIterator#next()} (or
         * <code>null</code> if no next entry exists).
         */
        Entry<V> next;
        /**
         * The last entry that was returned (or
         * <code>null</code> if we did not iterate or used {@link #remove()}).
         */
        Entry<V> curr;
        /**
         * The current index (in the sense of a {@link java.util.ListIterator}).
         * Note that this value is not meaningful when this {@link TreeIterator}
         * has been created using the nonempty constructor.
         */
        int index = 0;

        TreeIterator() {
            next = firstEntry;
        }

        TreeIterator(int k) {
            if ((next = locateEntry(k)) != null) {
                if (compare(next.key, k) < 0) {
                    prev = next;
                    next = next.next();
                } else {
                    prev = next.prev();
                }
            }
        }

        @Override
        public boolean hasNext() {
            return next != null;
        }

        @Override
        public boolean hasPrevious() {
            return prev != null;
        }

        void updateNext() {
            next = next.next();
        }

        @Override
        public Entry<V> next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            curr = prev = next;
            index++;
            updateNext();
            return curr;
        }

        void updatePrevious() {
            prev = prev.prev();
        }

        @Override
        public Entry<V> previous() {
            if (!hasPrevious()) {
                throw new NoSuchElementException();
            }
            curr = next = prev;
            index--;
            updatePrevious();
            return curr;
        }

        @Override
        public int nextIndex() {
            return index;
        }

        @Override
        public int previousIndex() {
            return index - 1;
        }

        @Override
        public void remove() {
            if (curr == null) {
                throw new IllegalStateException();
            }
            /* If the last operation was a next(), we are removing an entry that preceeds
             the current index, and thus we must decrement it. */
            if (curr == prev) { //NOPMD
                index--;
            }
            next = prev = curr;
            updatePrevious();
            updateNext();
            AIntRBTreeMap.this.remove(curr.key);
            curr = null;
        }

    }
    
    @SuppressFBWarnings("SE_INNER_CLASS")
    private final class Submap extends ASubmap implements java.io.Serializable {

        private static final long serialVersionUID = 2L;
        
        public Submap(int begin, boolean bottom, int end, boolean top) {
            super(begin, bottom, end, top);
        }
        
        @Override
        protected AIntRBTreeMap.Entry<V> locateEntry(int k) {
            return AIntRBTreeMap.this.locateEntry(k);
        }

        @Override
        protected AIntRBTreeMap.Entry<V> findEntry(int k) {
            if(!inside(k)) {
                return null;
            }
            return AIntRBTreeMap.this.findEntry(k);
        }

        @Override
        protected ListIterator<IntEntry<V>> entryIterator() {
            return new STreeIterator();
        }

        @Override
        protected ListIterator<IntEntry<V>> entryIterator(int key) {
            return new STreeIterator(key);
        }

        @Override
        public AIntRBTreeMap.Entry<V> firstEntry() {
            if (tree == null) {
                return null;
            }
            // If this submap goes to -infinity, we return the main map first entry; otherwise, we locate the start of the map.
            AIntRBTreeMap.Entry<V> entry;
            if (bottom) {
                entry = firstEntry;
            } else {
                entry = locateEntry(begin);
                // If we find either the start or something greater we're OK.
                if (entry!=null && compare(entry.key, begin) < 0) {
                    entry = entry.next();
                }
            }
            // Finally, if this submap doesn't go to infinity, we check that the resulting key isn't greater than the end.
            if (entry == null || !top && compare(entry.key, end) >= 0) {
                return null;
            }
            return entry;
        }

        @Override
        public AIntRBTreeMap.Entry<V> lastEntry() {
            if (tree == null) {
                return null;
            }
            // If this submap goes to infinity, we return the main map last entry; otherwise, we locate the end of the map.
            AIntRBTreeMap.Entry<V> entry;
            if (top) {
                entry = lastEntry;
            } else {
                entry = locateEntry(end);
                // If we find something smaller than the end we're OK.
                if (entry!=null && compare(entry.key, end) >= 0) {
                    entry = entry.prev();
                }
            }
            // Finally, if this submap doesn't go to -infinity, we check that the resulting key isn't smaller than the start.
            if (entry == null || !bottom && compare(entry.key, begin) < 0) {
                return null;
            }
            return entry;
        }

        /**
         * An iterator for subranges.
         *
         * <P>This class inherits from {@link TreeIterator}, but overrides the
         * methods that update the pointer after a
         * {@link java.util.ListIterator#next()} or
         * {@link java.util.ListIterator#previous()}. If we would move out of
         * the range of the submap we just overwrite the next or previous entry
         * with
         * <code>null</code>.
         */
        private class STreeIterator extends TreeIterator {

            STreeIterator() {
                next = firstEntry();
            }

            STreeIterator(int k) {
                this();
                if (next != null) {
                    if (!bottom && compare(k, next.key) < 0) {
                        prev = null;
                    } else if (!top && compare(k, (prev = lastEntry()).key) >= 0) {
                        next = null;
                    } else {
                        next = locateEntry(k);
                        if (compare(next.key, k) <= 0) {
                            prev = next;
                            next = next.next();
                        } else {
                            prev = next.prev();
                        }
                    }
                }
            }

            @Override
            void updatePrevious() {
                prev = prev.prev();
                if (!bottom && prev != null && AIntRBTreeMap.this.compare(prev.key, begin) < 0) {
                    prev = null;
                }
            }

            @Override
            void updateNext() {
                next = next.next();
                if (!top && next != null && AIntRBTreeMap.this.compare(next.key, end) >= 0) {
                    next = null;
                }
            }
        }

    }

}
