+}
+
+static void startup(void) {
+ int r;
+
+ if (nonblock(0,1)) sysfail("set stdin to nonblocking mode");
+ if (nonblock(1,1)) sysfail("set stdout to nonblocking mode");
+ memset(&sa,0,sizeof(sa));
+ sa.sin_family= AF_INET;
+ r= adns_init(&ads,0,0); if (r) adnsfail("init",r);
+ cbyte= -1;
+ inbyte= -1;
+ inbuf= 0;
+ if (!bracket) startaddr();
+}
+
+int main(int argc, const char *const *argv) {
+ int r, maxfd;
+ fd_set readfds, writefds, exceptfds;
+ struct outqueuenode *entry;
+ struct timeval *tv, tvbuf, now;
+
+ parseargs(argv);
+ startup();
+
+ while (!inputeof || outqueue.head) {
+ maxfd= 2;
+ tv= 0;
+ FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds);
+ if ((entry= outqueue.head) && !outblocked) {
+ if (!entry->addr) {
+ writestdout(entry);
+ continue;
+ }
+ if (entry->addr->ans) {
+ if (entry->addr->ans->nrrs)
+ replacetextwithname(entry);
+ entry->addr= 0;
+ continue;
+ }
+ r= gettimeofday(&now,0); if (r) sysfail("gettimeofday");
+ if (forever) {
+ tv= 0;
+ } else if (!timercmp(&now,&entry->printbefore,<)) {
+ entry->addr= 0;
+ continue;
+ } else {
+ tvbuf.tv_sec= entry->printbefore.tv_sec - now.tv_sec - 1;
+ tvbuf.tv_usec= entry->printbefore.tv_usec - now.tv_usec + 1000000;
+ tvbuf.tv_sec += tvbuf.tv_usec / 1000000;
+ tvbuf.tv_usec %= 1000000;
+ tv= &tvbuf;
+ }
+ adns_beforeselect(ads,&maxfd,&readfds,&writefds,&exceptfds,
+ &tv,&tvbuf,&now);
+ }
+ if (outblocked) FD_SET(1,&writefds);
+ if (!inputeof && outqueuelen<1024) FD_SET(0,&readfds);
+
+ r= select(maxfd,&readfds,&writefds,&exceptfds,tv);
+ if (r < 0) { if (r == EINTR) continue; else sysfail("select"); }
+
+ r= gettimeofday(&now,0); if (r) sysfail("gettimeofday");
+ adns_afterselect(ads,maxfd,&readfds,&writefds,&exceptfds,&now);
+ checkadnsqueries();
+
+ if (FD_ISSET(0,&readfds)) {
+ if (!forever) {
+ printbefore= now;
+ timevaladd(&printbefore,timeout);
+ }
+ readstdin();
+ } else if (FD_ISSET(1,&writefds)) {
+ outblocked= 0;
+ }
+ }
+ if (nonblock(0,0)) sysfail("un-nonblock stdin");
+ if (nonblock(1,0)) sysfail("un-nonblock stdout");
+ if (ferror(stdin) || fclose(stdin)) sysfail("read stdin");