コード例 #1
0
ファイル: totextmode.c プロジェクト: pexip/os-kbd
int
main(int argc, char *argv[]) {
	int fd, num;

	set_progname(argv[0]);
#ifndef __klibc__
	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);
#endif

	if (argc == 2 && !strcmp(argv[1], "-V"))
		print_version_and_exit();

	if (argc != 2) {
		fprintf(stderr, _("usage: totextmode\n"));
		exit(1);
	}
	fd = getfd(NULL);
	num = atoi(argv[1]);
	if (ioctl(fd,KDSETMODE,KD_TEXT)) {
		perror("totextmode: KDSETMODE");
		exit(1);
	}
	exit(0);
}
コード例 #2
0
ファイル: isl_arg.c プロジェクト: VanirLLVM/toolchain_isl
int isl_args_parse(struct isl_args *args, int argc, char **argv, void *opt,
	unsigned flags)
{
	int a = -1;
	int skip = 0;
	int i;
	int n;
	struct isl_prefixes prefixes = { 0 };

	n = n_arg(args->args);

	for (i = 1; i < argc; ++i) {
		if ((strcmp(argv[i], "--version") == 0 ||
		     strcmp(argv[i], "-V") == 0) && any_version(args->args))
			print_version_and_exit(args->args);
	}

	while (argc > 1 + skip) {
		int parsed;
		if (argv[1 + skip][0] != '-') {
			a = next_arg(args->args, a);
			if (a >= 0) {
				char **p;
				p = (char **)(((char *)opt)+args->args[a].offset);
				free(*p);
				*p = strdup(argv[1 + skip]);
				argc = drop_argument(argc, argv, 1 + skip, 1);
				--n;
			} else if (ISL_FL_ISSET(flags, ISL_ARG_ALL)) {
				fprintf(stderr, "%s: extra argument: %s\n",
					    prog_name(argv[0]), argv[1 + skip]);
				exit(-1);
			} else
				++skip;
			continue;
		}
		check_help(args, argv[1 + skip], argv[0], opt, flags);
		parsed = parse_option(args->args, &argv[1 + skip],
					&prefixes, opt);
		if (parsed)
			argc = drop_argument(argc, argv, 1 + skip, parsed);
		else if (ISL_FL_ISSET(flags, ISL_ARG_ALL)) {
			fprintf(stderr, "%s: unrecognized option: %s\n",
					prog_name(argv[0]), argv[1 + skip]);
			exit(-1);
		} else
			++skip;
	}

	if (n > 0) {
		fprintf(stderr, "%s: expecting %d more argument(s)\n",
				prog_name(argv[0]), n);
		exit(-1);
	}

	return argc;
}
コード例 #3
0
ファイル: deallocvt.c プロジェクト: Bolel/kbd
int
main(int argc, char *argv[]) {
	int fd, num, i;

	if (argc < 1)		/* unlikely */
		exit(1);
	set_progname(argv[0]);

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);

	if (argc == 2 && !strcmp(argv[1], "-V"))
		print_version_and_exit();

	for (i = 1; i < argc; i++) {
		if (!isdigit(argv[i][0])) {
			fprintf(stderr, _("%s: unknown option\n"), progname);
			exit(1);
		}
	}

	fd = getfd(NULL);

	if (argc == 1) {
		/* deallocate all unused consoles */
		if (ioctl(fd,VT_DISALLOCATE,0)) {
			perror("VT_DISALLOCATE");
			fprintf(stderr,
				_("%s: deallocating all unused consoles failed\n"),
				progname);
			exit(1);
		}
	} else for (i = 1; i < argc; i++) {
		num = atoi(argv[i]);
		if (num == 0) {
			fprintf(stderr,
				_("%s: 0: illegal VT number\n"), progname);
			exit(1);
		} else if (num == 1) {
			fprintf(stderr,
				_("%s: VT 1 is the console and cannot be deallocated\n"),
				progname);
			exit(1);
		} else if (ioctl(fd,VT_DISALLOCATE,num)) {
			perror("VT_DISALLOCATE");
			fprintf(stderr,
				_("%s: could not deallocate console %d\n"),
				progname, num);
			exit(1);
		}
	}
	exit(0);
}
コード例 #4
0
ファイル: setkeycodes.c プロジェクト: pexip/os-kbd
int
main(int argc, char **argv) {
	char *ep;
	int fd;
	struct kbkeycode a;

	set_progname(argv[0]);
#ifndef __klibc__
	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);
#endif

	if (argc == 2 && !strcmp(argv[1], "-V"))
		print_version_and_exit();

	if (argc % 2 != 1)
		usage(_("even number of arguments expected"));
	fd = getfd(NULL);

	while (argc > 2) {
		a.keycode = atoi(argv[2]);
		a.scancode = strtol(argv[1], &ep, 16);
		if (*ep)
			usage(_("error reading scancode"));
		if (a.scancode >= 0xe000) {
			a.scancode -= 0xe000;
			a.scancode += 128;	/* some kernels needed +256 */
		}
#if 0
		/* Test is OK up to 2.5.31--later kernels have more keycodes */
		if (a.scancode > 255 || a.keycode > 127)
			usage(_("code outside bounds"));

		/* Both fields are unsigned int, so can be large;
		   for current kernels the correct test might be
		     (a.scancode > 255 || a.keycode > 239)
		   but we can leave testing to the kernel. */
#endif
		if (ioctl(fd,KDSETKEYCODE,&a)) {
			perror("KDSETKEYCODE");
			fprintf(stderr,
				_("failed to set scancode %x to keycode %d\n"),
				a.scancode, a.keycode);
			exit(1);
		}
		argc -= 2;
		argv += 2;
	}
	return 0;
}
コード例 #5
0
ファイル: mapscrn.c プロジェクト: Mirppc/twin
int
main(int argc, char *argv[]) {
	int fd;

	set_progname(argv[0]);

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);

	if (argc == 2 && !strcmp(argv[1], "-V"))
	    print_version_and_exit();

	if (argc > 1 && !strcmp(argv[1], "-v")) {
		verbose = 1;
		argc--;
		argv++;
	}

	fd = getfd();

	if (argc >= 3 && !strcmp(argv[1], "-o")) {
	    saveoldmap(fd, argv[2]);
	    argc -= 2;
	    argv += 2;
	    if (argc == 1)
	      exit(0);
	}
		
	if (argc != 2) {
		fprintf(stderr, _("usage: %s [-v] [-o map.orig] map-file\n"),
			progname);
		exit(1);
	}

    	if (!TwOpen(NULL)) {
	    fprintf(stderr, _("mapscrn: libTw error: %s\n"), TwStrError(TwErrno));
	    exit(1);
	}
	loadnewmap(fd, argv[1]);

	if (TwErrno) {
	    fprintf(stderr, _("mapscrn: libTw error: %s\n"), TwStrError(TwErrno));
	}
	TwClose();
	
	exit(0);
}
コード例 #6
0
ファイル: setvtrgb.c プロジェクト: SvenDowideit/clearlinux
int
main(int argc, char **argv) {
	int c;
	const char *file;
	FILE *fd;

	set_progname(argv[0]);

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);

	while ((c = getopt(argc, argv, "hV")) != EOF) {
		switch (c) {
			case 'V':
				print_version_and_exit();
				break;
			case 'h':
				usage(EXIT_SUCCESS);
				break;
		}
	}

	if (optind == argc)
		usage(EXIT_FAILURE);

	file = argv[optind];

	if (!strcmp(file, "vga")) {
		set_colormap(vga_colors);
		return EXIT_SUCCESS;

	} else if (!strcmp(file, "-")) {
		parse_file(stdin, "stdin");

	} else {
		if ((fd = fopen(file, "r")) == NULL)
			error(EXIT_FAILURE, errno, "fopen");

		parse_file(fd, file);
		fclose(fd);
	}

	set_colormap(cmap);
	free(cmap);

	return EXIT_SUCCESS;
}
コード例 #7
0
int
main(int argc, char *argv[]) {
	int fd, c;
	char *console = NULL;
	char *outfnam = NULL;
	char *infnam = "def.uni";

	set_progname(argv[0]);

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);

	if (argc == 2 &&
	    (!strcmp(argv[1], "-V") || !strcmp(argv[1], "--version")))
		print_version_and_exit();

	while ((c = getopt(argc, argv, "C:o:")) != EOF) {
		switch (c) {
		case 'C':
			console = optarg;
			break;
		case 'o':
		     	outfnam = optarg;
			break;
		default:
			usage();
		}
	}

	if (argc > optind+1 || (argc == optind && !outfnam))
		usage();

	fd = getfd(console);

	if (outfnam) {
		saveunicodemap(fd, outfnam);
		if (argc == optind)
			exit(0);
	}

	if (argc == optind+1)
		infnam = argv[optind];
	loadunicodemap(fd, infnam);
	exit(0);
}
コード例 #8
0
ファイル: setmetamode.c プロジェクト: legionus/kbd
int main(int argc, char **argv)
{
	unsigned int ometa, nmeta;
	struct meta *mp;

	set_progname(argv[0]);

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);

	if (argc == 2 && !strcmp(argv[1], "-V"))
		print_version_and_exit();

	if (ioctl(0, KDGKBMETA, &ometa)) {
		kbd_error(EXIT_FAILURE, errno, _("Error reading current setting. Maybe stdin is not a VT?: "
		                                 "ioctl KDGKBMETA"));
	}

	if (argc <= 1) {
		report(ometa);
		exit(EXIT_SUCCESS);
	}

	nmeta = 0; /* make gcc happy */
	for (mp = metas; (unsigned)(mp - metas) < SIZE(metas); mp++) {
		if (!strcmp(argv[1], mp->name)) {
			nmeta = mp->val;
			goto fnd;
		}
	}
	fprintf(stderr, _("unrecognized argument: _%s_\n\n"), argv[1]);
	usage();

fnd:
	printf(_("old state:    "));
	report(ometa);
	if (ioctl(0, KDSKBMETA, nmeta)) {
		kbd_error(EXIT_FAILURE, errno, "ioctl KDSKBMETA");
	}
	printf(_("new state:    "));
	report(nmeta);

	return EXIT_SUCCESS;
}
コード例 #9
0
ファイル: main.cpp プロジェクト: Kermit/lxqt-config-randr
void parse_args(int argc, char* argv[], out bool& startup)
{
    int next_option;
    startup = false;
    do{
        next_option = getopt_long(argc, argv, short_options, long_options, NULL);
        switch(next_option)
        {
            case 'h':
                print_usage_and_exit(0);
            case 's':
                startup = true;
                break;
            case '?':
                print_usage_and_exit(1);
            case 'v':
                print_version_and_exit();
        }
    }
    while(next_option != -1);
}
コード例 #10
0
ファイル: main.cpp プロジェクト: lxde/qterminal
void parse_args(int argc, char* argv[], QString& workdir, QString & shell_command, out bool& dropMode)
{
    int next_option;
    dropMode = false;
    do{
        next_option = getopt_long(argc, argv, short_options, long_options, nullptr);
        switch(next_option)
        {
            case 'h':
                print_usage_and_exit(0);
                break;
            case 'w':
                workdir = QString::fromLocal8Bit(optarg);
                break;
            case 'e':
                shell_command = QString::fromLocal8Bit(optarg);
                // #15 "Raw" -e params
                // Passing "raw" params (like konsole -e mcedit /tmp/tmp.txt") is more preferable - then I can call QString("qterminal -e ") + cmd_line in other programs
                while (optind < argc)
                {
                    //printf("arg: %d - %s\n", optind, argv[optind]);
                    shell_command += QLatin1Char(' ') + QString::fromLocal8Bit(argv[optind++]);
                }
                break;
            case 'd':
                dropMode = true;
                break;
            case 'p':
                Properties::Instance(QString::fromLocal8Bit(optarg));
                break;
            case '?':
                print_usage_and_exit(1);
                break;
            case 'v':
                print_version_and_exit();
                break;
        }
    }
    while(next_option != -1);
}
コード例 #11
0
ファイル: Controller.c プロジェクト: prophile/clusterduck
int main ( int argc, char** argv )
{
	const char* op;
	const char** arg_array;
	int i, narg;
	int rc;
	if (argc == 1)
	{
		print_usage_and_exit(argv[0]);
	}
	op = argv[1];
	if (!strcmp("op", "-h") ||
	    !strcmp("op", "-help") ||
	    !strcmp("op", "--help"))
	{
		print_usage_and_exit(argv[0]);
	}
	else if (!strcmp("op", "-v") ||
	         !strcmp("op", "-V") ||
	         !strcmp("op", "-version") ||
	         !strcmp("op", "--version"))
	{
		print_version_and_exit();
	}
	else
	{
		narg = argc - 2;
		arg_array = (const char**)malloc(sizeof(const char*) * narg);
		for (i = 0; i < narg; i++)
		{
			arg_array[i] = argv[i + 2];
		}
		rc = cduck_dispatch_command(op, narg, arg_array);
		return rc;
	}
	return 0;
}
コード例 #12
0
ファイル: psfxtable.c プロジェクト: legionus/kbd
int main(int argc, char **argv)
{
	const char *ifname, *ofname, *itname, *otname;
	FILE *ifil, *ofil, *itab, *otab;
	int psftype, charsize, fontlen, hastable, notable;
	int i;
	int width = 8, bytewidth, height;
	char *inbuf, *fontbuf;
	int inbuflth, fontbuflth;

	set_progname(argv[0]);

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);

	if (argc == 2 && !strcmp(argv[1], "-V"))
		print_version_and_exit();

	ifil = ofil = itab = otab = NULL;
	ifname = ofname = itname = otname = NULL;
	fontbuf                           = NULL;
	notable                           = 0;

	if (!strcmp(get_progname(), "psfaddtable")) {
		/* Do not send binary data to stdout without explicit "-" */
		if (argc != 4) {
			char *u = _("Usage:\n\t%s infont intable outfont\n");
			fprintf(stderr, u, get_progname());
			exit(EX_USAGE);
		}
		ifname = argv[1];
		itname = argv[2];
		ofname = argv[3];
	} else if (!strcmp(get_progname(), "psfgettable")) {
		if (argc < 2 || argc > 3) {
			char *u = _("Usage:\n\t%s infont [outtable]\n");
			fprintf(stderr, u, get_progname());
			exit(EX_USAGE);
		}
		ifname = argv[1];
		otname = (argc == 3) ? argv[2] : "-";
	} else if (!strcmp(get_progname(), "psfstriptable")) {
		/* Do not send binary data to stdout without explicit "-" */
		if (argc != 3) {
			char *u = _("Usage:\n\t%s infont outfont\n");
			fprintf(stderr, u, get_progname());
			exit(EX_USAGE);
		}
		ifname  = argv[1];
		ofname  = argv[2];
		notable = 1;
	} else {
		for (i = 1; i < argc; i++) {
			if ((!strcmp(argv[i], "-i") || !strcmp(argv[i], "-if")) && i < argc - 1)
				ifname = argv[++i];
			else if ((!strcmp(argv[i], "-o") || !strcmp(argv[i], "-of")) && i < argc - 1)
				ofname = argv[++i];
			else if (!strcmp(argv[i], "-it") && i < argc - 1)
				itname = argv[++i];
			else if (!strcmp(argv[i], "-ot") && i < argc - 1)
				otname = argv[++i];
			else if (!strcmp(argv[i], "-nt"))
				notable = 1;
			else
				break;
		}
		if (i < argc || argc <= 1) {
			char *u = _("Usage:\n\t%s [-i infont] [-o outfont] "
			            "[-it intable] [-ot outtable] [-nt]\n");
			fprintf(stderr, u, get_progname());
			exit(EX_USAGE);
		}
	}

	if (!ifname)
		ifname = "-";
	if (!strcmp(ifname, "-"))
		ifil = stdin;
	else {
		ifil = fopen(ifname, "r");
		if (!ifil) {
			perror(ifname);
			exit(EX_NOINPUT);
		}
	}

	if (!itname)
		/* nothing */;
	else if (!strcmp(itname, "-"))
		itab = stdin;
	else {
		itab = fopen(itname, "r");
		if (!itab) {
			perror(itname);
			exit(EX_NOINPUT);
		}
	}

	/* Refuse ifil == itab == stdin ? Perhaps not. */

	if (!ofname)
		/* nothing */;
	else if (!strcmp(ofname, "-"))
		ofil = stdout;
	else {
		ofil = fopen(ofname, "w");
		if (!ofil) {
			perror(ofname);
			exit(EX_CANTCREAT);
		}
	}

	if (!otname)
		/* nothing */;
	else if (!strcmp(otname, "-"))
		otab = stdout;
	else {
		otab = fopen(otname, "w");
		if (!otab) {
			perror(otname);
			exit(EX_CANTCREAT);
		}
	}

	if (readpsffont(ifil, &inbuf, &inbuflth, &fontbuf, &fontbuflth,
	                &width, &fontlen, 0,
	                itab ? NULL : &uclistheads) == -1) {
		char *u = _("%s: Bad magic number on %s\n");
		fprintf(stderr, u, get_progname(), ifname);
		exit(EX_DATAERR);
	}
	fclose(ifil);

	charsize  = fontbuflth / fontlen;
	bytewidth = (width + 7) / 8;
	if (!bytewidth)
		bytewidth = 1;
	height            = charsize / bytewidth;

	hastable = (uclistheads != NULL);

	if (PSF1_MAGIC_OK((unsigned char *)inbuf)) {
		psftype = 1;
	} else if (PSF2_MAGIC_OK((unsigned char *)inbuf)) {
		psftype = 2;
	} else {
		char *u = _("%s: psf file with unknown magic\n");
		fprintf(stderr, u, get_progname());
		exit(EX_DATAERR);
	}

	if (itab) {
		read_itable(itab, fontlen, &uclistheads);
		fclose(itab);
	}

	if (otab) {
		struct unicode_list *ul;
		struct unicode_seq *us;
		const char *sep;

		if (!hastable) {
			char *u = _("%s: input font does not have an index\n");
			fprintf(stderr, u, get_progname());
			exit(EX_DATAERR);
		}
		fprintf(otab,
		        "#\n# Character table extracted from font %s\n#\n",
		        ifname);
		for (i = 0; i < fontlen; i++) {
			fprintf(otab, "0x%03x\t", i);
			sep = "";
			ul  = uclistheads[i].next;
			while (ul) {
				us = ul->seq;
				while (us) {
					fprintf(otab, "%sU+%04x", sep, us->uc);
					us  = us->next;
					sep = ", ";
				}
				ul  = ul->next;
				sep = " ";
			}
			fprintf(otab, "\n");
		}
		fclose(otab);
	}

	if (ofil) {
		writepsffont(ofil, fontbuf, width, height, fontlen, psftype,
		             notable ? NULL : uclistheads);
		fclose(ofil);
	}

	return EX_OK;
}
コード例 #13
0
ファイル: squash.c プロジェクト: szabadka/squash
int main (int argc, char** argv) {
  SquashStatus res;
  SquashCodec* codec = NULL;
  SquashOptions* options = NULL;
  SquashStreamType direction = SQUASH_STREAM_COMPRESS;
  FILE* input = NULL;
  FILE* output = NULL;
  char* input_name = NULL;
  char* output_name = NULL;
  bool list_codecs = false;
  bool list_plugins = false;
  char** option_keys = NULL;
  char** option_values = NULL;
  bool keep = false;
  bool force = false;
  int opt;
  int optc = 0;
  char* tmp_string;
  int retval = EXIT_SUCCESS;
  struct parg_state ps;
  int optend;
  const struct parg_option squash_options[] = {
    {"keep", PARG_NOARG, NULL, 'k'},
    {"option", PARG_REQARG, NULL, 'o'},
    {"codec", PARG_REQARG, NULL, 'c'},
    {"list-codecs", PARG_NOARG, NULL, 'L'},
    {"list-plugins", PARG_NOARG, NULL, 'P'},
    {"force", PARG_NOARG, NULL, 'f'},
    {"decompress", PARG_NOARG, NULL, 'd'},
    {"version", PARG_NOARG, NULL, 'V'},
    {"help", PARG_NOARG, NULL, 'h'},
    {NULL, 0, NULL, 0}
  };

  option_keys = (char**) malloc (sizeof (char*));
  option_values = (char**) malloc (sizeof (char*));
  *option_keys = NULL;
  *option_values = NULL;

  optend = parg_reorder (argc, argv, "c:ko:123456789LPfdhb:V", squash_options);

  parg_init(&ps);

  while ( (opt = parg_getopt_long (&ps, optend, argv, "c:ko:123456789LPfdhb:V", squash_options, NULL)) != -1 ) {
    switch ( opt ) {
      case 'c':
        codec = squash_get_codec (ps.optarg);
        if ( codec == NULL ) {
          fprintf (stderr, "Unable to find codec '%s'\n", ps.optarg);
          retval = exit_failure ();
          goto cleanup;
        }
        break;
      case 'k':
        keep = true;
        break;
      case 'o':
        parse_option (&option_keys, &option_values, ps.optarg);
        break;
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
        tmp_string = malloc (8);
        snprintf (tmp_string, 8, "level=%c", (char) opt);
        parse_option (&option_keys, &option_values, tmp_string);
        free (tmp_string);
        break;
      case 'L':
        list_codecs = true;
        break;
      case 'P':
        list_plugins = true;
        break;
      case 'f':
        force = true;
        break;
      case 'h':
        print_help_and_exit (argc, argv, EXIT_SUCCESS);
        break;
      case 'd':
        direction = SQUASH_STREAM_DECOMPRESS;
        break;
      case 'V':
        print_version_and_exit (argc, argv, EXIT_SUCCESS);
        break;
    }

    optc++;
  }

  if (list_plugins) {
    if (list_codecs)
      squash_foreach_plugin (list_plugins_and_codecs_foreach_cb, NULL);
    else
      squash_foreach_plugin (list_plugins_foreach_cb, NULL);

    goto cleanup;
  } else if (list_codecs) {
    squash_foreach_codec (list_codecs_foreach_cb, NULL);
    goto cleanup;
  }

  if ( ps.optind < argc ) {
    input_name = argv[ps.optind++];

    if ( (direction == SQUASH_STREAM_DECOMPRESS) && codec == NULL ) {
      char* extension;

      extension = strrchr (input_name, '.');
      if (extension != NULL)
        extension++;

      if (extension != NULL)
        codec = squash_get_codec_from_extension (extension);
    }
  } else {
    fprintf (stderr, "You must provide an input file name.\n");
    retval = exit_failure ();
    goto cleanup;
  }

  if ( ps.optind < argc ) {
    output_name = strdup (argv[ps.optind++]);

    if ( codec == NULL && direction == SQUASH_STREAM_COMPRESS ) {
      const char* extension = strrchr (output_name, '.');
      if (extension != NULL)
        extension++;

      if (extension != NULL)
        codec = squash_get_codec_from_extension (extension);
    }
  } else {
    if ( codec != NULL ) {
      const char* extension = squash_codec_get_extension (codec);
      if (extension != NULL) {
        if (strcmp (input_name, "-") == 0) {
          output_name = strdup ("-");
        } else {
          size_t extension_length = strlen (extension);
          size_t input_name_length = strlen (input_name);

          if ( (extension_length + 1) < input_name_length &&
               input_name[input_name_length - (1 + extension_length)] == '.' &&
               strcasecmp (extension, input_name + (input_name_length - (extension_length))) == 0 ) {
            output_name = squash_strndup (input_name, input_name_length - (1 + extension_length));
          }
        }
      }
    }
  }

  if ( ps.optind < argc ) {
    fprintf (stderr, "Too many arguments.\n");
  }

  if ( codec == NULL ) {
    fprintf (stderr, "Unable to determine codec.  Please pass -c \"codec\", or -L to see a list of available codecs.\n");
    retval = exit_failure ();
    goto cleanup;
  }

  if ( output_name == NULL ) {
    fprintf (stderr, "Unable to determine output file.\n");
    retval = exit_failure ();
    goto cleanup;
  }

  if ( strcmp (input_name, "-") == 0 ) {
    input = stdin;
  } else {
    input = fopen (input_name, "rb");
    if ( input == NULL ) {
      perror ("Unable to open input file");
      retval = exit_failure ();
      goto cleanup;
    }
  }

  if ( strcmp (output_name, "-") == 0 ) {
    output = stdout;
  } else {
    int output_fd = open (output_name,
#if !defined(_WIN32)
                          O_RDWR | O_CREAT | (force ? O_TRUNC : O_EXCL),
                          S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
#else
                          O_RDWR | O_CREAT | (force ? O_TRUNC : O_EXCL) | O_BINARY,
                          S_IREAD | S_IWRITE
#endif
    );
    if ( output_fd < 0 ) {
      perror ("Unable to open output file");
      retval = exit_failure ();
      goto cleanup;
    }
    output = fdopen (output_fd, "wb");
    if ( output == NULL ) {
      perror ("Unable to open output");
      retval = exit_failure ();
      goto cleanup;
    }
  }

  options = squash_options_newa (codec, (const char * const*) option_keys, (const char * const*) option_values);

  res = squash_splice_with_options (codec, direction, output, input, 0, options);

  if ( res != SQUASH_OK ) {
    fprintf (stderr, "Failed to %s: %s\n",
             (direction == SQUASH_STREAM_COMPRESS) ? "compress" : "decompress",
             squash_status_to_string (res));
    retval = exit_failure ();
    goto cleanup;
  }

  if ( !keep && input != stdin ) {
    fclose (input);
    if ( unlink (input_name) != 0 ) {
      perror ("Unable to remove input file");
    }
    input = NULL;
  }

 cleanup:

  if (input != stdin && input != NULL)
    fclose (stdin);

  if (output != stdout)
    fclose (stdout);

  if (option_keys != NULL) {
    for (opt = 0 ; option_keys[opt] != NULL ; opt++) {
      free(option_keys[opt]);
    }
    free (option_keys);
  }

  if (option_values != NULL) {
    for (opt = 0 ; option_values[opt] != NULL ; opt++) {
      free(option_values[opt]);
    }
    free (option_values);
  }

  free (output_name);

  return retval;
}
コード例 #14
0
ファイル: setfont.c プロジェクト: SvenDowideit/clearlinux
int
main(int argc, char *argv[]) {
	char *ifiles[MAXIFILES];
	char *mfil, *ufil, *Ofil, *ofil, *omfil, *oufil, *console;
	int ifilct = 0, fd, i, iunit, hwunit, no_m, no_u;
	int restore = 0;

	set_progname(argv[0]);

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);

	ifiles[0] = mfil = ufil = Ofil = ofil = omfil = oufil = NULL;
	iunit = hwunit = 0;
	no_m = no_u = 0;
	console = NULL;

	/*
	 * No getopt() here because of the -om etc options.
	 */
	for (i = 1; i < argc; i++) {
	    if (!strcmp(argv[i], "-V")) {
		print_version_and_exit();
	    } else if (!strcmp(argv[i], "-v")) {
	        verbose++;
	    } else if (!strcmp(argv[i], "-R")) {
		restore = 1;
	    } else if (!strcmp(argv[i], "-C")) {
		if (++i == argc || console)
		  usage();
		console = argv[i];
	    } else if (!strcmp(argv[i], "-O")) {
		if (++i == argc || Ofil)
		  usage();
		Ofil = argv[i];
	    } else if (!strcmp(argv[i], "-o")) {
		if (++i == argc || ofil)
		  usage();
		ofil = argv[i];
	    } else if (!strcmp(argv[i], "-om")) {
		if (++i == argc || omfil)
		  usage();
		omfil = argv[i];
	    } else if (!strcmp(argv[i], "-ou")) {
		if (++i == argc || oufil)
		  usage();
		oufil = argv[i];
	    } else if (!strcmp(argv[i], "-m")) {
		if (++i == argc || mfil)
		  usage();
		if (!strcmp(argv[i], "none"))
		  no_m = 1;
		else
		  mfil = argv[i];
	    } else if (!strcmp(argv[i], "-u")) {
		if (++i == argc || ufil)
		  usage();
		if (!strcmp(argv[i], "none"))
		  no_u = 1;
		else
		  ufil = argv[i];
	    } else if (!strcmp(argv[i], "-f")) {
		force = 1;
	    } else if (!strncmp(argv[i], "-h", 2)) {
		hwunit = atoi(argv[i]+2);
		if (hwunit <= 0 || hwunit > 32)
		  usage();
	    } else if (argv[i][0] == '-') {
		iunit = atoi(argv[i]+1);
		if(iunit <= 0 || iunit > 32)
		  usage();
	    } else {
		if (ifilct == MAXIFILES) {
		    fprintf(stderr, _("setfont: too many input files\n"));
		    exit(EX_USAGE);
		}
		ifiles[ifilct++] = argv[i];
	    }
	}

	if (ifilct && restore) {
	    fprintf(stderr, _("setfont: cannot both restore from character ROM"
			      " and from file. Font unchanged.\n"));
	    exit(EX_USAGE);
	}

	fd = getfd(console);

	int kd_mode = -1;
	if (!ioctl(fd, KDGETMODE, &kd_mode) && (kd_mode == KD_GRAPHICS))
	  {
	    /*
	     * PIO_FONT will fail on a console which is in foreground and in KD_GRAPHICS mode.
	     * 2005-03-03, [email protected].
	     */
	    if (verbose)
	      printf("setfont: graphics console %s skipped\n", console?console:"");
	    close(fd);
	    return 0;
	  }

	if (!ifilct && !mfil && !ufil &&
	    !Ofil && !ofil && !omfil && !oufil && !restore)
	  /* reset to some default */
	  ifiles[ifilct++] = "";

	if (Ofil)
	  saveoldfontplusunicodemap(fd, Ofil);

	if (ofil)
	  saveoldfont(fd, ofil);

	if (omfil)
	  saveoldmap(fd, omfil);

	if (oufil)
	  saveunicodemap(fd, oufil);

	if (mfil) {
	    loadnewmap(fd, mfil);
	    activatemap(fd);
	    no_m = 1;
	}

	if (ufil)
	  no_u = 1;

	if (restore)
	  restorefont(fd);

	if (ifilct)
	  loadnewfonts(fd, ifiles, ifilct, iunit, hwunit, no_m, no_u);

	if (ufil)
	  loadunicodemap(fd, ufil);

	return 0;
}
コード例 #15
0
int
main(int argc, char **argv) {
    int cons = 0;
    char infile[20];
    unsigned char header[4];
    unsigned int rows, cols;
    int fd, i, j;
    char *inbuf, *outbuf, *p, *q;

    set_progname(argv[0]);

    setlocale(LC_ALL, "");
    bindtextdomain(PACKAGE_NAME, LOCALEDIR);
    textdomain(PACKAGE_NAME);

    if (argc == 2 && !strcmp(argv[1], "-V"))
	print_version_and_exit();

    if (argc > 2) {
	fprintf(stderr, _("usage: screendump [n]\n"));
	exit(1);
    }

    cons = (argc == 2) ? atoi(argv[1]) : 0;

    sprintf(infile, "/dev/vcsa%d", cons);
    fd = open(infile, O_RDONLY);
    if (fd < 0 && cons == 0 && errno == ENOENT) {
      sprintf(infile, "/dev/vcsa");
      fd = open(infile, O_RDONLY);
    }
    if (fd < 0 && errno == ENOENT) {
      sprintf(infile, "/dev/vcs/a%d", cons);
      fd = open(infile, O_RDONLY);
    }
    if (fd < 0 && cons == 0 && errno == ENOENT) {
      sprintf(infile, "/dev/vcs/a");
      fd = open(infile, O_RDONLY);
    }
    if (fd < 0 || read(fd, header, 4) != 4)
      goto try_ioctl;
    rows = header[0];
    cols = header[1];
    if (rows * cols == 0)
      goto try_ioctl;
    inbuf = xmalloc(rows*cols*2);
    outbuf = xmalloc(rows*(cols+1));

    if (read(fd, inbuf, rows*cols*2) != rows*cols*2) {
        fprintf(stderr, _("Error reading %s\n"), infile);
        exit(1);
    }
    p = inbuf;
    q = outbuf;
    for(i=0; i<rows; i++) {
        for(j=0; j<cols; j++) {
            *q++ = *p;
            p += 2;
        }
        while(j-- > 0 && q[-1] == ' ')
          q--;
        *q++ = '\n';
    }
    goto done;

try_ioctl:
    {
	struct winsize win;
	char consnam[20], devfsconsnam[20];
	unsigned char *screenbuf;

	sprintf(consnam, "/dev/tty%d", cons);
	fd = open(consnam, O_RDONLY);
	if (fd < 0 && errno == ENOENT) {
	    sprintf(devfsconsnam, "/dev/vc/%d", cons);
	    fd = open(devfsconsnam, O_RDONLY);
	    if (fd < 0)
		errno = ENOENT;
	}
	if (fd < 0) {
	    perror(consnam);
	    fd = 0;
	}

	if (ioctl(fd, TIOCGWINSZ, &win)) {
	    perror("TIOCGWINSZ");
	    exit(1);
	}

	screenbuf = xmalloc(2 + win.ws_row * win.ws_col);
	screenbuf[0] = 0;
	screenbuf[1] = (unsigned char) cons;

	if (ioctl(fd,TIOCLINUX,screenbuf) &&
	    (!fd || ioctl(0,TIOCLINUX,screenbuf))) {
#if 0
	    perror("TIOCLINUX");
	    fprintf(stderr,_("couldn't read %s, and cannot ioctl dump\n"),
		    infile);
#else
	    /* we tried this just to be sure, but TIOCLINUX
	       function 0 has been disabled since 1.1.92
	       Do not mention `ioctl dump' in error msg */
	    fprintf(stderr,_("couldn't read %s\n"), infile);
#endif
	    exit(1);
	}

        rows = screenbuf[0];
        cols = screenbuf[1];
	if (rows != win.ws_row || cols != win.ws_col) {
	    fprintf(stderr,
		    _("Strange ... screen is both %dx%d and %dx%d ??\n"),
		    win.ws_col, win.ws_row, cols, rows);
	    exit(1);
	}

	outbuf = xmalloc(rows*(cols+1));
	p = ((char *)screenbuf) + 2;
	q = outbuf;
        for (i=0; i<rows; i++) {
	    for (j=0; j<cols; j++)
	      *q++ = *p++;
            while (j-- > 0 && (q[-1] == ' '))
              q--;
	    *q++ = '\n';
        }
    }
done:
    if (write(1, outbuf, q-outbuf) != q-outbuf) {
        fprintf(stderr, _("Error writing screendump\n"));
        exit(1);
    }
    exit(0);
}
コード例 #16
0
int
main(int argc, char **argv) {
	int fd, sc, sc0;
	struct kbkeycode a;
	int old_kernel = 0;

	set_progname(argv[0]);

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);

	if (argc == 2 && !strcmp(argv[1], "-V"))
		print_version_and_exit();

	if (argc != 1)
		usage();
	fd = getfd(NULL);

	/* Old kernels don't support changing scancodes below SC_LIM. */
	a.scancode = 0;
	a.keycode = 0;
	if (ioctl(fd, KDGETKEYCODE, &a)) {
		old_kernel = 1;
		sc0 = 89;
	} else
	for (sc0 = 1; sc0 <= 88; sc0++) {
		a.scancode = sc0;
		a.keycode = 0;
		if (ioctl(fd, KDGETKEYCODE, &a) || a.keycode != sc0)
			break;
	}

	printf(_("Plain scancodes xx (hex) versus keycodes (dec)\n"));

	if (sc0 == 89) {
		printf(_("0 is an error; "
			 "for 1-88 (0x01-0x58) scancode equals keycode\n"));
	} else if (sc0 > 1) {
		printf(_("for 1-%d (0x01-0x%02x) scancode equals keycode\n"),
		       sc0 - 1, sc0 - 1);
	}

	for (sc = (sc0 & ~7); sc < 256; sc++) {
		if (sc == 128)
			printf(_("\n\nEscaped scancodes e0 xx (hex)\n"));
		if (sc % 8 == 0) {
			if (sc < 128)
				printf("\n 0x%02x: ", sc);
			else
				printf("\ne0 %02x: ", sc-128);
		}

		if (sc < sc0) {
			printf(" %3d", sc);
			continue;
		}

		a.scancode = sc;
		a.keycode = 0;
		if (ioctl(fd, KDGETKEYCODE, &a) == 0) {
			printf(" %3d", a.keycode);
			continue;
		}
		if (errno == EINVAL) {
			printf("   -");
			continue;
		}
		perror("KDGETKEYCODE");
		fprintf(stderr,
			_("failed to get keycode for scancode 0x%x\n"), sc);
		exit(1);
	}
	printf("\n");
	return 0;
}
コード例 #17
0
ファイル: ctie-k.c プロジェクト: luigiScarso/mflua
int main P2C(int,argc,string*,argv)
#line 104 "./ctie.w"
{
#line 38 "./ctie-k.ch"
/*5:*/
#line 84 "./ctie-k.ch"

kpse_set_program_name(argv[0],"ctie");

/*:5*/
#line 38 "./ctie-k.ch"
;
/*19:*/
#line 300 "./ctie.w"

actual_input= 0;
out_mode= normal;

/*:19*/
#line 39 "./ctie-k.ch"
;
#line 106 "./ctie.w"
/*63:*/
#line 1135 "./ctie.w"

{
if(argc> max_file_index+5-1)usage_error();
no_ch= -1;
while(--argc> 0){
argv++;
if(strcmp("-help",*argv)==0||strcmp("--help",*argv)==0)
/*66:*/
#line 1202 "./ctie.w"

usage_help();



/*:66*/
#line 1142 "./ctie.w"
;
if(strcmp("-version",*argv)==0||strcmp("--version",*argv)==0)
/*67:*/
#line 1208 "./ctie.w"

{
print_version_and_exit("CTIE",version_number);

}


/*:67*/
#line 1144 "./ctie.w"
;
if(**argv=='-')/*64:*/
#line 1158 "./ctie.w"

if(prod_chf!=unknown)usage_error();
else
switch(*(*argv+1)){
case'c':case'C':prod_chf= chf;break;
case'm':case'M':prod_chf= master;break;
default:usage_error();
}


/*:64*/
#line 1145 "./ctie.w"

else/*65:*/
#line 1172 "./ctie.w"

{
if(no_ch==(-1)){
out_name= *argv;
}else{
register input_description*inp_desc;

inp_desc= (input_description*)malloc(sizeof(input_description));
if(inp_desc==NULL)
fatal_error(-1,"! No memory for input descriptor","");

inp_desc->mode= search;
inp_desc->line= 0;
inp_desc->type_of_file= chf;
inp_desc->limit= inp_desc->buffer;
inp_desc->buffer[0]= ' ';
inp_desc->loc= inp_desc->buffer+1;
inp_desc->buffer_end= inp_desc->buffer+buf_size-2;
inp_desc->file_name= *argv;
inp_desc->current_include= NULL;
input_organisation[no_ch]= inp_desc;
}
no_ch++;
}


/*:65*/
#line 1146 "./ctie.w"

}
if(no_ch<=0||prod_chf==unknown)usage_error();
}


/*:63*/
#line 106 "./ctie.w"

/*62:*/
#line 1118 "./ctie.w"

#line 382 "./ctie-k.ch"
{
extern KPSEDLL string kpathsea_version_string;
printf("%s (%s)\n",banner,kpathsea_version_string);
}
#line 1120 "./ctie.w"
printf("%s\n",copyright);


/*:62*/
#line 107 "./ctie.w"
;
/*42:*/
#line 277 "./ctie-k.ch"

{
string fullname;

fullname= kpse_find_cweb(input_organisation[0]->file_name);
if(fullname)
input_organisation[0]->the_file= fopen(fullname,"r");

if(fullname==NULL||input_organisation[0]->the_file==NULL){
if(fullname){
pfatal_error("! Cannot open master file ",
input_organisation[0]->file_name);
}else{
fatal_error(-1,"! Cannot find master file ",
input_organisation[0]->file_name);
}
}
else free(fullname);


#line 759 "./ctie.w"
printf("(%s)\n",input_organisation[0]->file_name);
input_organisation[0]->type_of_file= master;
get_line(0,true);
}


/*:42*/
#line 108 "./ctie.w"

/*43:*/
#line 313 "./ctie-k.ch"

{
file_index i;
string fullname;

i= 1;
while(i<no_ch){
fullname= kpse_find_cweb(input_organisation[i]->file_name);
if(fullname)
input_organisation[i]->the_file= fopen(fullname,"r");

if(fullname==NULL||input_organisation[i]->the_file==NULL){
if(fullname){
pfatal_error("! Cannot open change file ",
input_organisation[i]->file_name);
}else{
fatal_error(-1,"! Cannot find change file ",
input_organisation[i]->file_name);
}
}
else free(fullname);


#line 780 "./ctie.w"
printf("(%s)\n",input_organisation[i]->file_name);
init_change_file(i);
i++;
}
}


/*:43*/
#line 109 "./ctie.w"

/*40:*/
#line 729 "./ctie.w"

{
out_file= fopen(out_name,"w");
if(out_file==NULL){
pfatal_error("! Cannot open/create output file","");

}
}


/*:40*/
#line 110 "./ctie.w"

/*59:*/
#line 1074 "./ctie.w"

actual_input= 0;
input_has_ended= false;
while(input_has_ended==false||actual_input!=0)
/*51:*/
#line 917 "./ctie.w"

{
file_index test_file;

/*52:*/
#line 934 "./ctie.w"

{
register input_description*inp_desc;
while(actual_input> 0&&e_of_ch_module(actual_input)){
inp_desc= input_organisation[actual_input];
if(inp_desc->type_of_file==master){

fatal_error(-1,"! This can't happen: change file is master file","");

}
inp_desc->mode= search;
init_change_file(actual_input);
while((input_organisation[actual_input]->mode!=reading
&&actual_input> 0))
actual_input--;
}
}


/*:52*/
#line 921 "./ctie.w"

if(input_has_ended&&actual_input==0)break;
/*53:*/
#line 960 "./ctie.w"

test_input= none;
test_file= actual_input;
while(test_input==none&&test_file<no_ch-1){
test_file++;
switch(input_organisation[test_file]->mode){
case search:
if(lines_dont_match(actual_input,test_file)==false){
input_organisation[test_file]->mode= test;
test_input= test_file;
}
break;
case test:
if(lines_dont_match(actual_input,test_file)){

input_organisation[test_file]->dont_match++;
}
test_input= test_file;
break;
case reading:
break;
case ignore:
break;
}
}


/*:53*/
#line 923 "./ctie.w"

/*54:*/
#line 993 "./ctie.w"

if(prod_chf==chf){
while(1){
/*55:*/
#line 1007 "./ctie.w"

if(out_mode==normal){
if(test_input!=none){
fprintf(out_file,"@x\n");
out_mode= pre;
}else break;
}


/*:55*/
#line 996 "./ctie.w"

/*56:*/
#line 1021 "./ctie.w"

if(out_mode==pre){
if(test_input==none){
fprintf(out_file,"@y\n");
out_mode= post;
}else{
if(input_organisation[actual_input]->type_of_file==master)
put_line(actual_input);
break;
}
}


/*:56*/
#line 997 "./ctie.w"

/*57:*/
#line 1040 "./ctie.w"

if(out_mode==post){
if(input_organisation[actual_input]->type_of_file==chf){
if(test_input==none)put_line(actual_input);
break;
}else{
fprintf(out_file,"@z\n\n");
out_mode= normal;
}
}


/*:57*/
#line 998 "./ctie.w"

}
}else
if(test_input==none)put_line(actual_input);


/*:54*/
#line 924 "./ctie.w"

/*58:*/
#line 1055 "./ctie.w"

get_line(actual_input,true);
if(test_input!=none){
get_line(test_input,true);
if(e_of_ch_preamble(test_input)==true){
get_line(test_input,true);
input_organisation[test_input]->mode= reading;
actual_input= test_input;
test_input= none;
}
}


/*:58*/
#line 925 "./ctie.w"

}


/*:51*/
#line 1078 "./ctie.w"

if(out_mode==post)
fprintf(out_file,"@z\n");


/*:59*/
#line 111 "./ctie.w"

/*60:*/
#line 1087 "./ctie.w"

{
file_index i;

for(i= 1;i<no_ch;i++){
if(input_organisation[i]->mode!=ignore){
input_organisation[i]->loc= input_organisation[i]->buffer;
err_print(i,"! Change file entry did not match");

}
}
}


/*:60*/
#line 112 "./ctie.w"

exit(wrap_up());
}
コード例 #18
0
ファイル: showconsolefont.c プロジェクト: legionus/kbd
int main(int argc, char **argv)
{
	int c, n, cols, rows, nr, i, j, k;
	int mode;
	const char *space, *sep;
	char *console = NULL;
	int list[64], lth, info = 0, verbose = 0;

	set_progname(argv[0]);

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);

	if (argc == 2 &&
	    (!strcmp(argv[1], "-V") || !strcmp(argv[1], "--version")))
		print_version_and_exit();

	while ((c = getopt(argc, argv, "ivC:")) != EOF) {
		switch (c) {
			case 'i':
				info = 1;
				break;
			case 'v':
				verbose = 1;
				break;
			case 'C':
				console = optarg;
				break;
			default:
				usage();
		}
	}

	if (optind != argc)
		usage();

	if ((fd = getfd(console)) < 0)
		kbd_error(EXIT_FAILURE, 0, _("Couldn't get a file descriptor referring to the console"));

	if (ioctl(fd, KDGKBMODE, &mode)) {
		kbd_warning(errno, "ioctl KDGKBMODE");
		leave(EXIT_FAILURE);
	}
	if (mode == K_UNICODE)
		space = "\xef\x80\xa0"; /* U+F020 (direct-to-font space) */
	else
		space = " ";

	if (info) {
		nr = rows = cols = 0;
		n                = getfont(fd, NULL, &nr, &rows, &cols);
		if (n != 0)
			leave(EXIT_FAILURE);

		if (verbose) {
			printf(_("Character count: %d\n"), nr);
			printf(_("Font width     : %d\n"), rows);
			printf(_("Font height    : %d\n"), cols);
		} else
			printf("%dx%dx%d\n", rows, cols, nr);
		leave(EXIT_SUCCESS);
	}

	settrivialscreenmap();
	getoldunicodemap();

	n = getfontsize(fd);
	if (verbose)
		printf(_("Showing %d-char font\n\n"), n);
	cols = ((n > 256) ? 32 : 16);
	nr   = 64 / cols;
	rows = (n + cols - 1) / cols;
	sep  = ((cols == 16) ? "%1$s%1$s" : "%1$s");

	for (i = 0; i < rows; i++) {
		if (i % nr == 0) {
			lth = 0;
			for (k = i; k < i + nr; k++)
				for (j              = 0; j < cols; j++)
					list[lth++] = k + j * rows;
			setnewunicodemap(list, lth);
		}
		printf("%1$s%1$s%1$s%1$s", space);
		for (j = 0; j < cols && i + j * rows < n; j++) {
			putchar(BASE + (i % nr) * cols + j);
			printf(sep, space);
			if (j % 8 == 7)
				printf(sep, space);
		}
		putchar('\n');
		if (i % 8 == 7)
			putchar('\n');
		fflush(stdout);
	}

	leave(EXIT_SUCCESS);
	return EXIT_SUCCESS;
}
コード例 #19
0
ファイル: main.c プロジェクト: oloftangrot/misc
int main(int argc, char **argv) {
	unsigned int start;
	int bytes_count = 0;
	char filename[256];
	memset(filename, 0, sizeof(filename));
	// Parsing command line
	char c;
	action_t action = NONE;
	bool start_addr_specified = false,
		pgm_specified = false,
		part_specified = false,
        bytes_count_specified = false;
	memtype_t memtype = FLASH;
	int i;
	programmer_t *pgm = NULL;
	const stm8_device_t *part = NULL;
	while((c = getopt (argc, argv, "r:w:v:nc:p:s:b:luV")) != (char)-1) {
		switch(c) {
			case 'c':
				pgm_specified = true;
				for(i = 0; pgms[i].name; i++) {
					if(!strcmp(optarg, pgms[i].name))
						pgm = &pgms[i];
				}
				break;
			case 'p':
				part_specified = true;
				part = get_part(optarg);
				break;
			case 'l':
				for(i = 0; stm8_devices[i].name; i++)
					printf("%s ", stm8_devices[i].name);
				printf("\n");
				exit(0);
			case 'r':
				action = READ;
				strcpy(filename, optarg);
				break;
			case 'w':
				action = WRITE;
				strcpy(filename, optarg);
				break;
			case 'v':
				action = VERIFY;
				strcpy(filename, optarg);
				break;
                        case 'u':
				action = UNLOCK;
				start  = 0x4800;
				memtype = OPT;
				strcpy(filename, "Workaround");
				break;
			case 's':
                // Start addr is depending on MCU type
				if(strcasecmp(optarg, "flash") == 0) {
					memtype = FLASH;
                } else if(strcasecmp(optarg, "eeprom") == 0) {
					memtype = EEPROM;
                } else if(strcasecmp(optarg, "ram") == 0) {
					memtype = RAM;
                } else if(strcasecmp(optarg, "opt") == 0) {
					memtype = OPT;
				} else {
					// Start addr is specified explicitely
					memtype = UNKNOWN;
					int success = sscanf(optarg, "%x", &start);
					assert(success);
                    start_addr_specified = true;
				}
				break;
			case 'b':
				bytes_count = atoi(optarg);
                bytes_count_specified = true;
				break;
			case 'V':
                                print_version_and_exit( (bool)0);
				break;
			case '?':
                                print_help_and_exit(argv[0], false);
			default:
				print_help_and_exit(argv[0], true);
		}
	}
	if(argc <= 1)
		print_help_and_exit(argv[0], true);
	if(pgm_specified && !pgm) {
		fprintf(stderr, "No valid programmer specified. Possible values are:\n");
		dump_pgms( (programmer_t *) &pgms);
		exit(-1);
	}
	if(!pgm)
		spawn_error("No programmer has been specified");
	if(part_specified && !part) {
		fprintf(stderr, "No valid part specified. Use -l to see the list of supported devices.\n");
		exit(-1);
	}
	if(!part)
		spawn_error("No part has been specified");

    // Try define memory type by address
	if(memtype == UNKNOWN) {
        if((start >= 0x4800) && (start < 0x4880)) {
            memtype = OPT;
        }
        if((start >= part->ram_start) && (start < part->ram_start + part->ram_size)) {
            memtype = RAM;
        }
        else if((start >= part->flash_start) && (start < part->flash_start + part->flash_size)) {
            memtype = FLASH;
        }
        else if((start >= part->eeprom_start) && (start < part->eeprom_start + part->eeprom_size)) {
            memtype = EEPROM;
        }
    }

	if(memtype != UNKNOWN) {
		// Selecting start addr depending on
		// specified part and memtype
		switch(memtype) {
			case RAM:
                if(!start_addr_specified) {
                    start = part->ram_start;
                }
                if(!bytes_count_specified || bytes_count > part->ram_size) {
                    bytes_count = part->ram_size;
                }
                fprintf(stderr, "Determine RAM area\r\n");
				break;
			case EEPROM:
                if(!start_addr_specified) {
                    start = part->eeprom_start;
                }
                if(!bytes_count_specified || bytes_count > part->eeprom_size) {
                    bytes_count = part->eeprom_size;
                }
                fprintf(stderr, "Determine EEPROM area\r\n");
				break;
			case FLASH:
                if(!start_addr_specified) {
                    start = part->flash_start;
                }
                if(!bytes_count_specified || bytes_count > part->flash_size) {
                    bytes_count = part->flash_size;
                }
                fprintf(stderr, "Determine FLASH area\r\n");
				break;
			case OPT:
                if(!start_addr_specified) {
                    start = 0x4800;
                }
                size_t opt_size = (part->flash_size <= 8*1024 ? 0x40 : 0x80);
                if(!bytes_count_specified || bytes_count > opt_size) {
                    bytes_count = opt_size;
                }
                fprintf(stderr, "Determine OPT area\r\n");
                break;
		}
		start_addr_specified = true;
	}
	if(!action)
		spawn_error("No action has been specified");
	if(!start_addr_specified)
		spawn_error("No memtype or start_addr has been specified");
	if (!strlen(filename))
		spawn_error("No filename has been specified");
	if(!action || !start_addr_specified || !strlen(filename))
		print_help_and_exit(argv[0], true);
	if(!usb_init(pgm, pgm->usb_vid, pgm->usb_pid))
		spawn_error("Couldn't initialize stlink");
	if(!pgm->open(pgm))
		spawn_error("Error communicating with MCU. Please check your SWIM connection.");


	FILE *f;
	if(action == READ) {
		fprintf(stderr, "Reading %d bytes at 0x%x... ", bytes_count, start);
		fflush(stderr);
        int bytes_count_align = ((bytes_count-1)/256+1)*256; // Reading should be done in blocks of 256 bytes
		unsigned char *buf = malloc(bytes_count_align);
		if(!buf) spawn_error("malloc failed");
		int recv = pgm->read_range(pgm, part, buf, start, bytes_count_align);
        if(recv < bytes_count_align) {
            fprintf(stderr, "\r\nRequested %d bytes but received only %d.\r\n", bytes_count_align, recv);
			spawn_error("Failed to read MCU");
        }
		if(!(f = fopen(filename, "w")))
			spawn_error("Failed to open file");
		if(is_ext(filename, ".ihx") || is_ext(filename, ".hex"))
		{
			fprintf(stderr, "Reading from Intel hex file ");
			ihex_write(f, buf, start, start+bytes_count);
		}
		else if(is_ext(filename, ".s19") || is_ext(filename, ".s8") || is_ext(filename, ".srec"))
		{
			printf("Reading from Motorola S-record files are not implemented (yet)\n");
      printf("Exiting...\n");
			exit(-1);

			//TODO Remove the above message and exit, and implement reading from S-record.
			fprintf(stderr, "Reading from Motorola S-record file ");
			srec_write(f, buf, start, start+bytes_count);
		}
		else
		{
			fwrite(buf, 1, bytes_count, f);
		}
		fclose(f);
		fprintf(stderr, "OK\n");
		fprintf(stderr, "Bytes received: %d\n", bytes_count);
    } else if (action == VERIFY) {
		fprintf(stderr, "Verifing %d bytes at 0x%x... ", bytes_count, start);
		fflush(stderr);

        int bytes_count_align = ((bytes_count-1)/256+1)*256; // Reading should be done in blocks of 256 bytes
		unsigned char *buf = malloc(bytes_count_align);
		if(!buf) spawn_error("malloc failed");
		int recv = pgm->read_range(pgm, part, buf, start, bytes_count_align);
        if(recv < bytes_count_align) {
            fprintf(stderr, "\r\nRequested %d bytes but received only %d.\r\n", bytes_count_align, recv);
			spawn_error("Failed to read MCU");
        }

		if(!(f = fopen(filename, "r")))
			spawn_error("Failed to open file");
		unsigned char *buf2 = malloc(bytes_count);
		if(!buf2) spawn_error("malloc failed");
		int bytes_to_verify;
		/* reading bytes to RAM */
		if(is_ext(filename, ".ihx") || is_ext(filename, ".hex")) {
			bytes_to_verify = ihex_read(f, buf, start, start + bytes_count);
		} else {
			fseek(f, 0L, SEEK_END);
			bytes_to_verify = ftell(f);
            if(bytes_count_specified) {
                bytes_to_verify = bytes_count;
            } else if(bytes_count < bytes_to_verify) {
                bytes_to_verify = bytes_count;
            }
			fseek(f, 0, SEEK_SET);
			fread(buf2, 1, bytes_to_verify, f);
		}
		fclose(f);

        if(memcmp(buf, buf2, bytes_to_verify) == 0) {
            fprintf(stderr, "OK\n");
            fprintf(stderr, "Bytes verified: %d\n", bytes_to_verify);
        } else {
            fprintf(stderr, "FAILED\n");
            exit(-1);
        }


	} else if (action == WRITE) {
		if(!(f = fopen(filename, "r")))
			spawn_error("Failed to open file");
        int bytes_count_align = ((bytes_count-1)/part->flash_block_size+1)*part->flash_block_size;
		unsigned char *buf = malloc(bytes_count_align);
		if(!buf) spawn_error("malloc failed");
        memset(buf, 0, bytes_count_align); // Clean aligned buffer
		int bytes_to_write;

		/* reading bytes to RAM */
		if(is_ext(filename, ".ihx") || is_ext(filename, ".hex")) {
			fprintf(stderr, "Writing Intel hex file ");
			bytes_to_write = ihex_read(f, buf, start, start + bytes_count);
		} else if (is_ext(filename, ".s19") || is_ext(filename, ".s8") || is_ext(filename, ".srec")) {
			fprintf(stderr, "Writing Motorola S-record file ");
			bytes_to_write = srec_read(f, buf, start, start + bytes_count);
		} else {
			fprintf(stderr, "Writing binary file ");
			fseek(f, 0L, SEEK_END);
			bytes_to_write = ftell(f);
            if(bytes_count_specified) {
                bytes_to_write = bytes_count;
            } else if(bytes_count < bytes_to_write) {
                bytes_to_write = bytes_count;
            }
			fseek(f, 0, SEEK_SET);
			fread(buf, 1, bytes_to_write, f);
		}
		fprintf(stderr, "%d bytes at 0x%x... ", bytes_to_write, start);

		/* flashing MCU */
		int sent = pgm->write_range(pgm, part, buf, start, bytes_to_write, memtype);
		if(pgm->reset) {
			// Restarting core (if applicable)
			pgm->reset(pgm);
		}
		fprintf(stderr, "OK\n");
		fprintf(stderr, "Bytes written: %d\n", sent);
		fclose(f);
	} else if (action == UNLOCK) {
		int bytes_to_write=part->option_bytes_size;

		if (part->read_out_protection_mode==ROP_UNKNOWN) spawn_error("No unlocking mode defined for this device. You may need to edit the file stm8.c");

		unsigned char *buf=malloc(bytes_to_write);
		if(!buf) spawn_error("malloc failed");

		if (part->read_out_protection_mode==ROP_STM8S_STD) {
			for (int i=0; i<bytes_to_write;i++) {
				buf[i]=0;
				if ((i>0)&&((i&1)==0)) buf[i]=0xff;
			}
		}

		/* flashing MCU */
		int sent = pgm->write_range(pgm, part, buf, start, bytes_to_write, memtype);
		if(pgm->reset) {
			// Restarting core (if applicable)
			pgm->reset(pgm);
		}
		fprintf(stderr, "Unlocked device. Option bytes reset to default state.\n");
		fprintf(stderr, "Bytes written: %d\n", sent);
	}
	return(0);
}