amended working code

Amended code that works, thanks to help on SO!