Progress refactoring super-long function.
Fixed escaping.