Fixed some logic flaws