Some code cleanup and error handling (work in progress)