improvements in the code suggested by adampalay