Updated code to more readable and abstracted some functionality