bugfix and documentation. Also straightened up code a bit