working version with memory problem fixed