extracted most of the code into three methods