Condensed code, included some more comments for readability