Bug fixes, changes in writing functions