Complete rewrite.
Fix memory management.