First of many many many commits to get this ported from java