Code refactoring and an Appendix with the full code in it