Completely reworked the code