Overall the code needs some refactor. There exist repeated lines of code which can be reduced to a function.