divided the code into functions instead of doing all the processing in the callback function