full rewrite of code for cleanup