Reorganized and tested code.