refractored and cleaned up