Metrics Script refactoring and bug fixes

Extracted functions where possible in order to flatten the code, fixed
infinite recursion bug.