Code cleanup, tried to implement suggestions from @jvazquez-r7. Hopefully is much more readable.