refined and tested new code