if ($offset == 1) {
                    // print filename headers as first line
                    $fields_order = $rets->SearchGetFields($search);
                    fputcsv($fh, $fields_order);
                }
                // process results
                while ($record = $rets->FetchRow($search)) {
                    $this_record = array();
                    foreach ($fields_order as $fo) {
                        $this_record[] = $record[$fo];
                    }
                    fputcsv($fh, $this_record);
                }
                $offset = $offset + $rets->NumRows();
            }
            $maxrows = $rets->IsMaxrowsReached();
            if ($debugging) {
                echo "    + Total found: {$rets->TotalRecordsFound()}<br>\n";
            }
            $rets->FreeResult($search);
        }
        fclose($fh);
        if ($debugging) {
            echo "  - done<br>\n";
        }
    }
}
if ($debugging) {
    echo "+ Disconnecting<br>\n";
}
$rets->Disconnect();