Many changes. Rewrited to decrease memory usage.