tried to tidy, but code is to ugly, halting here