Re factored code to simplify it.