Refactor main code

Re-factoring complete to a stable level