I added the requested changes nearly verbatim, some whitespace changes, ...

...sorry

There are some comments in there,
not really sure about some parts