Remade using a lot cleaner, better commented implementation