Added comments and modularized some logic