/*
 * @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 AVL tree map implementation for primitive int keys.
 * 
 * The put()/remove() code is derived begin Ben Pfaff's GNU libavl
 * (http://www.msu.edu/~pfaffben/avl/). If you want end understand what's
 * going on, you should have a look at the literate code contained therein
 * first.
 * 
 * <P>The iterators can be safely cast end a {@linkplain java.util.ListIterator list iterator}.
 */
@SuppressWarnings({
    "PMD.AvoidReassigningParameters"
})
public class AIntAVLTreeMap<V> extends AIntSortedMap<V> implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
     
    protected final boolean unique;
    
    /**
     * A reference to the root entry.
     */
    protected transient Entry<V> tree;
    /**
     * Number of ientries 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 directions followed during the current
     * insertion. It suffices for about 2<sup>32</sup> ientries.
     */
    protected transient boolean dirPath[];
    
    /**
     * Creates a new empty tree map with the given comparator.
     *
     * @param comparator a (possibly type-specific) comparator.
     */
    protected AIntAVLTreeMap(Comparator<? super Integer> comparator, boolean unique) {
        super(comparator);
        this.tree = null;
        this.count = 0;
        this.unique = unique;
        allocatePaths();
    }

    private void allocatePaths() {
        dirPath = new boolean[48];
    }
    
    @Override
    protected Entry<V> findEntry(int k) {
        Entry<V> entry = tree;
        int cmp;
        while (entry != null && (cmp = compare(k, entry.key)) != 0) {
            entry = cmp < 0 ? entry.left() : entry.right();
        }
        return entry;
    }

    @Override
    protected Entry<V> locateEntry(int k) {
        Entry<V> entry = tree, last = tree;
        int cmp = 0;
        while (entry != null && (cmp = compare(k, entry.key)) != 0) {
            last = entry;
            entry = cmp < 0 ? entry.left() : entry.right();
        }
        return rewind(cmp == 0 ? entry : 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
    public Entry<V> firstEntry() {
        if (tree == null) {
            throw new NoSuchElementException();
        }
        return firstEntry;
    }

    @Override
    public 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;
    }

    @Override
    public V put(int key, V value) {
        return $put(key, value);
    }

    @SuppressWarnings("PMD")
    protected final V $put(int key, V value) {
        modified = false;
        if (tree == null) { // The case of the empty tree is treated separately.
            count++;
            tree = lastEntry = firstEntry = new Entry<>(key, value);
            modified = true;
        } else {
            Entry<V> pnode = tree, qnode = null, ynode = tree, znode = null, enode = null, wnode;
            int cmp, i = 0;
            while (true) {
                cmp = compare(key, pnode.key);
                if (cmp == 0 && (unique || CompareUtils.equals(pnode.value, value))) {
                    final V oldValue = pnode.value;
                    pnode.value = value;
                    return oldValue;
                }
                if (pnode.balance() != 0) {
                    i = 0;
                    znode = qnode;
                    ynode = pnode;
                }
                if (dirPath[ i++] = cmp > 0) {
                    if (pnode.succ()) {
                        count++;
                        enode = new Entry<>(key, value);
                        modified = true;
                        if (pnode.right == null) {
                            lastEntry = enode;
                        }
                        enode.left = pnode;
                        enode.right = pnode.right;
                        pnode.right(enode);
                        break;
                    }
                    qnode = pnode;
                    pnode = pnode.right;
                } else {
                    if (pnode.pred()) {
                        count++;
                        enode = new Entry<>(key, value);
                        modified = true;
                        if (pnode.left == null) {
                            firstEntry = enode;
                        }
                        enode.right = pnode;
                        enode.left = pnode.left;
                        pnode.left(enode);
                        break;
                    }
                    qnode = pnode;
                    pnode = pnode.left;
                }
            }
            pnode = ynode;
            i = 0;
            while (pnode != enode) { //NOPMD
                if (dirPath[ i]) {
                    pnode.incBalance();
                } else {
                    pnode.decBalance();
                }
                pnode = dirPath[ i++] ? pnode.right : pnode.left;
            }
            if (ynode.balance() == -2) {
                Entry<V> xnode = ynode.left;
                if (xnode.balance() == -1) {
                    wnode = xnode;
                    if (xnode.succ()) {
                        xnode.succ(false);
                        ynode.pred(xnode);
                    } else {
                        ynode.left = xnode.right;
                    }
                    xnode.right = ynode;
                    xnode.balance(0);
                    ynode.balance(0);
                } else {
                    assert xnode.balance() == 1;
                    wnode = xnode.right;
                    xnode.right = wnode.left;
                    wnode.left = xnode;
                    ynode.left = wnode.right;
                    wnode.right = ynode;
                    if (wnode.balance() == -1) {
                        xnode.balance(0);
                        ynode.balance(1);
                    } else if (wnode.balance() == 0) {
                        xnode.balance(0);
                        ynode.balance(0);
                    } else {
                        xnode.balance(-1);
                        ynode.balance(0);
                    }
                    wnode.balance(0);
                    if (wnode.pred()) {
                        xnode.succ(wnode);
                        wnode.pred(false);
                    }
                    if (wnode.succ()) {
                        ynode.pred(wnode);
                        wnode.succ(false);
                    }
                }
            } else if (ynode.balance() == +2) {
                Entry<V> xnode = ynode.right;
                if (xnode.balance() == 1) {
                    wnode = xnode;
                    if (xnode.pred()) {
                        xnode.pred(false);
                        ynode.succ(xnode);
                    } else {
                        ynode.right = xnode.left;
                    }
                    xnode.left = ynode;
                    xnode.balance(0);
                    ynode.balance(0);
                } else {
                    assert xnode.balance() == -1;
                    wnode = xnode.left;
                    xnode.left = wnode.right;
                    wnode.right = xnode;
                    ynode.right = wnode.left;
                    wnode.left = ynode;
                    if (wnode.balance() == 1) {
                        xnode.balance(0);
                        ynode.balance(-1);
                    } else if (wnode.balance() == 0) {
                        xnode.balance(0);
                        ynode.balance(0);
                    } else {
                        xnode.balance(1);
                        ynode.balance(0);
                    }
                    wnode.balance(0);
                    if (wnode.pred()) {
                        ynode.succ(wnode);
                        wnode.pred(false);
                    }
                    if (wnode.succ()) {
                        xnode.pred(wnode);
                        wnode.succ(false);
                    }
                }
            } else {
                return null;
            }
            if (znode == null) {
                tree = wnode;
            } else {
                if (znode.left == ynode) {
                    znode.left = wnode;
                } else {
                    znode.right = wnode;
                }
            }
        }
        return null;
    }

    /**
     * Finds the parent of an entry.
     *
     * @param entry a node of the tree.
     * @return the parent of the given node, or <code>null</code> for the root.
     */
    private Entry<V> parent(Entry<V> entry) {
        if (entry == tree) { //NOPMD
            return null;
        }
        Entry<V> xnode, ynode, pnode;
        xnode = ynode = entry;
        while (true) {
            if (ynode.succ()) {
                pnode = ynode.right;
                if (pnode == null || pnode.left != entry) {
                    while (!xnode.pred()) {
                        xnode = xnode.left;
                    }
                    pnode = xnode.left;
                }
                return pnode;
            } else if (xnode.pred()) {
                pnode = xnode.left;
                if (pnode == null || pnode.right != entry) {
                    while (!ynode.succ()) {
                        ynode = ynode.right;
                    }
                    pnode = ynode.right;
                }
                return pnode;
            }
            xnode = xnode.left;
            ynode = ynode.right;
        }
    }
    /* After execution of this method, {@link #modified} is true iff an entry
     has been deleted. */

    @SuppressWarnings({"PMD","unchecked"})
    @Override
    public V remove(int key) {
        modified = false;
        if (tree == null) {
            return null;
        }
        int cmp;
        Entry<V> pnode = tree, qnode = null;
        boolean dir = false;
        final int kk = key;
        while (true) {
            if ((cmp = compare(kk, pnode.key)) == 0) {
                break;
            } else if (dir = cmp > 0) {
                qnode = pnode;
                if ((pnode = pnode.right()) == null) {
                    return null;
                }
            } else {
                qnode = pnode;
                if ((pnode = pnode.left()) == null) {
                    return null;
                }
            }
        }
        if (pnode.left == null) {
            firstEntry = pnode.next();
        }
        if (pnode.right == null) {
            lastEntry = pnode.prev();
        }
        if (pnode.succ()) {
            if (pnode.pred()) {
                if (qnode != null) {
                    if (dir) {
                        qnode.succ(pnode.right);
                    } else {
                        qnode.pred(pnode.left);
                    }
                } else {
                    tree = dir ? pnode.right : pnode.left;
                }
            } else {
                pnode.prev().right = pnode.right;
                if (qnode != null) {
                    if (dir) {
                        qnode.right = pnode.left;
                    } else {
                        qnode.left = pnode.left;
                    }
                } else {
                    tree = pnode.left;
                }
            }
        } else {
            Entry<V> rnode = pnode.right;
            if (rnode.pred()) {
                rnode.left = pnode.left;
                rnode.pred(pnode.pred());
                if (!rnode.pred()) {
                    rnode.prev().right = rnode;
                }
                if (qnode != null) {
                    if (dir) {
                        qnode.right = rnode;
                    } else {
                        qnode.left = rnode;
                    }
                } else {
                    tree = rnode;
                }
                rnode.balance(pnode.balance());
                qnode = rnode;
                dir = true;
            } else {
                Entry<V> snode;
                while (true) {
                    snode = rnode.left;
                    if (snode.pred()) {
                        break;
                    }
                    rnode = snode;
                }
                if (snode.succ()) {
                    rnode.pred(snode);
                } else {
                    rnode.left = snode.right;
                }
                snode.left = pnode.left;
                if (!pnode.pred()) {
                    pnode.prev().right = snode;
                    snode.pred(false);
                }
                snode.right = pnode.right;
                snode.succ(false);
                if (qnode != null) {
                    if (dir) {
                        qnode.right = snode;
                    } else {
                        qnode.left = snode;
                    }
                } else {
                    tree = snode;
                }
                snode.balance(pnode.balance());
                qnode = rnode;
                dir = false;
            }
        }
        Entry<V> ynode;
        while (qnode != null) {
            ynode = qnode;
            qnode = parent(ynode);
            if (!dir) {
                dir = qnode != null && qnode.left != ynode;
                ynode.incBalance();
                if (ynode.balance() == 1) {
                    break;
                } else if (ynode.balance() == 2) {
                    Entry<V> xnode = ynode.right;
                    assert xnode != null;
                    if (xnode.balance() == -1) {
                        Entry<V> wnode;
                        assert xnode.balance() == -1;
                        wnode = xnode.left;
                        xnode.left = wnode.right;
                        wnode.right = xnode;
                        ynode.right = wnode.left;
                        wnode.left = ynode;
                        if (wnode.balance() == 1) {
                            xnode.balance(0);
                            ynode.balance(-1);
                        } else if (wnode.balance() == 0) {
                            xnode.balance(0);
                            ynode.balance(0);
                        } else {
                            assert wnode.balance() == -1;
                            xnode.balance(1);
                            ynode.balance(0);
                        }
                        wnode.balance(0);
                        if (wnode.pred()) {
                            ynode.succ(wnode);
                            wnode.pred(false);
                        }
                        if (wnode.succ()) {
                            xnode.pred(wnode);
                            wnode.succ(false);
                        }
                        if (qnode != null) {
                            if (dir) {
                                qnode.right = wnode;
                            } else {
                                qnode.left = wnode;
                            }
                        } else {
                            tree = wnode;
                        }
                    } else {
                        if (qnode != null) {
                            if (dir) {
                                qnode.right = xnode;
                            } else {
                                qnode.left = xnode;
                            }
                        } else {
                            tree = xnode;
                        }
                        if (xnode.balance() == 0) {
                            ynode.right = xnode.left;
                            xnode.left = ynode;
                            xnode.balance(-1);
                            ynode.balance(+1);
                            break;
                        }
                        assert xnode.balance() == 1;
                        if (xnode.pred()) {
                            ynode.succ(true);
                            xnode.pred(false);
                        } else {
                            ynode.right = xnode.left;
                        }
                        xnode.left = ynode;
                        ynode.balance(0);
                        xnode.balance(0);
                    }
                }
            } else {
                dir = qnode != null && qnode.left != ynode;
                ynode.decBalance();
                if (ynode.balance() == -1) {
                    break;
                } else if (ynode.balance() == -2) {
                    Entry<V> xnode = ynode.left;
                    assert xnode != null;
                    if (xnode.balance() == 1) {
                        Entry<V> wnode;
                        assert xnode.balance() == 1;
                        wnode = xnode.right;
                        xnode.right = wnode.left;
                        wnode.left = xnode;
                        ynode.left = wnode.right;
                        wnode.right = ynode;
                        if (wnode.balance() == -1) {
                            xnode.balance(0);
                            ynode.balance(1);
                        } else if (wnode.balance() == 0) {
                            xnode.balance(0);
                            ynode.balance(0);
                        } else {
                            assert wnode.balance() == 1;
                            xnode.balance(-1);
                            ynode.balance(0);
                        }
                        wnode.balance(0);
                        if (wnode.pred()) {
                            xnode.succ(wnode);
                            wnode.pred(false);
                        }
                        if (wnode.succ()) {
                            ynode.pred(wnode);
                            wnode.succ(false);
                        }
                        if (qnode != null) {
                            if (dir) {
                                qnode.right = wnode;
                            } else {
                                qnode.left = wnode;
                            }
                        } else {
                            tree = wnode;
                        }
                    } else {
                        if (qnode != null) {
                            if (dir) {
                                qnode.right = xnode;
                            } else {
                                qnode.left = xnode;
                            }
                        } else {
                            tree = xnode;
                        }
                        if (xnode.balance() == 0) {
                            ynode.left = xnode.right;
                            xnode.right = ynode;
                            xnode.balance(+1);
                            ynode.balance(-1);
                            break;
                        }
                        assert xnode.balance() == -1;
                        if (xnode.succ()) {
                            ynode.pred(true);
                            xnode.succ(false);
                        } else {
                            ynode.left = xnode.right;
                        }
                        xnode.right = ynode;
                        ynode.balance(0);
                        xnode.balance(0);
                    }
                }
            }
        }
        modified = true;
        count--;
        return pnode.value;
    }

    @Override
    public void clear() {
        count = 0;
        tree = null;
        firstEntry = null;
        lastEntry = null;
    }

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

    /**
     * Reads the given number of ientries from the input stream, returning the
     * corresponding tree.istream@param s the input stream.
     * @param n the (positive) number of ientries 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);
            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.right(new Entry<>(istream.readInt(), (V) istream.readObject()));
            top.right.pred(top);
            top.balance(1);
            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.right(readTree(istream, rightN, top, succ));
        if (n == (n & -n)) {
            top.balance(1); // Quick test for determining whether n 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 balance, 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> {

        /**
         * 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 bits in this mask hold the node balance info. You can get it just
         * by casting to byte.
         */
        private final static int BALANCE_MASK = 0xFF;
        /**
         * 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}, {@link #PRED_MASK} and {@link #BALANCE_MASK}).
         */
        int info;

        Entry() {
        }

        /**
         * Creates a new entry with the given key and key.
         *
         * @param k 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 the current level of the node.
         *
         * @return the current level of this node.
         */
        int balance() {
            return (byte) info;
        }

        /**
         * Sets the level of this node.
         *
         * @param level the new level of this node.
         */
        void balance(int level) {
            info &= ~BALANCE_MASK;
            info |= (level & BALANCE_MASK);
        }

        /**
         * Increments the level of this node.
         */
        void incBalance() {
            info = info & ~BALANCE_MASK | ((byte) info + 1) & 0xFF;
        }

        /**
         * Decrements the level of this node.
         */
        protected void decBalance() {
            info = info & ~BALANCE_MASK | ((byte) info - 1) & 0xFF;
        }

        /**
         * 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 CompareUtils.equals(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();
            AIntAVLTreeMap.this.remove(curr.key);
            curr = null;
        }

        @Override
        public void set(IntEntry<V> entry) {
            throw new UnsupportedOperationException();
        }

        @Override
        public void add(IntEntry<V> entry) {
            throw new UnsupportedOperationException();
        }
    }

    /**
     * A submap with given range.
     *
     * <P>This class represents a submap. One has to specify the left/right
     * limits (which can be set to -&infin; or &infin;). Since the submap is a
     * view on the map, at a given moment it could happen that the limits of the
     * range are not any longer in the main map. Thus, things such as
     * {@link java.util.SortedMap#firstKey()} or
     * {@link java.util.Collection#size()} must be always computed on-the-fly.
     */
    @SuppressFBWarnings("SE_INNER_CLASS")
    private final class Submap extends ASubmap implements java.io.Serializable {

        private static final long serialVersionUID = 3L;
        
        public Submap(int begin, boolean bottom, int end, boolean top) {
            super(begin, bottom, end, top);
        }

        @Override
        protected AIntAVLTreeMap.Entry<V> locateEntry(int k) {
            return AIntAVLTreeMap.this.locateEntry(k);
        }

        @Override
        protected AIntAVLTreeMap.Entry<V> findEntry(int k) {
            if(!inside(k)) {
                return null;
            }
            return AIntAVLTreeMap.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 AIntAVLTreeMap.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.
            AIntAVLTreeMap.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 subset 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;
        }

        /**
         * Locates the last entry.
         *
         * @return the last entry of this submap, or <code>null</code> if the
         * submap is empty.
         */
        @Override
        public AIntAVLTreeMap.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.
            AIntAVLTreeMap.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 subset 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 && AIntAVLTreeMap.this.compare(prev.key, begin) < 0) {
                    prev = null;
                }
            }

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

    }

}
