Fixes #4. Not fully tested but fixes everything I've found so far.