Working version. Requires a lot of memory