added write + restructured code