Added comments and changed code structure