almost complete re-write, much cleaner now...