At a glance (I could be wrong) both conditions have a lot of similar code. Could this be written more compactly to reduce code duplication?