Hacked to get vars working ok. NOT REENTRANT. Must rework :(