cleanup and refactoring

cleanup code, add comments, put code in privat function ... note: must be compiled, cause online editing on github.