Refactor code according.

Reformat code according to PEP8
Encapsulate different functionality within functions
Improve line parsing by using regexps.