Added comments and fixed some logic errors