Cleaned up duplicate code.
some tests fixed