fixed a horrible bug and optimized the code