Fixed bugs and extracted writing code