Almost done.
- Added function factory
- Fixed several bugs
- Some cleanup