Updated with Java implementation.