How do I get rid of duplication

Undoubtedly many ways, but the code is almost impossible to decipher by someone who has little or no idea what it does.

Consider adding some comments, and an overview statement.