fixed several memory leaks and array indexing errors, implemented window function maths