Refactored preprocess and render(), including cleanup and optimization.