Reorganized and simplied code