Just a thought, I think this function wraps too much functionality into one.
Makes it difficult to read.