Final code that seems to run OK...