Improved solution, thanks to looking at the work of others on the Interweb