add unit test, fix variable scoping issue