Cleaned the code + added some error handling