restructured function to be less stupid