Move generic attach and detach to utils

Reformat code a little, too.