condense repeated code and callbacks

While reviewing the compile warnings I noticed that some of the code was duplicated, so I have condensed it to remove the duplication