added write code and simplified some other parts