fixed segfault issue and improved logic