Finally works properly, now only some performance tweaks.