Restructure code and add comments.