lots of ifs and stuff, I think writing it in SQ would look considerably cleaner, readable and consise