Fix several bugs

Now the code is basically in working condition.