initial code rewrite from JS