This whole method is a bit ugly. I assume @tekin or @gma will have some refactoring suggestions.