Fix errors

There are still some minor logic errors, I will fix them in the following commits.