Added proper check of input and some other cosmetic changes to the code