Moved duplicate code into function

Signed-off-by: Nick Brook <nick@rmpenterprise.co.uk>