This is an unoptimized version with some bug fixes