Refactored into better structure, better output and more fault tolerance.