complete re-write of the code