예제 #1
0
파일: edit.c 프로젝트: cpplife/mycscope
void
edit(char *file, char *linenum)
{
	char	msg[MSGLEN + 1];	/* message */
	char	plusnum[NUMLEN + 20];	/* line number option: allow space for wordy line# flag */
	char	*s;
	char    path[PATHLEN + 1];

	file = filepath(file, path, PATHLEN + 1);
	(void) snprintf(msg, sizeof(msg), "%s +%s %s", mybasename(editor), linenum, file);
	postmsg(msg);
	(void) snprintf(plusnum, sizeof(plusnum), lineflag, linenum);
	/* if this is the more or page commands */
	if (strcmp(s = mybasename(editor), "more") == 0 || strcmp(s, "page") == 0) {
		
		/* get it to pause after displaying a file smaller than the screen
		   length */
		(void) execute(editor, editor, plusnum, file, "/dev/null", NULL);
	}
	else if (lineflagafterfile) {
		(void) execute(editor, editor, file, plusnum, NULL);
	}
	else {
		(void) execute(editor, editor, plusnum, file, NULL);
	}
	clear();	/* redisplay screen */
}
예제 #2
0
int
main(int argc, char *argv[])
{
      DWORD crc;
      long charcnt;
      register errors = 0;

      while(--argc > 0)
      {
            errors |= crc32file(*++argv, &crc, &charcnt);
            printf("%08X %7ld %s\n", (int) crc, charcnt, mybasename(*argv));
      }
      return(errors != 0);
}
예제 #3
0
파일: mypopen.c 프로젝트: acampbell/kscope
FILE *
mypopen(char *cmd, char *mode)
{
#if defined(WIN32)
	/* HBB 20010312: Has its own implementation of popen(), which
	 * is better suited to the platform than cscope's */
	return (popen)(cmd, mode);
#else
	int	p[2];
	pid_t *poptr;
	int myside, yourside;
	pid_t pid;

	if(pipe(p) < 0)
		return(NULL);
	myside = tst(p[WTR], p[RDR]);
	yourside = tst(p[RDR], p[WTR]);
	if((pid = fork()) == 0) {
		/* myside and yourside reverse roles in child */
		int	stdio;

		/* close all pipes from other popen's */
		for (poptr = popen_pid; poptr < popen_pid+20; poptr++) {
			if(*poptr)
				(void) close(poptr - popen_pid);
		}
		stdio = tst(0, 1);
		close(myside);
		close(stdio);
#if defined(HAVE_F_DUPFD)
		fcntl(yourside, F_DUPFD, stdio);
#else
		dup2(yourside, stdio);
#endif /* defined(HAVE_F_DUPFD) */
		close(yourside);
		execlp(shell, mybasename(shell), "-c", cmd, (void *)0);
		_exit(1);
	} else if (pid > 0)
#if defined(HAVE_SIGSTP)
		tstat = signal(SIGTSTP, SIG_DFL);
#endif
        
	if(pid == -1)
		return(NULL);
	popen_pid[myside] = pid;
	(void) close(yourside);
	return(fdopen(myside, mode));
#endif /* DJGPP */
}
예제 #4
0
mpeginfo *mpegOpen(char *filename)
{
  mpeginfo *mi;

  mi=(mpeginfo *) malloc(sizeof(mpeginfo));
  
  mi->fname=(char *) malloc(strlen(filename)+2);
  mi->iname=(char *) malloc(strlen(filename)+10);
  strcpy(mi->fname,filename);
  strcpy(mi->iname,mybasename(filename));
  strcat(mi->iname,".index");

  OpenMpegForStats(mi->fname,&mi->img);

  return(mi);
}
예제 #5
0
/* myexecvp is an interface to the execvp system call to
 * modify argv[0] to reference the last component of its path-name.
 */
static int
myexecvp(char *a, char **args)
{
    char    msg[MSGLEN + 1];
	
    /* modify argv[0] to reference the last component of its path name */
    args[0] = mybasename(args[0]);

    /* execute the program or shell script */
    execvp(a, args);	/* returns only on failure */
    snprintf(msg, sizeof(msg), "\nCannot exec %s", a);
    perror(msg);		/* display the reason */
    askforreturn();		/* wait until the user sees the message */
    myexit(1);		/* exit the child */
    /* NOTREACHED */
}
예제 #6
0
파일: wadder.cpp 프로젝트: arthuraa/quadra
void addfile(const char* fname) {
	Res_dos *res;
	char *data;

	printf("%s: ", fname);
	res = new Res_dos(fname, RES_TRY);
	data = new char[res->size()];
	res->read(data, res->size());

	wad->add(mybasename(fname), res->size(), data);

	delete res;
	delete data;

	printf("done\n");
}
예제 #7
0
void	server_reboot(void)
{
	Reg	int	i;

	sendto_flag(SCH_NOTICE, "Aieeeee!!!  Restarting server... (%u)",
		    (u_int)((char *)sbrk((size_t)0)-sbrk0));

	Debug((DEBUG_NOTICE,"Restarting server..."));
	flush_connections(me.fd);
	/*
	** fd 0 must be 'preserved' if either the -d or -i options have
	** been passed to us before restarting.
	*/
#ifdef USE_SYSLOG
	(void)closelog();
#endif
	logfiles_close();
	for (i = 3; i < MAXCONNECTIONS; i++)
		(void)close(i);
	if (!(bootopt & (BOOT_TTY|BOOT_DEBUG)))
	{
		(void)close(2);
		(void)close(1);
	}
	if ((bootopt & BOOT_CONSOLE) || isatty(0))
		(void)close(0);
	ircd_writetune(tunefile);
	if (!(bootopt & BOOT_INETD))
	    {
		(void)execv(IRCD_PATH, myargv);
#ifdef USE_SYSLOG
		/* Have to reopen since it has been closed above */
		
		openlog(mybasename(myargv[0]), LOG_PID|LOG_NDELAY, LOG_FACILITY);
		syslog(LOG_CRIT, "execv(%s,%s) failed: %m\n", IRCD_PATH,
		       myargv[0]);
		closelog();
#endif
		Debug((DEBUG_FATAL,"Couldn't restart server: %s",
		       strerror(errno)));
	    }
	exit(-1);
}
예제 #8
0
파일: map.c 프로젝트: AOSC-Dev/w3m-ng
Buffer *
follow_map_panel(Buffer *buf, char *name)
{
    Str mappage;
    MapList *ml;
    ListItem *al;
    MapArea *a;
    ParsedURL pu;
    char *p, *q;
    Buffer *newbuf;

    ml = searchMapList(buf, name);
    if (ml == NULL)
	return NULL;

    mappage = Strnew_charp(map1);
    for (al = ml->area->first; al != NULL; al = al->next) {
	a = (MapArea *) al->ptr;
	if (!a)
	    continue;
	parseURL2(a->url, &pu, baseURL(buf));
	p = parsedURL2Str(&pu)->ptr;
	q = html_quote(p);
	if (DecodeURL)
	    p = html_quote(url_unquote_conv(p, buf->document_charset));
	else
	    p = q;
	Strcat_m_charp(mappage, "<tr valign=top><td><a href=\"", q, "\">",
		       html_quote(*a->alt ? a->alt : mybasename(a->url)),
		       "</a><td>", p, NULL);
    }
    Strcat_charp(mappage, "</table></body></html>");

    newbuf = loadHTMLString(mappage);
#ifdef USE_M17N
    if (newbuf)
	newbuf->document_charset = buf->document_charset;
#endif
    return newbuf;
}
예제 #9
0
size_t read_dmatrix(dvarray* out, const char* filename) {
    FILE* fid = fopen(filename,"rt");
    double value;
    size_t i, j, width = 0, height = 0;

    printf("Opened file %s for matrix reading\n", mybasename(filename));

    fscanf(fid, "%d %d", &height, &width);

    dvarray_init(out, height, width);

    for (i=0; i<height; ++i) {
      for (j=0; j<width; ++j) {
        fscanf(fid,"%lf",&value);
        out->data[i].data[j] = value;
      }
    }

    printf("%g\n", out->data[i-1].data[j-1]);
    fclose(fid);
    printf("File read and closed\n");
    return i*j;
}
예제 #10
0
int	main(int argc, char *argv[])
{
	uid_t	uid, euid;

	sbrk0 = (char *)sbrk((size_t)0);
	uid = getuid();
	euid = geteuid();

#ifdef	CHROOTDIR
	ircd_res_init();
	if (chdir(ROOT_PATH)!=0)
	{
		perror("chdir");
		(void)fprintf(stderr,"%s: Cannot chdir: %s.\n", IRCD_PATH,
			ROOT_PATH);
		exit(5);
	}
	if (chroot(ROOT_PATH)!=0)
	    {
		perror("chroot");
		(void)fprintf(stderr,"%s: Cannot chroot: %s.\n", IRCD_PATH,
			      ROOT_PATH);
		exit(5);
	    }
#endif /*CHROOTDIR*/

#ifdef	ZIP_LINKS
	if (zlib_version[0] == '0')
	    {
		fprintf(stderr, "zlib version 1.0 or higher required\n");
		exit(1);
	    }
	if (zlib_version[0] != ZLIB_VERSION[0])
	    {
        	fprintf(stderr, "incompatible zlib version\n");
		exit(1);
	    }
	if (strcmp(zlib_version, ZLIB_VERSION) != 0)
	    {
		fprintf(stderr, "warning: different zlib version\n");
	    }
#endif

	myargv = argv;
	(void)umask(077);                /* better safe than sorry --SRB */
	bzero((char *)&me, sizeof(me));

	make_server(&me);
	register_server(&me);

	version = make_version();	/* Generate readable version string */

	/*
	** All command line parameters have the syntax "-fstring"
	** or "-f string" (e.g. the space is optional). String may
	** be empty. Flag characters cannot be concatenated (like
	** "-fxyz"), it would conflict with the form "-fstring".
	*/
	while (--argc > 0 && (*++argv)[0] == '-')
	    {
		char	*p = argv[0]+1;
		int	flag = *p++;

		if (flag == '\0' || *p == '\0')
		{
			if (argc > 1 && argv[1][0] != '-')
			{
				p = *++argv;
				argc -= 1;
			}
			else
			{
				p = "";
			}
		}

		switch (flag)
		    {
                    case 'a':
			bootopt |= BOOT_AUTODIE;
			break;
		    case 'b':
			bootopt |= BOOT_BADTUNE;
			break;
		    case 'c':
			bootopt |= BOOT_CONSOLE;
			break;
		    case 'q':
			bootopt |= BOOT_QUICK;
			break;
#ifdef CMDLINE_CONFIG
		    case 'f':
                        (void)setuid((uid_t)uid);
			configfile = p;
			break;
#endif
		    case 'h':
			if (*p == '\0')
				bad_command();
			strncpyzt(me.serv->namebuf, p, sizeof(me.serv->namebuf));
			break;
		    case 'i':
			bootopt |= BOOT_INETD|BOOT_AUTODIE;
		        break;
		    case 'p':
			if (!strcmp(p, "strict"))
				bootopt |= BOOT_PROT|BOOT_STRICTPROT;
			else if (!strcmp(p, "on"))
				bootopt |= BOOT_PROT;
			else if (!strcmp(p, "off"))
				bootopt &= ~(BOOT_PROT|BOOT_STRICTPROT);
			else if (!strcmp(p, "standalone"))
				bootopt |= BOOT_STANDALONE;
			else
				bad_command();
			break;
		    case 's':
			bootopt |= BOOT_NOIAUTH;
			break;
		    case 't':
#ifdef DEBUGMODE
                        (void)setuid((uid_t)uid);
#endif
			bootopt |= BOOT_TTY;
			break;
		    case 'T':
			tunefile = p;
			break;
		    case 'v':
			(void)printf("ircd %s %s\n\tzlib %s\n\tircd.conf delimiter %c\n\t%s #%s\n",
				     version, serveropts,
#ifndef	ZIP_LINKS
				     "not used",
#else
				     zlib_version,
#endif
					IRCDCONF_DELIMITER,
				     creation, generation);
			  exit(0);
		    case 'x':
#ifdef	DEBUGMODE
                        (void)setuid((uid_t)uid);
			debuglevel = atoi(p);
			debugmode = *p ? p : "0";
			bootopt |= BOOT_DEBUG;
			break;
#else
			(void)fprintf(stderr,
				"%s: DEBUGMODE must be defined for -x y\n",
				myargv[0]);
			exit(0);
#endif
		    default:
			bad_command();
		    }
	    }

	if (strlen(tunefile) > 1023 || strlen(mybasename(tunefile)) > 42)
	{
		fprintf(stderr, "Too long tune filename\n");
		exit(-1);
	}
	if (argc > 0)
		bad_command(); /* This exits out */

#ifndef IRC_UID
	if ((uid != euid) && !euid)
	    {
		(void)fprintf(stderr,
			"ERROR: do not run ircd setuid root. Make it setuid a\
 normal user.\n");
		exit(-1);
	    }
예제 #11
0
unsigned char *ramdisk_load (const char *filename, int32_t *outlen)
{
    ramdisk_t *ramfile = ramdisk_data;
    unsigned char *out;
    char *alt_filename;

    alt_filename = 0;

    /*
     * If the file is on disk and is newer than the program, use that in
     * preference.
     */
    if (file_exists(filename)) {
        if (strstr(filename, "data/")) {
            if (file_exists_and_is_newer_than(filename,
                                              EXEC_FULL_PATH_AND_NAME)) {
                out = file_read_if_exists(filename, outlen);
                if (out) {
                    DBG("Locdisk %s (newer than exec)", filename);
                    return (out);
                }
            }

            if (file_exists_and_is_newer_than(filename, ".o/ramdisk_data.o")) {
                out = file_read_if_exists(filename, outlen);
                if (out) {
                    DBG("Locdisk %s (newer than build)", filename);
                    return (out);
                }
            }

            if (file_exists_and_is_newer_than(filename, "src/.o/ramdisk_data.o")) {
                out = file_read_if_exists(filename, outlen);
                if (out) {
                    DBG("Locdisk %s (newer than src build)", filename);
                    return (out);
                }
            }
        } else {
            out = file_read_if_exists(filename, outlen);
            if (out) {
                DBG("Locdisk %s (exists locally)", filename);
                return (out);
            }
        }
    }

    if (EXEC_DIR) {
        alt_filename = strprepend(filename, EXEC_DIR);

        if (file_exists(alt_filename)) {
            if (file_exists_and_is_newer_than(alt_filename,
                                              EXEC_FULL_PATH_AND_NAME)) {
                out = file_read_if_exists(alt_filename, outlen);
                if (out) {
                    DBG("Locdisk %s", filename);
                    myfree(alt_filename);

                    return (out);
                }
            }

            if (file_exists_and_is_newer_than(alt_filename,
                                            ".o/ramdisk_data.o")) {
                out = file_read_if_exists(alt_filename, outlen);
                if (out) {
                    DBG("Locdisk %s", filename);
                    myfree(alt_filename);

                    return (out);
                }
            }

            if (file_exists_and_is_newer_than(alt_filename,
                                            "src/.o/ramdisk_data.o")) {
                out = file_read_if_exists(alt_filename, outlen);
                if (out) {
                    DBG("Locdisk %s", filename);
                    myfree(alt_filename);

                    return (out);
                }
            }
        }
    }

    while (ramfile->filename) {
        if (strcmp(ramfile->filename, filename)) {
            ramfile++;
            continue;
        }

        if (outlen) {
            *outlen = (int)ramfile->len;
        }

        DBG("Ramdisk %s, %d bytes", filename, ramfile->len);

        if (alt_filename) {
            myfree(alt_filename);
        }

        uint8_t *copy = (TYPEOF(copy))
                        mymalloc((int)ramfile->len + 1, "ramdisk load");
        if (!copy) {
            DBG("no memory for loading ramdisk copy, %s", filename);
            return (0);
        }

        memcpy(copy, (unsigned char*)ramfile->data, (int)ramfile->len);
        *(copy + (int)ramfile->len) = 0;

        return (copy);

#ifdef USE_ZLIB
        int32_t err;

        out = mymalloc(ramfile->orig_len, "RAMDISK scratchpad");
        if (!out) {
            ERR("no memory for ramdisk, %s", filename);
        }

        outlenl = ramfile->orig_len;
        err = uncompress(out, &outlenl,
                         (unsigned char *)ramfile->data,
                         ramfile->len);
        if (err) {
            ERR("file failed to decompress from ramdisk, %s, "
                "orig len %d, compressed len %d, err %d",
                filename, ramfile->orig_len, ramfile->len, err);
        }

        if (outlen) {
            *outlen = (int)outlenl;
        }
#endif

#ifdef USE_MINIZ
        int32_t err;

        out = (TYPEOF(out)) mymalloc(ramfile->orig_len, "RAMDISK scratchpad");
        if (!out) {
            ERR("no memory for ramdisk, %s", filename);
        }

        outlenl = ramfile->orig_len;
        err = mz_uncompress(out, &outlenl,
                            (unsigned char *)ramfile->data,
                            ramfile->len);
        if (err) {
            ERR("file failed to decompress from ramdisk, %s, err %d",
                filename, err);
        }

        if (outlen) {
            *outlen = (int32_t)outlenl;
        }
#endif

#ifdef USE_STB_IMAGE
        out = (TYPEOF(out))
            stbi_zlib_decode_malloc((const char *)ramfile->data,
                                    ramfile->len, &outlenl);
        if (!out) {
            ERR("file failed to decompress from ramdisk, %s", filename);
        }

        if (outlen) {
            *outlen = (int)outlenl;
        }
#endif

        return (out);
    }

    /*
     * Fallback to the disk.
     */
    out = file_read_if_exists(filename, outlen);
    if (out) {
        DBG("Locdisk %s", filename);

        if (alt_filename) {
            myfree(alt_filename);
        }

        return (out);
    }

    out = file_read_if_exists(alt_filename, outlen);
    if (out) {
        DBG("Locdisk %s", filename);

        if (alt_filename) {
            myfree(alt_filename);
        }

        return (out);
    }

    if (alt_filename) {
        myfree(alt_filename);
    }

    alt_filename = mybasename(filename, "strip dir");

    out = file_read_if_exists(alt_filename, outlen);
    if (out) {
        DBG("Locdisk %s", alt_filename);

        if (alt_filename) {
            myfree(alt_filename);
        }

        return (out);
    }

    /*
     * Fail. Caller should whinge.
     *
    char *popup_str = dynprintf("Filename was not found on ramdisk or "
                                "on the local disk, %s", filename);

    MSG_BOX("%s", popup_str);
    myfree(popup_str);
     */
    LOG("File not found \"%s\"", filename);

    if (alt_filename) {
        myfree(alt_filename);
    }

    return (0);
}
예제 #12
0
int
main (int argc, char **argv)
{
  int c;
  int i;

  char **saved_argv = 0;
  int cmdline_len = 0;

  int export_all = 0;

  int *dlltool_arg_indices;
  int *driver_arg_indices;

  char *driver_flags = 0;
  char *output_lib_file_name = 0;

  dyn_string_t dlltool_cmdline;
  dyn_string_t driver_cmdline;

  int def_file_seen = 0;

  char *image_base_str = 0;

  prog_name = argv[0];

#if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
  setlocale (LC_MESSAGES, "");
#endif
#if defined (HAVE_SETLOCALE)
  setlocale (LC_CTYPE, "");
#endif
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  expandargv (&argc, &argv);

  saved_argv = (char **) xmalloc (argc * sizeof (char*));
  dlltool_arg_indices = (int *) xmalloc (argc * sizeof (int));
  driver_arg_indices = (int *) xmalloc (argc * sizeof (int));
  for (i = 0; i < argc; ++i)
    {
      size_t len = strlen (argv[i]);
      char *arg = (char *) xmalloc (len + 1);
      strcpy (arg, argv[i]);
      cmdline_len += len;
      saved_argv[i] = arg;
      dlltool_arg_indices[i] = 0;
      driver_arg_indices[i] = 1;
    }
  cmdline_len++;

  /* We recognize dllwrap and dlltool options, and everything else is
     passed onto the language driver (eg., to GCC). We collect options
     to dlltool and driver in dlltool_args and driver_args.  */

  opterr = 0;
  while ((c = getopt_long_only (argc, argv, "nkAqve:Uho:l:L:I:",
				long_options, (int *) 0)) != EOF)
    {
      int dlltool_arg;
      int driver_arg;
      int single_word_option_value_pair;

      dlltool_arg = 0;
      driver_arg = 1;
      single_word_option_value_pair = 0;

      if (c != '?')
	{
	  /* We recognize this option, so it has to be either dllwrap or
	     dlltool option. Do not pass to driver unless it's one of the
	     generic options that are passed to all the tools (such as -v)
	     which are dealt with later.  */
	  driver_arg = 0;
	}

      /* deal with generic and dllwrap options first.  */
      switch (c)
	{
	case 'h':
	  usage (stdout, 0);
	  break;
	case 'q':
	  verbose = 0;
	  break;
	case 'v':
	  verbose = 1;
	  break;
	case OPTION_VERSION:
	  print_version (prog_name);
	  break;
	case 'e':
	  entry_point = optarg;
	  break;
	case OPTION_IMAGE_BASE:
	  image_base_str = optarg;
	  break;
	case OPTION_DEF:
	  def_file_name = optarg;
	  def_file_seen = 1;
	  delete_def_file = 0;
	  break;
	case 'n':
	  dontdeltemps = 1;
	  dlltool_arg = 1;
	  break;
	case 'o':
	  dll_file_name = optarg;
	  break;
	case 'I':
	case 'l':
	case 'L':
	  driver_arg = 1;
	  break;
	case OPTION_DLLNAME:
	  dll_name = optarg;
	  break;
	case OPTION_DRY_RUN:
	  dry_run = 1;
	  break;
	case OPTION_DRIVER_NAME:
	  driver_name = optarg;
	  break;
	case OPTION_DRIVER_FLAGS:
	  driver_flags = optarg;
	  break;
	case OPTION_DLLTOOL_NAME:
	  dlltool_name = optarg;
	  break;
	case OPTION_TARGET:
	  target = optarg;
	  break;
	case OPTION_MNO_CYGWIN:
	  target = "i386-mingw32";
	  break;
	case OPTION_NO_LEADING_UNDERSCORE:
	  is_leading_underscore = 0;
	  break;
	case OPTION_LEADING_UNDERSCORE:
	  is_leading_underscore = 1;
	  break;
	case OPTION_BASE_FILE:
	  base_file_name = optarg;
	  delete_base_file = 0;
	  break;
	case OPTION_OUTPUT_EXP:
	  exp_file_name = optarg;
	  delete_exp_file = 0;
	  break;
	case OPTION_EXPORT_ALL_SYMS:
	  export_all = 1;
	  break;
	case OPTION_OUTPUT_LIB:
	  output_lib_file_name = optarg;
	  break;
	case '?':
	  break;
	default:
	  dlltool_arg = 1;
	  break;
	}

      /* Handle passing through --option=value case.  */
      if (optarg
	  && saved_argv[optind-1][0] == '-'
	  && saved_argv[optind-1][1] == '-'
	  && strchr (saved_argv[optind-1], '='))
	single_word_option_value_pair = 1;

      if (dlltool_arg)
	{
	  dlltool_arg_indices[optind-1] = 1;
	  if (optarg && ! single_word_option_value_pair)
	    {
	      dlltool_arg_indices[optind-2] = 1;
	    }
	}

      if (! driver_arg)
	{
	  driver_arg_indices[optind-1] = 0;
	  if (optarg && ! single_word_option_value_pair)
	    {
	      driver_arg_indices[optind-2] = 0;
	    }
	}
    }

  /* Sanity checks.  */
  if (! dll_name && ! dll_file_name)
    {
      warn (_("Must provide at least one of -o or --dllname options"));
      exit (1);
    }
  else if (! dll_name)
    {
      dll_name = xstrdup (mybasename (dll_file_name));
    }
  else if (! dll_file_name)
    {
      dll_file_name = xstrdup (dll_name);
    }

  /* Deduce driver-name and dlltool-name from our own.  */
  if (driver_name == NULL)
    driver_name = deduce_name ("gcc");

  if (dlltool_name == NULL)
    dlltool_name = deduce_name ("dlltool");

  if (! def_file_seen)
    {
      char *fileprefix = choose_temp_base ();

      def_file_name = (char *) xmalloc (strlen (fileprefix) + 5);
      sprintf (def_file_name, "%s.def",
	       (dontdeltemps) ? mybasename (fileprefix) : fileprefix);
      delete_def_file = 1;
      free (fileprefix);
      delete_def_file = 1;
      warn (_("no export definition file provided.\n\
Creating one, but that may not be what you want"));
    }
예제 #13
0
파일: main.c 프로젝트: albfan/rlwrap
char *
read_options_and_command_name(int argc, char **argv)
{
  int c;
  char *opt_C = NULL;
  int option_count = 0;
  int opt_b = FALSE;
  int opt_f = FALSE;
  int remaining = -1; /* remaining number of arguments on command line */
  int longindex = -1; /* index of current option in longopts[], set by getopt_long */
  
  
  full_program_name = mysavestring(argv[0]);
  program_name = mybasename(full_program_name);	/* normally "rlwrap"; needed by myerror() */
  rl_basic_word_break_characters = " \t\n\r(){}[],+-=&^%$#@\";|\\";

  opterr = 0;			/* we do our own error reporting */

  while (1) {
#ifdef HAVE_GETOPT_LONG
    c = getopt_long(argc, argv, optstring, longopts, &longindex);
#else
    c = getopt(argc, argv, optstring);
#endif

    if (c == EOF)
      break;
    option_count++;
    last_option_didnt_have_optional_argument = FALSE;
    remaining = argc - optind;
    last_opt = c;    

    switch (c) {
    case 'a':
      always_readline = TRUE;
      if (check_optarg('a', remaining))
        password_prompt_search_string = mysavestring(optarg);
      break;
    case 'A':	ansi_colour_aware = TRUE; break;
    case 'b':
      rl_basic_word_break_characters = add3strings("\r\n \t", optarg, "");
      opt_b = TRUE;
      break;
    case 'c':	complete_filenames = TRUE; break;
    case 'C':	opt_C = mysavestring(optarg); break;
    case 'd':
#ifdef DEBUG
      if (option_count > 1)
        myerror("-d or --debug option has to be the *first* rlwrap option");
      if (check_optarg('d', remaining))
        debug = atoi(optarg);
      else
        debug = DEBUG_DEFAULT;
#else
      myerror
        ("To use -d( for debugging), configure %s with --enable-debug and rebuild",
         program_name);
#endif
      break;

    case 'D': 
      history_duplicate_avoidance_policy=atoi(optarg);
      if (history_duplicate_avoidance_policy < 0 || history_duplicate_avoidance_policy > 2)
        myerror("%s option with illegal value %d, should be 0, 1 or 2",
                current_option('D', longindex), history_duplicate_avoidance_policy);
      break;
    case 'f':
      if (strncmp(optarg, ".", 10) == 0)
        feed_history_into_completion_list =  TRUE;
      else
        feed_file_into_completion_list(optarg);
      opt_f = TRUE;
      break;
    case 'F': myerror("The -F (--history-format) option is obsolete. Use -z \"history_format '%s'\" instead", optarg);
    case 'g': forget_regexp = mysavestring(optarg); match_regexp("just testing", forget_regexp, 1); break;
    case 'h':	usage(EXIT_SUCCESS);		/* will call exit() */
    case 'H':	history_filename = mysavestring(optarg); break;
    case 'i': 
      if (opt_f)
        myerror("-i option has to precede -f options");
      completion_is_case_sensitive = FALSE;
      break;
    case 'I':	pass_on_sigINT_as_sigTERM = TRUE; break;
    case 'l':	open_logfile(optarg); break;
    case 'n':	nowarn = TRUE; break;
    case 'm':
#ifndef HAVE_SYSTEM
      mywarn("the -m option doesn't work on this system");
#endif
      multiline_separator =
        (check_optarg('m', remaining) ? mysavestring(optarg) : " \\ ");
      break;
    case 'N': commands_children_not_wrapped = TRUE; break;
    case 'o': 
      one_shot_rlwrap = TRUE;
      impatient_prompt = FALSE;
      wait_before_prompt = 200;
      break;
    case 'O': prompt_regexp = mysavestring(optarg); match_regexp("just testing", prompt_regexp, 1); break;
    case 'p':
      colour_the_prompt = TRUE;
      initialise_colour_codes(check_optarg('p', remaining) ?
                              colour_name_to_ansi_code(optarg) :
                              colour_name_to_ansi_code("Red"));
      break;
    case 'P':
      pre_given = mysavestring(optarg);
      always_readline = TRUE; /* pre_given does not work well with transparent mode */
	
      break;
    case 'q': rl_basic_quote_characters = mysavestring(optarg); break;
    case 'r':	remember_for_completion = TRUE;	break;
    case 'R': renice = TRUE;	break;
    case 's':
      histsize = atoi(optarg);
      if (histsize < 0) {
        write_histfile = 0;
        histsize = -histsize;
      }
      break;
    case 'S': substitute_prompt =  mysavestring(optarg);break;
    case 't':	client_term_name=mysavestring(optarg);break;
#ifdef DEBUG
    case 'T':	test_terminal(); exit(EXIT_SUCCESS);
#endif
    case 'v':	printf("rlwrap %s\n",  VERSION); exit(EXIT_SUCCESS);
    case 'w':
      wait_before_prompt = atoi(optarg);
      if (wait_before_prompt < 0) {
        wait_before_prompt *= -1;
        impatient_prompt =  FALSE;
      }
      break;
    case 'z': filter_command = mysavestring(optarg);	break;
    case '?':
      assert(optind > 0);
      myerror("unrecognised option %s\ntry '%s --help' for more information",
              argv[optind-1], full_program_name);
    case ':':
      assert(optind > 0);
      myerror
        ("option %s requires an argument \ntry '%s --help' for more information",
         argv[optind-1], full_program_name);

    default:
      usage(EXIT_FAILURE);
    }
  }

  if (!complete_filenames && !opt_b) {	/* use / and . as default breaking characters whenever we don't complete filenames */
    rl_basic_word_break_characters =
      add2strings(rl_basic_word_break_characters, "/.");
  }

  
  if (optind >= argc) { /* rlwrap -a -b -c with no command specified */
    if (filter_command) { /* rlwrap -z filter with no command specified */
      mysignal(SIGALRM, &handle_sigALRM); /* needed for read_patiently2 */
      spawn_filter(filter_command);
      pass_through_filter(TAG_OUTPUT,""); /* ignore result but allow TAG_OUTPUT_OUT_OF_BAND */
      cleanup_rlwrap_and_exit(EXIT_SUCCESS);
    } else {
      usage(EXIT_FAILURE); 
    }
  }
  if (opt_C) {
    int countback = atoi(opt_C);	/* investigate whether -C option argument is numeric */

    if (countback > 0) {	/* e.g -C 1 or -C 12 */
      if (argc - countback < optind)	/* -C 666 */
	myerror("when using -C %d you need at least %d non-option arguments",
		countback, countback);
      else if (argv[argc - countback][0] == '-')	/* -C 2 perl -d blah.pl */
	myerror("the last argument minus %d appears to be an option!",
		countback);
      else {			/* -C 1 perl test.cgi */
	command_name = mysavestring(mybasename(argv[argc - countback]));

      }
    } else if (countback == 0) {	/* -C name1 name2 or -C 0 */
      if (opt_C[0] == '0' && opt_C[1] == '\0')	/* -C 0 */
	myerror("-C 0 makes no sense");
      else if (strlen(mybasename(opt_C)) != strlen(opt_C))	/* -C dir/name */
	myerror("-C option argument should not contain directory components");
      else if (opt_C[0] == '-')	/* -C -d  (?) */
	myerror("-C option needs argument");
      else			/* -C name */
	command_name = opt_C;
    } else {			/* -C -2 */
      myerror
	("-C option needs string or positive number as argument, perhaps you meant -C %d?",
	 -countback);
    }
  } else {			/* no -C option given, use command name */
    command_name = mysavestring(mybasename(argv[optind]));
  }
  assert(command_name != NULL);
  return command_name;
}