this method could be split (refactored), this is pretty hard to follow on what's doing