Pre-attempt at rewrite
Gave the code a facelift