Updated version with comments and some extra improvements.