The flagging is purely geometric. Therefore the best way is to build a flag map accumulating all the causes for flagging. For each bad pixel, ON_BADPIX is written at the exact location of the bad pixel, CLOSE_TO_DEADPIX and CLOSE_TO_BRIGHTPIX are written in all 4 pixels immediately next to that location. Here 'written' means ORed with the previous value of that pixel.
For each event all one has to do then is OR the flag map at the event's location with the FLAG column. Note that only the main pixel of each event is considered. This is enough for most purposes because the majority of events are single. To do better (e.g. flag multiple events when a secondary pixel is next to a bad pixel), one needs to run epchain or emchain anew.