changed memory management and simplified some loops
more simplification