package chromaticTuner.tuner;

public class Normalizer {
	private int m_normalizeMaxValue = 0;
	private int m_normI = 0;
	
	public void normalizeBuffer(short[] buffer) {
		m_normalizeMaxValue = 0;
		for (m_normI = 0; m_normI < buffer.length; m_normI++) {
			if (Math.abs(buffer[m_normI]) > m_normalizeMaxValue) {
				m_normalizeMaxValue = Math.abs(buffer[m_normI]);
			}
		}

		if (m_normalizeMaxValue > Short.MAX_VALUE
				|| m_normalizeMaxValue >= -(int) (Short.MIN_VALUE)) {
			m_normalizeMaxValue = Short.MAX_VALUE;
		}

		for (m_normI = 0; m_normI < buffer.length; m_normI++) {
			if (Math.abs(buffer[m_normI]) > m_normalizeMaxValue) {
				buffer[m_normI] = (short) ((int) buffer[m_normI]
						* (Short.MAX_VALUE - 8) / m_normalizeMaxValue);
			}
		}
	}
}
