Moved most code out and into separate files