Bug and memleak fixed