Working version of previous optimization