Added sample averaging, code clean-ups