Implement delete function.

Also, refactor out some code.