Fixes lots of bugs and improves portability