Modified second example, added more functions to make the code more robust