cleaned, working single thread version