Fixed several nasty JNI and other bugs