added some hacks for more numerical accuracy. Code mostly works