working version - some memory leakage