added few comments and rewrote logic