code cleanup and some tests