Can you organize this a bit better to avoid code duplication?