Reorganised scripts again

Moved most code outside of the main script for added flexibility.