Reorganized code, fixes