Adding original Java implementation as a reference.