Fixed database errors and corrected logic.