let with_temp_file_opened_bin ~cleanup ~temp_dir prefix suffix func =
  let (path_tmp, out_ch) =
    try
      Filename.open_temp_file ~mode: [ Open_binary ] ~temp_dir prefix suffix
    with
    | e ->
        error ~opn: "with_temp_file_opened_bin/Filename.open_temp_file"
          ~fn:
            (Printf.sprintf "temp_dir=%S prefix=%S suffix=%S" temp_dir prefix
               suffix)
          ~e in
  let finally () =
    ((try close_out out_ch
      with
      | e ->
          error ~opn: "with_temp_file_opened_bin/close_out" ~fn: path_tmp ~e);
     if cleanup then remove_file path_tmp else ())
  in
    try let r = func path_tmp out_ch in (finally (); r)
    with | e -> (finally (); raise e)