Bug fix for issue #102 - Stack overflow while writing data. Also addresses issue #115 & issue #216. Thanks to teerapap for the patch. (it's being used with the addition of an autoreleasepool)