Move some code and add testcases.

Signed-off-by: crynobone <crynobone@gmail.com>