changed order, write to temp file first in case of longer search operation