Clean up code, improve performance, add proper tests