Final version with comments and bug fixes