Refactoring and reformatting
Added error handling
Hid environment in the Reader monad
Embedded normalization steps into a state monad
Improved error handling