(nearly) completed rewrite from C# to Java