Code restructure and more robust error handling