/*
 * The Broad Institute
 * SOFTWARE COPYRIGHT NOTICE AGREEMENT
 * This is copyright (2007-2008) by the Broad Institute/Massachusetts Institute 
 * of Technology.  It is licensed to You under the Gnu Public License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *    http://www.opensource.org/licenses/gpl-2.0.php
 *
 * This software is supplied without any warranty or guaranteed support
 * whatsoever. Neither the Broad Institute nor MIT can be responsible for its
 * use, misuse, or functionality.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.broad.igv.data;

/**
 *
 * @author jrobinso
 */
public class FloatArrayList {

    static final int maxGrowIncrement = Integer.MAX_VALUE / 10;
    int size = 0;
    float[] values;

    public FloatArrayList(int maxSize) {
        values = new float[maxSize];
    }

    public void add(float v) {
        if (size >= values.length) {
            grow();
        }
        values[size] = v;
        size++;
    }

    public void addAll(float[] array) {
        if (values.length - size < array.length) {
            grow(array.length);
        }
        System.arraycopy(array, 0, values, size, array.length);
        size += array.length;
    }

    public float[] toArray() {
        trim();
        return values;
    }

    public int getSize() {
        return size;
    }

    private void grow() {
        grow((int) (Math.max(1000, 0.2 * values.length)));
    }

    private void grow(int increment) {
        if (values.length >= Integer.MAX_VALUE) {
            throw new RuntimeException("Maximum array size exceeded");
        }
        int newSize = Math.min(Integer.MAX_VALUE, values.length + increment);
        resize(newSize);

    }

    private void resize(int newSize) {
        float[] tmp = new float[newSize];
        System.arraycopy(values, 0, tmp, 0, Math.min(tmp.length, values.length));
        values = tmp;
    }

    private void trim() {
        resize(size);
    }

    public void reorder(int[] indeces) {
        if (indeces.length != size) {
            throw new IllegalArgumentException(
                    "Index array length not equal to size");
        }
        float[] reorderedValues = new float[size];
        for (int i = 0; i < size; i++) {
            reorderedValues[i] = values[indeces[i]];
        }
        values = reorderedValues;
    }
}
