I tend to attack these kind of problems differently - not better, necessarily - by generalizing the steps and using simple math where possible:

- calculate the leading spaces
- print the spaces...