Added code and tests for stats
Minor refactroings