Fixed tabulation
Moved some code into separate func

+ some other small changes.