Add comments and restructure code