Converted some pieces of code into functions