Second commit, completely rewrote the code