Code has been refactored a bit. I hope it looks more elegant now