Adding changes to Nolds code (seems to work now).