First modifications, adding util functions and separating code into functions