Added support for writing. Some refactoring.