Fix a lot of issues (bugs), add unit tests