New python script with separation of concerns

Restructured the main script into a greater number of simpler functions
with less repetition and wider usability.