Some code changes thanks to @Cromon.