Neaten and document

Simplify boiler plate code, split the function into two and add
documentation