merged and cleaned up code