implementing a closure and fixing some scope  bugs