Refined error handling and improved readability of code

Signed-off-by: Ted Gibbons <ted.codes@gmail.com>