Some cleanup of the most complex bits related to the metric, much more to come
More cleanup and commenting. Renamed some important functions.