first step of cleaning up code; not usable at the moment
Further simplifications and clean-up
Rewriting for simplification