updated and cleaned up code