completely restructured write logic