Completely redesigned logic

some code from previous rewrites left in this version in case I need to
refer to them.