rewrite tested and working