Creation of various functions to make the code leaner. Many corrections made​​.