adding some comments and a little refactoring for code clarity