fixed segfault, next rewrite code