Added comments and algorithm to this code for better understanding