Completely ported SAPI cleanup process

Also fixed some small bugs and memory leaks.
Not final yet.