Tidied up main code - main points:
* Replaced all != None with not
* Reindented everything to (almost) PEP8
* Renamed all variables which used internal type names
* Replaced i = i+1 with i += 1