Modified quite heavily - added more functions so the whole thing isn't just a long unmanageable script.
The way it passes variables between functions still needs work.