Working write-state-function