/* Heap - Decompiled by JODE
 * Visit http://jode.sourceforge.net/
 */
package salvo.jesus.util;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Vector;

public class Heap implements Serializable
{
    Vector binarytree;
    HeapNodeComparator comparator;
    
    public Heap() {
	binarytree = new Vector();
	comparator = new HeapNodeComparator(-1);
    }
    
    public Heap(HeapNodeComparator heapnodecomparator) {
	binarytree = new Vector();
	comparator = heapnodecomparator;
    }
    
    public void insert(HeapNode heapnode) {
	int i = binarytree.size();
	binarytree.add(heapnode);
	upHeap(i);
    }
    
    public HeapNode remove() {
	HeapNode heapnode = (HeapNode) binarytree.get(0);
	HeapNode heapnode_0_
	    = (HeapNode) binarytree.get(binarytree.size() - 1);
	binarytree.set(0, heapnode_0_);
	binarytree.remove(binarytree.size() - 1);
	if (binarytree.size() > 0)
	    downHeap(0);
	return heapnode;
    }
    
    public void setPriority(HeapNode heapnode, double d) {
	if (binarytree.contains(heapnode)) {
	    heapnode.setPriority(d);
	    int i = binarytree.indexOf(heapnode);
	    i = upHeap(i);
	    downHeap(i);
	}
    }
    
    public void clear() {
	binarytree.clear();
    }
    
    public boolean isEmpty() {
	return binarytree.isEmpty();
    }
    
    public HeapNode contains(Object object, Comparator comparator) {
	return (HeapNode) Collections.contains(binarytree, object, comparator);
    }
    
    private int upHeap(int i) {
	HeapNode heapnode = (HeapNode) binarytree.get(i);
	while (i != 0) {
	    int i_1_ = i / 2;
	    if (i % 2 == 0)
		i_1_--;
	    HeapNode heapnode_2_ = (HeapNode) binarytree.get(i_1_);
	    if (comparator.compare(heapnode, heapnode_2_) <= 0)
		break;
	    binarytree.set(i, heapnode_2_);
	    i = i_1_;
	    if (i <= 0)
		break;
	}
	binarytree.set(i, heapnode);
	return i;
    }
    
    private int downHeap(int i) {
	HeapNode heapnode = (HeapNode) binarytree.get(i);
	int i_3_ = binarytree.size();
	while (i_3_ > 1) {
	    int i_4_ = i * 2 + 1;
	    int i_5_ = i * 2 + 2;
	    HeapNode heapnode_6_;
	    if (i_4_ >= i_3_)
		heapnode_6_ = null;
	    else
		heapnode_6_ = (HeapNode) binarytree.get(i_4_);
	    HeapNode heapnode_7_;
	    if (i_5_ >= i_3_)
		heapnode_7_ = null;
	    else
		heapnode_7_ = (HeapNode) binarytree.get(i_5_);
	    if (heapnode_6_ == null && heapnode_7_ == null)
		break;
	    int i_8_;
	    if (heapnode_6_ != null && heapnode_7_ == null)
		i_8_ = i_4_;
	    else if (comparator.compare(heapnode_6_, heapnode_7_) < 0)
		i_8_ = i_5_;
	    else
		i_8_ = i_4_;
	    HeapNode heapnode_9_ = (HeapNode) binarytree.get(i_8_);
	    if (comparator.compare(heapnode, heapnode_9_) >= 0)
		break;
	    binarytree.set(i, heapnode_9_);
	    i = i_8_;
	    if (i >= i_3_ - 1)
		break;
	}
	binarytree.set(i, heapnode);
	return i;
    }
    
    public String toString() {
	return binarytree.toString();
    }
}
