Code refactoring

Heya, I did some changes to remove duplicate code and adhere to the Don't Repeat Yourself principle.