added last function, cleaned up some code