In addition to Joe's answer and ibaranov's addition, I also had to add this:
if last.field2 then flag_out='';
after
if last.field2 then output;
to get it working.