Reworked code to make it cleaner