package rms

import (
	"encoding/binary"
	"math"
)

func RMS(voicedata []byte) float64 {
	var rms, sum, average float64
	rms = 0.0
	sum = 0.0
	length := len(voicedata)

	if length <= 0 {
		return 0.0
	}

	length /= 2

	for iter := 0; iter < length; iter++ {
		uval := binary.LittleEndian.Uint16(voicedata[iter*2 : iter*2+2])
		sval := int16(uval)
		pval := math.Pow(float64(sval), 2)
		sum += pval
	}
	average = sum / float64(length)

	/*
			for iter := 0; iter < length; iter++ {
				summs += math.Pow(float64(voicedata[iter])-average, float64(2))
			}
		avgms = summs / float64(length)
	*/

	rms = math.Sqrt(average)

	return rms
}
