Clean up some functions in util and metrics

Add documentation to some functions in util and metrics.

Refactor some code.

Write a few new functions and some tests.