Fix logic flaws