added function and cleaned up code