risky rewrite of some key functions but seems to work