Ejemplo n.º 1
0
/*@T
 *
 * The [[get_params]] function uses the [[getopt]] package
 * to handle the actual argument processing.  Note that
 * [[getopt]] is {\em not} thread-safe!  You will need to
 * do some synchronization if you want to use this function
 * safely with threaded code.
 *@c*/
int get_params(int argc, char** argv, sim_param_t* params)
{
    extern char* optarg;
    const char* optstring = "ho:F:f:t:s:d:k:v:g:";
    int c;

    #define get_int_arg(c, field) \
        case c: params->field = atoi(optarg); break
    #define get_flt_arg(c, field) \
        case c: params->field = (float) atof(optarg); break

    default_params(params);
    while ((c = getopt(argc, argv, optstring)) != -1) {
        switch (c) {
        case 'h': 
            print_usage(); 
            return -1;
        case 'o':
            strcpy(params->fname = malloc(strlen(optarg)+1), optarg);
            break;
        get_int_arg('F', nframes);
        get_int_arg('f', npframe);
        get_flt_arg('t', dt);
        get_flt_arg('s', h);
        get_flt_arg('d', rho0);
        get_flt_arg('k', k);
        get_flt_arg('v', mu);
        get_flt_arg('g', g);
        default:
            fprintf(stderr, "Unknown option\n");
            return -1;
        }
    }
    return 0;
}
Ejemplo n.º 2
0
long do_sigreturn(CPUState *env, int num)
{
    int i = 0;
    struct target_sigcontext *scp = get_int_arg(&i, env);
    fprintf(stderr, "do_sigreturn: not implemented\n");
    return -ENOSYS;
}
Ejemplo n.º 3
0
long do_lseek(void *cpu_env, int num)
{
    long ret;
    int i = 0;
    uint32_t arg1 = get_int_arg(&i, cpu_env);
    uint64_t offset = get_int64_arg(&i, cpu_env);
    uint32_t arg3 = get_int_arg(&i, cpu_env);
    uint64_t r = lseek(arg1, offset, arg3);
#ifdef TARGET_I386
    /* lowest word in eax, highest in edx */
    ret = r & 0xffffffff; /* will be set to eax after do_unix_syscall exit */
    ((CPUX86State *)cpu_env)->regs[R_EDX] = (uint32_t)((r >> 32) & 0xffffffff) ;
#elif defined TARGET_PPC
    ret = r & 0xffffffff; /* will be set to r3 after do_unix_syscall exit */
    ((CPUPPCState *)cpu_env)->gpr[4] = (uint32_t)((r >> 32) & 0xffffffff) ;
#else
    qerror("64 bit ret value on your arch?");
#endif
    return get_errno(ret);
}
Ejemplo n.º 4
0
long do_unix_syscall_indirect(void *cpu_env, int num)
{
    long ret;
    int new_num;
    int i = 0;

    new_num = get_int_arg(&i, cpu_env);
#ifdef TARGET_I386
    ((CPUX86State*)cpu_env)->regs[R_ESP] += 4;
    /* XXX: not necessary */
    ((CPUX86State*)cpu_env)->regs[R_EAX] = new_num;
#elif TARGET_PPC
    {
        int i;
        uint32_t **regs = ((CPUPPCState*)cpu_env)->gpr;
        for(i = 3; i < 11; i++)
            *regs[i] = *regs[i+1];
        /* XXX: not necessary */
        *regs[0] = new_num;
    }
#endif
    ret = do_unix_syscall(cpu_env, new_num);
#ifdef TARGET_I386
    ((CPUX86State*)cpu_env)->regs[R_ESP] -= 4;
    /* XXX: not necessary */
    ((CPUX86State*)cpu_env)->regs[R_EAX] = num;
#elif TARGET_PPC
    {
        int i;
        /* XXX: not really needed those regs are volatile accross calls */
        uint32_t **regs = ((CPUPPCState*)cpu_env)->gpr;
        for(i = 11; i > 3; i--)
            *regs[i] = *regs[i-1];
        regs[3] = new_num;
        *regs[0] = num;
    }
#endif
    return ret;
}
Ejemplo n.º 5
0
long do_sigreturn(CPUState *env, int num)
{
    int i = 0;
    struct target_sigcontext *scp = get_int_arg(&i, env);
    /* XXX Get current signal number */
    /* XXX Adjust accordin to sc_onstack, sc_mask */
    if(tswapl(scp->sc_onstack) & 0x1)
        target_sigaltstack_used.ss_flags |= ~SA_DISABLE;
    else
        target_sigaltstack_used.ss_flags &=  SA_DISABLE;
    int set = tswapl(scp->sc_eax);
    sigprocmask(SIG_SETMASK, &set, NULL);

    fprintf(stderr, "do_sigreturn: partially implemented %x EAX:%x EBX:%x\n", scp->sc_mask, tswapl(scp->sc_eax), tswapl(scp->sc_ebx));
    fprintf(stderr, "ECX:%x EDX:%x EDI:%x\n", scp->sc_ecx, tswapl(scp->sc_edx), tswapl(scp->sc_edi));
    fprintf(stderr, "EIP:%x\n", tswapl(scp->sc_eip));

    env->regs[R_EAX] = tswapl(scp->sc_eax);
    env->regs[R_EBX] = tswapl(scp->sc_ebx);
    env->regs[R_ECX] = tswapl(scp->sc_ecx);
    env->regs[R_EDX] = tswapl(scp->sc_edx);
    env->regs[R_EDI] = tswapl(scp->sc_edi);
    env->regs[R_ESI] = tswapl(scp->sc_esi);
    env->regs[R_EBP] = tswapl(scp->sc_ebp);
    env->regs[R_ESP] = tswapl(scp->sc_esp);
    env->segs[R_SS].selector = (void*)tswapl(scp->sc_ss);
    env->eflags = tswapl(scp->sc_eflags);
    env->eip = tswapl(scp->sc_eip);
    env->segs[R_CS].selector = (void*)tswapl(scp->sc_cs);
    env->segs[R_DS].selector = (void*)tswapl(scp->sc_ds);
    env->segs[R_ES].selector = (void*)tswapl(scp->sc_es);
    env->segs[R_FS].selector = (void*)tswapl(scp->sc_fs);
    env->segs[R_GS].selector = (void*)tswapl(scp->sc_gs);

    /* Again, because our caller's caller will reset EAX */
    return env->regs[R_EAX];
}
Ejemplo n.º 6
0
int main(int argc, const char *argv[])
{
  const char *dev_name="eps";
  int dev_name_len = 3;
  const char *out_fn=0;
  const char *stamp=0;
  const char *stamp_enc=0;
  const char *png_dump_fn=0;
  int ifile;
  char *aux_path;
  double x_dpi=72.0;
  double y_dpi=72.0;
  hpgs_bbox bbox= { 0.0, 0.0, 0.0, 0.0 };
  double paper_angle = 0.0;
  double paper_border = 0.0;
  double paper_width = 0.0;
  double paper_height = 0.0;
  double lw_factor=-1.0;
  double thin_alpha=0.25;
  double stamp_size=500.0;
  int x_px_size=0;
  int y_px_size=0;
  hpgs_bool multipage=HPGS_FALSE;
  hpgs_bool ignore_ps=HPGS_FALSE;
  hpgs_bool do_linewidth=HPGS_TRUE;
  hpgs_bool do_rop3=HPGS_TRUE;
  int verbosity=1;
  int compression=6;
  hpgs_bool antialias=HPGS_FALSE;
  int image_interpolation=0;
  hpgs_device *size_dev = 0;
  hpgs_device *plot_dev = 0;
  hpgs_istream *in = 0;
  hpgs_reader  *reader = 0;
  hpgs_png_image *image = 0;
  const char *plugin_argv[HPGS_MAX_PLUGIN_ARGS];
  int plugin_argc = 0;
  int ret = 1;

#ifdef LC_MESSAGES
  setlocale(LC_MESSAGES,"");
#endif
  setlocale(LC_CTYPE,"");

  aux_path = get_aux_path();

  if (!aux_path)
    {
      fprintf(stderr,hpgs_i18n("Error getting installation path: %s.\n"),
	      strerror(errno));
      return 1;
    }
  
  hpgs_init(aux_path);
  free(aux_path);

  memset(plugin_argv,0,sizeof(plugin_argv));

  ++argv;
  --argc;

  while (argc>0)
    {
      int narg = 1;
      const char *value;

      if (strcmp(argv[0],"--") == 0)
	{
	  ++argv;
	  --argc;
	  break;
	}
      else       if (strcmp(argv[0],"-v") == 0)
	{
	  ++verbosity;
	}
      else if (strcmp(argv[0],"-q") == 0 || strcmp(argv[0],"-dQUIET") == 0)
	{
	  --verbosity;
	}
      else if (strcmp(argv[0],"-i") == 0)
	{
	  ignore_ps=HPGS_TRUE;
	}
      else if (strcmp(argv[0],"-m") == 0)
	{
	  multipage=HPGS_TRUE;
	}
      else if (hpgs_get_arg_value("-d",argv,&value,&narg))
	{
	  dev_name = value;
          dev_name_len = strlen(dev_name);

          if (plugin_argc)
	    {
	      fprintf(stderr,hpgs_i18n("Error: Device options specified before -d argument.\n"));
	      return usage();
	    }
	}
      else if (hpgs_get_arg_value("--stamp=",argv,&value,&narg))
	{
	  stamp = value;
	}
      else if (hpgs_get_arg_value("--stamp-encoding=",argv,&value,&narg))
	{
	  stamp_enc = value;
	}
      else if (hpgs_get_arg_value("--stamp-size=",argv,&value,&narg))
	{
          if (hpgs_parse_length(value,&stamp_size))
	    {
	      fprintf(stderr,hpgs_i18n("Error: --stamp-size= must be followed by a valid length.\n"));
	      return usage();
	    }

	  if (stamp_size < 20.0 || stamp_size > 2000.0)
	    {
	      fprintf(stderr,hpgs_i18n("Error: stamp-size must lie in the interval [20,2000]pt.\n"));
	      return usage();
	    }
	}
      else if (hpgs_get_arg_value("--dump-png=",argv,&value,&narg))
	{
          png_dump_fn = value;
	}
       else if (hpgs_get_arg_value("-o",argv,&value,&narg))
	{
	  out_fn = value;
	}
      else if (strcmp(argv[0],"-a") == 0)
	{
          antialias = HPGS_TRUE;
	}
      else if (hpgs_get_arg_value("-I",argv,&value,&narg))
	{
	  if (get_int_arg(value,&image_interpolation))
	    {
	      if (narg == 1)
		{
		  fprintf(stderr,hpgs_i18n("Error: -I must be followed by an integer number.\n"));
		  return usage();
		}
	      else
		{
		  image_interpolation= 1;
		  narg = 1;
		}
	    }

	  if (image_interpolation < 0 || image_interpolation > 1)
	    {
	      fprintf(stderr,hpgs_i18n("Error: The argument to -I must be 0 or 1.\n"));
	      return usage();
	    }
	}
      else if (hpgs_get_arg_value("-c",argv,&value,&narg))
	{
	  if (get_int_arg(value,&compression))
	    {
	      fprintf(stderr,hpgs_i18n("Error: -c must be followed by an integer number.\n"));
	      return usage();
	    }
	  
	  if (compression < 1 || compression > 9)
	    {
	      fprintf(stderr,hpgs_i18n("Error: compression factor must lie in the interval [1,9].\n"));
	      return usage();
	    }
	}
      else if (hpgs_get_arg_value("-w",argv,&value,&narg))
	{
	  if (get_double_arg(value,&lw_factor))
	    {
	      fprintf(stderr,hpgs_i18n("Error: -w must be followed by a floating point number.\n"));
	      return usage();
	    }
	  
	  if (lw_factor < 0.0 || lw_factor > 10.0)
	    {
	      fprintf(stderr,hpgs_i18n("Error: Linewidth factor must lie in the interval [0.0,10.0].\n"));
	      return usage();
	    }
	}
      else if (hpgs_get_arg_value("--thin-alpha=",argv,&value,&narg))
	{
	  if (get_double_arg(value,&thin_alpha))
	    {
	      fprintf(stderr,hpgs_i18n("Error: --thin-alpha= must be followed by a floating point number.\n"));
	      return usage();
	    }
	  
	  if (thin_alpha < 0.01 || thin_alpha > 10.0)
	    {
	      fprintf(stderr,hpgs_i18n("Error: Thin alpha must lie in the interval [0.01,10.0].\n"));
	      return usage();
	    }
	}
      else if (hpgs_get_arg_value("-r",argv,&value,&narg))
	{
	  if (get_double_pair(value,&x_dpi,&y_dpi))
	    {
	      fprintf(stderr,hpgs_i18n("Error: -r must be followed by <res> or <xres>x<yres>.\n"));
	      return usage();
            }

          if (x_dpi < 5.0 || y_dpi < 5.0)
            {
              fprintf(stderr,hpgs_i18n("Error: Resolutions must be at least 5 dpi.\n"));
              return usage();
            }
	}
      else if (hpgs_get_arg_value("-p",argv,&value,&narg))
	{
	  if (get_int_pair(value,&x_px_size,&y_px_size))
	    {
	      fprintf(stderr,hpgs_i18n("Error: -p must be followed by <sz> or <xsz>x<ysz>.\n"));
	      return usage();
            }

          if (y_px_size < 20 ||  x_px_size < 20)
            {
              fprintf(stderr,hpgs_i18n("Error: Pixel sizes must be at least 20px.\n"));
              return usage();
            }
	}
      else if (hpgs_get_arg_value("-s",argv,&value,&narg))
	{
          double x_size,y_size;

          if (hpgs_parse_papersize(value,&x_size, &y_size)<0)
            {
	      fprintf(stderr,hpgs_i18n("Error: -s must be followed by a valid paper size.\n"));
	      return usage();
            }

          if (x_size < 72.0 || y_size < 72.0)
            {
              fprintf(stderr,hpgs_i18n("Error: The plot size must be at least 72 pt.\n"));
              return usage();
            }

          bbox.urx = bbox.llx + x_size;
          bbox.ury = bbox.lly + y_size;
	}
      else if (hpgs_get_arg_value("--origin=",argv,&value,&narg))
	{
          double xo,yo;

          if (hpgs_parse_papersize(value,&xo, &yo)<0)
            {
	      fprintf(stderr,hpgs_i18n("Error: --origin= must be followed by a valid pair of length specification.\n"));
	      return usage();
            }

          

          bbox.urx = (bbox.urx - bbox.llx) + xo;
          bbox.ury = (bbox.ury - bbox.lly) + yo;
          bbox.llx = xo;
          bbox.lly = yo;
	}
      else if (hpgs_get_arg_value("--paper=",argv,&value,&narg))
	{
          if (hpgs_parse_papersize(value,&paper_width,&paper_height)<0)
            {
	      fprintf(stderr,hpgs_i18n("Error: --paper= must be followed by a valid paper size.\n"));
	      return usage();
            }

          if (paper_width < 72.0 || paper_height < 72.0)
            {
              fprintf(stderr,hpgs_i18n("Error: The paper size must be at least 72 pt.\n"));
              return usage();
            }
	}
      else if (hpgs_get_arg_value("--border=",argv,&value,&narg) ||
               // Allow old device-specific border parameters.
               get_dev_arg_value(dev_name,dev_name_len,"-border=",argv,&value,&narg)     )
	{
          if (hpgs_parse_length(value,&paper_border)<0)
            {
	      fprintf(stderr,hpgs_i18n("Error: --border= must be followed by a valid length.\n"));
	      return usage();
            }

          if (paper_border < 0.0 || paper_border > 144.0)
            {
              fprintf(stderr,hpgs_i18n("Error: The page border must lie in the interval [0,144] pt.\n"));
              return usage();
            }
	}
      else if (hpgs_get_arg_value("--rotation=",argv,&value,&narg) ||
               // Allow old device-specific rotation parameters.
               get_dev_arg_value(dev_name,dev_name_len,"-rotation=",argv,&value,&narg)       )
	{
          if (hpgs_parse_length(value,&paper_angle)<0)
            {
	      fprintf(stderr,hpgs_i18n("Error: --angle= must be followed by a valid angle.\n"));
	      return usage();
            }
	}
      else if (strcmp(argv[0],"--linewidth-size") == 0)
	{
	  do_linewidth = HPGS_TRUE;
	}
      else if (strcmp(argv[0],"--no-linewidth-size") == 0)
  	{
	  do_linewidth = HPGS_FALSE;
	}
      else if (strcmp(argv[0],"--rop3") == 0)
	{
	  do_rop3 = HPGS_TRUE;
	}
      else if (strcmp(argv[0],"--no-rop3") == 0)
	{
	  do_rop3 = HPGS_FALSE;
	}
      else if (strcmp(argv[0],"--help") == 0)
	{
	  return help();
	}
      else if (strcmp(argv[0],"--version") == 0)
	{
	  usage();
	  return 0;
	}
      else if (strncmp(argv[0],"--",2) == 0 &&
               strncmp(argv[0]+2,dev_name,dev_name_len) == 0 &&
               argv[0][dev_name_len+2] == '-')
	{
          int l=strlen(argv[0]);

          if (plugin_argc >= HPGS_MAX_PLUGIN_ARGS-1)
	    {
	      fprintf(stderr,hpgs_i18n("Error: Number of plugin-args exceeds maximum of %d.\n"),
                      HPGS_MAX_PLUGIN_ARGS-1);
	      return usage();
	    }

          plugin_argv[plugin_argc] = argv[0]+dev_name_len+2;
          ++plugin_argc;

          if (argv[0][l-1] == '=')
            {
              if (plugin_argc >= HPGS_MAX_PLUGIN_ARGS-1)
                {
                  fprintf(stderr,hpgs_i18n("Error: Number of plugin-args exceed maximum of %d.\n"),
                          HPGS_MAX_PLUGIN_ARGS-1);
                  usage();
                }

              plugin_argv[plugin_argc] = argv[2];
              ++plugin_argc;

              narg=2;
            }
	}
      else
	{
	  if (argv[0][0] == '-')
	    {
	      fprintf(stderr,hpgs_i18n("Error: Unknown option %s given.\n"),argv[0]);
	      return usage();
	    }

          break;
	}

      argv+=narg;
      argc-=narg;
    }
  
  if (argc < 1)
    {
      fprintf(stderr,hpgs_i18n("Error: No input file given.\n"));
      return usage();
    }

  if (argc > 1 && !multipage)
    {
      multipage = HPGS_TRUE;
    }

  // adjust default linewidth factor.
  if (lw_factor < 0.0)
    {
      // This is the best choice for our basic, non-antialiased renderer,
      // which rounds up pixel line widths.
      if (antialias == 0 && strncmp(dev_name,"png_",4) == 0)
        lw_factor = 0.5;
      else
        lw_factor = 1.0;
    }

  size_dev = (hpgs_device*)hpgs_new_plotsize_device(ignore_ps,do_linewidth);

  if (!size_dev)
    {
      fprintf(stderr,hpgs_i18n("Error: Cannot create plotsize device.\n"));
      goto cleanup;
    }

  in = hpgs_new_file_istream(argv[0]);

  if (!in)
    {
      fprintf(stderr,hpgs_i18n("Error: Cannot open input file %s: %s\n"),
	      argv[0],strerror(errno));
      hpgs_device_destroy((hpgs_device*)size_dev);
      goto cleanup;
    }

  reader = hpgs_new_reader(in,size_dev,
			   multipage,verbosity);

  if (!reader)
    {
      fprintf(stderr,hpgs_i18n("Error: Cannot create hpgl reader: %s\n"),strerror(errno));
      goto cleanup;
    }
 
  hpgs_reader_set_lw_factor(reader,lw_factor);

  // determine plot size, if not specified on the cmd line
  if (bbox.urx-bbox.llx < 72.0 || bbox.ury-bbox.lly < 72.0)
    {
      // read in multiple pages.
      for (ifile = 1; ifile < argc; ++ifile)
        {
          if (hpgs_read(reader,HPGS_FALSE))
            {
              fprintf(stderr,hpgs_i18n("Error: Cannot determine plot size of file %s: %s\n"),
                      argv[ifile-1],hpgs_get_error());
              goto cleanup;
            }

          in = hpgs_new_file_istream(argv[ifile]);

          if (!in)
            {
              fprintf(stderr,hpgs_i18n("Error: Cannot open input file %s: %s\n"),
                      argv[ifile],strerror(errno));
              goto cleanup;
            }

          hpgs_reader_attach(reader,in);
        }
      
      if (hpgs_read(reader,HPGS_TRUE))
	{
	  fprintf(stderr,hpgs_i18n("Error: Cannot determine plot size of file %s: %s\n"),
		  argv[ifile-1],hpgs_get_error());
	  goto cleanup;
	}

      // get bounding box of first page.
      // (will return overall boundingbox, if in singlepage mode.)
      if (hpgs_getplotsize(size_dev,1,&bbox)<0)
	{
	  fprintf(stderr,hpgs_i18n("Error: Cannot determine plotsize: %s\n"),
		  hpgs_get_error());
	  goto cleanup;
	}

      if (hpgs_bbox_isempty(&bbox))
	{
	  fprintf(stderr,hpgs_i18n("Error: Empty bounding:  %g %g %g %g.\n"),
		  bbox.llx,bbox.lly,bbox.urx,bbox.ury);
	  goto cleanup;
	}

      if (verbosity >= 1)
	fprintf(stderr,"BoundingBox: %g %g %g %g.\n",bbox.llx,bbox.lly,bbox.urx,bbox.ury);
    }

  // set the appropriate page placement.
  if (paper_width > 0.0 && paper_height > 0.0)
    {
      hpgs_reader_set_fixed_page(reader,&bbox,
                                 paper_width,paper_height,
                                 paper_border,paper_angle );
    }
  else
    {
      paper_width = 200.0 * 72.0;
      paper_height = 200.0 * 72.0;

      hpgs_reader_set_dynamic_page(reader,&bbox,
                                   paper_width,paper_height,
                                   paper_border,paper_angle );
    }

  if (strcmp(dev_name,"bbox") == 0)
    {
      int i;
      FILE *out = out_fn ? fopen(out_fn,"wb") : stdout;

      if (!out)
	{
	  fprintf(stderr,hpgs_i18n("Error: Cannot open output file <%s>.\n"),out_fn);
	  goto cleanup;
	}

      for (i=0;i<10000;++i)
        {
          int r = hpgs_getplotsize(size_dev,i,&bbox);

          if (r < 0)
            {
              fprintf(stderr,hpgs_i18n("Error: Cannot determine plotsize: %s\n"),
                      hpgs_get_error());
              fclose(out);
              goto cleanup;
            }

          if (r) break;

          if (i>0)
            {
              fprintf(out,"%%%%Page: %d %d.\n",i,i);
              fprintf(out,"%%%%PageBoundingBox: %d %d %d %d.\n",
                      (int)floor(bbox.llx),(int)floor(bbox.lly),
                      (int)ceil(bbox.urx),(int)ceil(bbox.ury));
              fprintf(out,"%%%%PageHiResBoundingBox: %g %g %g %g.\n",bbox.llx,bbox.lly,bbox.urx,bbox.ury);
            }
          else
            {
              fprintf(out,"%%%%BoundingBox: %d %d %d %d.\n",
                      (int)floor(bbox.llx),(int)floor(bbox.lly),
                      (int)ceil(bbox.urx),(int)ceil(bbox.ury));
              fprintf(out,"%%%%HiResBoundingBox: %g %g %g %g.\n",bbox.llx,bbox.lly,bbox.urx,bbox.ury);
            }
        }

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

      ret=0;
      goto cleanup;
    }
  else if (strcmp(dev_name,"eps") == 0)
    {
      plot_dev =
	(hpgs_device*)hpgs_new_eps_device(out_fn,&bbox,do_rop3);

      if (!plot_dev)
	{
	  fprintf(stderr,hpgs_i18n("Error: Cannot create eps device.\n"));
	  goto cleanup;
	}
    }
  else if (strcmp(dev_name,"ps") == 0)
    {
      plot_dev =
	(hpgs_device*)hpgs_new_ps_device(out_fn,&bbox,do_rop3);

      if (!plot_dev)
	{
	  fprintf(stderr,hpgs_i18n("Error: Cannot create postscript device.\n"));
	  goto cleanup;
	}
    }
  else if (strncmp(dev_name,"png_",4) == 0)
    {
      int depth = 8;
      int palette = 0;
      hpgs_paint_device *pdv;

      if (strcmp(dev_name+4,"gray") == 0)
	depth = 8;
      else if (strcmp(dev_name+4,"gray_alpha") == 0)
	depth = 16;
      else if (strcmp(dev_name+4,"rgb") == 0)
	depth = 24;
      else if (strcmp(dev_name+4,"rgb_alpha") == 0)
	depth = 32;
      else if (strcmp(dev_name+4,"256") == 0)
	palette = 1;
      else
	{
	  fprintf(stderr,hpgs_i18n("Error: png device %s in not supported.\n"),
		  dev_name);
	  goto cleanup;
	}

      if (x_px_size >= 20 && y_px_size >= 20)
	{
          // get overall bounding box, if pixel size is specified.
          // This way no page image exceeds the given size and
          // all images have the same resolution.
          hpgs_bbox bb;

          if (hpgs_getplotsize(size_dev,0,&bb)<0)
            {
              fprintf(stderr,hpgs_i18n("Error: Cannot determine overall plotsize: %s\n"),
                      hpgs_get_error());
              goto cleanup;
            }

	  x_dpi = 72.0 * x_px_size / (bb.urx-bb.llx);
	  y_dpi = 72.0 * y_px_size / (bb.ury-bb.lly);

	  if (x_dpi > y_dpi)
	    {
	      x_dpi = y_dpi;
	      x_px_size = x_dpi * (bb.urx-bb.llx) / 72.0;
	    }
	  else
	    {
	      y_dpi = x_dpi;
	      y_px_size = y_dpi * (bb.ury-bb.lly) / 72.0;
	    }
	}
      else
	{
          // initialize the pixel size from the first page.
	  x_px_size = x_dpi * (bbox.urx-bbox.llx) / 72.0;
	  y_px_size = y_dpi * (bbox.ury-bbox.lly) / 72.0;
	}

      image = hpgs_new_png_image(x_px_size,y_px_size,depth,palette,do_rop3);
	
      if (!image)
	{
	  fprintf(stderr,hpgs_i18n("Error creating %dx%dx%d sized png image: %s.\n"),
		  x_px_size,y_px_size,depth,strerror(errno));
	  goto cleanup;
	}

      hpgs_png_image_set_compression(image,compression);

      pdv = hpgs_new_paint_device((hpgs_image*)image,
                                  out_fn,&bbox,
                                  antialias);
      if (!pdv)
	{
	  fprintf(stderr,hpgs_i18n("Error: Cannot create paint device.\n"));
	  goto cleanup;
	}

      hpgs_paint_device_set_image_interpolation(pdv,image_interpolation);
      hpgs_paint_device_set_thin_alpha(pdv,thin_alpha);
      // set the resolution of the image, although
      // hpgs_new_paint_device has done this before.
      // The reason is, that we know the resolution with more precision
      // than hpgs_new_paint_device.
      hpgs_image_set_resolution((hpgs_image*)image,x_dpi,y_dpi);

      plot_dev = (hpgs_device *)pdv;
    }
  else
    {
      if (x_px_size >= 20 && y_px_size >= 20)
	{
          // calculate resolution from overall bounding box,
          // if pixel size is specified.
          // This way no page image exceeds the given size and
          // all images have the same resolution.
          hpgs_bbox bb;

          if (hpgs_getplotsize(size_dev,0,&bb)<0)
            {
              fprintf(stderr,hpgs_i18n("Error: Cannot determine overall plotsize: %s\n"),
                      hpgs_get_error());
              goto cleanup;
            }

	  x_dpi = 72.0 * x_px_size / (bb.urx-bb.llx);
	  y_dpi = 72.0 * y_px_size / (bb.ury-bb.lly);

	  if (x_dpi > y_dpi)
	    x_dpi = y_dpi;
	  else
	    y_dpi = x_dpi;
	}

      void *page_asset_ctxt = 0;
      hpgs_reader_asset_func_t page_asset_func = 0;
      void *frame_asset_ctxt = 0;
      hpgs_reader_asset_func_t frame_asset_func = 0;

      if (hpgs_new_plugin_device(&plot_dev,
                                 &page_asset_ctxt,
                                 &page_asset_func,
                                 &frame_asset_ctxt,
                                 &frame_asset_func,
                                 dev_name,out_fn,&bbox,
                                 x_dpi,y_dpi,do_rop3,
                                 plugin_argc,plugin_argv))
	{
	  fprintf(stderr,hpgs_i18n("Error: Cannot create plugin device: %s\n"),
                  hpgs_get_error());
	  goto cleanup;
	}

      if (page_asset_func)
        hpgs_reader_set_page_asset_func(reader,page_asset_ctxt,page_asset_func);

      if (frame_asset_func)
        hpgs_reader_set_frame_asset_func(reader,frame_asset_ctxt,frame_asset_func);
    }

  if (!plot_dev)
    {
      fprintf (stderr,hpgs_i18n("Error: invalid plot device name %s specified.\n"),dev_name);
      goto cleanup;
    }

  if (png_dump_fn && hpgs_reader_set_png_dump(reader,png_dump_fn))
    {
      fprintf(stderr,hpgs_i18n("Error: Cannot set png_dump filename to reader: %s\n"),
	      hpgs_get_error());
      goto cleanup;
    }

  if (stamp && hpgs_device_stamp(plot_dev,&bbox,stamp,stamp_enc,stamp_size))
    {
      fprintf(stderr,hpgs_i18n("Error: Cannot stamp plot: %s\n"),
	      hpgs_get_error());
      goto cleanup;
    }

  if (hpgs_reader_imbue(reader,plot_dev))
    {
      fprintf(stderr,hpgs_i18n("Error: Cannot imbue plot device to reader: %s\n"),
	      hpgs_get_error());
      goto cleanup;
    }

  // re-open first file, if we have more than one input file.
  if (argc > 1)
    {
      in = hpgs_new_file_istream(argv[0]);

      if (!in)
        {
          fprintf(stderr,hpgs_i18n("Error: Cannot open input file %s: %s\n"),
                  argv[0],strerror(errno));
          goto cleanup;
        }
      hpgs_reader_attach(reader,in);
    }

  // read in multiple pages.
  for (ifile = 1; ifile < argc; ++ifile)
    {
      if (hpgs_read(reader,HPGS_FALSE))
        {
          fprintf(stderr,hpgs_i18n("Error: Cannot process plot file %s: %s\n"),
                  argv[ifile-1],hpgs_get_error());
          goto cleanup;
        }
      
      in = hpgs_new_file_istream(argv[ifile]);

      if (!in)
        {
          fprintf(stderr,hpgs_i18n("Error: Cannot open input file %s: %s\n"),
                  argv[ifile],strerror(errno));
          goto cleanup;
        }
      
      hpgs_reader_attach(reader,in);
    }

  if (hpgs_read(reader,HPGS_TRUE))
    {
      fprintf(stderr,hpgs_i18n("Error: Cannot process plot file %s: %s\n"),
	      argv[ifile-1],hpgs_get_error());
      goto cleanup;
    }

  if (verbosity >= 2)
    fprintf(stderr,hpgs_i18n("Success.\n"));

  ret = 0;

 cleanup:
  if (reader)
    hpgs_destroy_reader(reader);

  hpgs_cleanup();

  return ret;
}
Ejemplo n.º 7
0
int main(int argc, char **argv)
{
  int  i, j, k;
  int  line, dim, max_byte;
  int  split, *num = NULL;
  char **buffer;
  char ofname[NAME_LEN] = {'\0'}, str[NAME_LEN] = {'\0'};
  FILE *fp = NULL;

  /* 引数の確認 */
  if(argc < 4){
    fprintf(stderr, "\n[使用法] : file_split <file> [-q (num) / -s (M) (n1)...(nM)] (-o (str))\n");
    exit(1);
  }

  strcpy(ofname, argv[1]);
  if(is_opt(argc, argv, "-o"))
    strcpy(ofname, get_char_arg(argc, argv, "-o"));

  /* 1行当たりのバイト数の最大値とデータの行の総数を調べる */
  get_max_byte(argv[1], &max_byte);
  get_size(argv[1], &dim, &line);

  /* データの分割数を設定する */
  if(is_opt(argc, argv, "-q")){
    split = get_int_arg(argc, argv, "-q");
    
    num = new_int_vector(split);
    
    for(i = 0; i < split; i++)
      num[i] = line / split;

    for(i = 0; i < (line % split); i++)
      num[i]++;
  }
  else if(is_opt(argc, argv, "-s")){
    num = get_int_arg_list(argc, argv, "-s", &split);

    j = 0;
    for(i = 0; i < split; i++)
      j += num[i];

    if(j != line){
      fprintf(stderr, "\n[エラー] : 指定された分割方法は正しくありません\n");
      exit(1);
    }
  }
  else{
    fprintf(stderr, "\n[エラー] : 分割方法を必ず指定して下さい\n");
    exit(1);
  }
  
  /* データを確保するための配列を準備する */
  buffer = new_char_matrix(line, sizeof(char)*(max_byte + 2));
  for(i = 0; i < line; i++) 
    for(j = 0; j <= sizeof(char)*max_byte + 1; j++)
      buffer[i][j] = '\0';

  /* ファイルからデータを読み込む */
  if((fp = fopen(argv[1], "r")) == NULL){
    fprintf(stderr, "\n[エラー] : ファイル %s が開けません\n", argv[1]);
    exit(1);
  }
  
  for(i = 0; i < line; i++){
    for(j = 0; j <= max_byte*sizeof(char); j++){
      fscanf(fp, "%c", &buffer[i][j]);
      if(buffer[i][j] == '\n')
        break;
    }
  }

  fclose(fp);

  /* 指定された方法によりデータを分割する */
  line = 0;
  for(i = 0; i < split; i++){

    sprintf(str, "%s_%d", ofname, i+1);
    if((fp = fopen(str, "w")) == NULL){
      fprintf(stderr, "\n[エラー] : ファイル %s が開けません\n", str);
      exit(1);
    }

    for(j = 0; j < num[i]; j++){
      for(k = 0; k <= max_byte*sizeof(char); k++){
        fprintf(fp, "%c", buffer[line + j][k]);
        if(buffer[line + j][k] == '\n')
          break;
      }
    }

    fclose(fp);
    line += num[i];
  }

  /* 作業用の配列を解放 */
  free_char_matrix(buffer);
  free_int_vector(num);

  exit(0);
}
Ejemplo n.º 8
0
Archivo: ui.cpp Proyecto: pd/benthos
///////////////////////////////
// reads in the time controls (a hassle), stores the information
// into the search info structure, then calls the search.
///////////////////////////////
static bool
cmd_go(const char *args)
{
	int mtg = 0, depthmax = 0;
	int wtime = 0, btime = 0, winc = 0, binc = 0;
	long nodemax = 0, movetime = 0;
	int time, inc;

	if (rootPosition == NULL) {
		cout << "Invalid position: can't go." << endl;
		return false;
	}

	if (args == NULL || strstr(args, "infinite") != NULL)
		searchInfo->inf = true;
	else {
		searchInfo->inf = false;
		if (get_long_arg(args, "movetime", movetime))
			searchInfo->endTime = clock() + movetime;
		else {
			get_int_arg(args,  "wtime",     wtime);
			get_int_arg(args,  "btime",     btime);
			get_int_arg(args,  "winc",      winc);
			get_int_arg(args,  "binc",      binc);
			get_int_arg(args,  "movestogo", mtg);
			get_int_arg(args,  "depth",     depthmax);
			get_long_arg(args, "nodes",     nodemax);

			if (depthmax != 0)
				searchInfo->depthLimit = depthmax;
			if (nodemax != 0)
				searchInfo->nodeLimit = nodemax;

			// found this time calculation in scatha.
			// much better than what i came up with.
			if (Stm(0) == WHITE) {
				time = wtime;
				inc  = winc;
			} else {
				time = btime;
				inc  = binc;
			}

			if (mtg == 0) {
				if (inc != 0)
					time = time / 30 + inc;
				else
					time = time / 40;
			} else {
				if (mtg == 1)
					time = time / 2;
				else
					time = time / Min(mtg, 20);
			}

			searchInfo->endTime = clock() + time;
		}
	}

	move_t move = search(rootPosition);
	if (!move) {
		cout << "Error: Search failed to find a move..." << endl;
		return false;
	}

	make_history_move(rootPosition, move);
	cout << "bestmove " << move2str(move) << endl;
	cout.flush();
	return true;
}
Ejemplo n.º 9
0
// All FindArg calls should be here to keep the code clean
void ReadCmdArgs(void)
{
	// System Options

	GameArg.SysShowCmdHelp 		= (FindArg( "-help" ) || FindArg( "-h" ) || FindArg( "-?" ) || FindArg( "?" ));
	GameArg.SysUseNiceFPS 		= !FindArg("-nonicefps");

	GameArg.SysMaxFPS = get_int_arg("-maxfps", MAXIMUM_FPS);
	if (GameArg.SysMaxFPS <= 0 || GameArg.SysMaxFPS > MAXIMUM_FPS)
		GameArg.SysMaxFPS = MAXIMUM_FPS;

	GameArg.SysHogDir = get_str_arg("-hogdir", NULL);
	if (GameArg.SysHogDir == NULL)
		GameArg.SysNoHogDir = FindArg("-nohogdir");

	GameArg.SysUsePlayersDir 	= FindArg("-use_players_dir");
	GameArg.SysLowMem 		= FindArg("-lowmem");
	GameArg.SysPilot 		= get_str_arg("-pilot", NULL);
	GameArg.SysWindow 		= FindArg("-window");
	GameArg.SysNoBorders 		= FindArg("-noborders");
	GameArg.SysNoMovies 		= FindArg("-nomovies");
	GameArg.SysAutoDemo 		= FindArg("-autodemo");

	// Control Options

	GameArg.CtlNoCursor 		= FindArg("-nocursor");
	GameArg.CtlNoMouse 		= FindArg("-nomouse");
	GameArg.CtlNoJoystick 		= FindArg("-nojoystick");
	GameArg.CtlNoStickyKeys		= FindArg("-nostickykeys");
	if (GameArg.CtlNoStickyKeys) // Must happen before SDL_Init!
		SDL_putenv("SDL_DISABLE_LOCK_KEYS=1");
	else
		SDL_putenv("SDL_DISABLE_LOCK_KEYS=0");

	// Sound Options

	GameArg.SndNoSound 		= FindArg("-nosound");
	GameArg.SndNoMusic 		= FindArg("-nomusic");
	GameArg.SndDigiSampleRate 	= (FindArg("-sound11k") ? SAMPLE_RATE_11K : SAMPLE_RATE_22K);

#ifdef USE_SDLMIXER
	GameArg.SndDisableSdlMixer 	= FindArg("-nosdlmixer");
#else
	GameArg.SndDisableSdlMixer	= 1;
#endif


	// Graphics Options

	GameArg.GfxHiresGFXAvailable	= !FindArg("-lowresgraphics");
	GameArg.GfxHiresFNTAvailable	= !FindArg("-lowresfont");
	GameArg.GfxMovieHires 		= !FindArg( "-lowresmovies" );

#ifdef OGL
	// OpenGL Options

	GameArg.OglFixedFont 		= FindArg("-gl_fixedfont");
#endif

	// Multiplayer Options

#ifdef USE_UDP
	GameArg.MplUdpHostAddr		= get_str_arg("-udp_hostaddr", UDP_MANUAL_ADDR_DEFAULT);
	GameArg.MplUdpHostPort		= get_int_arg("-udp_hostport", 0);
	GameArg.MplUdpMyPort		= get_int_arg("-udp_myport", 0);
#ifdef USE_TRACKER
	GameArg.MplTrackerAddr		= get_str_arg("-tracker_hostaddr", TRACKER_ADDR_DEFAULT);
	GameArg.MplTrackerPort		= get_int_arg("-tracker_hostport", TRACKER_PORT_DEFAULT);
#endif
#endif

#ifdef EDITOR
	// Editor Options

	GameArg.EdiAutoLoad 		= get_str_arg("-autoload", NULL);
	GameArg.EdiMacData 		= FindArg("-macdata");
	GameArg.EdiSaveHoardData 	= FindArg("-hoarddata");
#endif

	// Debug Options

	if (FindArg("-debug"))		GameArg.DbgVerbose = CON_DEBUG;
	else if (FindArg("-verbose"))	GameArg.DbgVerbose = CON_VERBOSE;
	else				GameArg.DbgVerbose = CON_NORMAL;

	GameArg.DbgSafelog 		= FindArg("-safelog");
	GameArg.DbgNoRun 		= FindArg("-norun");
	GameArg.DbgRenderStats 		= FindArg("-renderstats");
	GameArg.DbgAltTex 		= get_str_arg("-text", NULL);
	GameArg.DbgTexMap 		= get_str_arg("-tmap", NULL);
	GameArg.DbgShowMemInfo 		= FindArg("-showmeminfo");
	GameArg.DbgUseDoubleBuffer 	= !FindArg("-nodoublebuffer");
	GameArg.DbgBigPig 		= !FindArg("-bigpig");
	GameArg.DbgBpp 			= (FindArg("-16bpp") ? 16 : 32);

#ifdef OGL
	GameArg.DbgAltTexMerge 		= !FindArg("-gl_oldtexmerge");
	GameArg.DbgGlIntensity4Ok 	= get_int_arg("-gl_intensity4_ok", 1);
	GameArg.DbgGlLuminance4Alpha4Ok = get_int_arg("-gl_luminance4_alpha4_ok", 1);
	GameArg.DbgGlRGBA2Ok 		= get_int_arg("-gl_rgba2_ok", 1);
	GameArg.DbgGlReadPixelsOk 	= get_int_arg("-gl_readpixels_ok", 1);
	GameArg.DbgGlGetTexLevelParamOk = get_int_arg("-gl_gettexlevelparam_ok", 1);
#else
	GameArg.DbgSdlHWSurface = FindArg("-hwsurface");
	GameArg.DbgSdlASyncBlit = FindArg("-asyncblit");
#endif

	GameArg.LogNetTraffic 		= FindArg("-netlog");
}
Ejemplo n.º 10
0
void read_cli_options(int argc, char **argv,
                        struct kw_conf * (*kw)(const char *), FILE ** fin, FILE ** fout)
{
    int i;
    if (argc == 1) return; // use stdin and stdout

    if (argc == 2 && strcmp(argv[1], "--create-config-file") == 0) {
        if (create_conf_file(FSQLF_CONFFILE_NAME) != 0) {
            exit(1);
        } else {
            fprintf(stderr, "File '%s' (re)created.\n", FSQLF_CONFFILE_NAME);
            exit(0);
        }
    }

    for (i = 1; i < argc; i++) {
        if (argv[i][0] != '-') {
            if ((*fin) == stdin) {
                //try to openinig INPUT file
                (*fin) = fopen(argv[1], "r");
                if (!(*fin)) {
                    FAIL_WITH_ERROR(1, "Error opening input file: %s", argv[i]);
                }
            }
            else if ((*fout) == stdout) {   //try to openinig OUTPUT file (only if INPUT file is set)
                (*fout) = fopen(argv[2], "w+");
                if (!(*fout)) FAIL_WITH_ERROR(1, "Error opening output file: %s", argv[i]);
            }
        } else if (ARGV_MATCH(i, "-i")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            (*fin) = fopen(argv[i], "r");
            if (!(*fin)) FAIL_WITH_ERROR(1, "Error opening input file: %s", argv[i]);
        } else if (ARGV_MATCH(i, "-o")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            (*fout) = fopen(argv[i], "w+");
            if (!(*fout)) FAIL_WITH_ERROR(1, "Error opening output file: %s", argv[i]);
        } else if (ARGV_MATCH(i, "--config-file")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (read_conf_file(argv[i], kw) == READ_FAILED) {
                FAIL_WITH_ERROR(1, "Error reading configuration file: %s", argv[i]);
            }
        } else if (ARGV_MATCH(i, "--select-comma-newline")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (strcmp(argv[i], "after") == 0) {
                kw("kw_comma")->before.new_line = 0;
                kw("kw_comma")->after.new_line  = 1;
            } else if (strcmp(argv[i], "before") == 0) {
                kw("kw_comma")->before.new_line = 1;
                kw("kw_comma")->after.new_line  = 0;
            } else if (strcmp(argv[i], "none") == 0) {
                kw("kw_comma")->before.new_line = 0;
                kw("kw_comma")->after.new_line  = 0;
            }
        } else if (ARGV_MATCH(i, "--keyword-case")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (strcmp(argv[i], "none") == 0) {
                set_case(CASE_none);
            } else if (strcmp(argv[i], "upper") == 0) {
                set_case(CASE_UPPER);
            } else if (strcmp(argv[i], "lower") == 0) {
                set_case(CASE_lower);
            } else if (strcmp(argv[i], "initcap") == 0) {
                set_case(CASE_Initcap);
            }
        } else if (ARGV_MATCH(i, "--keyword-text")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (strcmp(argv[i], "original") == 0) {
                set_text_original(1);
            } else if (strcmp(argv[i], "default") == 0) {
                set_text_original(0);
            }
        } else if (ARGV_MATCH(i, "--select-newline-after")) {
            kw("kw_select")->after.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-or-before")) {
            kw("kw_or")->before.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-or-after")) {
            kw("kw_or")->after.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-and-before")) {
            kw("kw_and")->before.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-and-after")) {
            kw("kw_and")->after.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-major-sections")) {
            int new_line_count = get_int_arg(++i, argc, argv);
            kw("kw_from")->before.new_line = new_line_count;
            kw("kw_where")->before.new_line = new_line_count;
            kw("kw_inner_join")->before.new_line = new_line_count;
            kw("kw_left_join")->before.new_line  = new_line_count;
            kw("kw_right_join")->before.new_line = new_line_count;
            kw("kw_full_join")->before.new_line  = new_line_count;
            kw("kw_cross_join")->before.new_line = new_line_count;
        } else if (ARGV_MATCH(i, "--debug")) {
            if (++i >= argc ) FAIL_WITH_ERROR(1, "Missing or invalid value for option : %s", argv[i-1]);
            if (ARGV_MATCH(i, "none")) debug_level |= DEBUGNONE;
            else if (ARGV_MATCH(i, "state")) debug_level |= DEBUGSTATES;
            else if (ARGV_MATCH(i, "match")) debug_level |= DEBUGMATCHES;
            else if (ARGV_MATCH(i, "parenthesis")) debug_level |= DEBUGPARCOUNTS;
            else FAIL_WITH_ERROR(1, "Missing or invalid value for option : %s", argv[i-1]);
        } else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
            usage_info(argc, argv);
            exit(0);
        } else FAIL_WITH_ERROR(1, "Option `%s' is not recognised or used incorrectly.\nTry `%s --help' for more information\n", argv[i], argv[0]);
    }
}
int
main(int argc,char *argv[])
{
  int   toc_bias             =  0;
  int   force_cdrom_endian   = -1;
  int   output_type          =  1; /* 0=raw, 1=wav, 2=aifc */
  int   output_endian        =  0; /* -1=host, 0=little, 1=big */
  int   query_only           =  0;
  int   batch                =  0;
  int   run_cache_test       =  0;
  long int force_cdrom_overlap  = -1;
  long int force_cdrom_sectors  = -1;
  long int force_cdrom_speed    =  0;
  long int force_overread       =  0;
  long int sample_offset        =  0;
  long int test_flags           =  0;
  long int toc_offset           =  0;
  long int max_retries          = 20;

  char *logfile_name=NULL;
  char *reportfile_name=NULL;

  /* full paranoia, but allow skipping */
  int paranoia_mode=PARANOIA_MODE_FULL^PARANOIA_MODE_NEVERSKIP;

  int out;

  int c,long_option_index;

  atexit(cleanup);

  while((c=getopt_long(argc,argv,optstring,options,&long_option_index))!=EOF){
    switch(c){
    case 'a':
      output_type=2;
      output_endian=1;
      break;
    case 'B':
      batch=1;
      break;
    case 'c':
      force_cdrom_endian=0;
      break;
    case 'C':
      force_cdrom_endian=1;
      break;
    case 'e':
      callscript=1;
      fprintf(stderr,
              "Sending all callback output to stderr for wrapper script\n");
      break;
    case 'f':
      output_type=3;
      output_endian=1;
      break;
    case 'F':
      paranoia_mode&=~(PARANOIA_MODE_FRAGMENT);
      break;
    case 'g':
    case 'k':
    case 'd':
      if (force_cdrom_device) {
        fprintf(stderr,
                "Multiple cdrom devices given. Previous device %s ignored\n",
                force_cdrom_device);
        free(force_cdrom_device);
      }
      force_cdrom_device=strdup(optarg);
      break;
    case 'h':
      usage(stdout);
      exit(0);
    case 'l':
      if(logfile_name)free(logfile_name);
      logfile_name=NULL;
      if(optarg)
	logfile_name=strdup(optarg);
      logfile_open=1;
      break;
    case 'L':
      if(reportfile_name)free(reportfile_name);
      reportfile_name=NULL;
      if(optarg)
	reportfile_name=strdup(optarg);
      reportfile_open=1;
      break;
    case 'm':
      {
        long int mmc_timeout_sec;
        if (get_int_arg(c, &mmc_timeout_sec)) {
          mmc_timeout_ms = 1000*mmc_timeout_sec;
        }
      }
      break;
    case 'n':
      get_int_arg(c, &force_cdrom_sectors);
      break;
    case 'o':
      get_int_arg(c, &force_cdrom_overlap);
      break;
    case 'O':
      get_int_arg(c, &sample_offset);
      break;
    case 'p':
      output_type=0;
      output_endian=-1;
      break;
    case 'r':
      output_type=0;
      output_endian=0;
      break;
    case 'q':
      verbose=CDDA_MESSAGE_FORGETIT;
      quiet=1;
      break;
    case 'Q':
      query_only=1;
      break;
    case 'R':
      output_type=0;
      output_endian=1;
      break;
    case 'S':
      get_int_arg(c, &force_cdrom_speed);
      break;
    case 't':
      get_int_arg(c, &toc_offset);
      break;
    case 'T':
      toc_bias=-1;
      break;
    case 'v':
      verbose=CDDA_MESSAGE_PRINTIT;
      quiet=0;
      break;
    case 'V':
      fprintf(stderr,PARANOIA_VERSION);
      fprintf(stderr,"\n");
      exit(0);
      break;
    case 'w':
      output_type=1;
      output_endian=0;
      break;
    case 'W':
      paranoia_mode&=~PARANOIA_MODE_REPAIR;
      break;
    case 'x':
      get_int_arg(c, &test_flags);
      break;
    case 'X':
      /*paranoia_mode&=~(PARANOIA_MODE_SCRATCH|PARANOIA_MODE_REPAIR);*/
      abort_on_skip=1;
      break;
    case 'Y':
      paranoia_mode|=PARANOIA_MODE_OVERLAP; /* cdda2wav style overlap
                                                check only */
      paranoia_mode&=~PARANOIA_MODE_VERIFY;
      break;
    case 'Z':
      paranoia_mode=PARANOIA_MODE_DISABLE;
      break;
    case 'A':
      run_cache_test=1;
      query_only=1;
      reportfile_open=1;
      verbose=CDDA_MESSAGE_PRINTIT;
      break;
    case 'z':
      if (optarg) {
        get_int_arg(c, &max_retries);
        paranoia_mode&=~PARANOIA_MODE_NEVERSKIP;
      } else {
        paranoia_mode|=PARANOIA_MODE_NEVERSKIP;
      }
      break;
    case 'E':
      force_overread=1;
      break;
    default:
      usage(stderr);
      exit(1);
    }
  }

  if(logfile_open){
    if(logfile_name==NULL)
      logfile_name=strdup("cdparanoia.log");
    if(!strcmp(logfile_name,"-")){
      logfile=stdout;
      logfile_open=0;
    }else{
      logfile=fopen(logfile_name,"w");
      if(logfile==NULL){
	report("Cannot open log summary file %s: %s",logfile_name,
	       strerror(errno));
	exit(1);
      }
    }
  }
  if(reportfile_open){
    if(reportfile_name==NULL)
      reportfile_name=strdup("cdparanoia.log");
    if(!strcmp(reportfile_name,"-")){
      reportfile=stdout;
      reportfile_open=0;
    }else{
      if(logfile_name && !strcmp(reportfile_name,logfile_name)){
	reportfile=logfile;
	reportfile_open=0;
      }else{
	reportfile=fopen(reportfile_name,"w");
	if(reportfile==NULL){
	  report("Cannot open debug log file %s: %s",reportfile_name,
		 strerror(errno));
	  exit(1);
	}
      }
    }
  }

  if(logfile){
    /* log command line and version */
    int i;
    for (i = 0; i < argc; i++)
      fprintf(logfile,"%s ",argv[i]);
    fprintf(logfile,"\n");

    if(reportfile!=logfile){
      fprintf(logfile,VERSION);
      fprintf(logfile,"\n");
      fprintf(logfile,"Using cdda library version: %s\n",cdda_version());
      fprintf(logfile,"Using paranoia library version: %s\n",paranoia_version());
    }
    fflush(logfile);
  }

  if(reportfile && reportfile!=logfile){
    /* log command line */
    int i;
    for (i = 0; i < argc; i++)
      fprintf(reportfile,"%s ",argv[i]);
    fprintf(reportfile,"\n");
    fflush(reportfile);
  }

  if(optind>=argc && !query_only){
    if(batch)
      span=NULL;
    else{
      /* D'oh.  No span. Fetch me a brain, Igor. */
      usage(stderr);
      exit(1);
    }
  }else
    if (argv[optind]) span=strdup(argv[optind]);

  report(PARANOIA_VERSION);
  if(verbose){
    report("Using cdda library version: %s",cdda_version());
    report("Using paranoia library version: %s",paranoia_version());
  }

  /* Query the cdrom/disc; we may need to override some settings */

  if(force_cdrom_device)
    d=cdda_identify(force_cdrom_device,verbose,NULL);
  else {
    driver_id_t driver_id;
    char **ppsz_cd_drives = cdio_get_devices_with_cap_ret(NULL,
                                                          CDIO_FS_AUDIO,
                                                          false,
                                                          &driver_id);
    if (ppsz_cd_drives && *ppsz_cd_drives) {
      d=cdda_identify(*ppsz_cd_drives,verbose, NULL);
    } else {
      report("\nUnable find or access a CD-ROM drive with an audio CD"
             " in it.");
      report("\nYou might try specifying the drive, especially if it has"
             " mixed-mode (and non-audio) format tracks");
      exit(1);
    }

    cdio_free_device_list(ppsz_cd_drives);
  }

  if(!d){
    if(!verbose)
      report("\nUnable to open cdrom drive; -v might give more information.");
    exit(1);
  }

  if(verbose)
    cdda_verbose_set(d,CDDA_MESSAGE_PRINTIT,CDDA_MESSAGE_PRINTIT);
  else
    cdda_verbose_set(d,CDDA_MESSAGE_PRINTIT,CDDA_MESSAGE_FORGETIT);

  /* possibly force hand on endianness of drive, sector request size */
  if(force_cdrom_endian!=-1){
    d->bigendianp=force_cdrom_endian;
    switch(force_cdrom_endian){
    case 0:
      report("Forcing CDROM sense to little-endian; ignoring preset and autosense");
      break;
    case 1:
      report("Forcing CDROM sense to big-endian; ignoring preset and autosense");
      break;
    }
  }
  if (force_cdrom_sectors!=-1) {
    if(force_cdrom_sectors<0 || force_cdrom_sectors>100){
      report("Default sector read size must be 1<= n <= 100\n");
      cdda_close(d);
      d=NULL;
      exit(1);
    }
    report("Forcing default to read %ld sectors; "
	   "ignoring preset and autosense",force_cdrom_sectors);
    d->nsectors=force_cdrom_sectors;
  }
  if (force_cdrom_overlap!=-1) {
    if (force_cdrom_overlap<0 || force_cdrom_overlap>CDIO_CD_FRAMES_PER_SEC) {
      report("Search overlap sectors must be 0<= n <=75\n");
      cdda_close(d);
      d=NULL;
      if(logfile && logfile != stdout)
        fclose(logfile);
      exit(1);
    }
    report("Forcing search overlap to %ld sectors; "
	   "ignoring autosense",force_cdrom_overlap);
  }

  switch( cdda_open(d) ) {
  case -2:case -3:case -4:case -5:
    report("\nUnable to open disc.  Is there an audio CD in the drive?");
    exit(1);
  case -6:
    report("\nCdparanoia could not find a way to read audio from this drive.");
    exit(1);
  case 0:
    break;
  default:
    report("\nUnable to open disc.");
    exit(1);
  }

  d->i_test_flags = test_flags;

  if (force_cdrom_speed == 0) force_cdrom_speed = -1;

  if (force_cdrom_speed != -1) {
    report("\nAttempting to set speed to %ldx... ", force_cdrom_speed);
  } else {
    if (verbose)
      report("\nAttempting to set cdrom to full speed... ");
  }

  if (cdda_speed_set(d, force_cdrom_speed)) {
    if (verbose || force_cdrom_speed != -1)
      report("\tCDROM speed set FAILED. Continuing anyway...");
  } else {
    if (verbose)
      report("\tdrive returned OK.");
  }

  if(run_cache_test){
    int warn=analyze_cache(d, stderr, reportfile, force_cdrom_speed);

    if(warn==0){
      reportC("\nDrive tests OK with Paranoia.\n\n");
      return 0;
    }

    if(warn==1)
      reportC("\nWARNING! PARANOIA MAY NOT BE TRUSTWORTHY WITH THIS DRIVE!\n"
	      "\nThe Paranoia library may not model this CDROM drive's cache"
	      "\ncorrectly according to this analysis run. Analysis is not"
	      "\nalways accurate (it can be fooled by machine load or random"
	      "\nkernel latencies), but if a failed result happens more often"
	      "\nthan one time in twenty on an unloaded machine, please mail"
	      "\nthe %s file produced by this failed analysis to"
	      "\[email protected] to assist developers in extending"
	      "\nParanoia to handle this CDROM properly.\n\n",reportfile_name);
    return 1;
  }


  /* Dump the TOC */
  if (query_only || verbose ) display_toc(d);

  if (query_only) exit(0);

  /* bias the disc.  A hack.  Of course. this is never the default. */
  /*
     Some CD-ROM/CD-R drives will add an offset to the position on
     reading audio data. This is usually around 500-700 audio samples
     (ca. 1/75 second) on reading. So when this program queries a
     specific sector, it might not receive exactly that sector, but
     shifted by some amount.

     Note that if ripping includes the end of the CD, this will this
     cause this program to attempt to read partial sectors before or
     past the known user data area of the disc, probably causing read
     errors on most drives and possibly even hard lockups on some
     buggy hardware.

     [Note to libcdio driver hackers: make sure all CD-drivers don't
     try to read outside of the stated disc boundaries.]
  */
  if(sample_offset){
    toc_offset+=sample_offset/588;
    sample_offset%=588;
    if(sample_offset<0){
      sample_offset+=588;
      toc_offset--;
    }
  }

  if (toc_bias) {
    toc_offset = -cdda_track_firstsector(d,1);
  }

  {
    int i;
    for( i=0; i < d->tracks+1; i++ )
      d->disc_toc[i].dwStartSector+=toc_offset;
  }

  if (d->nsectors==1) {
    report("WARNING: The autosensed/selected sectors per read value is\n"
           "         one sector, making it very unlikely Paranoia can \n"
           "         work.\n\n"
           "         Attempting to continue...\n\n");
  }

  /* parse the span, set up begin and end sectors */

  {
    long i_first_lsn;
    long i_last_lsn;
    long batch_first;
    long batch_last;
    int batch_track;

    if (span) {
      /* look for the hyphen */
      char *span2=strchr(span,'-');
      if(strrchr(span,'-')!=span2){
        report("Error parsing span argument");
        exit(1);
      }

      if (span2!=NULL) {
        *span2='\0';
        span2++;
      }

      i_first_lsn=parse_offset(d, span, -1);

      if(i_first_lsn==-1)
        i_last_lsn=parse_offset(d, span2, cdda_disc_firstsector(d));

      else
        i_last_lsn=parse_offset(d, span2, i_first_lsn);

      if (i_first_lsn == -1) {
        if (i_last_lsn == -1) {
          report("Error parsing span argument");
          exit(1);
        } else {
          i_first_lsn=cdda_disc_firstsector(d);
        }
      } else {
        if (i_last_lsn==-1) {
          if (span2) { /* There was a hyphen */
            i_last_lsn=cdda_disc_lastsector(d);
          } else {
            i_last_lsn=
              cdda_track_lastsector(d,cdda_sector_gettrack(d, i_first_lsn));
          }
        }
      }
    } else {
      i_first_lsn = cdda_disc_firstsector(d);
      i_last_lsn  = cdda_disc_lastsector(d);
    }

    {
      int track1 = cdda_sector_gettrack(d, i_first_lsn);

      int track2 = cdda_sector_gettrack(d, i_last_lsn);
      long off1  = i_first_lsn - cdda_track_firstsector(d, track1);
      long off2  = i_last_lsn  - cdda_track_firstsector(d, track2);
      int i;

      for( i=track1; i<=track2; i++ ) {
        if(i != 0 && !cdda_track_audiop(d,i)){
	  report("Selected span contains non audio track at track %02d.  Aborting.\n\n", i);
          exit(1);
          if (i == 0)
            i = cdio_get_first_track_num(d->p_cdio) - 1;
        }
      }

      report("Ripping from sector %7ld (track %2d [%d:%02d.%02d])\n"
	     "\t  to sector %7ld (track %2d [%d:%02d.%02d])\n",
	     i_first_lsn,
	     track1,
	     (int) (off1/(CDIO_CD_FRAMES_PER_MIN)),
	     (int) ((off1/CDIO_CD_FRAMES_PER_SEC) % CDIO_CD_SECS_PER_MIN),
	     (int)(off1 % CDIO_CD_FRAMES_PER_SEC),
	     i_last_lsn,
	     track2,
	     (int) (off2/(CDIO_CD_FRAMES_PER_MIN)),
	     (int) ((off2/CDIO_CD_FRAMES_PER_SEC) % CDIO_CD_SECS_PER_MIN),
	     (int)(off2 % CDIO_CD_FRAMES_PER_SEC));

    }

    if (toc_offset && !force_overread) {
	d->disc_toc[d->tracks].dwStartSector -= toc_offset;
	if (i_last_lsn > cdda_track_lastsector(d, d->tracks))
		i_last_lsn -= toc_offset;
    }
    {
      long cursor;
      int16_t offset_buffer[1176];
      int offset_buffer_used=0;
      int offset_skip=sample_offset*4;
      off_t sectorlen;

#if defined(HAVE_GETUID) && (defined(HAVE_SETEUID) || defined(HAVE_SETEGID))
      int dummy __attribute__((unused));
#endif
      p=paranoia_init(d);
      paranoia_modeset(p,paranoia_mode);
      if(force_cdrom_overlap!=-1)paranoia_overlapset(p,force_cdrom_overlap);

      if(verbose) {
        cdda_verbose_set(d,CDDA_MESSAGE_LOGIT,CDDA_MESSAGE_LOGIT);
        cdio_loglevel_default = CDIO_LOG_INFO;
      } else
        cdda_verbose_set(d,CDDA_MESSAGE_FORGETIT,CDDA_MESSAGE_FORGETIT);

      paranoia_seek(p,cursor=i_first_lsn,SEEK_SET);

      /* this is probably a good idea in general */
#if defined(HAVE_GETUID) && defined(HAVE_SETEUID)
      dummy = seteuid(getuid());
#endif
#if defined(HAVE_GETGID) && defined(HAVE_SETEGID)
      dummy = setegid(getgid());
#endif

      /* we'll need to be able to read one sector past user data if we
         have a sample offset in order to pick up the last bytes.  We
         need to set the disc length forward here so that the libs are
         willing to read past, assuming that works on the hardware, of
         course */
      if(sample_offset && force_overread)
        d->disc_toc[d->tracks].dwStartSector++;

      while(cursor<=i_last_lsn){
        char outfile_name[PATH_MAX];
        if ( batch ){
          batch_first = cursor;
          batch_track = cdda_sector_gettrack(d,cursor);
          batch_last  = cdda_track_lastsector(d, batch_track);
          if (batch_last>i_last_lsn) batch_last=i_last_lsn;
        } else {
          batch_first = i_first_lsn;
          batch_last  = i_last_lsn;
          batch_track = -1;
        }

        callbegin=batch_first;
        callend=batch_last;

        /* argv[optind] is the span, argv[optind+1] (if exists) is outfile */

        if (optind+1<argc) {
          if (!strcmp(argv[optind+1],"-") ){
            out = dup(fileno(stdout));
            if(out==-1){
              report("Cannot dupplicate stdout: %s",
                     strerror(errno));
              exit(1);
            }
            if(batch)
              report("Are you sure you wanted 'batch' "
                     "(-B) output with stdout?");
            report("outputting to stdout\n");
            if(logfile){
              fprintf(logfile,"outputting to stdout\n");
              fflush(logfile);
            }
            outfile_name[0]='\0';
          } else {
            char dirname[PATH_MAX];
            char *basename=split_base_dir(argv[optind+1], dirname,
					  PATH_MAX);

	    if (NULL == basename) {
	      report("Output filename too long");
	      exit(1);
	    }

            if(batch) {
	      if (strlen(argv[optind+1]) - 10 > PATH_MAX) {
		report("Output filename too long");
		exit(1);
	      }
              snprintf(outfile_name, PATH_MAX,
		       " %strack%02d.%s", dirname,
                       batch_track, basename);
            } else
              snprintf(outfile_name, PATH_MAX, "%s%s", dirname, basename);

            if(basename[0]=='\0'){
              switch (output_type) {
              case 0: /* raw */
                strncat(outfile_name, "cdda.raw", sizeof("cdda.raw"));
                break;
              case 1:
                strncat(outfile_name, "cdda.wav", sizeof("cdda.wav"));
                break;
              case 2:
                strncat(outfile_name, "cdda.aifc", sizeof("cdda.aifc"));
                break;
              case 3:
                strncat(outfile_name, "cdda.aiff", sizeof("cdda.aiff"));
                break;
              }
            }

            out=open(outfile_name,O_RDWR|O_CREAT|O_TRUNC|O_BINARY,0666);
            if(out==-1){
              report("Cannot open specified output file %s: %s",
                      outfile_name, strerror(errno));
              exit(1);
            }
            report("outputting to %s\n", outfile_name);
            if(logfile){
              fprintf(logfile,"outputting to %s\n",outfile_name);
              fflush(logfile);
            }
          }
        } else {
          /* default */
          if (batch)
            sprintf(outfile_name,"track%02d.", batch_track);
          else
            outfile_name[0]='\0';

          switch(output_type){
          case 0: /* raw */
            strncat(outfile_name, "cdda.raw", sizeof("cdda.raw"));
            break;
          case 1:
            strncat(outfile_name, "cdda.wav", sizeof("cdda.wav"));
            break;
          case 2:
            strncat(outfile_name, "cdda.aifc", sizeof("cdda.aifc"));
            break;
          case 3:
            strncat(outfile_name, "cdda.aiff", sizeof("cdda.aiff"));
            break;
          }

          out = open(outfile_name, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, 0666);
          if(out==-1){
            report("Cannot open default output file %s: %s", outfile_name,
                    strerror(errno));
            exit(1);
          }
          report("outputting to %s\n", outfile_name);
          if(logfile){
            fprintf(logfile,"outputting to %s\n",outfile_name);
            fflush(logfile);
          }

        }

	sectorlen = batch_last - batch_first + 1;
	if (cdda_sector_gettrack(d, cursor) == d->tracks &&
		toc_offset > 0 && !force_overread){
		sectorlen += toc_offset;
	}
        switch(output_type) {
        case 0: /* raw */
          break;
        case 1: /* wav */
	  WriteWav(out, sectorlen * CD_FRAMESIZE_RAW);
          break;
        case 2: /* aifc */
	  WriteAifc(out, sectorlen * CD_FRAMESIZE_RAW);
          break;
        case 3: /* aiff */
	  WriteAiff(out, sectorlen * CD_FRAMESIZE_RAW);
          break;
        }

        /* Off we go! */

        if(offset_buffer_used){
          /* partial sector from previous batch read */
          cursor++;
          if (buffering_write(out,
                              ((char *)offset_buffer)+offset_buffer_used,
                              CDIO_CD_FRAMESIZE_RAW-offset_buffer_used)){
            report("Error writing output: %s", strerror(errno));
            exit(1);
          }
        }

        skipped_flag=0;
        while(cursor<=batch_last){
          /* read a sector */
          int16_t *readbuf=paranoia_read_limited(p, callback, max_retries);
          char *err=cdda_errors(d);
          char *mes=cdda_messages(d);

          if(mes || err)
            fprintf(stderr,"\r                               "
                    "                                           \r%s%s\n",
                    mes?mes:"",err?err:"");

          if (err) free(err);
          if (mes) free(mes);
          if( readbuf==NULL) {
	    if(errno==EBADF || errno==ENOMEDIUM){
	      report("\nparanoia_read: CDROM drive unavailable, bailing.\n");
	      exit(1);
	    }
            skipped_flag=1;
            report("\nparanoia_read: Unrecoverable error, bailing.\n");
            break;
          }
          if(skipped_flag && abort_on_skip){
            cursor=batch_last+1;
            break;
          }

          skipped_flag=0;
          cursor++;

          if (output_endian!=bigendianp()) {
            int i;
            for (i=0; i<CDIO_CD_FRAMESIZE_RAW/2; i++)
              readbuf[i]=UINT16_SWAP_LE_BE_C(readbuf[i]);
          }

          callback(cursor*(CD_FRAMEWORDS)-1, PARANOIA_CB_WROTE);

          if (buffering_write(out,((char *)readbuf)+offset_skip,
                             CDIO_CD_FRAMESIZE_RAW-offset_skip)){
            report("Error writing output: %s", strerror(errno));
            exit(1);
          }
          offset_skip=0;

          if (output_endian != bigendianp()){
            int i;
            for (i=0; i<CDIO_CD_FRAMESIZE_RAW/2; i++)
              readbuf[i] = UINT16_SWAP_LE_BE_C(readbuf[i]);
          }

          /* One last bit of silliness to deal with sample offsets */
          if(sample_offset && cursor>batch_last){
	    if (cdda_sector_gettrack(d, batch_last) < d->tracks || force_overread) {
	      int i;

	      /* Need to flush the buffer when overreading into the leadout */
	      if (cdda_sector_gettrack(d, batch_last) == d->tracks)
		paranoia_seek(p, cursor, SEEK_SET);

	      /* read a sector and output the partial offset.  Save the
		 rest for the next batch iteration */
	      readbuf=paranoia_read_limited(p,callback,max_retries);
	      err=cdda_errors(d);mes=cdda_messages(d);

	      if(mes || err)
		fprintf(stderr,"\r                               "
			"                                           \r%s%s\n",
			mes?mes:"",err?err:"");

	      if(err)free(err);if(mes)free(mes);
	      if(readbuf==NULL){
		skipped_flag=1;
		report("\nparanoia_read: Unrecoverable error reading through "
		       "sample_offset shift\n\tat end of track, bailing.\n");
		break;
	      }
	      if (skipped_flag && abort_on_skip) break;
	      skipped_flag=0;
	      /* do not move the cursor */

	      if(output_endian!=bigendianp())
		for(i=0;i<CD_FRAMESIZE_RAW/2;i++)
		  offset_buffer[i]=UINT16_SWAP_LE_BE_C(readbuf[i]);
	      else
		memcpy(offset_buffer,readbuf,CD_FRAMESIZE_RAW);
	      offset_buffer_used=sample_offset*4;
	      callback(cursor* (CD_FRAMEWORDS), PARANOIA_CB_WROTE);
	    } else {
	      memset(offset_buffer, 0, sizeof(offset_buffer));
	      offset_buffer_used = sample_offset * 4;
	    }

	    if(buffering_write(out,(char *)offset_buffer,
			       offset_buffer_used)){
	      report("Error writing output: %s", strerror(errno));
	      exit(1);
	    }
	  }
        }

	/* Write sectors of silent audio to compensate for
	   missing samples that would be in the leadout */
	if (cdda_sector_gettrack(d, batch_last) == d->tracks &&
		toc_offset > 0 && !force_overread)
	{
		char *silence;
		size_t missing_sector_bytes = CD_FRAMESIZE_RAW * toc_offset;

		silence = calloc(toc_offset, CD_FRAMESIZE_RAW);
		if (!silence || buffering_write(out, silence, missing_sector_bytes)) {
		      report("Error writing output: %s", strerror(errno));
		      exit(1);
		}
		free(silence);
	}

        callback(cursor* (CDIO_CD_FRAMESIZE_RAW/2)-1,
		 PARANOIA_CB_FINISHED);
        buffering_close(out);
        if(skipped_flag){
          /* remove the file */
          report("\nRemoving aborted file: %s", outfile_name);
          unlink(outfile_name);
          /* make the cursor correct if we have another track */
          if(batch_track!=-1){
            batch_track++;
            cursor=cdda_track_firstsector(d,batch_track);
            paranoia_seek(p,cursor, SEEK_SET);
            offset_skip=sample_offset*4;
            offset_buffer_used=0;
          }
        }
        report("\n");
      }

      paranoia_free(p);
      p=NULL;
    }
  }

  report("Done.\n\n");

  return 0;
}
Ejemplo n.º 12
0
static int
get_ftm(term_t t, ftm *ftm)
{ GET_LD
  term_t tmp = PL_new_term_ref();
  int date9;

  memset(ftm, 0, sizeof(*ftm));

  if ( (date9=PL_is_functor(t, FUNCTOR_date9)) )
  { if ( get_int_arg  (1, t, tmp, &ftm->tm.tm_year) &&
	 get_int_arg  (2, t, tmp, &ftm->tm.tm_mon)  &&
	 get_int_arg  (3, t, tmp, &ftm->tm.tm_mday) &&
	 get_int_arg  (4, t, tmp, &ftm->tm.tm_hour) &&
	 get_int_arg  (5, t, tmp, &ftm->tm.tm_min)  &&
	 get_float_arg(6, t, tmp, &ftm->sec)	    &&
	 get_voff_arg (7, t, tmp, &ftm->utcoff)     &&
	 get_tz_arg   (8, t, tmp, &ftm->tzname)     &&
	 get_dst_arg  (9, t, tmp, &ftm->isdst) )
    { double fp, ip;

      ftm->tm.tm_isdst = (ftm->isdst == -2 ? -1 : ftm->isdst);

    fixup:
      fp = modf(ftm->sec, &ip);
      if ( fp < 0.0 )
      { fp += 1.0;
	ip -= 1.0;
      }

      ftm->tm.tm_sec = (int)ip;
      ftm->tm.tm_year -= 1900;		/* 1900 based */
      ftm->tm.tm_mon--;			/* 0-based */

      if ( ftm->utcoff == NO_UTC_OFFSET )
      { if ( ftm->tm.tm_isdst < 0 )	/* unknown DST */
	{ int offset;

	  if ( mktime(&ftm->tm) == (time_t)-1 )
	    return PL_representation_error("dst");
	  ftm->flags |= HAS_WYDAY;

	  offset = tz_offset();
	  if ( ftm->tm.tm_isdst > 0 )
	    offset -= 3600;
	  ftm->utcoff = offset;

	  if ( date9 ) /* variable */
	  { _PL_get_arg(7, t, tmp);
	    if ( !PL_unify_integer(tmp, ftm->utcoff) )
	      return FALSE;
	  } else
	  { ftm->utcoff = offset;
	  }
	}

	if ( ftm->isdst == -2 )
	{ ftm->isdst = ftm->tm.tm_isdst;
	  _PL_get_arg(9, t, tmp);
	  if ( ftm->isdst < 0 )
	  { if ( !PL_unify_atom(tmp, ATOM_minus) )
	      return FALSE;
	  } else
	  { if ( !PL_unify_bool(tmp, ftm->isdst) )
	      return FALSE;
	  }
	}

	if ( !ftm->tzname )
	{ ftm->tzname = tz_name_as_atom(ftm->isdst);
	  _PL_get_arg(8, t, tmp);
	  if ( PL_is_variable(tmp) &&
	       !PL_unify_atom(tmp, ftm->tzname) )
	    return FALSE;
	}
      }

      succeed;
    }
  } else if ( PL_is_functor(t, FUNCTOR_date3) )
  { if ( get_int_arg  (1, t, tmp, &ftm->tm.tm_year) &&
	 get_int_arg  (2, t, tmp, &ftm->tm.tm_mon)  &&
	 get_int_arg  (3, t, tmp, &ftm->tm.tm_mday) )
    { ftm->tm.tm_isdst = -1;
      ftm->utcoff = NO_UTC_OFFSET;
      goto fixup;
    }
  }

  return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_time, t);
}
Ejemplo n.º 13
0
/***
*int _output(stream, format, argptr), static int output(format, argptr)
*
*Purpose:
*   Output performs printf style output onto a stream.  It is called by
*   printf/fprintf/sprintf/vprintf/vfprintf/vsprintf to so the dirty
*   work.  In multi-thread situations, _output assumes that the given
*   stream is already locked.
*
*   Algorithm:
*       The format string is parsed by using a finite state automaton
*       based on the current state and the current character read from
*       the format string.  Thus, looping is on a per-character basis,
*       not a per conversion specifier basis.  Once the format specififying
*       character is read, output is performed.
*
*Entry:
*   FILE *stream   - stream for output
*   char *format   - printf style format string
*   va_list argptr - pointer to list of subsidiary arguments
*
*Exit:
*   Returns the number of characters written, or -1 if an output error
*   occurs.
*ifdef _UNICODE
*   The wide-character flavour returns the number of wide-characters written.
*endif
*
*Exceptions:
*
*******************************************************************************/
#ifdef CPRFLAG
#ifndef FORMAT_VALIDATIONS
_CRTIMP int __cdecl _vtcprintf (
    const _TCHAR *format,
    va_list argptr
)
{
    return _vtcprintf_l(format, NULL, argptr);
}

#else  /* FORMAT_VALIDATIONS */
_CRTIMP int __cdecl _vtcprintf_s (
    const _TCHAR *format,
    va_list argptr
)
{
    return _vtcprintf_s_l(format, NULL, argptr);
}

#endif  /* FORMAT_VALIDATIONS */
#endif  /* CPRFLAG */

#ifdef CPRFLAG
#ifndef FORMAT_VALIDATIONS
_CRTIMP int __cdecl _vtcprintf_l (
#else  /* FORMAT_VALIDATIONS */
_CRTIMP int __cdecl _vtcprintf_s_l (
#endif  /* FORMAT_VALIDATIONS */
#else  /* CPRFLAG */

#ifdef _UNICODE
#ifndef FORMAT_VALIDATIONS
int __cdecl _woutput (
    miniFILE *stream,
#else  /* FORMAT_VALIDATIONS */
int __cdecl _woutput_s (
    miniFILE *stream,
#endif  /* FORMAT_VALIDATIONS */
#else  /* _UNICODE */
#ifndef FORMAT_VALIDATIONS
int __cdecl _output (
    miniFILE *stream,
#else  /* FORMAT_VALIDATIONS */
int __cdecl _output_s (
    miniFILE *stream,

#endif  /* FORMAT_VALIDATIONS */
#endif  /* _UNICODE */

#endif  /* CPRFLAG */
    const _TCHAR *format,
    va_list argptr
)
{
    int hexadd=0;     /* offset to add to number to get 'a'..'f' */
    TCHAR ch;       /* character just read */
    int flags=0;      /* flag word -- see #defines above for flag values */
    enum STATE state;   /* current state */
    enum CHARTYPE chclass; /* class of current character */
    int radix;      /* current conversion radix */
    int charsout;   /* characters currently written so far, -1 = IO error */
    int fldwidth = 0;   /* selected field width -- 0 means default */
    int precision = 0;  /* selected precision  -- -1 means default */
    TCHAR prefix[2];    /* numeric prefix -- up to two characters */
    int prefixlen=0;  /* length of prefix -- 0 means no prefix */
    int capexp = 0;     /* non-zero = 'E' exponent signifient, zero = 'e' */
    int no_output=0;  /* non-zero = prodcue no output for this specifier */
    union {
        const char *sz;   /* pointer text to be printed, not zero terminated */
        const wchar_t *wz;
    } text;

    int textlen;    /* length of the text in bytes/wchars to be printed.
                       textlen is in multibyte or wide chars if _UNICODE */
    union {
        char sz[BUFFERSIZE];
#ifdef _UNICODE
        wchar_t wz[BUFFERSIZE];
#endif  /* _UNICODE */
    } buffer;
    wchar_t wchar;                      /* temp wchar_t */
    int buffersize;                     /* size of text.sz (used only for the call to _cfltcvt) */
    int bufferiswide=0;         /* non-zero = buffer contains wide chars already */

#ifndef CPRFLAG
    _VALIDATE_RETURN( (stream != NULL), EINVAL, -1);
#endif  /* CPRFLAG */
    _VALIDATE_RETURN( (format != NULL), EINVAL, -1);

    charsout = 0;       /* no characters written yet */
    textlen = 0;        /* no text yet */
    state = ST_NORMAL;  /* starting state */
    buffersize = 0;

    /* main loop -- loop while format character exist and no I/O errors */
    while ((ch = *format++) != _T('\0') && charsout >= 0) {
#ifndef FORMAT_VALIDATIONS
        chclass = FIND_CHAR_CLASS(__lookuptable, ch);  /* find character class */
        state = FIND_NEXT_STATE(__lookuptable, chclass, state); /* find next state */
#else  /* FORMAT_VALIDATIONS */
        chclass = FIND_CHAR_CLASS(__lookuptable_s, ch);  /* find character class */
        state = FIND_NEXT_STATE(__lookuptable_s, chclass, state); /* find next state */

        _VALIDATE_RETURN((state != ST_INVALID), EINVAL, -1);

#endif  /* FORMAT_VALIDATIONS */

        /* execute code for each state */
        switch (state) {

        case ST_NORMAL:

NORMAL_STATE:

            /* normal state -- just write character */
#ifdef _UNICODE
            bufferiswide = 1;
#else  /* _UNICODE */
            bufferiswide = 0;
#endif  /* _UNICODE */
            WRITE_CHAR(ch, &charsout);
            break;

        case ST_PERCENT:
            /* set default value of conversion parameters */
            prefixlen = fldwidth = no_output = capexp = 0;
            flags = 0;
            precision = -1;
            bufferiswide = 0;   /* default */
            break;

        case ST_FLAG:
            /* set flag based on which flag character */
            switch (ch) {
            case _T('-'):
                flags |= FL_LEFT;   /* '-' => left justify */
                break;
            case _T('+'):
                flags |= FL_SIGN;   /* '+' => force sign indicator */
                break;
            case _T(' '):
                flags |= FL_SIGNSP; /* ' ' => force sign or space */
                break;
            case _T('#'):
                flags |= FL_ALTERNATE;  /* '#' => alternate form */
                break;
            case _T('0'):
                flags |= FL_LEADZERO;   /* '0' => pad with leading zeros */
                break;
            }
            break;

        case ST_WIDTH:
            /* update width value */
            if (ch == _T('*')) {
                /* get width from arg list */
                fldwidth = get_int_arg(&argptr);
                if (fldwidth < 0) {
                    /* ANSI says neg fld width means '-' flag and pos width */
                    flags |= FL_LEFT;
                    fldwidth = -fldwidth;
                }
            }
            else {
                /* add digit to current field width */
                fldwidth = fldwidth * 10 + (ch - _T('0'));
            }
            break;

        case ST_DOT:
            /* zero the precision, since dot with no number means 0
               not default, according to ANSI */
            precision = 0;
            break;

        case ST_PRECIS:
            /* update precison value */
            if (ch == _T('*')) {
                /* get precision from arg list */
                precision = get_int_arg(&argptr);
                if (precision < 0)
                    precision = -1; /* neg precision means default */
            }
            else {
                /* add digit to current precision */
                precision = precision * 10 + (ch - _T('0'));
            }
            break;

        case ST_SIZE:
            /* just read a size specifier, set the flags based on it */
            switch (ch) {
            case _T('l'):
                /*
                 * In order to handle the ll case, we depart from the
                 * simple deterministic state machine.
                 */
                if (*format == _T('l'))
                {
                    ++format;
                    flags |= FL_LONGLONG;   /* 'll' => long long */
                }
                else
                {
                    flags |= FL_LONG;   /* 'l' => long int or wchar_t */
                }
                break;

            case _T('I'):
                /*
                 * In order to handle the I, I32, and I64 size modifiers, we
                 * depart from the simple deterministic state machine. The
                 * code below scans for characters following the 'I',
                 * and defaults to 64 bit on WIN64 and 32 bit on WIN32
                 */
#if PTR_IS_INT64
                flags |= FL_I64;    /* 'I' => __int64 on WIN64 systems */
#endif  /* PTR_IS_INT64 */
                if ( (*format == _T('6')) && (*(format + 1) == _T('4')) )
                {
                    format += 2;
                    flags |= FL_I64;    /* I64 => __int64 */
                }
                else if ( (*format == _T('3')) && (*(format + 1) == _T('2')) )
                {
                    format += 2;
                    flags &= ~FL_I64;   /* I32 => __int32 */
                }
                else if ( (*format == _T('d')) ||
                          (*format == _T('i')) ||
                          (*format == _T('o')) ||
                          (*format == _T('u')) ||
                          (*format == _T('x')) ||
                          (*format == _T('X')) )
                {
                    /*
                     * Nothing further needed.  %Id (et al) is
                     * handled just like %d, except that it defaults to 64 bits
                     * on WIN64.  Fall through to the next iteration.
                     */
                }
                else {
                    state = ST_NORMAL;
                    goto NORMAL_STATE;
                }
                break;

            case _T('h'):
                flags |= FL_SHORT;  /* 'h' => short int or char */
                break;

            case _T('w'):
                flags |= FL_WIDECHAR;  /* 'w' => wide character */
                break;

            }
            break;

        case ST_TYPE:
            /* we have finally read the actual type character, so we       */
            /* now format and "print" the output.  We use a big switch     */
            /* statement that sets 'text' to point to the text that should */
            /* be printed, and 'textlen' to the length of this text.       */
            /* Common code later on takes care of justifying it and        */
            /* other miscellaneous chores.  Note that cases share code,    */
            /* in particular, all integer formatting is done in one place. */
            /* Look at those funky goto statements!                        */

            switch (ch) {

            case _T('C'):   /* ISO wide character */
                if (!(flags & (FL_SHORT|FL_LONG|FL_WIDECHAR)))
#ifdef _UNICODE
                    flags |= FL_SHORT;
#else  /* _UNICODE */
                    flags |= FL_WIDECHAR;   /* ISO std. */
#endif  /* _UNICODE */
            /* fall into 'c' case */

            case _T('c'): {
                /* print a single character specified by int argument */
#ifdef _UNICODE
                bufferiswide = 1;
                wchar = (wchar_t) get_int_arg(&argptr);
                if (flags & FL_SHORT) {
                    /* format multibyte character */
                    /* this is an extension of ANSI */
                    char tempchar[2];
                    {
                        tempchar[0] = (char)(wchar & 0x00ff);
                        tempchar[1] = '\0';
                    }

                    if (_MBTOWC(buffer.wz,tempchar, MB_CUR_MAX) < 0)
                    {
                        /* ignore if conversion was unsuccessful */
                        no_output = 1;
                    }
                } else {
                    buffer.wz[0] = wchar;
                }
                text.wz = buffer.wz;
                textlen = 1;    /* print just a single character */
#else  /* _UNICODE */
                if (flags & (FL_LONG|FL_WIDECHAR)) {
                    wchar = (wchar_t) get_short_arg(&argptr);
                    no_output = 1;
                } else {
                    /* format multibyte character */
                    /* this is an extension of ANSI */
                    unsigned short temp;
                    wchar = (wchar_t)get_int_arg(&argptr);
                    temp = (unsigned short)wchar;
                    {
                        buffer.sz[0] = (char) temp;
                        textlen = 1;
                    }
                }
                text.sz = buffer.sz;
#endif  /* _UNICODE */
            }
            break;

            case _T('Z'): {
                /* print a Counted String */
                struct _count_string {
                    short Length;
                    short MaximumLength;
                    char *Buffer;
                } *pstr;

                pstr = (struct _count_string *)get_ptr_arg(&argptr);
                if (pstr == NULL || pstr->Buffer == NULL) {
                    /* null ptr passed, use special string */
                    text.sz = __nullstring;
                    textlen = (int)strlen(text.sz);
                } else {
                    if (flags & FL_WIDECHAR) {
                        text.wz = (wchar_t *)pstr->Buffer;
                        textlen = pstr->Length / (int)sizeof(wchar_t);
                        bufferiswide = 1;
                    } else {
                        bufferiswide = 0;
                        text.sz = pstr->Buffer;
                        textlen = pstr->Length;
                    }
                }
            }
            break;

            case _T('S'):   /* ISO wide character string */
#ifndef _UNICODE
                if (!(flags & (FL_SHORT|FL_LONG|FL_WIDECHAR)))
                    flags |= FL_WIDECHAR;
#else  /* _UNICODE */
                if (!(flags & (FL_SHORT|FL_LONG|FL_WIDECHAR)))
                    flags |= FL_SHORT;
#endif  /* _UNICODE */

            case _T('s'): {
                /* print a string --                            */
                /* ANSI rules on how much of string to print:   */
                /*   all if precision is default,               */
                /*   min(precision, length) if precision given. */
                /* prints '(null)' if a null string is passed   */

                int i;
                const char *p;       /* temps */
                const wchar_t *pwch;

                /* At this point it is tempting to use strlen(), but */
                /* if a precision is specified, we're not allowed to */
                /* scan past there, because there might be no null   */
                /* at all.  Thus, we must do our own scan.           */

                i = (precision == -1) ? INT_MAX : precision;
                text.sz = (char *)get_ptr_arg(&argptr);

                /* scan for null upto i characters */
#ifdef _UNICODE
                if (flags & FL_SHORT) {
                    if (text.sz == NULL) /* NULL passed, use special string */
                        text.sz = __nullstring;
                    p = text.sz;
                    for (textlen=0; textlen<i && *p; textlen++) {
                        ++p;
                    }
                    /* textlen now contains length in multibyte chars */
                } else {
                    if (text.wz == NULL) /* NULL passed, use special string */
                        text.wz = __wnullstring;
                    bufferiswide = 1;
                    pwch = text.wz;
                    while (i-- && *pwch)
                        ++pwch;
                    textlen = (int)(pwch - text.wz);       /* in wchar_ts */
                    /* textlen now contains length in wide chars */
                }
#else  /* _UNICODE */
                if (flags & (FL_LONG|FL_WIDECHAR)) {
                    if (text.wz == NULL) /* NULL passed, use special string */
                        text.wz = __wnullstring;
                    bufferiswide = 1;
                    pwch = text.wz;
                    while ( i-- && *pwch )
                        ++pwch;
                    textlen = (int)(pwch - text.wz);
                    /* textlen now contains length in wide chars */
                } else {
                    if (text.sz == NULL) /* NULL passed, use special string */
                        text.sz = __nullstring;
                    p = text.sz;
                    while (i-- && *p)
                        ++p;
                    textlen = (int)(p - text.sz);    /* length of the string */
                }

#endif  /* _UNICODE */
            }
            break;


            case _T('n'): {
                /* write count of characters seen so far into */
                /* short/int/long thru ptr read from args */

                void *p;        /* temp */

                p = get_ptr_arg(&argptr);

                /* %n is disabled */
                _VALIDATE_RETURN(("'n' format specifier disabled" && 0), EINVAL, -1);
                break;

                /* store chars out into short/long/int depending on flags */
#if !LONG_IS_INT
                if (flags & FL_LONG)
                    *(long *)p = charsout;
                else
#endif  /* !LONG_IS_INT */

#if !SHORT_IS_INT
                    if (flags & FL_SHORT)
                        *(short *)p = (short) charsout;
                    else
#endif  /* !SHORT_IS_INT */
                        *(int *)p = charsout;

                no_output = 1;              /* force no output */
            }
            break;

            case _T('E'):
            case _T('G'):
            case _T('A'):
                capexp = 1;                 /* capitalize exponent */
                ch += _T('a') - _T('A');    /* convert format char to lower */
            /* DROP THROUGH */
            case _T('e'):
            case _T('f'):
            case _T('g'):
            case _T('a'): {
                /* floating point conversion -- we call cfltcvt routines */
                /* to do the work for us.                                */
                flags |= FL_SIGNED;         /* floating point is signed conversion */
                text.sz = buffer.sz;        /* put result in buffer */
                buffersize = BUFFERSIZE;

                /* compute the precision value */
                if (precision < 0)
                    precision = 6;          /* default precision: 6 */
                else if (precision == 0 && ch == _T('g'))
                    precision = 1;          /* ANSI specified */
                else if (precision > MAXPRECISION)
                    precision = MAXPRECISION;

                if (precision > BUFFERSIZE - _CVTBUFSIZE) {
                    precision = BUFFERSIZE - _CVTBUFSIZE;
                }

                /* for safecrt, we pass along the FL_ALTERNATE flag to _safecrt_cfltcvt */
                if (flags & FL_ALTERNATE)
                {
                    capexp |= FL_ALTERNATE;
                }

                _CRT_DOUBLE tmp;
                tmp=va_arg(argptr, _CRT_DOUBLE);
                /* Note: assumes ch is in ASCII range */
                /* In safecrt, we provide a special version of _cfltcvt which internally calls printf (see safecrt_output_s.c) */
                _CFLTCVT(&tmp, buffer.sz, buffersize, (char)ch, precision, capexp);

                /* check if result was negative, save '-' for later */
                /* and point to positive part (this is for '0' padding) */
                if (*text.sz == '-') {
                    flags |= FL_NEGATIVE;
                    ++text.sz;
                }

                textlen = (int)strlen(text.sz);     /* compute length of text */
            }
            break;

            case _T('d'):
            case _T('i'):
                /* signed decimal output */
                flags |= FL_SIGNED;
                radix = 10;
                goto COMMON_INT;

            case _T('u'):
                radix = 10;
                goto COMMON_INT;

            case _T('p'):
                /* write a pointer -- this is like an integer or long */
                /* except we force precision to pad with zeros and */
                /* output in big hex. */

                precision = 2 * sizeof(void *);     /* number of hex digits needed */
#if PTR_IS_INT64
                flags |= FL_I64;                    /* assume we're converting an int64 */
#elif !PTR_IS_INT
                flags |= FL_LONG;                   /* assume we're converting a long */
#endif  /* !PTR_IS_INT */
            /* DROP THROUGH to hex formatting */

            case _T('X'):
                /* unsigned upper hex output */
                hexadd = _T('A') - _T('9') - 1;     /* set hexadd for uppercase hex */
                goto COMMON_HEX;

            case _T('x'):
                /* unsigned lower hex output */
                hexadd = _T('a') - _T('9') - 1;     /* set hexadd for lowercase hex */
                /* DROP THROUGH TO COMMON_HEX */

COMMON_HEX:
                radix = 16;
                if (flags & FL_ALTERNATE) {
                    /* alternate form means '0x' prefix */
                    prefix[0] = _T('0');
                    prefix[1] = (TCHAR)(_T('x') - _T('a') + _T('9') + 1 + hexadd);  /* 'x' or 'X' */
                    prefixlen = 2;
                }
                goto COMMON_INT;

            case _T('o'):
                /* unsigned octal output */
                radix = 8;
                if (flags & FL_ALTERNATE) {
                    /* alternate form means force a leading 0 */
                    flags |= FL_FORCEOCTAL;
                }
                /* DROP THROUGH to COMMON_INT */

COMMON_INT: {
                    /* This is the general integer formatting routine. */
                    /* Basically, we get an argument, make it positive */
                    /* if necessary, and convert it according to the */
                    /* correct radix, setting text and textlen */
                    /* appropriately. */

#if _INTEGRAL_MAX_BITS >= 64
//                unsigned __int64 number;    /* number to convert */
                    __uint64_t number;      /* number to convert */
                    int digit;              /* ascii value of digit */
                    __int64 l;              /* temp long value */
#else  /* _INTEGRAL_MAX_BITS >= 64        */
                    unsigned long number;   /* number to convert */
                    int digit;              /* ascii value of digit */
                    long l;                 /* temp long value */
#endif  /* _INTEGRAL_MAX_BITS >= 64        */

                    /* 1. read argument into l, sign extend as needed */
#if _INTEGRAL_MAX_BITS >= 64
                    if (flags & FL_I64)
                        l = get_int64_arg(&argptr);
                    else
#endif  /* _INTEGRAL_MAX_BITS >= 64        */

                        if (flags & FL_LONGLONG)
                            l = get_long_long_arg(&argptr);
                        else

#if !LONG_IS_INT
                            if (flags & FL_LONG)
                                l = get_long_arg(&argptr);
                            else
#endif  /* !LONG_IS_INT */

#if !SHORT_IS_INT
                                if (flags & FL_SHORT) {
                                    if (flags & FL_SIGNED)
                                        l = (short) get_int_arg(&argptr); /* sign extend */
                                    else
                                        l = (unsigned short) get_int_arg(&argptr);    /* zero-extend*/

                                } else
#endif  /* !SHORT_IS_INT */
                                {
                                    if (flags & FL_SIGNED)
                                        l = get_int_arg(&argptr); /* sign extend */
                                    else
                                        l = (unsigned int) get_int_arg(&argptr);    /* zero-extend*/

                                }

                    /* 2. check for negative; copy into number */
                    if ( (flags & FL_SIGNED) && l < 0) {
                        number = -l;
                        flags |= FL_NEGATIVE;   /* remember negative sign */
                    } else {
                        number = l;
                    }

#if _INTEGRAL_MAX_BITS >= 64
                    if ( (flags & FL_I64) == 0 && (flags & FL_LONGLONG) == 0 ) {
                        /*
                         * Unless printing a full 64-bit value, insure values
                         * here are not in cananical longword format to prevent
                         * the sign extended upper 32-bits from being printed.
                         */
                        number &= 0xffffffff;
                    }
#endif  /* _INTEGRAL_MAX_BITS >= 64        */

                    /* 3. check precision value for default; non-default */
                    /*    turns off 0 flag, according to ANSI. */
                    if (precision < 0)
                        precision = 1;  /* default precision */
                    else {
                        flags &= ~FL_LEADZERO;
                        if (precision > MAXPRECISION)
                            precision = MAXPRECISION;
                    }

                    /* 4. Check if data is 0; if so, turn off hex prefix */
                    if (number == 0)
                        prefixlen = 0;

                    /* 5. Convert data to ASCII -- note if precision is zero */
                    /*    and number is zero, we get no digits at all.       */

                    char *sz;
                    sz = &buffer.sz[BUFFERSIZE-1];    /* last digit at end of buffer */

                    while (precision-- > 0 || number != 0) {
                        digit = (int)(number % radix) + '0';
                        number /= radix;                /* reduce number */
                        if (digit > '9') {
                            /* a hex digit, make it a letter */
                            digit += hexadd;
                        }
                        *sz-- = (char)digit;       /* store the digit */
                    }

                    textlen = (int)((char *)&buffer.sz[BUFFERSIZE-1] - sz); /* compute length of number */
                    ++sz;          /* text points to first digit now */


                    /* 6. Force a leading zero if FORCEOCTAL flag set */
                    if ((flags & FL_FORCEOCTAL) && (textlen == 0 || sz[0] != '0')) {
                        *--sz = '0';
                        ++textlen;      /* add a zero */
                    }

                    text.sz = sz;
                }
                break;
            }


            /* At this point, we have done the specific conversion, and */
            /* 'text' points to text to print; 'textlen' is length.  Now we */
            /* justify it, put on prefixes, leading zeros, and then */
            /* print it. */

            if (!no_output) {
                int padding;    /* amount of padding, negative means zero */

                if (flags & FL_SIGNED) {
                    if (flags & FL_NEGATIVE) {
                        /* prefix is a '-' */
                        prefix[0] = _T('-');
                        prefixlen = 1;
                    }
                    else if (flags & FL_SIGN) {
                        /* prefix is '+' */
                        prefix[0] = _T('+');
                        prefixlen = 1;
                    }
                    else if (flags & FL_SIGNSP) {
                        /* prefix is ' ' */
                        prefix[0] = _T(' ');
                        prefixlen = 1;
                    }
                }

                /* calculate amount of padding -- might be negative, */
                /* but this will just mean zero */
                padding = fldwidth - textlen - prefixlen;

                /* put out the padding, prefix, and text, in the correct order */

                if (!(flags & (FL_LEFT | FL_LEADZERO))) {
                    /* pad on left with blanks */
                    WRITE_MULTI_CHAR(_T(' '), padding, &charsout);
                }

                /* write prefix */
                WRITE_STRING(prefix, prefixlen, &charsout);

                if ((flags & FL_LEADZERO) && !(flags & FL_LEFT)) {
                    /* write leading zeros */
                    WRITE_MULTI_CHAR(_T('0'), padding, &charsout);
                }

                /* write text */
#ifndef _UNICODE
                if (bufferiswide && (textlen > 0)) {
                    charsout = -1;
                } else {
                    WRITE_STRING(text.sz, textlen, &charsout);
                }
#else  /* _UNICODE */
                if (!bufferiswide && textlen > 0) {
                    char *p;
                    int retval = 0
                                 int count;

                    p = text.sz;
                    count = textlen;
                    while (count-- > 0) {
                        retval = _MBTOWC(&wchar, p, MB_CUR_MAX);
                        if (retval <= 0) {
                            charsout = -1;
                            break;
                        }
                        WRITE_CHAR(wchar, &charsout);
                        p += retval;
                    }
                } else {
                    WRITE_STRING(text.wz, textlen, &charsout);
                }
#endif  /* _UNICODE */

                if (charsout >= 0 && (flags & FL_LEFT)) {
                    /* pad on right with blanks */
                    WRITE_MULTI_CHAR(_T(' '), padding, &charsout);
                }

                /* we're done! */
            }
Ejemplo n.º 14
0
Archivo: cli.c Proyecto: dnsmkl/fsqlf
void read_cli_options(struct fsqlf_kw_conf *kwall, int argc, char **argv,
                      FILE **fin, FILE **fout)
{
    int i;
    if (argc == 1) return; // use stdin and stdout

    if (argc == 2 && strcmp(argv[1], "--create-config-file") == 0) {
        FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[1]);
    }
    if (argc == 3 && strcmp(argv[1], "--create-config-file") == 0) {
        if (fsqlf_kwmap_conffile_create(argv[2]) != FSQLF_OK) {
            fprintf(stderr, "Problem occurred during creation of config file '%s'.\n", argv[2]);
            exit(1);
        } else {
            fprintf(stderr, "Configuration was written to file '%s'.\n", argv[2]);
            exit(0);
        }
    }

    for (i = 1; i < argc; i++) {
        if (argv[i][0] != '-') {
            if ((*fin) == stdin) {
                //try to openinig INPUT file
                (*fin) = fopen(argv[1], "r");
                if (!(*fin)) {
                    FAIL_WITH_ERROR(1, "Error opening input file: %s", argv[i]);
                }
            }
            else if ((*fout) == stdout) {   //try to openinig OUTPUT file (only if INPUT file is set)
                (*fout) = fopen(argv[2], "w+");
                if (!(*fout)) FAIL_WITH_ERROR(1, "Error opening output file: %s", argv[i]);
            }
        } else if (ARGV_MATCH(i, "-i")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            (*fin) = fopen(argv[i], "r");
            if (!(*fin)) FAIL_WITH_ERROR(1, "Error opening input file: %s", argv[i]);
        } else if (ARGV_MATCH(i, "-o")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            (*fout) = fopen(argv[i], "w+");
            if (!(*fout)) FAIL_WITH_ERROR(1, "Error opening output file: %s", argv[i]);
        } else if (ARGV_MATCH(i, "--config-file")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (fsqlf_kwmap_conffile_read(kwall, argv[i]) == FSQLF_FAIL) {
                FAIL_WITH_ERROR(1, "Error reading configuration file: %s", argv[i]);
            }
        } else if (ARGV_MATCH(i, "--select-comma-newline")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (strcmp(argv[i], "after") == 0) {
                fsqlf_kw_get(kwall, "kw_comma")->before.new_line = 0;
                fsqlf_kw_get(kwall, "kw_comma")->after.new_line  = 1;
            } else if (strcmp(argv[i], "before") == 0) {
                fsqlf_kw_get(kwall, "kw_comma")->before.new_line = 1;
                fsqlf_kw_get(kwall, "kw_comma")->after.new_line  = 0;
            } else if (strcmp(argv[i], "none") == 0) {
                fsqlf_kw_get(kwall, "kw_comma")->before.new_line = 0;
                fsqlf_kw_get(kwall, "kw_comma")->after.new_line  = 0;
            }
        } else if (ARGV_MATCH(i, "--keyword-case")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (strcmp(argv[i], "none") == 0) {
                fsqlf_kwmap_set_case(kwall, FSQLF_KWCASE_ORIGINAL);
            } else if (strcmp(argv[i], "upper") == 0) {
                fsqlf_kwmap_set_case(kwall, FSQLF_KWCASE_UPPER);
            } else if (strcmp(argv[i], "lower") == 0) {
                fsqlf_kwmap_set_case(kwall, FSQLF_KWCASE_LOWER);
            } else if (strcmp(argv[i], "initcap") == 0) {
                fsqlf_kwmap_set_case(kwall, FSQLF_KWCASE_INITCAP);
            }
        } else if (ARGV_MATCH(i, "--keyword-text")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (strcmp(argv[i], "original") == 0) {
                fsqlf_kwmap_set_spelling(kwall, FSQLF_KWSPELLING_USE_ORIGINAL);
            } else if (strcmp(argv[i], "default") == 0) {
                fsqlf_kwmap_set_spelling(kwall, FSQLF_KWSPELLING_USE_HARDCODED_DEFAULT);
            }
        } else if (ARGV_MATCH(i, "--select-newline-after")) {
            fsqlf_kw_get(kwall, "kw_select")->after.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-or-before")) {
            fsqlf_kw_get(kwall, "kw_or")->before.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-or-after")) {
            fsqlf_kw_get(kwall, "kw_or")->after.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-and-before")) {
            fsqlf_kw_get(kwall, "kw_and")->before.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-and-after")) {
            fsqlf_kw_get(kwall, "kw_and")->after.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-major-sections")) {
            int new_line_count = get_int_arg(++i, argc, argv);
            fsqlf_kwmap_set_major_clause_nl(kwall, new_line_count);
        } else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
            usage_info(argc, argv);
            exit(0);
        } else FAIL_WITH_ERROR(1, "Option `%s' is not recognised or used incorrectly.\nTry `%s --help' for more information\n", argv[i], argv[0]);
    }
}