Fix bug reported by @Dandandan in which a runtime error leads to a crash
Format code to be a bit more readable