fixed a major error, and simplified some code