Adding the reworked code - work in progress. Does not compile yet.