working kod with some memory problems