Massive (complicated) changes to the main script.