BUG FIXES AND CODE FORMATTING

Few bug fixes. Complete code reformatting.