Clean code and add type checking
Moved decision on whether to continue to outer shell
Added imperative version
Simplification
Minor change