refactor the crazy nesting 
https://gist.github.com/keyvanfatehi/80a341f0a92445a41ef1