First working version

Needs refactoring, but basic functionality is intact.