Ported completely to scala