Enhancement: move logic to a library
Refactor: improve variable naming
Refactor: use a loop to do the same thing twice