Refactored PR #40, and moved all the logic to hook.