Move functions to a common lib

Caution, this may break stuff.

Please help test.