Several improvements

This pull request includes a lot of commits. From fixing bugs to better testing.