Fixed a few logic mistakes in the code