Fixing bugs in previous implementation.