try to make some sense in some of the funm code, still has obvious problems with regards to semantics of the function. Related to issue #490
add a number of missing includes