completed code, it now needs debugging, especially because of a nested lambda