restructuring and clean up in the hope that I can reuse a bit of code