cleanup and rewritten