cleaning some memory problems and bad handling of special cases