fixed some bad logic; added more comments