Various fixes and debugging help: particularly don't use random().