refactored main body as function

Redesigned this file to be imported as a library by the main code
(hopefully)