adding apply, cleaning up some code