Refactor bufferd

This includes a fix for a memory leak due to unoptimized tail recursion.