Totally overhaul code; practically a rewrite