Improved code based on comments from @arthurschreiber