finally working efficient version