Refactor code layout. Add extra functionality and error checking.