enclosing function, v1, many bugs and todo