Code cleaned and rearanged

Code has been cleaned and readablity has been improved. Lots of tweaks
and small additions. No basic functionality has been changed.