fixed memory leaks and cast away const that could have resulted in problems