translated to javascript - still needs full review/commenting