Completely re-factored - very old code (needs updating)