refined code per Pete's suggestions