finished rewriting
finished rewritting and bugfix