working single thread version