Ported some code from c# to java