Exemplo n.º 1
0
static void write_pfgw_file(uint64_t p)
{
  FILE *file;
  char file_name[FILENAME_MAX+1];
  uint32_t count;

  snprintf(file_name, FILENAME_MAX, "sr_%"PRIu32".%s", base, PFGW_EXT);
  file_name[FILENAME_MAX] = '\0';
  if ((file = xfopen(file_name,"w",warning)) == NULL)
    return;

  fprintf(file,"ABC $a*%"PRIu32"^$b$c // Sieved to %"PRIu64" with srsieve\n",
          base,p);
  count = for_each_term((kcn_app_t)write_knc,file);

  report_wrote(count,seq_count,"abc",file_name);
  xfclose(file,file_name);
}
Exemplo n.º 2
0
static void write_srsieve_file(const char *file_name, uint64_t p)
{
  FILE *file;
  uint32_t seq, count;

  if ((file = xfopen(file_name, "w", warning)) == NULL)
    return;

  fprintf(file, "pmin=%"PRIu64"\n", p);
  for (count = 0, seq = 0; seq < seq_count; seq++)
  {
    fprintf(file, "%s\n", seq_str(seq));
    count += seq_for_each_term(seq,(kcn_app_t)write_n,file);
  }

  report_wrote(count, seq_count, "srsieve", file_name);
  xfclose(file,file_name);
}
Exemplo n.º 3
0
static void
read_all_cnf P1H(void)
{
  string *cnf_files;
  const_string cnf_path = kpse_init_format (kpse_cnf_format);

  cnf_hash = hash_create (CNF_HASH_SIZE);

  for (cnf_files = kpse_all_path_search (cnf_path, CNF_NAME);
       cnf_files && *cnf_files; cnf_files++) {
    string line;
    string cnf_filename = *cnf_files;
    FILE *cnf_file = xfopen (cnf_filename, FOPEN_R_MODE);

    while ((line = read_line (cnf_file)) != NULL) {
      unsigned len = strlen (line);
      /* Strip trailing spaces. */
      while (len > 0 && ISSPACE(line[len-1])) {
        line[len - 1] = 0;
        --len;
      }
      /* Concatenate consecutive lines that end with \.  */
      while (len > 0 && line[len - 1] == '\\') {
        string next_line = read_line (cnf_file);
        line[len - 1] = 0;
        if (!next_line) {
          WARNING1 ("%s: Last line ends with \\", cnf_filename);
        } else {
          string new_line;
          new_line = concat (line, next_line);
          free (line);
          line = new_line;
          len = strlen (line);
        }
      }

      do_line (line);
      free (line);
    }

    xfclose (cnf_file, cnf_filename);
  }
}
/* Checkpoint, append current p and speed in kp/s to SoBStatus.dat
 */
void sob_write_checkpoint(uint64_t p)
{
  FILE *file;
  uint32_t this_time, kp_per_sec;

  if ((this_time = millisec_elapsed_time()) != last_checkpoint_time)
    if ((file = xfopen(sob_status_file_name,"a",warning)) != NULL)
    {
      kp_per_sec = /* kp/s == p/ms */
        (p-last_checkpoint_prime)/(this_time-last_checkpoint_time);

      if (fprintf(file,"pmin=%"PRIu64" @ %"PRIu32" kp/s\n",p,kp_per_sec) < 0)
        warning("Writing to file `%s' failed.",sob_status_file_name);
      xfclose(file,sob_status_file_name);

      last_checkpoint_time = this_time;
      last_checkpoint_prime = p;
    }
}
Exemplo n.º 5
0
void
print_xml (void)
{
  state_number i;
  int level = 0;

  FILE *out = xfopen (spec_xml_file, "w");

  fputs ("<?xml version=\"1.0\"?>\n\n", out);
  xml_printf (out, level,
              "<bison-xml-report version=\"%s\" bug-report=\"%s\""
              " url=\"%s\">",
              xml_escape_n (0, VERSION),
              xml_escape_n (1, PACKAGE_BUGREPORT),
              xml_escape_n (2, PACKAGE_URL));

  fputc ('\n', out);
  xml_printf (out, level + 1, "<filename>%s</filename>",
	      xml_escape (grammar_file));

  /* print grammar */
  print_grammar (out, level + 1);

  new_closure (nritems);
  no_reduce_set =  bitset_create (ntokens, BITSET_FIXED);

  /* print automaton */
  fputc ('\n', out);
  xml_puts (out, level + 1, "<automaton>");
  for (i = 0; i < nstates; i++)
    print_state (out, level + 2, states[i]);
  xml_puts (out, level + 1, "</automaton>");

  bitset_free (no_reduce_set);
  free_closure ();

  xml_puts (out, 0, "</bison-xml-report>");

  free (escape_bufs[0].ptr);
  free (escape_bufs[1].ptr);

  xfclose (out);
}
Exemplo n.º 6
0
extern void
cosmoPk_dumpToFile(cosmoPk_t pk, const char *fname, uint32_t numSubSample)
{
	FILE   *f;
	assert(pk != NULL && fname != NULL);
	double k, P;

	numSubSample = (numSubSample == 0) ? 1 : numSubSample;

	f            = xfopen(fname, "w");
	for (uint32_t i = 0; i < pk->numPoints - 1; i++) {
		for (uint32_t j = 0; j < numSubSample; j++) {
			k = pk->k[i] + j * (pk->k[i + 1] - pk->k[i]) / numSubSample;
			P = cosmoPk_eval(pk, k);
			fprintf(f, "%15.12g\t%15.12g\n", k, P);
		}
	}
	xfclose(&f);
}
Exemplo n.º 7
0
/* A 'prp' file is just a series of NewPGen files all of the same type
   merged together and sorted in order of increasing n. This is convenient
   when testing with PRP or LLR, although NewPGen 2.82 itself does not read
   these files. Note that PRP version 24.14 does not correctly read type 19
   and 20 files. LLR version 3.7.0 reads all types 16, 17, 19, and 20.
*/
static void write_prp_files(uint64_t p)
{
  FILE *file[NUM_NPG_FORMATS];
  char file_name[NUM_NPG_FORMATS][FILENAME_MAX+1];
  int t;
  uint32_t i, seqs[NUM_NPG_FORMATS];

  for (t = 0; t < NUM_NPG_FORMATS; t++)
  {
    seqs[t] = 0;
    kn4_count[t] = 0;
  }

  for (i = 0; i < seq_count; i++)
  {
    assert(ABS(SEQ[i].c) == 1 || SEQ[i].k == 1);
    t = npg_format_index(SEQ[i].c);
    seqs[t]++;
  }

  for (t = 0; t < NUM_NPG_FORMATS; t++)
    if (seqs[t])
    {
      snprintf(file_name[t], FILENAME_MAX, "t%d_b%"PRIu32".%s",
               npg_formats[t].sieve_type, base, PRP_EXT);
      file_name[t][FILENAME_MAX] = '\0';
      file[t] = xfopen(file_name[t], "w", warning);
      if (file[t] != NULL)
        fprintf(file[t], "%"PRIu64":%c:1:%"PRIu32":%d\n",
                p, npg_formats[t].mode_char, base, npg_formats[t].mode_bits);
    }
    else
      file[t] = NULL;

  for_each_term((kcn_app_t)write_kn4,file);

  for (i = 0; i < NUM_NPG_FORMATS; i++)
    if (file[i] != NULL)
    {
      report_wrote(kn4_count[i], seqs[i], "PRP", file_name[i]);
      xfclose(file[i],file_name[i]);
    }
}
Exemplo n.º 8
0
static void dump_font_as_parseable_c_struct_as_it_is(char *filename,
		struct bitmap_font font, char *name)
{
	FILE *f = xfopen(filename, "w");
	fprintf(f, "unsigned char %s_data[] =", name);
	dump_data_in_c(f, font.data, font.ndata, font.packing);
	fprintf(f, ";\n");
	fprintf(f, "struct bitmap_font %s[1] = "
			"{{%d, %d, %d, %s, \"%s\", %s_data}};\n",
		name, font.number_of_glyphs, font.width, font.height,
		packing_string(font.packing), name, name);
	xfclose(f);

	double e = entropy(font.data, font.ndata);
	double cs = font.ndata * e/8;
	double cf = 100.0*cs/font.ndata;
	fprintf(stderr, "entropy %s %s  = %g  %d => %g %g%%\n",
			name, packing_string(font.packing),
			e,font.ndata, cs, cf);
}
Exemplo n.º 9
0
int read_cloud_mask_from_txt_file(struct cloud_mask *m, char *filename)
{
	m->n = 0;
	m->t = NULL;

	FILE *f = xfopen(filename, "r");
	while (1) {
		int n, maxlin = 1000*12*4;
		char line[maxlin], *sl = fgets_until(line, maxlin, f, '\n');
		if (!sl) break;
		struct cloud_polygon p;
		p.v = alloc_parse_doubles(maxlin, line, &p.n);
		p.n /= 2;
		cloud_add_polygon(m, p);
	}
	xfclose(f);
	m->low[0] = NAN;
	//update_uplow(m);
	return 0;
}
Exemplo n.º 10
0
Arquivo: main.c Projeto: KeenS/xfile
void
test_memio(void)
{
  xFILE *mem;
  char c;

  mem = xmopen();

  /* output */
  xfprintf(mem, "%d %s %c\n", 42, "hello", 'A');

  xrewind(mem);

  /* input */
  while ((c = xfgetc(mem)) != -1) {
    xputchar(c);
  }
  puts(" equals ?: \n42 hello A\n");

  assert(xfclose(mem) == 0);
}
Exemplo n.º 11
0
bool SrcFile_pop( SrcFile *self )
{
	FileStackElem *elem;
	
	if ( List_empty( self->file_stack ) )
		return false;
		
	if ( self->file != NULL )
		xfclose( self->file );
		
	elem = List_pop( self->file_stack );
	self->file		= elem->file;
	self->filename = elem->filename;
	self->line_filename = elem->line_filename;
	self->line_nr   = elem->line_nr;
	self->line_inc = elem->line_inc;
	self->is_c_source = elem->is_c_source;

	m_free( elem );
	return true;
}
Exemplo n.º 12
0
int glp_write_sol(glp_prob *lp, const char *fname)
{   XFILE *fp;
    int i, j, ret = 0;
    xprintf("Writing basic solution to `%s'...\n", fname);
    fp = xfopen(fname, "w");
    if (fp == NULL)
    {   xprintf("Unable to create `%s' - %s\n", fname, xerrmsg());
        ret = 1;
        goto done;
    }
    /* number of rows, number of columns */
    xfprintf(fp, "%d %d\n", lp->m, lp->n);
    /* primal status, dual status, objective value */
    xfprintf(fp, "%d %d %.*g\n", lp->pbs_stat, lp->dbs_stat, DBL_DIG,
             lp->obj_val);
    /* rows (auxiliary variables) */
    for (i = 1; i <= lp->m; i++)
    {   GLPROW *row = lp->row[i];
        /* status, primal value, dual value */
        xfprintf(fp, "%d %.*g %.*g\n", row->stat, DBL_DIG, row->prim,
                 DBL_DIG, row->dual);
    }
    /* columns (structural variables) */
    for (j = 1; j <= lp->n; j++)
    {   GLPCOL *col = lp->col[j];
        /* status, primal value, dual value */
        xfprintf(fp, "%d %.*g %.*g\n", col->stat, DBL_DIG, col->prim,
                 DBL_DIG, col->dual);
    }
    xfflush(fp);
    if (xferror(fp))
    {   xprintf("Write error on `%s' - %s\n", fname, xerrmsg());
        ret = 1;
        goto done;
    }
    xprintf("%d lines were written\n", 2 + lp->m + lp->n);
done:
    if (fp != NULL) xfclose(fp);
    return ret;
}
Exemplo n.º 13
0
void
se_pcre_init(const char *project, const char *index)
{
  static int initialized = 0;
  static char *iproject = NULL, *iindex = NULL;
  FILE *fp;
  static char glist_fname[_MAX_PATH];

  if (!project || !*project)
    project = "cdli";

  if (initialized && !strcmp(iproject,project) && !strcmp(iindex,index))
    return;
  if (iproject)
    free(iproject);
  if (iindex)
    free(iindex);
  iproject = strdup(project);
  iindex = strdup(index);
  initialized = 1;

  strcpy(glist_fname, se_file(project, index, "key.lst"));
  xaccess (glist_fname, R_OK, TRUE);
  glist_buf_len = fsize_t (glist_fname, NULL);
  glist_buf = malloc(glist_buf_len+3);
  *glist_buf = '\n';
  fp = xfopen (glist_fname, "rb");
  xfread (glist_fname, TRUE, &glist_buf[1], 1, glist_buf_len, fp);
  xfclose (glist_fname, fp);
  ++glist_buf_len;
  glist_buf[glist_buf_len++] = '\n';
  glist_buf[glist_buf_len++] = '\0';
  for (glist_begin = glist_buf+1; '#' == *glist_begin; ++glist_begin)
    {
      while ('\n' != *glist_begin)
	++glist_begin;
    }
  glist_len = glist_buf_len - (glist_begin - glist_buf);
}
Exemplo n.º 14
0
/* Open a profiled XFILE */
afs_uint32
xfopen_profile(XFILE * X, int flag, char *xname, char *profile)
{
    PFILE *PF;
    afs_uint32 err;

    PF = malloc(sizeof(*PF));
    if (!PF)
	return ENOMEM;
    memset(PF, 0, sizeof(*PF));

    err = xfopen(&PF->profile, O_RDWR | O_CREAT | O_TRUNC, profile);
    if (err) {
	free(PF);
	return err;
    }

    err = xfopen(&PF->content, flag, xname);
    if (err) {
	xfclose(&PF->profile);
	free(PF);
	return err;
    }

    memset(X, 0, sizeof(*X));
    X->refcon = PF;
    X->do_read = xf_PROFILE_do_read;
    X->do_write = xf_PROFILE_do_write;
    X->do_tell = xf_PROFILE_do_tell;
    X->do_close = xf_PROFILE_do_close;
    X->is_writable = PF->content.is_writable;
    if (PF->content.is_seekable) {
	X->is_seekable = 1;
	X->do_seek = xf_PROFILE_do_seek;
	X->do_skip = xf_PROFILE_do_skip;
    }
    xfprintf(&PF->profile, "OPEN %s\n", xname);
    return 0;
}
Exemplo n.º 15
0
static int
output_file(const char *message_file)
{
    unsigned char  buf[65536U];
    FILE          *fp;
    size_t         n;

    if ((fp = fopen(message_file, "rb")) == NULL) {
        exit_err(message_file);
    }
    while ((n = fread(buf, 1U, sizeof buf, fp)) > 0U) {
        if (fwrite(buf, 1U, n, stdout) != n) {
            exit_err(message_file);
        }
    }
    if (!feof(fp) || fflush(stdout) != 0) {
        exit_err(message_file);
    }
    xfclose(fp);

    return 0;
}
Exemplo n.º 16
0
File *
file_pop ()
{
  File *old = list_pop (file_stack_base);

  if (FALSE == old->stdio_flag)
    xfclose (old->name, old->fp);
  if (curr_file->unput_allocated)
    free (curr_file->unput_buffer);
  if (curr_file->buf_allocated)
    free (curr_file->buffer);
  free (old);

  if (0 == file_stack_base->count)
    {
      free (file_stack_base);
      file_stack_base = NULL;
      return NULL;
    }
  else
    return file_stack_base->last->data;
}
Exemplo n.º 17
0
static void write_newpgen_files(uint64_t p)
{
  FILE *file;
  char file_name[FILENAME_MAX+1];
  int t;
  uint32_t i, count, total;

  for (total = 0, i = 0; i < seq_count; i++)
  {
    assert(ABS(SEQ[i].c) == 1 || SEQ[i].k == 1);

    t = npg_format_index(SEQ[i].c);
    if (t == 0 || t == 1)
      snprintf(file_name, FILENAME_MAX, "t%d_b%" PRIu32 "_k%" PRIu64 ".%s",
               npg_formats[t].sieve_type, base, SEQ[i].k, NEWPGEN_EXT);
    else
      snprintf(file_name, FILENAME_MAX, "t%d_b%" PRIu32 "_k%" PRIu64 ".%s",
               npg_formats[t].sieve_type, base, ABS(SEQ[i].c), NEWPGEN_EXT);
    file_name[FILENAME_MAX] = '\0';

    if ((file = xfopen(file_name, "w", warning)) == NULL)
      continue;

    fprintf(file, "%"PRIu64":%c:1:%"PRIu32":%d\n",
            p, npg_formats[t].mode_char, base, npg_formats[t].mode_bits);
    count = seq_for_each_term(i,npg_formats[t].write_fun,file);

    if (seq_count == 1 || verbose > 1)
      report("Wrote %"PRIu32" term%s for sequence %s to NewPGen format file"
             " `%s'.", count, plural(count), seq_str(i), file_name);
    xfclose(file,file_name);
    total += count;
  }

  if (seq_count > 1 && verbose == 1) /* don't report twice */
    report("Wrote %"PRIu32" term%s for %"PRIu32" sequence%s to NewPGen format"
           " files t*_b%"PRIu32"_k*.%s.", total, plural(total),
           seq_count, plural(seq_count), base, NEWPGEN_EXT);
}
Exemplo n.º 18
0
void read_checkpoint(uint64_t pmin, uint64_t pmax)
{
  FILE *file;
  uint64_t p;

  if ((file = fopen(checkpoint_file_name,"r")) == NULL)
    return;

  if (fscanf(file,"pmin=%" SCNu64, &p) == 1)
  {
    if (p > pmin && p < pmax)
    {
      report("Resuming from checkpoint pmin=%" PRIu64 " in `%s'.",
             p, checkpoint_file_name);
      set_p_min(p,checkpoint_file_name);
    }
  }
  else
    error("Cannot read checkpoint from `%s'.", checkpoint_file_name);

  xfclose(file,checkpoint_file_name);
}
Exemplo n.º 19
0
static void write_abcd_file(uint64_t p)
{
  FILE *file;
  uint32_t seq, count;
  char file_name[FILENAME_MAX+1];

  snprintf(file_name, FILENAME_MAX, "sr_%"PRIu32".%s", base, ABCD_EXT);
  file_name[FILENAME_MAX] = '\0';
  if ((file = xfopen(file_name, "w", warning)) == NULL)
    return;

  abcd_p = p;
  for (count = 0, seq = 0; seq < seq_count; seq++)
  {
    fprintf(file, "ABCD %" PRIu64 "*%" PRIu32 "^$a%+" PRId64,
            SEQ[seq].k, base, SEQ[seq].c);
    abcd_n = UINT32_MAX;
    count += seq_for_each_term(seq,(kcn_app_t)write_abcd_delta,file);
  }

  report_wrote(count,seq_count,"ABCD",file_name);
  xfclose(file,file_name);
}
Exemplo n.º 20
0
int
main (int argc, char **argv)
{
  char *fn = NULL;
  List *files = list_create(LIST_SINGLE);
  while (NULL != (fn = fgets(fnbuf,_MAX_PATH,stdin)))
    {
      fn[strlen(fn)-1] = '\0';
      list_add(files,strdup(fn));
    }
  fnlist = malloc((1+files->count) * sizeof(const char *));
  findex = 0;
  list_exec(files,fn_expand);
  fnlist[findex] = NULL;

  kwic_fp = xfopen(kwic_fn,"b");
  unit_fp = xfopen(unit_f,"b");

  runexpatNS(i_list, fnlist, start_wm, end_wm, "|");

  xfclose(kwic_fn,kwic_fp;
  xfclose(unit_fn_kwic_fp);
}
Exemplo n.º 21
0
/**
 * @param {level} level Message log level
 * @param {format} format format of the message as used for printf
 * @param {...} Variables used in the message
 */
int	log_write(int level, const char *format, ...)
{
	FILE	*log_file;
	char	message[MAX_LINE_LEN];
	va_list	args;

	log_file = NULL;
	if (!log_check_level(level))
	{
		return 0;
	}

	if (xiniparser_getint("Logs:use_syslog", 0))
	{
		openlog(SYSLOG_IDENT, LOG_PID, LOG_DAEMON);
		va_start(args, format);
		vsyslog(level, format, args);
		va_end(args);
		closelog();
		return 0;
	}

	if ((log_file = log_open_file()) == NULL)
	{
		return -1;
	}

	va_start(args, format);
	if ((vsprintf(message, format, args)) > 0)
	{
		log_write_in(log_file, message);
	}

	va_end(args);
	xfclose(log_file);
	return 0;
}
Exemplo n.º 22
0
int glp_free_env(void)
{     ENV *env = tls_get_ptr();
      MEM *desc;
      /* check if the environment is active */
      if (env == NULL) return 1;
      /* check if the environment block is valid */
      if (env->magic != ENV_MAGIC)
      {  fprintf(stderr, "Invalid GLPK environment\n");
         fflush(stderr);
         abort();
      }
      /* close handles to shared libraries */
      if (env->h_odbc != NULL)
         xdlclose(env->h_odbc);
      if (env->h_mysql != NULL)
         xdlclose(env->h_mysql);
      /* close streams which are still open */
      while (env->file_ptr != NULL)
         xfclose(env->file_ptr);
      /* free memory blocks which are still allocated */
      while (env->mem_ptr != NULL)
      {  desc = env->mem_ptr;
         env->mem_ptr = desc->next;
         free(desc);
      }
      /* invalidate the environment block */
      env->magic = -1;
      /* free memory allocated to the environment block */
      free(env->term_buf);
      free(env->ioerr_msg);
      free(env);
      /* reset a pointer to the environment block */
      tls_set_ptr(NULL);
      /* termination successful */
      return 0;
}
Exemplo n.º 23
0
static void
read_all_cnf (kpathsea kpse)
{
  string *cnf_files;
  string *cnf;
  const_string cnf_path = kpathsea_init_format (kpse, kpse_cnf_format);

  kpse->cnf_hash = hash_create (CNF_HASH_SIZE);

  cnf_files = kpathsea_all_path_search (kpse, cnf_path, CNF_NAME);
  if (cnf_files && *cnf_files) {
    for (cnf = cnf_files; *cnf; cnf++) {
      string line;
      string msg;
      unsigned lineno = 0;
      FILE *cnf_file = xfopen (*cnf, FOPEN_R_MODE);
      if (kpse->record_input)
        kpse->record_input (*cnf);

      while ((line = read_line (cnf_file)) != NULL) {
        unsigned len;
        lineno++;
        len = strlen (line);
        /* Strip trailing spaces. */
        while (len > 0 && ISSPACE(line[len-1])) {
          line[len - 1] = 0;
          --len;
        }
        /* Concatenate consecutive lines that end with \.  */
        while (len > 0 && line[len - 1] == '\\') {
          string next_line = read_line (cnf_file);
          lineno++;
          line[len - 1] = 0;
          if (!next_line) {
            WARNING2 ("%s:%d: (kpathsea) Last line of file ends with \\",
                       *cnf, lineno);
          } else {
            string new_line;
            new_line = concat (line, next_line);
            free (line);
            line = new_line;
            len = strlen (line);
          }
        }

        msg = do_line (kpse, line);
        if (msg) {
          WARNING4 ("%s:%d: (kpathsea) %s on line: %s",
                    *cnf, lineno, msg, line);
        }
        free (line);
      }

      xfclose (cnf_file, *cnf);
      free (*cnf);
    }
    free (cnf_files);
  } else {
    string warn = getenv ("KPATHSEA_WARNING");
    if (!(warn && STREQ (warn, "0"))) {
      WARNING1
  ("kpathsea: configuration file texmf.cnf not found in these directories: %s",
        cnf_path);
    }
  }
}
Exemplo n.º 24
0
Arquivo: file.c Projeto: gapato/viking
VikLoadType_t a_file_load ( VikAggregateLayer *top, VikViewport *vp, const gchar *filename_or_uri )
{
  g_return_val_if_fail ( vp != NULL, LOAD_TYPE_READ_FAILURE );

  char *filename = (char *)filename_or_uri;
  if (strncmp(filename, "file://", 7) == 0) {
    // Consider replacing this with:
    // filename = g_filename_from_uri ( entry, NULL, NULL );
    // Since this doesn't support URIs properly (i.e. will failure if is it has %20 characters in it)
    filename = filename + 7;
    g_debug ( "Loading file %s from URI %s", filename, filename_or_uri );
  }
  FILE *f = xfopen ( filename );

  if ( ! f )
    return LOAD_TYPE_READ_FAILURE;

  VikLoadType_t load_answer = LOAD_TYPE_OTHER_SUCCESS;

  gchar *dirpath = g_path_get_dirname ( filename );
  // Attempt loading the primary file type first - our internal .vik file:
  if ( check_magic ( f, VIK_MAGIC ) )
  {
    if ( file_read ( top, f, dirpath, vp ) )
      load_answer = LOAD_TYPE_VIK_SUCCESS;
    else
      load_answer = LOAD_TYPE_VIK_FAILURE_NON_FATAL;
  }
  else if ( a_jpg_magic_check ( filename ) ) {
    if ( ! a_jpg_load_file ( top, filename, vp ) )
      load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
  }
  else
  {
	// For all other file types which consist of tracks, routes and/or waypoints,
	//  must be loaded into a new TrackWaypoint layer (hence it be created)
    gboolean success = TRUE; // Detect load failures - mainly to remove the layer created as it's not required

    VikLayer *vtl = vik_layer_create ( VIK_LAYER_TRW, vp, FALSE );
    vik_layer_rename ( vtl, a_file_basename ( filename ) );

    // In fact both kml & gpx files start the same as they are in xml
    if ( a_file_check_ext ( filename, ".kml" ) && check_magic ( f, GPX_MAGIC ) ) {
      // Implicit Conversion
      if ( ! ( success = a_babel_convert_from ( VIK_TRW_LAYER(vtl), "-i kml", filename, NULL, NULL, NULL ) ) ) {
        load_answer = LOAD_TYPE_GPSBABEL_FAILURE;
      }
    }
    // NB use a extension check first, as a GPX file header may have a Byte Order Mark (BOM) in it
    //    - which currently confuses our check_magic function
    else if ( a_file_check_ext ( filename, ".gpx" ) || check_magic ( f, GPX_MAGIC ) ) {
      if ( ! ( success = a_gpx_read_file ( VIK_TRW_LAYER(vtl), f ) ) ) {
        load_answer = LOAD_TYPE_GPX_FAILURE;
      }
    }
    else {
      // Try final supported file type
      if ( ! ( success = a_gpspoint_read_file ( VIK_TRW_LAYER(vtl), f, dirpath ) ) ) {
        // Failure here means we don't know how to handle the file
        load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
      }
    }
    g_free ( dirpath );

    // Clean up when we can't handle the file
    if ( ! success ) {
      // free up layer
      g_object_unref ( vtl );
    }
    else {
      // Complete the setup from the successful load
      vik_layer_post_read ( vtl, vp, TRUE );
      vik_aggregate_layer_add_layer ( top, vtl, FALSE );
      vik_trw_layer_auto_set_view ( VIK_TRW_LAYER(vtl), vp );
    }
  }
  xfclose(f);
  return load_answer;
}
Exemplo n.º 25
0
Arquivo: io.c Projeto: ewxrjk/nps
void xexit(int rc) {
  if(!rc)
    xfclose(stdout, "stdout");
  exit(rc);
}
Exemplo n.º 26
0
Arquivo: alias.c Projeto: oracc/oracc
/*#define PADDED_GRAPHEME_LEN 32*/
void
alias_index_aliases (const char *project,const char *index)
{
    const char *alias_fn, *alias_dir;
    FILE *alias_fp;
    Dbi_index *alias_dip;
    Uchar padded_grapheme[PADDED_GRAPHEME_LEN], head_grapheme[PADDED_GRAPHEME_LEN];
    Uchar *s, *t;
    int last_grapheme_len = PADDED_GRAPHEME_LEN;
    int line_num = 0;
    int hg_len = 0;

    alias_fn = strdup(se_file(project, index, "aliases"));
    alias_dir = se_dir(project,index);

    if (xaccess(alias_fn,W_OK|R_OK,0))
    {
        if (verbose)
            mwarning(NULL,"no aliases file %s; proceeding without aliasing",alias_fn);
        return;
    }

    alias_fp = xfopen (alias_fn, "r");
    alias_dip = dbi_create ("aliases", alias_dir, 1024, 1, DBI_BALK);
    dbi_set_cache (alias_dip, 32);
    while (NULL != (s = getline (alias_fp)))
    {
        if ('#' == *s)
            continue;

        if (!isspace(*s))
        {
            memset (head_grapheme, '\0', last_grapheme_len);
            t = head_grapheme;
            while (*s && !isspace(*s))
            {
                if (t - head_grapheme == PADDED_GRAPHEME_LEN)
                {
                    *t = '\0';
                    error (ewfile(alias_fn, line_num),
                           "%s...: grapheme too long (max %d chars)",
                           head_grapheme, PADDED_GRAPHEME_LEN-1);
                }
                *t++ = *s++;
            }
            *t++ = '\0';
            hg_len = t - head_grapheme;
            while (*s && isspace(*s))
                ++s;
        }
        else
        {
            do
                ++s;
            while (*s && isspace(*s));
        }
        while (*s)
        {
            t = padded_grapheme;
            while (*s && !isspace(*s))
            {
                if (t - padded_grapheme == PADDED_GRAPHEME_LEN)
                {
                    *t = '\0';
                    error (ewfile(alias_fn, line_num), "%s...: grapheme too long (max %d chars)",padded_grapheme,PADDED_GRAPHEME_LEN-1);
                }
                *t++ = *s++;
            }
            *t = '\0';
            last_grapheme_len = t - padded_grapheme;
            if (DBI_BALK == dbi_add (alias_dip, padded_grapheme, head_grapheme, hg_len))
                mwarning (NULL, "duplicate grapheme alias %s -> %s", padded_grapheme, head_grapheme);
            while (*s && isspace(*s))
                ++s;
        }
    }
    dbi_flush (alias_dip);
    xfclose (alias_fn, alias_fp);
}
Exemplo n.º 27
0
static void
output_skeleton (void)
{
  FILE *in;
  FILE *out;
  int filter_fd[2];
  char const *argv[6];
  pid_t pid;

  /* Compute the names of the package data dir and skeleton file.
     Test whether m4sugar.m4 is readable, to check for proper
     installation.  A faulty installation can cause deadlock, so a
     cheap sanity check is worthwhile.  */
  char const m4sugar[] = "m4sugar/m4sugar.m4";
  char *full_m4sugar;
  char *full_skeleton;
  char const *p;
  char const *m4 = (p = getenv ("M4")) ? p : M4;
  char const *pkgdatadir = (p = getenv ("BISON_PKGDATADIR")) ? p : PKGDATADIR;
  size_t skeleton_size = strlen (skeleton) + 1;
  size_t pkgdatadirlen = strlen (pkgdatadir);
  while (pkgdatadirlen && pkgdatadir[pkgdatadirlen - 1] == '/')
    pkgdatadirlen--;
  full_skeleton = xmalloc (pkgdatadirlen + 1
			   + (skeleton_size < sizeof m4sugar
			      ? sizeof m4sugar : skeleton_size));
  strcpy (full_skeleton, pkgdatadir);
  full_skeleton[pkgdatadirlen] = '/';
  strcpy (full_skeleton + pkgdatadirlen + 1, m4sugar);
  full_m4sugar = xstrdup (full_skeleton);
  strcpy (full_skeleton + pkgdatadirlen + 1, skeleton);
  xfclose (xfopen (full_m4sugar, "r"));

  /* Create an m4 subprocess connected to us via two pipes.  */

  if (trace_flag & trace_tools)
    fprintf (stderr, "running: %s %s - %s\n",
	     m4, full_m4sugar, full_skeleton);

  argv[0] = m4;
  argv[1] = full_m4sugar;
  argv[2] = "-";
  argv[3] = full_skeleton;
  argv[4] = trace_flag & trace_m4 ? "-dV" : NULL;
  argv[5] = NULL;

  init_subpipe ();
  pid = create_subpipe (argv, filter_fd);
  free (full_m4sugar);
  free (full_skeleton);

  out = fdopen (filter_fd[0], "w");
  if (! out)
    error (EXIT_FAILURE, get_errno (),
	   "fdopen");

  /* Output the definitions of all the muscles.  */
  fputs ("m4_init()\n", out);

  user_actions_output (out);
  merger_output (out);
  token_definitions_output (out);
  symbol_destructors_output (out);
  symbol_printers_output (out);

  muscles_m4_output (out);

  fputs ("m4_wrap([m4_divert_pop(0)])\n", out);
  fputs ("m4_divert_push(0)dnl\n", out);
  xfclose (out);

  /* Read and process m4's output.  */
  timevar_push (TV_M4);
  end_of_output_subpipe (pid, filter_fd);
  in = fdopen (filter_fd[1], "r");
  if (! in)
    error (EXIT_FAILURE, get_errno (),
	   "fdopen");
  scan_skel (in);
  xfclose (in);
  reap_subpipe (pid, m4);
  timevar_pop (TV_M4);
}
Exemplo n.º 28
0
int lpx_write_cpxlp(LPX *lp, const char *fname)
{     /* write problem data in CPLEX LP format */
      FILE *fp;
      int nrows, ncols, i, j, t, len, typx, flag, kind, *ind;
      double lb, ub, temp, *val;
      char line[1023+1], term[1023+1], rname[255+1], cname[255+1];
      print("lpx_write_cpxlp: writing problem data to `%s'...", fname);
      /* open the output text file */
      fp = xfopen(fname, "w");
      if (fp == NULL)
      {  print("lpx_write_cpxlp: unable to create `%s' - %s", fname,
            strerror(errno));
         goto fail;
      }
      /* determine the number of rows and columns */
      nrows = lpx_get_num_rows(lp);
      ncols = lpx_get_num_cols(lp);
      /* the problem should contain at least one row and one column */
      if (!(nrows > 0 && ncols > 0))
         fault("lpx_write_cpxlp: problem has no rows/columns");
      /* write problem name */
      {  const char *name = lpx_get_prob_name(lp);
         if (name == NULL) name = "Unknown";
         fprintf(fp, "\\* Problem: %s *\\\n", name);
         fprintf(fp, "\n");
      }
      /* allocate working arrays */
      ind = xcalloc(1+ncols, sizeof(int));
      val = xcalloc(1+ncols, sizeof(double));
      /* write the objective function definition and the constraints
         section */
      for (i = 0; i <= nrows; i++)
      {  if (i == 0)
         {  switch (lpx_get_obj_dir(lp))
            {  case LPX_MIN:
                  fprintf(fp, "Minimize\n");
                  break;
               case LPX_MAX:
                  fprintf(fp, "Maximize\n");
                  break;
               default:
                  xassert(lp != lp);
            }
         }
         else if (i == 1)
         {  temp = lpx_get_obj_coef(lp, 0);
            if (temp != 0.0)
               fprintf(fp, "\\* constant term = %.*g *\\\n", DBL_DIG,
                  temp);
            fprintf(fp, "\n");
            fprintf(fp, "Subject To\n");
         }
         row_name(lp, i, rname);
         if (i == 0)
         {  len = 0;
            for (j = 1; j <= ncols; j++)
            {  temp = lpx_get_obj_coef(lp, j);
               if (temp != 0.0)
                  len++, ind[len] = j, val[len] = temp;
            }
         }
         else
         {  lpx_get_row_bnds(lp, i, &typx, &lb, &ub);
            if (typx == LPX_FR) continue;
            len = lpx_get_mat_row(lp, i, ind, val);
         }
         flag = 0;
more:    if (!flag)
            sprintf(line, " %s:", rname);
         else
            sprintf(line, " %*s ", strlen(rname), "");
         for (t = 1; t <= len; t++)
         {  col_name(lp, ind[t], cname);
            if (val[t] == +1.0)
               sprintf(term, " + %s", cname);
            else if (val[t] == -1.0)
               sprintf(term, " - %s", cname);
            else if (val[t] > 0.0)
               sprintf(term, " + %.*g %s", DBL_DIG, +val[t], cname);
            else if (val[t] < 0.0)
               sprintf(term, " - %.*g %s", DBL_DIG, -val[t], cname);
            else
               xassert(lp != lp);
            if (strlen(line) + strlen(term) > 72)
               fprintf(fp, "%s\n", line), line[0] = '\0';
            strcat(line, term);
         }
         if (len == 0)
         {  /* empty row */
            sprintf(term, " 0 %s", col_name(lp, 1, cname));
            strcat(line, term);
         }
         if (i > 0)
         {  switch (typx)
            {  case LPX_LO:
               case LPX_DB:
                  sprintf(term, " >= %.*g", DBL_DIG, lb);
                  break;
               case LPX_UP:
                  sprintf(term, " <= %.*g", DBL_DIG, ub);
                  break;
               case LPX_FX:
                  sprintf(term, " = %.*g", DBL_DIG, lb);
                  break;
               default:
                  xassert(typx != typx);
            }
            if (strlen(line) + strlen(term) > 72)
               fprintf(fp, "%s\n", line), line[0] = '\0';
            strcat(line, term);
         }
         fprintf(fp, "%s\n", line);
         if (i > 0 && typx == LPX_DB)
         {  /* double-bounded row needs a copy for its upper bound */
            flag = 1;
            typx = LPX_UP;
            goto more;
         }
      }
      /* free working arrays */
      xfree(ind);
      xfree(val);
      /* write the bounds section */
      flag = 0;
      for (j = 1; j <= ncols; j++)
      {  col_name(lp, j, cname);
         lpx_get_col_bnds(lp, j, &typx, &lb, &ub);
         if (typx == LPX_LO && lb == 0.0) continue;
         if (!flag)
         {  fprintf(fp, "\n");
            fprintf(fp, "Bounds\n");
            flag = 1;
         }
         switch (typx)
         {  case LPX_FR:
               fprintf(fp, " %s free\n", cname);
               break;
            case LPX_LO:
               fprintf(fp, " %s >= %.*g\n", cname, DBL_DIG, lb);
               break;
            case LPX_UP:
               fprintf(fp, " %s <= %.*g\n", cname, DBL_DIG, ub);
               break;
            case LPX_DB:
               fprintf(fp, " %.*g <= %s <= %.*g\n", DBL_DIG, lb, cname,
                  DBL_DIG, ub);
               break;
            case LPX_FX:
               fprintf(fp, " %s = %.*g\n", cname, DBL_DIG, lb);
               break;
            default:
               xassert(typx != typx);
         }
      }
      /* write the general section */
      if (lpx_get_class(lp) == LPX_MIP)
      {  flag = 0;
         for (j = 1; j <= ncols; j++)
         {  kind = lpx_get_col_kind(lp, j);
            if (kind == LPX_CV) continue;
            xassert(kind == LPX_IV);
            if (!flag)
            {  fprintf(fp, "\n");
               fprintf(fp, "Generals\n");
               flag = 1;
            }
            fprintf(fp, " %s\n", col_name(lp, j, cname));
         }
      }
      /* write the end keyword */
      fprintf(fp, "\n");
      fprintf(fp, "End\n");
      /* close the output text file */
      fflush(fp);
      if (ferror(fp))
      {  print("lpx_write_cpxlp: write error on `%s' - %s", fname,
            strerror(errno));
         goto fail;
      }
      xfclose(fp);
      /* return to the calling program */
      return 0;
fail: /* the operation failed */
      if (fp != NULL) xfclose(fp);
      return 1;
}
Exemplo n.º 29
0
LPX *lpx_read_cpxlp(const char *fname)
{     /* read problem data in CPLEX LP format */
      struct dsa _dsa, *dsa = &_dsa;
      if (setjmp(dsa->jump)) goto fail;
      dsa->lp = NULL;
      dsa->fname = fname;
      dsa->fp = NULL;
      dsa->count = 0;
      dsa->c = '\n';
      dsa->token = T_EOF;
      dsa->image[0] = '\0';
      dsa->imlen = 0;
      dsa->value = 0.0;
      dsa->n_max = 100;
      dsa->map = xcalloc(1+dsa->n_max, sizeof(int));
      memset(&dsa->map[1], 0, dsa->n_max * sizeof(int));
      dsa->ind = xcalloc(1+dsa->n_max, sizeof(int));
      dsa->val = xcalloc(1+dsa->n_max, sizeof(double));
      dsa->lb = xcalloc(1+dsa->n_max, sizeof(double));
      dsa->ub = xcalloc(1+dsa->n_max, sizeof(double));
      print("lpx_read_cpxlp: reading problem data from `%s'...",
         dsa->fname);
      dsa->fp = xfopen(dsa->fname, "r");
      if (dsa->fp == NULL)
      {  print("lpx_read_cpxlp: unable to open `%s' - %s", dsa->fname,
            strerror(errno));
         goto fail;
      }
      dsa->lp = lpx_create_prob();
      lpx_create_index(dsa->lp);
#if 0
      /* read very first character */
      read_char(dsa);
#endif
      /* scan very first token */
      scan_token(dsa);
      /* parse definition of the objective function */
      if (!(dsa->token == T_MINIMIZE || dsa->token == T_MAXIMIZE))
         fatal(dsa, "`minimize' or `maximize' keyword missing");
      parse_objective(dsa);
      /* parse constraints section */
      if (dsa->token != T_SUBJECT_TO)
         fatal(dsa, "constraints section missing");
      parse_constraints(dsa);
      /* parse optional bounds section */
      if (dsa->token == T_BOUNDS) parse_bounds(dsa);
      /* parse optional general, integer, and binary sections */
      while (dsa->token == T_GENERAL ||
             dsa->token == T_INTEGER ||
             dsa->token == T_BINARY) parse_integer(dsa);
      /* check for the keyword 'end' */
      if (dsa->token == T_END)
         scan_token(dsa);
      else if (dsa->token == T_EOF)
         print("%s:%d: warning: keyword `end' missing", dsa->fname,
            dsa->count);
      else
         fatal(dsa, "symbol `%s' in wrong position", dsa->image);
      /* nothing must follow the keyword 'end' (except comments) */
      if (dsa->token != T_EOF)
         fatal(dsa, "extra symbol(s) detected beyond `end'");
      /* set bounds of variables */
      {  int j, type;
         double lb, ub;
         for (j = lpx_get_num_cols(dsa->lp); j >= 1; j--)
         {  lb = dsa->lb[j];
            ub = dsa->ub[j];
            if (lb == +DBL_MAX) lb = 0.0;      /* default lb */
            if (ub == -DBL_MAX) ub = +DBL_MAX; /* default ub */
            if (lb == -DBL_MAX && ub == +DBL_MAX)
               type = LPX_FR;
            else if (ub == +DBL_MAX)
               type = LPX_LO;
            else if (lb == -DBL_MAX)
               type = LPX_UP;
            else if (lb != ub)
               type = LPX_DB;
            else
               type = LPX_FX;
            lpx_set_col_bnds(dsa->lp, j, type, lb, ub);
         }
      }
      /* print some statistics */
      {  int m = lpx_get_num_rows(dsa->lp);
         int n = lpx_get_num_cols(dsa->lp);
         int nnz = lpx_get_num_nz(dsa->lp);
         print("lpx_read_cpxlp: %d row%s, %d column%s, %d non-zero%s",
            m, m == 1 ? "" : "s", n, n == 1 ? "" : "s", nnz, nnz == 1 ?
            "" : "s");
      }
      if (lpx_get_class(dsa->lp) == LPX_MIP)
      {  int ni = lpx_get_num_int(dsa->lp);
         int nb = lpx_get_num_bin(dsa->lp);
         char s[50];
         if (nb == 0)
            strcpy(s, "none of");
         else if (ni == 1 && nb == 1)
            strcpy(s, "");
         else if (nb == 1)
            strcpy(s, "one of");
         else if (nb == ni)
            strcpy(s, "all of");
         else
            sprintf(s, "%d of", nb);
         print("lpx_read_cpxlp: %d integer column%s, %s which %s binary"
            , ni, ni == 1 ? "" : "s", s, nb == 1 ? "is" : "are");
      }
      print("lpx_read_cpxlp: %d lines were read", dsa->count);
      xfclose(dsa->fp);
      xfree(dsa->map);
      xfree(dsa->ind);
      xfree(dsa->val);
      xfree(dsa->lb);
      xfree(dsa->ub);
      lpx_delete_index(dsa->lp);
      lpx_order_matrix(dsa->lp);
      return dsa->lp;
fail: if (dsa->lp != NULL) lpx_delete_prob(dsa->lp);
      if (dsa->fp != NULL) xfclose(dsa->fp);
      if (dsa->map != NULL) xfree(dsa->map);
      if (dsa->ind != NULL) xfree(dsa->ind);
      if (dsa->val != NULL) xfree(dsa->val);
      if (dsa->lb != NULL) xfree(dsa->lb);
      if (dsa->ub != NULL) xfree(dsa->ub);
      return NULL;
}
Exemplo n.º 30
0
int lpx_print_prob(LPX *lp, const char *fname)
{     XFILE *fp;
      int m, n, mip, i, j, len, t, type, *ndx;
      double coef, lb, ub, *val;
      char *str, name[255+1];
      xprintf("lpx_write_prob: writing problem data to `%s'...\n",
         fname);
      fp = xfopen(fname, "w");
      if (fp == NULL)
      {  xprintf("lpx_write_prob: unable to create `%s' - %s\n",
            fname, strerror(errno));
         goto fail;
      }
      m = lpx_get_num_rows(lp);
      n = lpx_get_num_cols(lp);
      mip = (lpx_get_class(lp) == LPX_MIP);
      str = (void *)lpx_get_prob_name(lp);
      xfprintf(fp, "Problem:    %s\n", str == NULL ? "(unnamed)" : str);
      xfprintf(fp, "Class:      %s\n", !mip ? "LP" : "MIP");
      xfprintf(fp, "Rows:       %d\n", m);
      if (!mip)
         xfprintf(fp, "Columns:    %d\n", n);
      else
         xfprintf(fp, "Columns:    %d (%d integer, %d binary)\n",
            n, lpx_get_num_int(lp), lpx_get_num_bin(lp));
      xfprintf(fp, "Non-zeros:  %d\n", lpx_get_num_nz(lp));
      xfprintf(fp, "\n");
      xfprintf(fp, "*** OBJECTIVE FUNCTION ***\n");
      xfprintf(fp, "\n");
      switch (lpx_get_obj_dir(lp))
      {  case LPX_MIN:
            xfprintf(fp, "Minimize:");
            break;
         case LPX_MAX:
            xfprintf(fp, "Maximize:");
            break;
         default:
            xassert(lp != lp);
      }
      str = (void *)lpx_get_obj_name(lp);
      xfprintf(fp, " %s\n", str == NULL ? "(unnamed)" : str);
      coef = lpx_get_obj_coef(lp, 0);
      if (coef != 0.0)
         xfprintf(fp, "%*.*g %s\n", DBL_DIG+7, DBL_DIG, coef,
            "(constant term)");
      for (i = 1; i <= m; i++)
#if 0
      {  coef = lpx_get_row_coef(lp, i);
#else
      {  coef = 0.0;
#endif
         if (coef != 0.0)
            xfprintf(fp, "%*.*g %s\n", DBL_DIG+7, DBL_DIG, coef,
               row_name(lp, i, name));
      }
      for (j = 1; j <= n; j++)
      {  coef = lpx_get_obj_coef(lp, j);
         if (coef != 0.0)
            xfprintf(fp, "%*.*g %s\n", DBL_DIG+7, DBL_DIG, coef,
               col_name(lp, j, name));
      }
      xfprintf(fp, "\n");
      xfprintf(fp, "*** ROWS (CONSTRAINTS) ***\n");
      ndx = xcalloc(1+n, sizeof(int));
      val = xcalloc(1+n, sizeof(double));
      for (i = 1; i <= m; i++)
      {  xfprintf(fp, "\n");
         xfprintf(fp, "Row %d: %s", i, row_name(lp, i, name));
         lpx_get_row_bnds(lp, i, &type, &lb, &ub);
         switch (type)
         {  case LPX_FR:
               xfprintf(fp, " free");
               break;
            case LPX_LO:
               xfprintf(fp, " >= %.*g", DBL_DIG, lb);
               break;
            case LPX_UP:
               xfprintf(fp, " <= %.*g", DBL_DIG, ub);
               break;
            case LPX_DB:
               xfprintf(fp, " >= %.*g <= %.*g", DBL_DIG, lb, DBL_DIG,
                  ub);
               break;
            case LPX_FX:
               xfprintf(fp, " = %.*g", DBL_DIG, lb);
               break;
            default:
               xassert(type != type);
         }
         xfprintf(fp, "\n");
#if 0
         coef = lpx_get_row_coef(lp, i);
#else
         coef = 0.0;
#endif
         if (coef != 0.0)
            xfprintf(fp, "%*.*g %s\n", DBL_DIG+7, DBL_DIG, coef,
               "(objective)");
         len = lpx_get_mat_row(lp, i, ndx, val);
         for (t = 1; t <= len; t++)
            xfprintf(fp, "%*.*g %s\n", DBL_DIG+7, DBL_DIG, val[t],
               col_name(lp, ndx[t], name));
      }
      xfree(ndx);
      xfree(val);
      xfprintf(fp, "\n");
      xfprintf(fp, "*** COLUMNS (VARIABLES) ***\n");
      ndx = xcalloc(1+m, sizeof(int));
      val = xcalloc(1+m, sizeof(double));
      for (j = 1; j <= n; j++)
      {  xfprintf(fp, "\n");
         xfprintf(fp, "Col %d: %s", j, col_name(lp, j, name));
         if (mip)
         {  switch (lpx_get_col_kind(lp, j))
            {  case LPX_CV:
                  break;
               case LPX_IV:
                  xfprintf(fp, " integer");
                  break;
               default:
                  xassert(lp != lp);
            }
         }
         lpx_get_col_bnds(lp, j, &type, &lb, &ub);
         switch (type)
         {  case LPX_FR:
               xfprintf(fp, " free");
               break;
            case LPX_LO:
               xfprintf(fp, " >= %.*g", DBL_DIG, lb);
               break;
            case LPX_UP:
               xfprintf(fp, " <= %.*g", DBL_DIG, ub);
               break;
            case LPX_DB:
               xfprintf(fp, " >= %.*g <= %.*g", DBL_DIG, lb, DBL_DIG,
                  ub);
               break;
            case LPX_FX:
               xfprintf(fp, " = %.*g", DBL_DIG, lb);
               break;
            default:
               xassert(type != type);
         }
         xfprintf(fp, "\n");
         coef = lpx_get_obj_coef(lp, j);
         if (coef != 0.0)
            xfprintf(fp, "%*.*g %s\n", DBL_DIG+7, DBL_DIG, coef,
               "(objective)");
         len = lpx_get_mat_col(lp, j, ndx, val);
         for (t = 1; t <= len; t++)
            xfprintf(fp, "%*.*g %s\n", DBL_DIG+7, DBL_DIG, val[t],
               row_name(lp, ndx[t], name));
      }
      xfree(ndx);
      xfree(val);
      xfprintf(fp, "\n");
      xfprintf(fp, "End of output\n");
      xfflush(fp);
      if (xferror(fp))
      {  xprintf("lpx_write_prob: write error on `%s' - %s\n", fname,
            strerror(errno));
         goto fail;
      }
      xfclose(fp);
      return 0;
fail: if (fp != NULL) xfclose(fp);
      return 1;
}

#undef row_name
#undef col_name

/*----------------------------------------------------------------------
-- lpx_print_sol - write LP problem solution in printable format.
--
-- *Synopsis*
--
-- #include "glplpx.h"
-- int lpx_print_sol(LPX *lp, char *fname);
--
-- *Description*
--
-- The routine lpx_print_sol writes the current basic solution of an LP
-- problem, which is specified by the pointer lp, to a text file, whose
-- name is the character string fname, in printable format.
--
-- Information reported by the routine lpx_print_sol is intended mainly
-- for visual analysis.
--
-- *Returns*
--
-- If the operation was successful, the routine returns zero. Otherwise
-- the routine prints an error message and returns non-zero. */

int lpx_print_sol(LPX *lp, const char *fname)
{     XFILE *fp;
      int what, round;
      xprintf(
         "lpx_print_sol: writing LP problem solution to `%s'...\n",
         fname);
      fp = xfopen(fname, "w");
      if (fp == NULL)
      {  xprintf("lpx_print_sol: can't create `%s' - %s\n", fname,
            strerror(errno));
         goto fail;
      }
      /* problem name */
      {  const char *name;
         name = lpx_get_prob_name(lp);
         if (name == NULL) name = "";
         xfprintf(fp, "%-12s%s\n", "Problem:", name);
      }
      /* number of rows (auxiliary variables) */
      {  int nr;
         nr = lpx_get_num_rows(lp);
         xfprintf(fp, "%-12s%d\n", "Rows:", nr);
      }
      /* number of columns (structural variables) */
      {  int nc;
         nc = lpx_get_num_cols(lp);
         xfprintf(fp, "%-12s%d\n", "Columns:", nc);
      }
      /* number of non-zeros (constraint coefficients) */
      {  int nz;
         nz = lpx_get_num_nz(lp);
         xfprintf(fp, "%-12s%d\n", "Non-zeros:", nz);
      }
      /* solution status */
      {  int status;
         status = lpx_get_status(lp);
         xfprintf(fp, "%-12s%s\n", "Status:",
            status == LPX_OPT    ? "OPTIMAL" :
            status == LPX_FEAS   ? "FEASIBLE" :
            status == LPX_INFEAS ? "INFEASIBLE (INTERMEDIATE)" :
            status == LPX_NOFEAS ? "INFEASIBLE (FINAL)" :
            status == LPX_UNBND  ? "UNBOUNDED" :
            status == LPX_UNDEF  ? "UNDEFINED" : "???");
      }
      /* objective function */
      {  char *name;
         int dir;
         double obj;
         name = (void *)lpx_get_obj_name(lp);
         dir = lpx_get_obj_dir(lp);
         obj = lpx_get_obj_val(lp);
         xfprintf(fp, "%-12s%s%s%.10g %s\n", "Objective:",
            name == NULL ? "" : name,
            name == NULL ? "" : " = ", obj,
            dir == LPX_MIN ? "(MINimum)" :
            dir == LPX_MAX ? "(MAXimum)" : "(" "???" ")");
      }
      /* main sheet */
      for (what = 1; what <= 2; what++)
      {  int mn, ij;
         xfprintf(fp, "\n");
         xfprintf(fp, "   No. %-12s St   Activity     Lower bound   Upp"
            "er bound    Marginal\n",
            what == 1 ? "  Row name" : "Column name");
         xfprintf(fp, "------ ------------ -- ------------- -----------"
            "-- ------------- -------------\n");
         mn = (what == 1 ? lpx_get_num_rows(lp) : lpx_get_num_cols(lp));
         for (ij = 1; ij <= mn; ij++)
         {  const char *name;
            int typx, tagx;
            double lb, ub, vx, dx;
            if (what == 1)
            {  name = lpx_get_row_name(lp, ij);
               if (name == NULL) name = "";
               lpx_get_row_bnds(lp, ij, &typx, &lb, &ub);
               round = lpx_get_int_parm(lp, LPX_K_ROUND);
               lpx_set_int_parm(lp, LPX_K_ROUND, 1);
               lpx_get_row_info(lp, ij, &tagx, &vx, &dx);
               lpx_set_int_parm(lp, LPX_K_ROUND, round);
            }
            else
            {  name = lpx_get_col_name(lp, ij);
               if (name == NULL) name = "";
               lpx_get_col_bnds(lp, ij, &typx, &lb, &ub);
               round = lpx_get_int_parm(lp, LPX_K_ROUND);
               lpx_set_int_parm(lp, LPX_K_ROUND, 1);
               lpx_get_col_info(lp, ij, &tagx, &vx, &dx);
               lpx_set_int_parm(lp, LPX_K_ROUND, round);
            }
            /* row/column ordinal number */
            xfprintf(fp, "%6d ", ij);
            /* row column/name */
            if (strlen(name) <= 12)
               xfprintf(fp, "%-12s ", name);
            else
               xfprintf(fp, "%s\n%20s", name, "");
            /* row/column status */
            xfprintf(fp, "%s ",
               tagx == LPX_BS ? "B " :
               tagx == LPX_NL ? "NL" :
               tagx == LPX_NU ? "NU" :
               tagx == LPX_NF ? "NF" :
               tagx == LPX_NS ? "NS" : "??");
            /* row/column primal activity */
            xfprintf(fp, "%13.6g ", vx);
            /* row/column lower bound */
            if (typx == LPX_LO || typx == LPX_DB || typx == LPX_FX)
               xfprintf(fp, "%13.6g ", lb);
            else
               xfprintf(fp, "%13s ", "");
            /* row/column upper bound */
            if (typx == LPX_UP || typx == LPX_DB)
               xfprintf(fp, "%13.6g ", ub);
            else if (typx == LPX_FX)
               xfprintf(fp, "%13s ", "=");
            else
               xfprintf(fp, "%13s ", "");
            /* row/column dual activity */
            if (tagx != LPX_BS)
            {  if (dx == 0.0)
                  xfprintf(fp, "%13s", "< eps");
               else
                  xfprintf(fp, "%13.6g", dx);
            }
            /* end of line */
            xfprintf(fp, "\n");
         }
      }
      xfprintf(fp, "\n");
#if 1
      if (lpx_get_prim_stat(lp) != LPX_P_UNDEF &&
          lpx_get_dual_stat(lp) != LPX_D_UNDEF)
      {  int m = lpx_get_num_rows(lp);
         LPXKKT kkt;
         xfprintf(fp, "Karush-Kuhn-Tucker optimality conditions:\n\n");
         lpx_check_kkt(lp, 1, &kkt);
         xfprintf(fp, "KKT.PE: max.abs.err. = %.2e on row %d\n",
            kkt.pe_ae_max, kkt.pe_ae_row);
         xfprintf(fp, "        max.rel.err. = %.2e on row %d\n",
            kkt.pe_re_max, kkt.pe_re_row);
         switch (kkt.pe_quality)
         {  case 'H':
               xfprintf(fp, "        High quality\n");
               break;
            case 'M':
               xfprintf(fp, "        Medium quality\n");
               break;
            case 'L':
               xfprintf(fp, "        Low quality\n");
               break;
            default:
               xfprintf(fp, "        PRIMAL SOLUTION IS WRONG\n");
               break;
         }
         xfprintf(fp, "\n");
         xfprintf(fp, "KKT.PB: max.abs.err. = %.2e on %s %d\n",
            kkt.pb_ae_max, kkt.pb_ae_ind <= m ? "row" : "column",
            kkt.pb_ae_ind <= m ? kkt.pb_ae_ind : kkt.pb_ae_ind - m);
         xfprintf(fp, "        max.rel.err. = %.2e on %s %d\n",
            kkt.pb_re_max, kkt.pb_re_ind <= m ? "row" : "column",
            kkt.pb_re_ind <= m ? kkt.pb_re_ind : kkt.pb_re_ind - m);
         switch (kkt.pb_quality)
         {  case 'H':
               xfprintf(fp, "        High quality\n");
               break;
            case 'M':
               xfprintf(fp, "        Medium quality\n");
               break;
            case 'L':
               xfprintf(fp, "        Low quality\n");
               break;
            default:
               xfprintf(fp, "        PRIMAL SOLUTION IS INFEASIBLE\n");
               break;
         }
         xfprintf(fp, "\n");
         xfprintf(fp, "KKT.DE: max.abs.err. = %.2e on column %d\n",
            kkt.de_ae_max, kkt.de_ae_col);
         xfprintf(fp, "        max.rel.err. = %.2e on column %d\n",
            kkt.de_re_max, kkt.de_re_col);
         switch (kkt.de_quality)
         {  case 'H':
               xfprintf(fp, "        High quality\n");
               break;
            case 'M':
               xfprintf(fp, "        Medium quality\n");
               break;
            case 'L':
               xfprintf(fp, "        Low quality\n");
               break;
            default:
               xfprintf(fp, "        DUAL SOLUTION IS WRONG\n");
               break;
         }
         xfprintf(fp, "\n");
         xfprintf(fp, "KKT.DB: max.abs.err. = %.2e on %s %d\n",
            kkt.db_ae_max, kkt.db_ae_ind <= m ? "row" : "column",
            kkt.db_ae_ind <= m ? kkt.db_ae_ind : kkt.db_ae_ind - m);
         xfprintf(fp, "        max.rel.err. = %.2e on %s %d\n",
            kkt.db_re_max, kkt.db_re_ind <= m ? "row" : "column",
            kkt.db_re_ind <= m ? kkt.db_re_ind : kkt.db_re_ind - m);
         switch (kkt.db_quality)
         {  case 'H':
               xfprintf(fp, "        High quality\n");
               break;
            case 'M':
               xfprintf(fp, "        Medium quality\n");
               break;
            case 'L':
               xfprintf(fp, "        Low quality\n");
               break;
            default:
               xfprintf(fp, "        DUAL SOLUTION IS INFEASIBLE\n");
               break;
         }
         xfprintf(fp, "\n");
      }
#endif
#if 1
      if (lpx_get_status(lp) == LPX_UNBND)
      {  int m = lpx_get_num_rows(lp);
         int k = lpx_get_ray_info(lp);
         xfprintf(fp, "Unbounded ray: %s %d\n",
            k <= m ? "row" : "column", k <= m ? k : k - m);
         xfprintf(fp, "\n");
      }
#endif
      xfprintf(fp, "End of output\n");
      xfflush(fp);
      if (xferror(fp))
      {  xprintf("lpx_print_sol: can't write to `%s' - %s\n", fname,
            strerror(errno));
         goto fail;
      }
      xfclose(fp);
      return 0;
fail: if (fp != NULL) xfclose(fp);
      return 1;
}