Ejemplo n.º 1
0
// -----------------------------------------------------------------------------
void
dotest (bool shuffle_) {
  void *ptrs[20];
  uint16_t i;

  dprintf ("allocating\n");
  showmem();
  for (i = 0; i < sizeof (ptrs) / sizeof (ptrs[0]); i++) {

    ptrs[i] = malloc (20);
    showmem();
  }

  if (shuffle_) {

    shuffle (ptrs, sizeof (ptrs) / sizeof (ptrs[0]));
  }

  dprintf ("freeing\n");
  for (i = 0; i < sizeof (ptrs) / sizeof (ptrs[0]); i++) {

    free (ptrs[i]);
    showmem();
  }
}
Ejemplo n.º 2
0
static void error (int code, ...)
{                               /* --- print an error message */
  #ifndef QUIET                 /* if not quiet version */
  va_list    args;              /* list of variable arguments */
  const char *msg;              /* error message */

  assert(prgname);              /* check the program name */
  if (code < E_UNKNOWN) code = E_UNKNOWN;
  if (code < 0) {               /* if to report an error, */
    msg = errmsgs[-code];       /* get the error message */
    if (!msg) msg = errmsgs[-E_UNKNOWN];
    fprintf(stderr, "\n%s: ", prgname);
    va_start(args, code);       /* get variable arguments */
    vfprintf(stderr, msg, args);/* print error message */
    va_end(args);               /* end argument evaluation */
  }
  #endif
  #ifndef NDEBUG                /* if debug version */
  if (istree)  ist_delete(istree);   /* clean up memory */
  if (tatree)  tat_delete(tatree);   /* and close files */
  if (taset)   tas_delete(taset, 0);
  if (itemset) is_delete(itemset);
  if (in  && (in  != stdin))  fclose(in);
  if (out && (out != stdout)) fclose(out);
  #endif
  #ifdef STORAGE                /* if storage debugging */
  showmem("at end of program"); /* check memory usage */
  #endif
  exit(code);                   /* abort the program */
}  /* error() */
Ejemplo n.º 3
0
static void error (int code, ...)
{                               /* --- print error message */
  va_list    args;              /* list of variable arguments */
  const char *msg;              /* error message */

  assert(prgname);              /* check the program name */
  if (code < E_UNKNOWN) code = E_UNKNOWN;
  if (code < 0) {               /* if to report an error, */
    msg = errmsgs[-code];       /* get error message */
    if (!msg) msg = errmsgs[-E_UNKNOWN];
    fprintf(stderr, "\n%s: ", prgname);
    va_start(args, code);       /* get variable arguments */
    vfprintf(stderr, msg, args);/* print error message */
    va_end(args);               /* end argument evaluation */
  }
  #ifndef NDEBUG
  if (nbc)    nbc_delete(nbc, 0);
  if (fbc)    fbc_delete(fbc, 0);
  if (attset) as_delete(attset);   /* clean up memory */
  if (scan)   sc_delete(scan);     /* and close files */
  if (out && (out != stdout)) fclose(out);
  #endif
  #ifdef STORAGE
  showmem("at end of program"); /* check memory usage */
  #endif
  exit(code);                   /* abort programm */
}  /* error() */
static void error (int code, ...)
{                               
  #ifndef QUIET                
  va_list    args;           
  const char *msg;            

  assert(prgname);            
  if (code < E_UNKNOWN) code = E_UNKNOWN;
  if (code < 0) {              
    msg = errmsgs[-code];      
    if (!msg) msg = errmsgs[-E_UNKNOWN];
    fprintf(stderr, "\n%s: ", prgname);
    va_start(args, code);      
    vfprintf(stderr, msg, args);
    va_end(args);               
  }
  #endif
  #ifndef NDEBUG                
  if (map)    free(map);        
  if (isrep)  isr_delete(isrep, 0); 
  if (istree) ist_delete(istree);
  if (tatree) tt_delete(tatree, 0);
  if (tabag)  tb_delete(tabag, 0);
  if (ibase)  ib_delete(ibase);
  if (in  && (in  != stdin))  fclose(in);
  if (out && (out != stdout)) fclose(out);
  #endif
  #ifdef STORAGE       
  showmem("at end of program"); 
  #endif
  exit(code);                  
}  /* error() */
Ejemplo n.º 5
0
void mdiskgo()
{
   Z80 &cpu = CpuMgr.Cpu();
   if (editor == ED_MEM) return;
   for (;;) {
      *(unsigned*)str = mem_disk + 'A';
      if (!inputhex(mem_x+5, mem_y-1, 1, true)) return;
      if (*str >= 'A' && *str <= 'D') break;
   }
   mem_disk = *str-'A'; showmem();
   unsigned x = input2(mem_x+12, mem_y-1, mem_track);
   if (x == -1) return;
   mem_track = x;
   if (editor == ED_PHYS) return;
   showmem();
   // enter sector
   for (;;) {
      findsector(cpu.mem_curs); x = input2(mem_x+20, mem_y-1, sector);
      if (x == -1) return; if (x < edited_track.s) break;
   }
   for (cpu.mem_curs = 0; x; x--) cpu.mem_curs += edited_track.hdr[x-1].datlen;
}
Ejemplo n.º 6
0
void show_prof(void)
{
	int n,m;
	double proz;
	int tab[100];
#ifdef BIGPROF
	unsigned long long total=0;
#endif

	for (n=0; n<100; n++) {
		tab[n]=n;
	}

	qsort(tab,100,sizeof(int),profsort);

	xlog("----- Profile: -----");

	for (n=1; n<100; n++) {
		m=tab[n];
		if (!proftab[m].cycles) break;
		proz=100.0/proftab[0].cycles*proftab[m].cycles;
		if (proz<0.1) break;
                xlog("%-13.13s %5.2f%%",profname[m],proz);
	}
	xlog("--------------------");	
	showmem();
#ifdef BIGPROF
	
	qsort(prof,maxprof,sizeof(struct profile),profcomp);
	
	for (n=0; n<maxprof; n++) if (!prof[n].task[1]) total+=prof[n].cycles;
	
	for (n=0; n<maxprof; n++) {
		for (m=0; m<10 && prof[n].task[m]; m++) {
			printf("%s ",profname[prof[n].task[m]]);
		}
		printf("%llu calls, %llu cycles, %.2f%%\n",prof[n].calls,prof[n].cycles,100.0/total*prof[n].cycles);
	}

	bzero(prof,sizeof(prof));
	maxprof=0;
#endif
	//xcheck();

	xlog("serials: char=%d, item=%d",sercn,serin);
}
Ejemplo n.º 7
0
t_ram		*xdeclare(void)
{
  t_ram		*ram;

  ram = malloc(sizeof(*ram));
  if (ram == NULL)
    {
      err_msg("Critical error: ", 0, "Can't init XMap system.");
      exit(EXIT_FAILURE);
    }
  ram->next = NULL;
  ram->memory = NULL;
  ram->name = "Xmap root";
  debug(-1, "XMap System: No leak allowed", "");
  xmalloc(0, (char*)ram, INIT);
  xfree(ram, INIT);
  xfreedom(ram, INIT);
  xftmp(ram, INIT);
  showmem(INIT, ram);
  liveliness(ram, INIT);
  return (ram);
}
Ejemplo n.º 8
0
int detailset::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QWidget::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: showtop((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 1: showcpu((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 2: showmem((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 3: slotshowtop((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 4: slotshowcpu((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 5: slotshowmem((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 6: slotOK(); break;
        case 7: slotAbout(); break;
        case 8: slotQuit(); break;
        default: ;
        }
        _id -= 9;
    }
    return _id;
}
Ejemplo n.º 9
0
int do_apriori (int argc, char *argv[])
{                               /* --- main function */
  int    i, k = 0, n;           /* loop variables, counters */
  char   *s;                    /* to traverse the options */
  char   **optarg = NULL;       /* option argument */
  char   *fn_in   = NULL;       /* name of input  file */
  char   *fn_out  = NULL;       /* name of output file */
  char   *fn_app  = NULL;       /* name of item appearances file */
  char   *blanks  = NULL;       /* blanks */
  char   *fldseps = NULL;       /* field  separators */
  char   *recseps = NULL;       /* record separators */
  char   *comment = NULL;       /* comment indicators */
  char   *used    = NULL;       /* item usage vector */
  double supp     = 0.1;        /* minimal support    (in percent) */
  double smax     = 1.0;        /* maximal support    (in percent) */
  double conf     = 0.8;        /* minimal confidence (in percent) */
  int    mode     = IST_BODY;   /* search mode (rule support def.) */
  int    target   = 'r';        /* target type (sets/rules/h.edges) */
  int    arem     = 0;          /* additional rule evaluation measure */
  int    lift     = 0;          /* flag for printing the lift */
  double minval   = 0.1;        /* minimal evaluation measure value */
  double lftval   = 0;          /* lift value (confidence/prior) */
  int    minlen   = 1;          /* minimal rule length */
  int    maxlen   = INT_MAX;    /* maximal rule length */
  int    load     = 1;          /* flag for loading transactions */
  int    sort     = 2;          /* flag for item sorting and recoding */
  double filter   = 0.1;        /* item usage filtering parameter */
  int    tree     = 1;          /* flag for transaction tree */
  int    heap     = 1;          /* flag for heap sort vs. quick sort */
  int    c2scf    = 0;          /* flag for conv. to scanable form */
  char   *sep     = " ";        /* item separator for output */
  char   *fmt     = "%.1f";     /* output format for support/conf. */
  int    sout     = 1;          /* flag for abs./rel. support output */
  int    ext      = 0;          /* flag for extended support output */
  int    aval     = 0;          /* flag for add. eval. measure value */
  int    maxcnt   = 0;          /* maximal number of items per set */
  int    tacnt;                 /* number of transactions */
  int    frq;                   /* frequency of an item set */
  int    *map, *set;            /* identifier map, item set */
  int    verbose  = 0;          /* flag for verboseness */
  const  char *name;            /* buffer for item names */
  static char buf[4*TS_SIZE+4]; /* buffer for formatting */
  clock_t     t, tt, tc, x;     /* timer for measurements */

  #ifndef QUIET                 /* if not quiet version */
  prgname = argv[0];            /* get program name for error msgs. */

  /* --- print usage message --- */
  if (argc > 1) {               /* if arguments are given */
    fprintf(stderr, "%s - %s\n", argv[0], DESCRIPTION);
    fprintf(stderr, VERSION); } /* print a startup message */
  else {                        /* if no arguments given */
    printf("usage: %s [options] infile outfile [appfile]\n", argv[0]);
    printf("%s\n", DESCRIPTION);
    printf("%s\n", VERSION);
    printf("-t#      target type (default: association rules)\n"
           "         (s: item sets, c: closed item sets,"
                    " m: maximal item sets,\n"
           "          r: association rules,"
                    " h: association hyperedges)\n");
    printf("-m#      minimal number of items per set/rule/hyperedge "
                    "(default: %d)\n", minlen);
    printf("-n#      maximal number of items per set/rule/hyperedge "
                    "(default: no limit)\n");
    printf("-s#      minimal support    of a     set/rule/hyperedge "
                    "(default: %g%%)\n", supp *100);
    printf("-S#      maximal support    of a     set/rule/hyperedge "
                    "(default: %g%%)\n", smax *100);
    printf("-c#      minimal confidence of a         rule/hyperedge "
                    "(default: %g%%)\n", conf *100);
    printf("-o       use original definition of the support of a rule "
                    "(body & head)\n");
    printf("-k#      item separator for output "
                    "(default: \"%s\")\n", sep);
    printf("-p#      output format for support/confidence "
                    "(default: \"%s\")\n", fmt);
    printf("-x       extended support output "
                    "(print both rule support types)\n");
    printf("-a       print absolute support "
                    "(number of transactions)\n");
    printf("-y       print lift value (confidence divided by prior)\n");
    printf("-e#      additional evaluation measure (default: none)\n");
    printf("-!       print a list of additional evaluation measures\n");
    printf("-d#      minimal value of additional evaluation measure "
                    "(default: %g%%)\n", minval *100);
    printf("-v       print value of additional "
                    "rule evaluation measure\n");
    printf("-g       write output in scanable form "
                    "(quote certain characters)\n");
    printf("-l       do not load transactions into memory "
                    "(work on input file)\n");
    printf("-q#      sort items w.r.t. their frequency (default: %d)\n"
           "         (1: ascending, -1: descending, 0: do not sort,\n"
           "          2: ascending, -2: descending w.r.t. "
                    "transaction size sum)\n", sort);
    printf("-u#      filter unused items from transactions "
                    "(default: %g)\n", filter);
    printf("         (0: do not filter items w.r.t. usage in sets,\n"
           "         <0: fraction of removed items for filtering,\n"
           "         >0: take execution times ratio into account)\n");
    printf("-h       do not organize transactions as a prefix tree\n");
    printf("-j       use quicksort to sort the transactions "
                    "(default: heapsort)\n");
    printf("-z       minimize memory usage "
                    "(default: maximize speed)\n");
    printf("-b/f/r#  blank characters, field and record separators\n"
           "         (default: \" \\t\\r\", \" \\t\", \"\\n\")\n");
    printf("-C#      comment characters (default: \"#\")\n");
    printf("-V       verbose\n");

    printf("infile   file to read transactions from\n");
    printf("outfile  file to write item sets/association rules"
                    "/hyperedges to\n");
    printf("appfile  file stating item appearances (optional)\n");
    return 0;                   /* print a usage message */
  }                             /* and abort the program */
  #endif  /* #ifndef QUIET */

  /* --- evaluate arguments --- */
  for (i = 1; i < argc; i++) {  /* traverse arguments */
    s = argv[i];                /* get option argument */
    if (optarg) { *optarg = s; optarg = NULL; continue; }
    if ((*s == '-') && *++s) {  /* -- if argument is an option */
      while (*s) {              /* traverse options */
        switch (*s++) {         /* evaluate switches */
          case '!': help();                         break;
          case 't': target = (*s) ? *s++ : 'r';     break;
          case 'm': minlen = (int)strtol(s, &s, 0); break;
          case 'n': maxlen = (int)strtol(s, &s, 0); break;
          case 's': supp   = 0.01*strtod(s, &s);    break;
          case 'S': smax   = 0.01*strtod(s, &s);    break;
          case 'c': conf   = 0.01*strtod(s, &s);    break;
          case 'o': mode  |= IST_BOTH;              break;
          case 'k': optarg = &sep;                  break;
          case 'p': optarg = &fmt;                  break;
          case 'x': ext    = 1;                     break;
          case 'a': sout  |= 2;                     break;
          case 'y': lift   = 1;                     break;
          case 'e': arem   = (*s) ? *s++ : 0;       break;
          case 'd': minval = 0.01*strtod(s, &s);    break;
          case 'v': aval   = 1;                     break;
          case 'g': c2scf  = 1;                     break;
          case 'l': load   = 0;                     break;
          case 'q': sort   = (int)strtol(s, &s, 0); break;
          case 'u': filter =      strtod(s, &s);    break;
          case 'h': tree   = 0;                     break;
          case 'j': heap   = 0;                     break;
          case 'z': mode  |= IST_MEMOPT;            break;
          case 'b': optarg = &blanks;               break;
          case 'f': optarg = &fldseps;              break;
          case 'r': optarg = &recseps;              break;
          case 'C': optarg = &comment;              break;
          case 'V': verbose = 1;                    break;
          default : error(E_OPTION, *--s);          break;
        }                       /* set option variables */
        if (optarg && *s) { *optarg = s; optarg = NULL; break; }
      } }                       /* get option argument */
    else {                      /* -- if argument is no option */
      switch (k++) {            /* evaluate non-options */
        case  0: fn_in  = s;      break;
        case  1: fn_out = s;      break;
        case  2: fn_app = s;      break;
        default: error(E_ARGCNT); break;
      }                         /* note filenames */
    }
  }
  if (optarg) error(E_OPTARG);  /* check option argument */
  if ((k < 2) || (k > 3))       /* and the number of arguments */
    error(E_ARGCNT);            /* (either in/out or in/out/app) */
  if ((!fn_in || !*fn_in) && (fn_app && !*fn_app))
    error(E_STDIN);             /* stdin must not be used twice */
  switch (target) {             /* check and translate target type */
    case 's': target = TT_SET;               break;
    case 'c': target = TT_CLSET;             break;
    case 'm': target = TT_MFSET;             break;
    case 'r': target = TT_RULE;              break;
    case 'h': target = TT_HEDGE;             break;
    case 'g': target = TT_GROUP;             break;
    default : error(E_TARGET, (char)target); break;
  }
  if (supp > 1)                 /* check the minimal support */
    error(E_SUPP, supp);        /* (< 0: absolute number) */
  if ((conf  <  0) || (conf > 1))
    error(E_CONF, conf);        /* check the minimal confidence */
  if (minlen <= 0) error(E_RULELEN, minlen);  /* check the limits */
  if (maxlen <= 0) error(E_RULELEN, maxlen);  /* for the rule length */
  switch (arem) {               /* check and translate measure */
    case  0 : case '0': arem = EM_NONE;     break;
    case 'd': case '1': arem = EM_DIFF;     break;
    case 'q': case '2': arem = EM_QUOT;     break;
    case 'a': case '3': arem = EM_AIMP;     break;
    case 'i': case '4': arem = EM_INFO;     break;
    case 'c': case '5': arem = EM_CHI2;     break;
    case 'p': case '6': arem = EM_PVAL;     break;
    default : error(E_MEASURE, (char)arem); break;
  }
  if (target <= TT_MFSET) {     /* in item set mode neutralize */
    mode |= IST_BOTH; conf = 1;}/* rule specific settings */
  if (arem == EM_NONE)          /* if no add. rule eval. measure, */
    aval = 0;                   /* clear the corresp. output flag */
  if ((filter <= -1) || (filter >= 1)) filter = 0;

  /* --- create item set and transaction set --- */
  itemset = is_create(-1);      /* create an item set and */
  if (!itemset) error(E_NOMEM); /* set the special characters */
  is_chars(itemset, blanks, fldseps, recseps, comment);
  if (load) {                   /* if to load the transactions */
    taset = tas_create(itemset);
    if (!taset) error(E_NOMEM); /* create a transaction set */
  }                             /* to store the transactions */
  MSG(fprintf(stderr, "\n"));   /* terminate the startup message */

  /* --- read item appearances --- */
  if (fn_app) {                 /* if item appearances are given */
    t = clock();                /* start the timer */
    if (*fn_app)                /* if an app. file name is given, */
      in = fopen(fn_app, "r");  /* open the item appearances file */
    else {                      /* if no app. file name is given, */
      in = stdin; fn_app = "<stdin>"; }   /* read from std. input */
    MSG(fprintf(stderr, "reading %s ... ", fn_app));
    if (!in) error(E_FOPEN, fn_app);
    k = is_readapp(itemset,in); /* read the item appearances */
    if (k  != 0) error(k, fn_app, RECCNT(itemset), BUFFER(itemset));
    if (in != stdin)            /* if not read from standard input, */
      fclose(in);               /* close the input file */
    MSG(fprintf(stderr, "[%d item(s)]", is_cnt(itemset)));
    MSG(fprintf(stderr, " done [%.2fs].\n", SEC_SINCE(t)));
  }                             /* print a log message */

  /* --- read transactions --- */
  t = clock();                  /* start the timer */
  if (fn_in && *fn_in)          /* if an input file name is given, */
    in = fopen(fn_in, "r");     /* open input file for reading */
  else {                        /* if no input file name is given, */
    in = stdin; fn_in = "<stdin>"; }   /* read from standard input */
  MSG(fprintf(stderr, "reading %s ... \n", fn_in));
  if (!in) error(E_FOPEN, fn_in);
  while (1) {                   /* transaction read loop */
    k = is_read(itemset, in);   /* read the next transaction */
    if (k < 0) error(k, fn_in, RECCNT(itemset), BUFFER(itemset));
    if (k > 0) break;           /* check for error and end of file */
    k = is_tsize(itemset);      /* update the maximal */
    if (k > maxcnt) maxcnt = k; /* transaction size */
    if (taset && (tas_add(taset, NULL, 0) != 0))
      error(E_NOMEM);           /* add the loaded transaction */
  }                             /* to the transaction set */
  if (taset) {                  /* if transactions have been loaded */
    if (in != stdin) fclose(in);/* if not read from standard input, */
    in = NULL;                  /* close the input file */
  }                             /* clear the file variable */
  n     = is_cnt(itemset);      /* get the number of items */
  tacnt = is_gettac(itemset);   /* and the number of transactions */
  MSG(fprintf(stderr, "[%d item(s), %d transaction(s)]", n, tacnt));
  MSG(fprintf(stderr, " done [%.2fs].", SEC_SINCE(t)));
  if ((n <= 0) || (tacnt <= 0)) error(E_NOTAS);
  MSG(fprintf(stderr, "\n"));   /* check for at least one transaction */
  if (supp >= 0)                /* if relative support is given */
    supp = ceil(tacnt *supp);   /* compute absolute support */
  else {                        /* if absolute support is given, */
    supp = ceil(-100  *supp);   /* make the support value positive */
    if (!(sout & 2)) sout = 2;  /* switch to absolute support output */
  }                             /* do the same with the max. support */
  smax = floor(((smax >= 0) ? tacnt : -100) *smax);

  /* --- sort and recode items --- */
  MSG(fprintf(stderr, "filtering, sorting and recoding items ... "));
  t   = clock();                /* start the timer */
  map = (int*)malloc(is_cnt(itemset) *sizeof(int));
  if (!map) error(E_NOMEM);     /* create an item identifier map */
  k = (int)((mode & IST_HEAD) ? supp : ceil(supp *conf));
  n = is_recode(itemset, k, sort, map);
  if (taset) {                  /* sort and recode the items and */
    tas_recode(taset, map,n);   /* recode the loaded transactions */
    maxcnt = tas_max(taset);    /* get the new maximal t.a. size */
  }                             /* (may be smaller than before) */
  free(map);                    /* delete the item identifier map */
  MSG(fprintf(stderr, "[%d item(s)] ", n));
  MSG(fprintf(stderr, "done [%.2fs].", SEC_SINCE(t)));
  if (n <= 0) error(E_NOFREQ);  /* print a log message and */
  MSG(fprintf(stderr, "\n"));   /* check the number of items */
  if (maxlen > maxcnt)          /* clamp the set/rule length */
    maxlen = maxcnt;            /* to the maximum set size */

  /* --- create a transaction tree --- */
  tt = 0;                       /* init. the tree construction time */
  if (tree && taset) {          /* if transactions were loaded */
    MSG(fprintf(stderr, "creating transaction tree ... "));
    t = clock();                /* start the timer */
    tatree = tat_create(taset, heap); 
    if (!tatree) error(E_NOMEM);/* create a transaction tree */
    if (filter == 0) {          /* if a tree rebuild is not needed, */
      tas_delete(taset, 0); taset = NULL; }  /* delete transactions */
    tt = clock() -t;            /* note the time for the construction */
    MSG(fprintf(stderr, "done [%.2fs].\n", SEC_SINCE(t)));
  }                             /* print a log message */

  /* --- create an item set tree --- */
  t = clock(); tc = 0;          /* start the timer */
  istree = ist_create(itemset, mode, (int)supp, conf);
  if (!istree) error(E_NOMEM);  /* create an item set tree */

  /* --- check item subsets --- */
  if (filter) {                 /* if to filter unused items */
    used = (char*)malloc(is_cnt(itemset) *sizeof(char));
    if (!used) error(E_NOMEM);  /* create a flag vector */
  }                             /* for the items */
  MSG(fprintf(stderr, "checking subsets of size 1"));
  while (ist_height(istree) < maxlen) {
    if (filter != 0) {          /* if to filter w.r.t. item usage, */
      i = ist_check(istree, used);     /* check current item usage */
      if (i < maxlen) maxlen = i;      /* update the maximum size */
      if (ist_height(istree) >= i) break;
    }                           /* check the tree height */
    k = ist_addlvl(istree);     /* while max. height is not reached, */
    if (k <  0) error(E_NOMEM); /* add a level to the item set tree */
    if (k != 0) break;          /* if no level was added, abort */
    MSG(fprintf(stderr, " %d", ist_height(istree)));
    if (tatree) {               /* if a transaction tree was created */
      if (((filter < 0)         /* if to filter w.r.t. item usage */
      &&   (i < -filter *n))    /* and enough items were removed */
      ||  ((filter > 0)         /* or counting time is long enough */
      &&   (i < n) && (i *(double)tt < filter *n *tc))) {
        n = i; x = clock();     /* note the new number of items */
        tas_filter(taset, used);/* and remove unnecessary items */
        tat_delete(tatree);     /* delete the transaction tree */
        tatree = tat_create(taset, heap);
        if (!tatree) error(E_NOMEM);
        tt = clock() -x;        /* rebuild the transaction tree and */
      }                         /* note the new construction time */
      x  = clock();             /* count the transaction tree */
      ist_countx(istree, tatree);
      tc = clock() -x; }        /* note the new count time */
    else if (taset) {           /* if transactions were loaded */
      if (((filter < 0)         /* if to filter w.r.t. item usage */
      &&   (i <= -filter *n))   /* and enough items were removed */
      ||  ((filter > 0)         /* or counting time is long enough */
      &&   (i *(double)tt <= filter *n *tc))) {
        n = i; x = clock();     /* note the new number of items */
        tas_filter(taset, used);/* and remove unnecessary items */
        tt = clock() -t;        /* from the transactions */
      }                         /* note the filtering time */
      for (i = tacnt; --i >= 0;)/* traverse and count transactions */
        ist_count(istree, tas_tract(taset, i), tas_tsize(taset, i));
      tc = clock() -t; }        /* note the new count time */
    else {                      /* if to work on the input file, */
      rewind(in);               /* reset the file position */
      for (maxcnt = 0; (i = is_read(itemset, in)) == 0; ) {
        if (filter != 0)        /* (re)read the transactions and */
          is_filter(itemset, used);  /* remove unnecessary items */
        k = is_tsize(itemset);  /* update the maximum size */
        if (k > maxcnt) maxcnt = k;  /* of a transaction */
        ist_count(istree, is_tract(itemset), k);
      }                         /* count the transaction in the tree */
      if (i < 0) error(i, fn_in, RECCNT(itemset), BUFFER(itemset));
      if (maxcnt < maxlen)      /* update the maximal rule length */
        maxlen = maxcnt;        /* according to the max. t.a. size */
    }                           /* (may be smaller than before) */
  }
  if (!taset && !tatree) {      /* if transactions were not loaded */
    if (in != stdin) fclose(in);/* if not read from standard input, */
    in = NULL;                  /* close the input file */
  }                             /* clear the file variable */
  MSG(fprintf(stderr, " done [%.2fs].\n", SEC_SINCE(t)));

  /* --- filter found item sets --- */
  if ((target == TT_CLSET) || (target == TT_MFSET)) {
    MSG(fprintf(stderr, "filtering %s item sets ... ",
        (target == TT_MFSET) ? "maximal" : "closed"));
    t = clock();                /* filter the item sets */
    ist_filter(istree, (target == TT_MFSET) ? IST_MAXFRQ : IST_CLOSED);
    MSG(fprintf(stderr, "done [%.2fs].\n", SEC_SINCE(t)));
  }                             /* (filter takes longer than print) */

  /* --- sort transactions --- */
  if (target <= TT_MFSET) {     /* if to find frequent item sets */
    if (!taset)                 /* transactions must be loaded */
      ext = 0;                  /* for extended support output */
    else if (ext) {             /* if extended output is requested */
      MSG(fprintf(stderr, "sorting transactions ... "));
      t = clock();              /* start the timer */
      tas_sort(taset, heap);    /* sort the transactions */
      MSG(fprintf(stderr, "done [%.2fs].\n", SEC_SINCE(t)));
    }                           /* (sorting is necessary to find the */
  }                             /* number of identical transactions) */

  /* --- print item sets/rules/hyperedges --- */
  t = clock();                  /* start the timer */
  if (fn_out && *fn_out)        /* if an output file name is given, */
    out = fopen(fn_out, "w");   /* open the output file */
  else {                        /* if no output file name is given, */
    out = stdout; fn_out = "<stdout>"; }    /* write to std. output */
  MSG(fprintf(stderr, "writing %s ... ", fn_out));
  if (!out) error(E_FOPEN, fn_out);
  ist_init(istree, minlen, arem, minval);
  set = is_tract(itemset);      /* get the transaction buffer */
  if (target <= TT_MFSET) {     /* if to find frequent item sets */
    for (n = 0; 1; ) {          /* extract item sets from the tree */
      k = ist_set(istree, set, &frq, &conf);
      if (k <= 0) break;        /* get the next frequent item set */
      if (frq > smax) continue; /* check against maximal support */
      for (i = 0; i < k; i++) { /* traverse the set's items */
        name = is_name(itemset, set[i]);
        if (c2scf) { sc_format(buf, name, 0); name = buf; }
        fputs(name, out);       /* print the name of the next item */
        fputs((i < k-1) ? sep : " ", out);
      }                         /* print a separator */
      fputs(" (", out);         /* print the item set's support */
      if (sout & 1) { fprintf(out, fmt, (frq/(double)tacnt) *100);
                      if (sout & 2) fputc('/', out); }
      if (sout & 2) { fprintf(out, "%d", frq); }
      if (ext) {                /* if to print the extended support */
        frq = tas_occur(taset, set, k);
        fputs(", ", out);       /* get the number of occurrences */
        fprintf(out, fmt, (frq/(double)tacnt) *100);
        if (sout & 2) fprintf(out, "/%d", frq);
      }                         /* print the extended support data */
      if (aval) { fputs(", ", out); fprintf(out, fmt, conf *100); }
      fputs(")\n", out);        /* print the add. eval. measure, */
      n++;                      /* terminate the support output, */
    } }                         /* and count the item set */
  else if (target == TT_RULE) { /* if to find association rules, */
    for (n = 0; 1; ) {          /* extract rules from tree */
      k = ist_rule(istree, set, &frq, &conf, &lftval, &minval);
      if (k <= 0) break;        /* get the next association rule */
      if (frq > smax) continue; /* check against maximal support */
      for (i = 0; i < k; i++) { /* traverse the rule's items */
        name = is_name(itemset, set[i]);
        if (c2scf) { sc_format(buf, name, 0); name = buf; }
        fputs(name, out);       /* print the next item */
        fputs((i <= 0) ? " <- " : ((i < k-1) ? sep : " "), out);
      }                         /* print a separator */
      fputs(" (", out);         /* print the rule evaluation */
      if (sout & 1) supp = frq/(double)tacnt;
      if (ext && !(mode & IST_HEAD)) {
        if (sout & 1) { fprintf(out, fmt, supp *conf *100);
                        if (sout & 2) fputc('/', out); }
        if (sout & 2) { fprintf(out, "%d", (int)(frq *conf +0.5));}
        fputs(", ", out);       /* print the support of the rule */
      }                         /* from  the support of the body */
      if (sout & 1) { fprintf(out, fmt, supp *100);
                      if (sout & 2) fputc('/', out); }
      if (sout & 2) { fprintf(out, "%d", frq); }
      fputs(", ", out);         /* print the rule support */
      if (ext && (mode & IST_HEAD)) {
        if (sout & 1) { fprintf(out, fmt, (supp/conf) *100);
                        if (sout & 2) fputc('/', out); }
        if (sout & 2) { fprintf(out, "%d", (int)(frq /conf +0.5));}
        fputs(", ", out);       /* print the support of the body */
      }                         /* from  the support of the rule */
      fprintf(out, fmt, conf *100); /* print the rule confidence */
      if (lift) { fputs(", ", out); fprintf(out, fmt, lftval *100); }
      if (aval) { fputs(", ", out); fprintf(out, fmt, minval *100); }
      fputs(")\n", out);        /* print the value of the additional */
      n++;                      /* rule evaluation measure and */
    } }                         /* count the association rule */
  else if (target == TT_HEDGE){ /* if to find association hyperedges */
    for (n = 0; 1; ) {          /* extract hyperedges from tree */
      k = ist_hedge(istree, set, &frq, &conf, &minval);
      if (k <= 0) break;        /* get the next hyperedge */
      if (frq > smax) continue; /* check against maximal support */
      for (i = 0; i < k; i++) { /* traverse the edge's items */
        name = is_name(itemset, set[i]);
        if (c2scf) { sc_format(buf, name, 0); name = buf; }
        fputs(name, out);       /* print the name of the next item */
        fputs((i < k-1) ? sep : " ", out);
      }                         /* print a separator */
      fputs(" (", out);         /* print the hyperedge evaluation */
      if (sout & 1) { fprintf(out, fmt, (frq/(double)tacnt) *100);
                      if (sout & 2) fputc('/', out); }
      if (sout & 2) { fprintf(out, "%d", frq); }
      fputs(", ", out); fprintf(out, fmt, conf *100);
      if (aval) { fputs(", ", out); fprintf(out, fmt, minval *100); }
      fputs(")\n", out);        /* print support and confidence */
      n++;                      /* of the hyperedge and */
    } }                         /* count the hyperedge */
  else {                        /* if to find association groups */
    for (n = 0; 1; ) {          /* extract groups from tree */
      k = ist_group(istree, set, &frq, &minval);
      if (k <= 0) break;        /* get the next group */
      if (frq > smax) continue; /* check against maximal support */
      for (i = 0; i < k; i++) { /* traverse the group's items */
        name = is_name(itemset, set[i]);
        if (c2scf) { sc_format(buf, name, 0); name = buf; }
        fputs(name, out);       /* print the name of the next item */
        fputs((i < k-1) ? sep : " ", out);
      }                         /* print a separator */
      fputs(" (", out);         /* print the group evaluation */
      if (sout & 1) { fprintf(out, fmt, (frq/(double)tacnt) *100);
                      if (sout & 2) fputc('/', out); }
      if (sout & 2) { fprintf(out, "%d", frq); }
      if (aval) { fputs(", ", out); fprintf(out, fmt, minval *100); }
      fputs(")\n", out);        /* print support and add. measure */
      n++;                      /* and count the group */
    }
  }  /* if (target <= TT_MFSET) .. else .. */
  if (fflush(out) != 0) error(E_FWRITE, fn_out);
  if (out != stdout) fclose(out);
  out = NULL;                   /* close the output file */
  MSG(fprintf(stderr, "[%d %s(s)] done ", n, ttypes[target]));
  MSG(fprintf(stderr, "[%.2fs].\n", SEC_SINCE(t)));
  #ifdef BENCH
  printf("number of support counters: %d\n", istree->sccnt);
  printf("necessary support counters: %d\n", istree->scnec);
  printf("number of child pointers  : %d\n", istree->cpcnt);
  printf("necessary child pointers  : %d\n", istree->cpnec);
  printf("allocated memory (bytes)  : %d\n", istree->bytes);
  #endif

  /* --- clean up --- */
  #ifndef NDEBUG                /* if this is a debug version */
  free(used);                   /* delete the item app. vector */
  ist_delete(istree);           /* delete the item set tree, */
  if (tatree) tat_delete(tatree);     /* the transaction tree, */
  if (taset)  tas_delete(taset, 0);   /* the transaction set, */
  is_delete(itemset);                 /* and the item set */
  #endif
  #ifdef STORAGE                /* if storage debugging */
  showmem("at end of program"); /* check memory usage */
  #endif
  return 0;                     /* return 'ok' */
}  /* main() */
Ejemplo n.º 10
0
int main (int argc, char* argv[])
{                               /* --- main function */
  int    i, k = 0;              /* loop variables, buffer */
  char   *s;                    /* to traverse options */
  char   **optarg = NULL;       /* option argument */
  char   *fn_bc   = NULL;       /* name of classifier file */
  char   *fn_out  = NULL;       /* name of output file */
  char   *blank   = NULL;       /* blank */
  char   *fldsep  = NULL;       /* field  separator */
  char   *recsep  = NULL;       /* record separator */
  int    flags    = AS_ATT;     /* table file write flags */
  double lcorr    = -DBL_MAX;   /* Laplace correction value */
  int    dwnull   = 0;          /* distribute weight of null values */
  int    maxllh   = 0;          /* max. likelihood est. of variance */
  int    tplcnt   = 1000;       /* number of tuples to generate */
  long   seed;                  /* seed for random number generator */
  int    mode;                  /* classifier setup mode */

  prgname = argv[0];            /* get program name for error msgs. */
  seed    = (long)time(NULL);   /* and get a default seed value */

  /* --- print startup/usage message --- */
  if (argc > 1) {               /* if arguments are given */
    fprintf(stderr, "%s - %s\n", argv[0], DESCRIPTION);
    fprintf(stderr, VERSION); } /* print a startup message */
  else {                        /* if no argument given */
    printf("usage: %s [options] bcfile "
                     "[-d|-h hdrfile] tabfile\n", argv[0]);
    printf("%s\n", DESCRIPTION);
    printf("%s\n", VERSION);
    printf("-n#      number of tuples to generate "
                    "(default: %d)\n", tplcnt);
    printf("-s#      seed for random number generator "
                    "(default: time)\n");
    printf("-L#      Laplace correction "
                    "(default: as specified in classifier)\n");
    printf("-v/V     (do not) distribute tuple weight "
                    "for null values\n");
    printf("-m/M     (do not) use maximum likelihood estimate "
                    "for the variance\n");
    printf("-a       align fields (default: do not align)\n");
    printf("-w       do not write field names to the output file\n");
    printf("-b/f/r#  blank character, field and record separator\n"
           "         (default: \" \", \" \", \"\\n\")\n");
    printf("bcfile   file containing classifier description\n");
    printf("tabfile  table file to write\n");
    return 0;                   /* print a usage message */
  }                             /* and abort the program */

  /* --- evaluate arguments --- */
  for (i = 1; i < argc; i++) {  /* traverse arguments */
    s = argv[i];                /* get option argument */
    if (optarg) { *optarg = s; optarg = NULL; continue; }
    if ((*s == '-') && *++s) {  /* -- if argument is an option */
      while (*s) {              /* traverse options */
        switch (*s++) {         /* evaluate option */
          case 'n': tplcnt  = (int)strtol(s, &s, 0); break;
          case 's': seed    =      strtol(s, &s, 0); break;
          case 'L': lcorr   = strtod(s, &s);         break;
          case 'v': dwnull  = NBC_ALL;               break;
          case 'V': dwnull |= NBC_DWNULL|NBC_ALL;    break;
          case 'm': maxllh  = NBC_ALL;               break;
          case 'M': maxllh |= NBC_MAXLLH|NBC_ALL;    break;
          case 'a': flags  |= AS_ALIGN;              break;
          case 'w': flags  &= ~AS_ATT;               break;
          case 'b': optarg  = &blank;                break;
          case 'f': optarg  = &fldsep;               break;
          case 'r': optarg  = &recsep;               break;
          default : error(E_OPTION, *--s);           break;
        }                       /* set option variables */
        if (!*s) break;         /* if at end of string, abort loop */
        if (optarg) { *optarg = s; optarg = NULL; break; }
      } }                       /* get option argument */
    else {                      /* if argument is no option */
      switch (k++) {            /* evaluate non-option */
        case  0: fn_bc  = s;      break;
        case  1: fn_out = s;      break;
        default: error(E_ARGCNT); break;
      }                         /* note filenames */
    }
  }
  if (optarg) error(E_OPTARG);  /* check the option argument */
  if (k != 2) error(E_ARGCNT);  /* and the number of arguments */
  if ((lcorr < 0) && (lcorr > -DBL_MAX))
    error(E_NEGLC);             /* check the Laplace correction */
  if ((flags & AS_ATT) && (flags & AS_ALIGN))
    flags |= AS_ALNHDR;         /* set align to header flag */

  /* --- read Bayes classifier --- */
  scan = sc_create(fn_bc);      /* create a scanner */
  if (!scan) error((!fn_bc || !*fn_bc) ? E_NOMEM : E_FOPEN, fn_bc);
  attset = as_create("domains", att_delete);
  if (!attset) error(E_NOMEM);  /* create an attribute set */
  fprintf(stderr, "\nreading %s ... ", sc_fname(scan));
  if ((sc_nexter(scan)   <  0)  /* start scanning (get first token) */
  ||  (as_parse(attset, scan, AT_ALL) != 0)
  ||  (as_attcnt(attset) <= 0)) /* parse attribute set */
    error(E_PARSE, sc_fname(scan));
  if ((sc_token(scan) == T_ID)  /* determine classifier type */
  &&  (strcmp(sc_value(scan), "fbc") == 0))
       fbc = fbc_parse(attset, scan);
  else nbc = nbc_parse(attset, scan);
  if ((!fbc && !nbc)            /* parse the Bayes classifier */
  ||   !sc_eof(scan))           /* and check for end of file */
    error(E_PARSE, sc_fname(scan));
  sc_delete(scan); scan = NULL; /* delete the scanner */
  fprintf(stderr, "[%d attribute(s)] done.\n", as_attcnt(attset));
  if ((lcorr >= 0) || dwnull || maxllh) {
    if (lcorr < 0)              /* get the classifier's parameters */
      lcorr = (fbc) ? fbc_lcorr(fbc) : nbc_lcorr(nbc);
    mode    = (fbc) ? fbc_mode(fbc)  : nbc_mode(nbc);
    if (dwnull) mode = (mode & ~NBC_DWNULL) | dwnull;
    if (maxllh) mode = (mode & ~NBC_MAXLLH) | maxllh;
                                /* adapt the estimation parameters */
    if (fbc) fbc_setup(fbc, mode, lcorr);
    else     nbc_setup(nbc, mode, lcorr);
  }                             /* set up the classifier anew */

  /* --- generate database --- */
  if (fn_out && *fn_out)        /* if an output file name is given, */
    out = fopen(fn_out, "w");   /* open output file for writing */
  else {                        /* if no output file name is given, */
    out = stdout; fn_out = "<stdout>"; }    /* write to std. output */
  fprintf(stderr, "writing %s ... ", fn_out);
  if (!out) error(E_FOPEN, fn_out);
  if ((flags & AS_ATT)          /* if to write a table header */
  &&  (as_write(attset, out, flags) != 0))
    error(E_FWRITE, fn_out);    /* write the attributes names */
  flags = AS_INST | (flags & ~AS_ATT);
  dseed(seed);                  /* init. random number generator */
  for (i = tplcnt; --i >= 0;) { /* generate random tuples */
    if (fbc) fbc_rand(fbc, drand);   /* instantiate the */
    else     nbc_rand(nbc, drand);   /* attribute set */
    if (as_write(attset, out, flags) != 0)
      error(E_FWRITE,fn_out);   /* write the generated tuple */
  }                             /* to the output file */
  if (out != stdout) {          /* if not written to stdout */
    i = fclose(out); out = NULL;/* close the output file */
    if (i != 0) error(E_FWRITE, fn_out);
  }                             /* print a success message */
  fprintf(stderr, "[%d tuple(s)] done.\n", tplcnt);

  /* --- clean up --- */
  #ifndef NDEBUG
  if (fbc) fbc_delete(fbc, 1);  /* delete full  Bayes classifier */
  if (nbc) nbc_delete(nbc, 1);  /* or     naive Bayes classifier */
  #endif                        /* and underlying attribute set */
  #ifdef STORAGE
  showmem("at end of program"); /* check memory usage */
  #endif
  return 0;                     /* return 'ok' */
}  /* main() */
Ejemplo n.º 11
0
void	HandleQuery(Host Session_SN, uchar *Query, int Size)
{
    uchar		*Browser;
    SResponse	Response;
    CLocation	TesterLocation;
    Host		Tested;
    SessProp	*SessionProposal;
    uint Idx = 0;
    uint Rank = 0;

    Browser = Query;

    while (Size > 0)
    {
        Response.Objs = NULL;
        Response.NbObj = 0;
        TCPResponseManager(&Browser, (uint *)&Size, &Response);
        uint Idx = 0;

        switch (Response.Cmd / 8)
        {
        case CMD_QUERY_IPING:
            printf("Received Incoming Initial Ping..\n");
            for (Idx = 0; Idx < Response.NbObj; Idx++)
            {
                switch (Response.Objs[Idx].Id)
                {
                case OBJ_ID_PINGER:
                    printf("Ping Coming From : %s.. Let's Reply..\n", Response.Objs[Idx].Value.Memory.Memory);
                    PingReply(Session_SN, Response.Reply2ID);
                    break;
                default:
                    break;
                }
            }
            break;
        case CMD_QUERY_SESSION:
            printf("Received session proposal..\n");

            SessionProposal = (SessProp *)malloc(sizeof(SessProp));
            SessionProposal->Relays = new queue<Host>;
            SessionProposal->SessID = BytesRandomWord() % 0x7FFF;
            *(uint *)(SessionProposal->PeerChallenge) = BytesRandom();
            *(uint *)(SessionProposal->PeerChallenge + 4) = BytesRandom();

            printf("Challenge to propose to Peer : ");
            showmem((uchar *)SessionProposal->PeerChallenge, 0x08);

            SessionProposal->CreatedSID = 0x00;
            SessionProposal->LocalCreatedSID = 0x00;

            for (Idx = 0; Idx < Response.NbObj; Idx++)
            {
                if (Response.Objs[Idx].ObjListInfos.Id == -1)
                {
                    switch(Response.Objs[Idx].Id)
                    {
                    case OBJ_ID_SESPROPOSER:
                        LocationBlob2Location(Response.Objs[Idx].Value.Memory.Memory, &(SessionProposal->ProposerLocation), Response.Objs[Idx].Value.Memory.MsZ);
                        printf("Proposer Node : ");
                        DumpLocation(&(SessionProposal->ProposerLocation));
                        break;
                    case OBJ_ID_SESCHALLENG:
                        printf("Session Challenge : ");
                        showmem(Response.Objs[Idx].Value.Table, sizeof(Response.Objs[Idx].Value.Table));
                        memcpy_s(SessionProposal->Challenge, sizeof(SessionProposal->Challenge), Response.Objs[Idx].Value.Table, sizeof(SessionProposal->Challenge));
                        break;
                    case OBJ_ID_PEERSESSID:
                        printf("Peer Choosen Session ID : 0x%x\n", Response.Objs[Idx].Value.Nbr);
                        SessionProposal->PeerSessID = Response.Objs[Idx].Value.Nbr;
                    default:
                        break;
                    }
                }
            }

            uint		NbObjLists;
            Memory_U	RelaysInfos;

            RelaysInfos.Memory = (uchar *)malloc(0xFF);
            ZeroMemory(RelaysInfos.Memory, 0xFF);
            RelaysInfos.MsZ = 0xFF;
            Browser = RelaysInfos.Memory;

            NbObjLists = DefNbObjList(Response);
            for (Rank = 0; Rank < NbObjLists + 1; Rank++)
            {
                Host	Relay;
                uint	State, ObjOccur;

                State = ObjOccur = 0;
                for (uint Idx = 0; Idx < Response.NbObj; Idx++)
                {
                    if ((Response.Objs[Idx].ObjListInfos.Id == 0x07) && (Response.Objs[Idx].ObjListInfos.Rank == Rank))
                    {
                        if (!ObjOccur)
                        {
                            memcpy_s(Browser, 0xFF, "\x05\x07\x41\x03", 0x04);
                            Browser += 0x04;
                            ObjOccur = 1;
                        }
                        WriteObject(&Browser, Response.Objs[Idx]);
                        switch(Response.Objs[Idx].Id)
                        {
                        case OBJ_ID_RELAY:
                            printf("Proposed Relay : %s:%d\n", Response.Objs[Idx].Value.Addr.ip, Response.Objs[Idx].Value.Addr.port);
                            strcpy_s(Relay.ip, MAX_IP_LEN + 1, Response.Objs[Idx].Value.Addr.ip);
                            Relay.port = Response.Objs[Idx].Value.Addr.port;
                            State += 1;
                            break;
                        case OBJ_ID_SID2DEC:
                            printf("Session To Declare on this relay : 0x%x\n", Response.Objs[Idx].Value.Nbr);
                            Relay.SessionID2Declare = Response.Objs[Idx].Value.Nbr;
                            State += 1;
                        default:
                            break;
                        }
                    }
                }
                if (State == 2)
                    SessionProposal->Relays->push(Relay);
            }
            RelaysInfos.MsZ = (uint)(Browser - RelaysInfos.Memory);
            SessionProposal->RelaysInfos = RelaysInfos;

            printf("Accepted session.. Let's initialize..\n");

            uchar	RecvCopy[0xFFFF];
            int		RecvSzCopy;

            ZeroMemory(RecvCopy, 0xFFFF);
            memcpy_s(RecvCopy, 0xFFFF, Query, Size);
            RecvSzCopy = Size;

            SessionPropReply(Session_SN, Response.Reply2ID);
            InitSession(SessionProposal);

            ZeroMemory(RecvBuffer, 0xFFFF);
            memcpy_s(Query, 0xFFFF, RecvCopy, RecvSzCopy);
            Size = RecvSzCopy;
            break;
        case CMD_QUERY_UDPTEST:
            printf("Received UDP Test report..\n");
            Tested.port = 0;
            for (Idx = 0; Idx < Response.NbObj; Idx++)
            {
                switch(Response.Objs[Idx].Id)
                {
                case OBJ_ID_TESTED:
                    printf("Peer Tested my UDP Address : %s:%d\n", Response.Objs[Idx].Value.Addr.ip, Response.Objs[Idx].Value.Addr.port);
                    if (Tested.port == 0)
                        Tested = Response.Objs[Idx].Value.Addr;
                    break;
                case OBJ_ID_TESTER:
                    LocationBlob2Location(Response.Objs[Idx].Value.Memory.Memory, &TesterLocation, Response.Objs[Idx].Value.Memory.MsZ);
                    printf("Tester Node : ");
                    DumpLocation(&TesterLocation);
                    printf("Should UDP Test %s:%d\n", TesterLocation.PVAddr.ip, TesterLocation.PVAddr.port);
                    break;
                default:
                    break;
                }
            }
            UDPTestReply(Session_SN, Response.Reply2ID, Tested);
            break;
        default:
            printf("Unhandled Query.. Sending ACK..\n");
            SendACK(Response.PacketID, Session_SN.socket, Session_SN, HTTPS_PORT, &(Session_SN.Connected), &Keys);
            break;
        }
        printf("\n");
    }
}
Ejemplo n.º 12
0
int main(int argc,char *args[])
{
	int n,c;
	unsigned long long prof,start,end;

	end_of_data_ptr=sbrk(0);

	time_now=time(NULL);

	printf("\n");
	printf("   ********************************************\n");
        printf("   *     Astonia 3 - The Conflict Server      *\n");
	printf("   *             Version %d.%02d.%02d              *\n",VERSION>>16,(VERSION>>8)&255,VERSION&255);
	printf("   ********************************************\n");
        printf("   * Copyright (C) 2001-2008 Intent Software  *\n");
	printf("   * Copyright (C) 1997-2001 Daniel Brockhaus *\n");
	printf("   ********************************************\n");
	printf("\n");

        if (argc>1) {
		while (1) {
			c=getopt(argc,args,"a:m:i:dhc");
			if (c==-1) break;

			switch (c) {
				case 'a': 	if (optarg) areaID=atoi(optarg); break;
				case 'm': 	if (optarg) areaM=atoi(optarg); break;
				case 'd': 	demon=1; break;
				case 'h':	fprintf(stderr,"Usage: %s [-a <areaID>] [-m <mirror>] [-n <use this class A net>] [-d] [-c]\n\n-d Demonize\n-c Disable concurrent database access\n\n",args[0]); exit(0);
				case 'c':	multi=0; break;
				//case 'n':	if (optarg) server_net=atoi(optarg); break;
				case 'i':	if (optarg) serverID=atoi(optarg); break;
			}
		}
	}

	if (!areaID) {
		printf("No areaID given, assuming areaID=1\n");
		areaID=1;
	}
	if (!areaM) {
		printf("No mirror given, assuming areaM=1\n");
		areaM=1;
	}
	if (!serverID) {
		printf("No serverID given, assuming serverID=1\n");
		serverID=1;
	}

#ifdef STAFF
	while (!check_staff_start()) sleep(1);
#endif


        // set character number limit depending on area
	switch(areaID) {
		case 1:		maxchars=512; break;
		case 2:		maxchars=896; break;
		case 3:		maxchars=384; break;
		case 4:		maxchars=2048; break;
		case 5:		maxchars=768; break;
		case 6:		maxchars=384; break;
		case 7:		maxchars=1280; break;
		case 8:		maxchars=384; break;
		case 9:		maxchars=1280; break;
		case 10:	maxchars=512; break;
		case 11:	maxchars=384; break;
		case 12:	maxitem=1024*48; maxchars=384; break;
		case 13:	maxchars=9*50+200; break;
		case 14:	maxchars=16*50+200; break;
		case 15:	maxchars=384; break;
		case 16:	maxchars=384; break;
		case 17:	maxchars=512; break;
		case 18:	maxchars=768; break;
		case 19:	maxchars=384; break;
		case 20:	maxchars=768; break;
		case 21:	maxchars=768; break;
		case 22:	maxchars=512; break;
		case 23:	maxchars=512; break;
		case 24:	maxchars=384; break;
		case 25:	maxchars=384+8*25*2; break;
		case 26:	maxchars=256; break;
		case 27:	maxchars=2048; break;
		case 28:	maxchars=384; break;
		case 29:	maxchars=512; break;
		case 30:	maxchars=384; break;
		case 31:	maxitem=1024*40; maxchars=512; break;
		case 32:	maxchars=1280; break;
		case 33:	maxchars=1600; break;
		case 34:	maxchars=1280; break;
		case 35:	maxchars=768; break;
		case 36:	maxchars=768; break;
		case 37:	maxchars=1024; break;

		default:	maxchars=768; break;
	}
	
	// set item and effect limit
	if (!maxitem) maxitem=max(maxchars*12+10240,20480);
	if (!maxeffect) maxeffect=max(maxchars*2,1024);

	printf("serverID=%d, areaID=%d, areaM=%d, maxchars=%d, maxitem=%d, maxeffect=%d\n\n",
	       serverID,areaID,areaM,maxchars,maxitem,maxeffect);

	if (demon) {
		printf("Demonizing...\n\n");
		
		if (fork()) exit(0);
		for (n=0; n<256; n++) close(n);
		setsid();
#ifndef STAFF
		nologin=1;
#endif
	}

        // ignore the silly pipe errors:
        signal(SIGPIPE,SIG_IGN);

	// ignore sighup - just to be safe
        signal(SIGHUP,SIG_IGN);

	/*signal(SIGSEGV,sig_crash);
	signal(SIGFPE,sig_crash);
	signal(SIGBUS,sig_crash);
	signal(SIGSTKFLT,sig_crash);*/

        // shutdown gracefully if possible:
        signal(SIGQUIT,sig_leave);
        signal(SIGINT,sig_leave);
        signal(SIGTERM,sig_leave);

	// show profile info on CTRL-Z
	signal(SIGTSTP,sig_showprof);

	// init random number generator
        srand(time_now);

	if (!init_smalloc()) exit(1);
	if (!init_mem()) exit(1);
        if (!init_prof()) exit(1);
	if (!init_log()) exit(1);	
        if (!init_database()) exit(1);
	if (!init_lookup())  exit(1);
        if (!init_sector())  exit(1);
        if (!init_los()) exit(1);
	if (!init_timer()) exit(1);
        if (!init_notify()) exit(1);
	if (!init_create()) exit(1);
        if (!init_lib()) exit(1);
	if (!init_io()) exit(1);
        if (!init_path()) exit(1);	
	if (!init_effect()) exit(1);
	if (!init_container()) exit(1);
	if (!init_store()) exit(1);
	if (!init_chat()) exit(1);

	init_sound_sector();

	xlog("AreaID=%d, AreaM=%d, entering game loop...",areaID,areaM);

	dlog(0,0,"Server started");
	prof_reset();

        while (!quit) {
		sprintf(args[0],"./server -a %d -m %d -i %d # %d on %d%% load (busy)",areaID,areaM,serverID,online,(10000-server_idle)/100);
		start=rdtsc();
		lock_server();

		time_now=time(NULL);
		prof=prof_start(26); tick_date(); prof_stop(26,prof);
		prof=prof_start(22); tick_timer(); prof_stop(22,prof);
                prof=prof_start(4); tick_char(); prof_stop(4,prof);
                prof=prof_start(24); tick_effect(); prof_stop(24,prof);
		prof=prof_start(36); tick_clan(); prof_stop(36,prof);
		prof=prof_start(39); tick_club(); prof_stop(39,prof);
		prof=prof_start(5); tick_player(); prof_stop(5,prof);
		prof=prof_start(34); tick_login(); prof_stop(34,prof);
                prof=prof_start(6); pflush(); prof_stop(6,prof);
		prof=prof_start(7); io_loop(); prof_stop(7,prof);
                prof=prof_start(3); tick_chat(); prof_stop(3,prof);

		if (showprof) {
			show_prof();
			showprof=0;
		}
		
		prof=prof_start(8); prof_update(); prof_stop(8,prof);

		end=rdtsc();
		cycles=end-start;

		if ((ticker&2047)==0) {
			prof=prof_start(27); area_alive(0); prof_stop(27,prof);
			prof=prof_start(28); backup_players(); prof_stop(28,prof);
			call_stat_update();
			read_motd();			
			reinit_log();
		}

		if ((ticker&255)==0) {
			call_check_task();
			call_area_load();
			shutdown_warn();
#ifdef STAFF
			check_staff_stop();
#endif
		}

		if ((ticker&255)==168) {
			prof=prof_start(38);
			consistency_check_items();
			consistency_check_map();
			consistency_check_chars();
			consistency_check_containers();
			prof_stop(38,prof);
		}

                unlock_server();

		sprintf(args[0],"./server -a %d -m %d -i %d # %d on %d%% load (idle)",areaID,areaM,serverID,online,(10000-server_idle)/100);

		prof=prof_start(1); tick_sleep(0); prof_stop(1,prof);
		
		ticker++;
	}

        xlog("Left game loop");
	respawn_check();

	for (n=1; n<MAXCHARS; n++) {
		if (ch[n].flags&CF_PLAYER) {
			exit_char(n);
		}
	}
	area_alive(1);

        show_prof();

	dlog(0,0,"Server stopped");

	xlog("map check");
	check_map();

        exit_lib();
	exit_database();

	xlog("Clean shutdown");
	showmem();
	exit_log();
	exit_io();

        return 0;
}
Ejemplo n.º 13
0
int main (int argc, char *argv[])
{                               /* --- main function */
  int    i, k = 0;              /* loop variables, counters */
  char   *s;                    /* to traverse options */
  char   **optarg = NULL;       /* option argument */
  char   *fn_hdr  = NULL;       /* name of table header file */
  char   *fn_tab  = NULL;       /* name of table file */
  char   *fn_frq  = NULL;       /* name of frequency file */
  char   *fn_out  = NULL;       /* name of output file */
  char   *blanks  = NULL;       /* blank  characters */
  char   *fldseps = NULL;       /* field  separators */
  char   *recseps = NULL;       /* record separators */
  char   *nullchs = NULL;       /* null value characters */
  char   *comment = NULL;       /* comment characters */
  char   *clsname = NULL;       /* name of class column to balance */
  int    inflags  = 0;                 /* table file read  flags */
  int    outflags = AS_ATT|AS_WEIGHT;  /* table file write flags */
  double wgtsum   = 0;          /* weight of tuples in output table */
  int    valcnt;                /* number of attribute values */
  int    clsid;                 /* id of class column */
  ATT    *att;                  /* class attribute */
  int    d;                     /* delimiter type */

  prgname = argv[0];            /* get program name for error msgs. */

  /* --- print startup/usage message --- */
  if (argc > 1) {               /* if arguments are given */
    fprintf(stderr, "%s - %s\n", argv[0], DESCRIPTION);
    fprintf(stderr, VERSION); } /* print a startup message */
  else {                        /* if no argument is given */
    printf("usage: %s [options] [-q frqfile] "
                     "[-d|-h hdrfile] tabfile outfile\n", argv[0]);
    printf("%s\n", DESCRIPTION);
    printf("%s\n", VERSION);
    printf("-c#      name of field to balance (default: last field)\n");
    printf("-s#      sum of tuple weights in output table "
                    "(default: as in input table)\n");
    printf("         (-2: lower, -1: boost, 0: shift weights)\n");
    printf("-q       adjust to relative frequencies stated in frqfile\n");
    printf("frqfile  file containing value/relative frequency pairs\n");
    printf("-a       align fields of output table "
                    "(default: do not align)\n");
    printf("-w       do not write field names to output file\n");
    printf("-b#      blank   characters    (default: \" \\t\\r\")\n");
    printf("-f#      field   separators    (default: \" \\t\")\n");
    printf("-r#      record  separators    (default: \"\\n\")\n");
    printf("-C#      comment characters    (default: \"#\")\n");
    printf("-u#      null value characters (default: \"?*\")\n");
    printf("-n       number of tuple occurrences in last field\n");
    printf("-d       use default header "
                    "(field names = field numbers)\n");
    printf("-h       read table header (field names) from hdrfile\n");
    printf("hdrfile  file containing table header (field names)\n");
    printf("tabfile  table file to read "
                    "(field names in first record)\n");
    printf("outfile  file to write output table to\n");
    return 0;                   /* print a usage message */
  }                             /* and abort the program */

  /* --- evaluate arguments --- */
  for (i = 1; i < argc; i++) {  /* traverse arguments */
    s = argv[i];                /* get option argument */
    if (optarg) { *optarg = s; optarg = NULL; continue; }
    if ((*s == '-') && *++s) {  /* -- if argument is an option */
      while (1) {               /* traverse characters */
        switch (*s++) {         /* evaluate option */
          case 'c': optarg    = &clsname;      break;
          case 's': wgtsum    = strtod(s, &s); break;
          case 'q': optarg    = &fn_frq;       break;
          case 'a': outflags |= AS_ALIGN;      break;
          case 'w': outflags &= ~AS_ATT;       break;
  	  case 'b': optarg    = &blanks;       break;
          case 'f': optarg    = &fldseps;      break;
          case 'r': optarg    = &recseps;      break;
          case 'u': optarg    = &nullchs;      break;
          case 'C': optarg    = &comment;      break;
          case 'n': inflags  |= AS_WEIGHT;     break;
          case 'd': inflags  |= AS_DFLT;       break;
          case 'h': optarg    = &fn_hdr;       break;
          default : error(E_OPTION, *--s);     break;
        }                       /* set option variables */
        if (!*s) break;         /* if at end of string, abort loop */
        if (optarg) { *optarg = s; optarg = NULL; break; }
      } }                       /* get option argument */
    else {                      /* -- if argument is no option */
      switch (k++) {            /* evaluate non-option */
        case  0: fn_tab = s;      break;
        case  1: fn_out = s;      break;
        default: error(E_ARGCNT); break;
      }                         /* note filenames */
    }
  }
  if (optarg) error(E_OPTARG);  /* check option argument */
  if (k != 2) error(E_ARGCNT);  /* check number of arguments */
  if (fn_hdr) {                 /* set header flags */
    inflags = AS_ATT | (inflags & ~AS_DFLT);
    if (strcmp(fn_hdr, "-") == 0) fn_hdr = "";
  }                             /* convert "-" to "" */

  /* --- read table header --- */
  attset = as_create("domains", att_delete);
  if (!attset) error(E_NOMEM);  /* create an attribute set */
  as_chars(attset, recseps, fldseps, blanks, nullchs, comment);
  fprintf(stderr, "\n");        /* set delimiter characters */
  in = io_hdr(attset, fn_hdr, fn_tab, inflags, 1);
  if (!in) error(1);            /* read the table header */

  /* --- determine id of class attribute --- */
  if (!clsname)                 /* if no class attribute name given, */
    clsid = as_attcnt(attset) -1;     /* use last column as class */
  else {                        /* if class attribute name is given */
    if ((clsid = as_attid(attset, clsname)) < 0) {
      s = (inflags & AS_ATT) ? fn_hdr : fn_tab;
      io_error(E_MISFLD, s, 1, clsname); error(1);
    }                           /* check whether class exists */
  }                             /* and abort on error */

  /* --- read table --- */
  table = io_bodyin(attset, in, fn_tab, inflags, "table", 1);
  in    = NULL;                 /* read the table and */
  if (!table) error(1);         /* check for an error */

  /* --- balance frequencies --- */
  if (fn_frq) {                 /* if frequencies are given */
    if (*fn_frq)                /* if a proper file name is given, */
      in = fopen(fn_frq, "rb"); /* open frequency file for reading */
    else {                      /* if no proper file name is given, */
      in = stdin; fn_frq = "<stdin>"; } /* read from standard input */
    fprintf(stderr, "reading %s ... ", fn_frq);
    if (!in) error(E_FOPEN, fn_frq);
    att    = as_att(attset, clsid);
    valcnt = att_valcnt(att);   /* get att. and number of values */
    freqs  = (double*)malloc(valcnt *sizeof(double));
    if (!freqs) error(E_NOMEM); /* allocate a frequency vector */
    for (i = valcnt; --i >= 0; ) freqs[i] = 1.0F;
    for (k = 0; 1; k++) {       /* frequency read loop */
      d = ts_next(as_tabscan(attset), in, buf, AS_MAXLEN);
      if (d <= TS_EOF) {        /* read next value */
        if (d == TS_ERR) error(E_FREAD, fn_frq); else break; }
      if (buf[0] == '\0') {     /* if name read is empty */
        if (d != TS_REC) error(E_EXPVAL, fn_frq, k+1);
        continue;               /* check for a missing name */
      }                         /* and skip empty lines */
      if (d != TS_FLD) error(E_EXPNUM, fn_frq, k+1);
      i = att_valid(att, buf);  /* get the value identifier */
      if (i < 0) {              /* and check it */
        io_error(E_VALUE, fn_frq, k+1, buf, 1); error(1); }
      d = ts_next(as_tabscan(attset), in, buf, AS_MAXLEN);
      if (d == TS_ERR) error(E_FREAD, fn_frq);
      if (d != TS_REC) {        /* check the number of fields */
        io_error(E_FLDCNT, fn_frq, k+1, "", 3, 2); error(1); }
      freqs[i] = strtod(buf, &s);    /* read the value frequency */
      if ((s == buf) || *s || (freqs[i] < 0)) {
        io_error(E_NUMBER, fn_frq, k+1, buf, 2); error(1); }
    }                           /* convert frequency to a number */
    if (in != stdin) fclose(in);/* close the input file */
    in = NULL;                  /* and clear the variable */
    fprintf(stderr, "done.\n"); /* print a success message */
  }
  tab_reduce(table);            /* reduce and balance the table */
  tab_balance(table, clsid, wgtsum, freqs);

  /* --- write output table --- */
  if (io_tabout(table, fn_out, outflags, 1) != 0)
    error(1);                   /* write the balanced table */

  /* --- clean up --- */
  #ifndef NDEBUG
  if (freqs) free(freqs);       /* delete frequency vector, */
  tab_delete(table, 1);         /* table, and attribute set */
  #endif
  #ifdef STORAGE
  showmem("at end of program"); /* check memory usage */
  #endif
  return 0;                     /* return 'ok' */
}  /* main() */
Ejemplo n.º 14
0
int main (int argc, char *argv[])
{                               /* --- main function */
  int  i, k = 0;                /* loop variables, counter */
  char *s;                      /* to traverse the options */
  char **optarg = NULL;         /* option argument */
  char *fn_hdr  = NULL;         /* name of table header file */
  char *fn_tab  = NULL;         /* name of table file */
  char *fn_dom  = NULL;         /* name of domains file */
  char *blanks  = NULL;         /* blanks */
  char *fldseps = NULL;         /* field  separators */
  char *recseps = NULL;         /* record separators */
  char *nullchs = NULL;         /* null value characters */
  char *comment = NULL;         /* comment characters */
  int  flags    = 0;            /* table file read flags */
  int  sort     = 0;            /* flag for domain sorting */
  int  atdet    = 0;            /* flag for automatic type determ. */
  int  ivals    = AS_IVALS;     /* flag for numeric intervals */
  int  maxlen   = 0;            /* maximal output line length */
  int  attid;                   /* loop variable for attributes */
  ATT  *att;                    /* to traverse attributes */
  clock_t t;                    /* timer for measurement */

  prgname = argv[0];            /* get program name for error msgs. */

  /* --- print startup/usage message --- */
  if (argc > 1) {               /* if arguments are given */
    fprintf(stderr, "%s - %s\n", argv[0], DESCRIPTION);
    fprintf(stderr, VERSION); } /* print a startup message */
  else {                        /* if no argument is given */
    printf("usage: %s [options] "
                     "[-d|-h hdrfile] tabfile domfile\n", argv[0]);
    printf("%s\n", DESCRIPTION);
    printf("%s\n", VERSION);
    printf("-s       sort domains alphabetically "
                    "(default: order of appearance)\n");
    printf("-S       sort domains numerically/alphabetically\n");
    printf("-a       automatic type determination "
                    "(default: all nominal)\n");
    printf("-i       do not print intervals for numeric attributes\n");
    printf("-l#      output line length (default: no limit)\n");
    printf("-b#      blank   characters    (default: \" \\t\\r\")\n");
    printf("-f#      field   separators    (default: \" \\t\")\n");
    printf("-r#      record  separators    (default: \"\\n\")\n");
    printf("-C#      comment characters    (default: \"#\")\n");
    printf("-u#      null value characters (default: \"?*\")\n");
    printf("-n       number of tuple occurrences in last field\n");
    printf("-d       use default header "
                    "(field names = field numbers)\n");
    printf("-h       read table header (field names) from hdrfile\n");
    printf("hdrfile  file containing table header (field names)\n");
    printf("tabfile  table file to read "
                    "(field names in first record)\n");
    printf("domfile  file to write domain descriptions to\n");
    return 0;                   /* print a usage message */
  }                             /* and abort the program */

  /* --- evaluate arguments --- */
  for (i = 1; i < argc; i++) {  /* traverse the arguments */
    s = argv[i];                /* get option argument */
    if (optarg) { *optarg = s; optarg = NULL; continue; }
    if ((*s == '-') && *++s) {  /* -- if argument is an option */
      while (1) {               /* traverse characters */
        switch (*s++) {         /* evaluate option */
          case 's': sort   = 1;                     break;
          case 'S': sort   = 2;                     break;
          case 'a': atdet  = 1;                     break;
          case 'i': ivals  = 0;                     break;
          case 'l': maxlen = (int)strtol(s, &s, 0); break;
  	  case 'b': optarg = &blanks;               break;
          case 'f': optarg = &fldseps;              break;
          case 'r': optarg = &recseps;              break;
          case 'u': optarg = &nullchs;              break;
          case 'C': optarg = &comment;              break;
          case 'n': flags |= AS_WEIGHT;             break;
          case 'd': flags |= AS_DFLT;               break;
          case 'h': optarg = &fn_hdr;               break;
          default : error(E_OPTION, *--s);          break;
        }                       /* set option variables */
        if (!*s) break;         /* if at end of string, abort loop */
        if (optarg) { *optarg = s; optarg = NULL; break; }
      } }                       /* get option argument */
    else {                      /* -- if argument is no option */
      switch (k++) {            /* evaluate non-option */
        case  0: fn_tab = s;      break;
        case  1: fn_dom = s;      break;
        default: error(E_ARGCNT); break;
      }                         /* note filenames */
    }
  }
  if (optarg) error(E_OPTARG);  /* check option argument */
  if (k != 2) error(E_ARGCNT);  /* check number of arguments */
  if (fn_hdr && (strcmp(fn_hdr, "-") == 0))
    fn_hdr = "";                /* convert "-" to "" */
  if (fn_hdr)                   /* set header flags */
    flags = AS_ATT | (flags & ~AS_DFLT);

  /* --- determine attributes and domains --- */
  attset = as_create("domains", att_delete);
  if (!attset) error(E_NOMEM);  /* create an attribute set */
  as_chars(attset, recseps, fldseps, blanks, nullchs, comment);
  fprintf(stderr, "\n");        /* set delimiter characters */
  i = io_tab(attset, fn_hdr, fn_tab, flags, 1);
  if (i != 0) error(-i);        /* read the table */

  /* --- convert/sort domains --- */
  if (atdet) {                  /* if automatic type determination */
    for (attid = as_attcnt(attset); --attid >= 0; )
      att_conv(as_att(attset, attid), AT_AUTO, NULL);
  }                             /* try to convert attributes */
  if (sort) {                   /* if to sort domains (values) */
    for (attid = as_attcnt(attset); --attid >= 0; ) {
      att = as_att(attset, attid);
      if (att_type(att) != AT_NOM) continue;
      att_valsort(att, (sort > 1) ? numcmp : strcmp, NULL, 0);
    }                           /* traverse nominal attributes */
  }                             /* and sort their domains */

  /* --- write output file --- */
  t = clock();                  /* start the timer */
  if (fn_dom && *fn_dom)        /* if a domain file name is given, */
    out = fopen(fn_dom, "w");   /* open domain file for writing */
  else {                        /* if no domain file name is given, */
    out = stdout; fn_dom = "<stdout>"; }         /* write to stdout */
  fprintf(stderr, "writing %s ... ", fn_dom);
  if (!out) error(E_FOPEN, fn_dom);
  if (as_desc(attset, out, AS_TITLE|ivals, maxlen) != 0)
    error(E_FWRITE, fn_dom);    /* write domain descriptions */
  if (out != stdout) {          /* if not written to stdout, */
    i = fclose(out); out = NULL;/* close the output file */
    if (i != 0) error(E_FWRITE, fn_dom);
  }                             /* print a success message */
  fprintf(stderr, "[%d attribute(s)] done", as_attcnt(attset));
  fprintf(stderr, " [%.2fs].\n", SEC_SINCE(t));

  /* --- clean up --- */
  #ifndef NDEBUG
  as_delete(attset);            /* delete attribute set */
  #endif
  #ifdef STORAGE
  showmem("at end of program"); /* check memory usage */
  #endif
  return 0;                     /* return 'ok' */
}  /* main() */
Ejemplo n.º 15
0
int main (int argc, char *argv[])
{                               /* --- main function */
  int     i, k = 0, n;          /* loop variables, counters */
  char    *s;                   /* to traverse the options */
  char    **optarg = NULL;      /* option argument */
  char    *fn_in   = NULL;      /* name of input  file */
  char    *fn_out  = NULL;      /* name of output file */
  char    *fn_app  = NULL;      /* name of item appearances file */
  char    *blanks  = NULL;      /* blanks */
  char    *fldseps = NULL;      /* field  separators */
  char    *recseps = NULL;      /* record separators */
  char    *comment = NULL;      /* comment indicators */
  char    *isep    = " ";       /* item separator for output */
  char    *impl    = " <- ";    /* implication sign for ass. rules */
  char    *dflt    = "  (%1S)"; /* default format for check */
  char    *format  = dflt;      /* format for information output */
  int     target   = 's';       /* target type (sets/rules/h.edges) */
  int     min      = 1;         /* minimum rule/item set size */
  int     max      = INT_MAX;   /* maximum rule/item set size */
  double  supp     = 10;        /* minimum support    (in percent) */
  double  smax     = 100;       /* maximum support    (in percent) */
  double  conf     = 80;        /* minimum confidence (in percent) */
  int     dir      = 0;         /* direction for size sorting */
  int     eval     = 0;         /* additional evaluation measure */
  int     zero     = 0;         /* flag for zero eval. below expect. */
  int     aggm     = 0;         /* aggregation mode for eval. measure */
  double  minval   = 10;        /* minimum evaluation measure value */
  int     prune    = 0;         /* (min. size for) evaluation pruning */
  double  filter   = 0.1;       /* item usage filtering parameter */
  int     sort     = 2;         /* flag for item sorting and recoding */
  int     tree     = 1;         /* flag for transaction tree */
  int     heap     = 1;         /* flag for heap sort vs. quick sort */
  int     post     = 0;         /* flag for a-posteriori pruning */
  int     report   = 0;         /* other flags for reporting */
  int     mode     = APP_BODY|IST_PERFECT;    /* search mode */
  int     size;                 /* current item set size */
  int     wgt;                  /* total transaction weight */
  int     frq, body, head;      /* frequency of an item set */
  int     *items;               /* item set (for reporting) */
  clock_t t, tt, tc, x;         /* timers for measurements */

  #ifndef QUIET                 /* if not quiet version */
  prgname = argv[0];            /* get program name for error msgs. */

  /* --- print usage message --- */
  if (argc > 1) {               /* if arguments are given */
    fprintf(stderr, "%s - %s\n", argv[0], DESCRIPTION);
    fprintf(stderr, VERSION); } /* print a startup message */
  else {                        /* if no arguments are given */
    printf("usage: %s [options] infile outfile [appfile]\n", argv[0]);
    printf("%s\n", DESCRIPTION);
    printf("%s\n", VERSION);
    printf("-t#      target type                              "
                    "(default: %c)\n", target);
    printf("         (s: frequent item sets, c: closed item sets,\n"
           "          m: maximal item sets,  r: association rules)\n");
    printf("-m#      minimum number of items per set/rule     "
                    "(default: %d)\n", min);
    printf("-n#      maximum number of items per set/rule     "
                    "(default: no limit)\n");
    printf("-s#      minimum support    of a     set/rule     "
                    "(default: %g%%)\n", supp);
    printf("-S#      maximum support    of a     set/rule     "
                    "(default: %g%%)\n", smax);
    printf("         (positive: percentage, "
                     "negative: absolute number)\n");
    printf("-c#      minimum confidence of a     rule         "
                    "(default: %g%%)\n", conf);
    printf("-o       use the original rule support definition "
                    "(body & head)\n");
    printf("-e#      additional evaluation measure            "
                    "(default: none)\n");
    printf("-a#      aggregation mode for evaluation measure  "
                    "(default: none)\n");
    printf("-z       zero evaluation below expected support   "
                    "(default: evaluate all)\n");
    printf("-d#      minimum value of add. evaluation measure "
                    "(default: %g%%)\n", minval);
    printf("-p#      (min. size for) pruning with evaluation  "
                    "(default: no pruning)\n");
    printf("         (< 0: backward,   > 0: forward)\n");
    printf("-l#      sort item sets in output by their size   "
                    "(default: no sorting)\n");
    printf("         (< 0: descending, > 0: ascending)\n");
    printf("-g       write item names in scanable form "
                    "(quote certain characters)\n");
    printf("-k#      item separator for output                "
                    "(default: \"%s\")\n", isep);
    printf("-i#      implication sign for association rules   "
                    "(default: \"%s\")\n", impl);
    printf("-v#      output format for set/rule information   "
                    "(default: \"%s\")\n", format);
    printf("-q#      sort items w.r.t. their frequency        "
                    "(default: %d)\n", sort);
    printf("         (1: ascending, -1: descending, 0: do not sort,\n"
           "          2: ascending, -2: descending w.r.t. "
                    "transaction size sum)\n");
    printf("-u#      filter unused items from transactions    "
                    "(default: %g)\n", filter);
    printf("         (0: do not filter items w.r.t. usage in sets,\n"
           "         <0: fraction of removed items for filtering,\n"
           "         >0: take execution times ratio into account)\n");
    printf("-j       use quicksort to sort the transactions   "
                    "(default: heapsort)\n");
    printf("-x       do not prune the search "
                    "with perfect extensions\n");
    printf("-y       a-posteriori pruning of infrequent item sets\n");
    printf("-h       do not organize transactions as a prefix tree\n");
    printf("-b#      blank   characters                       "
                    "(default: \" \\t\\r\")\n");
    printf("-f#      field   separators                       "
                    "(default: \" \\t,\")\n");
    printf("-r#      record  separators                       "
                    "(default: \"\\n\")\n");
    printf("-C#      comment characters                       "
                    "(default: \"#\")\n");
    printf("-!       print additional option information\n");
    printf("infile   file to read transactions from\n");
    printf("outfile  file to write item sets/association rules"
                    "/hyperedges to\n");
    printf("appfile  file stating item appearances (optional)\n");
    return 0;                   /* print a usage message */
  }                             /* and abort the program */
  #endif  /* #ifndef QUIET */
  /* free option characters: w [A-Z]\[SC] */

  /* --- evaluate arguments --- */
  for (i = 1; i < argc; i++) {  /* traverse the arguments */
    s = argv[i];                /* get an option argument */
    if (optarg) { *optarg = s; optarg = NULL; continue; }
    if ((*s == '-') && *++s) {  /* -- if argument is an option */
      while (*s) {              /* traverse the options */
        switch (*s++) {         /* evaluate the options */
          case '!': help();                         break;
          case 't': target = (*s) ? *s++ : 's';     break;
          case 'm': min    = (int)strtol(s, &s, 0); break;
          case 'n': max    = (int)strtol(s, &s, 0); break;
          case 's': supp   =      strtod(s, &s);    break;
          case 'S': smax   =      strtod(s, &s);    break;
          case 'c': conf   =      strtod(s, &s);    break;
          case 'o': mode  |= APP_BOTH;              break;
          case 'e': eval   = (*s) ? *s++ : 0;       break;
          case 'z': zero   = IST_ZERO;              break;
          case 'a': aggm   = (*s) ? *s++ : 0;       break;
          case 'd': minval =      strtod(s, &s);    break;
          case 'p': prune  = (int)strtol(s, &s, 0); break;
          case 'g': report = ISR_SCAN;              break;
          case 'k': optarg = &isep;                 break;
          case 'i': optarg = &impl;                 break;
          case 'v': optarg = &format;               break;
          case 'l': dir    = (int)strtol(s, &s, 0); break;
          case 'q': sort   = (int)strtol(s, &s, 0); break;
          case 'u': filter =      strtod(s, &s);    break;
          case 'h': tree   = 0;                     break;
          case 'j': heap   = 0;                     break;
          case 'x': mode  &= ~IST_PERFECT;          break;
          case 'y': post   = 1;                     break;
          case 'b': optarg = &blanks;               break;
          case 'f': optarg = &fldseps;              break;
          case 'r': optarg = &recseps;              break;
          case 'C': optarg = &comment;              break;
          default : error(E_OPTION, *--s);          break;
        }                       /* set the option variables */
        if (optarg && *s) { *optarg = s; optarg = NULL; break; }
      } }                       /* get an option argument */
    else {                      /* -- if argument is no option */
      switch (k++) {            /* evaluate non-options */
        case  0: fn_in  = s;      break;
        case  1: fn_out = s;      break;
        case  2: fn_app = s;      break;
        default: error(E_ARGCNT); break;
      }                         /* note filenames */
    }
  }
  if (optarg) error(E_OPTARG);  /* check the option argument */
  if ((k < 2) || (k > 3))       /* and the number of arguments */
    error(E_ARGCNT);            /* (either in/out or in/out/app) */
  if ((!fn_in || !*fn_in) && (fn_app && !*fn_app))
    error(E_STDIN);             /* stdin must not be used twice */
  switch (target) {             /* check and translate target type */
    case 's': target = TT_ALL;               break;
    case 'c': target = TT_CLOSED;            break;
    case 'm': target = TT_MAXIMAL;           break;
    case 'r': target = TT_RULE;              break;
    default : error(E_TARGET, (char)target); break;
  }
  if (min < 0) error(E_SIZE, min); /* check the limits */
  if (max < 0) error(E_SIZE, max); /* for the set size */
  if (supp > 100)               /* check the minimum support */
    error(E_SUPP, supp);        /* (< 0: absolute support) */
  if ((conf < 0) || (conf > 100))
    error(E_CONF, conf);        /* check the minimum confidence */
  switch (eval) {               /* check and translate measure */
    case 'x': case 0: eval = IST_NONE;      break;
    case 'c': eval = IST_CONF;              break;
    case 'd': eval = IST_CONF_DIFF;         break;
    case 'l': eval = IST_LIFT;              break;
    case 'a': eval = IST_LIFT_DIFF;         break;
    case 'q': eval = IST_LIFT_QUOT;         break;
    case 'v': eval = IST_CVCT;              break;
    case 'e': eval = IST_CVCT_DIFF;         break;
    case 'r': eval = IST_CVCT_QUOT;         break;
    case 'f': eval = IST_CERT;              break;
    case 'n': eval = IST_CHI2;              break;
    case 'p': eval = IST_CHI2_PVAL;         break;
    case 'i': eval = IST_INFO;              break;
    case 'g': eval = IST_INFO_PVAL;         break;
    case 'b': eval = IST_LOGQ;              break;
    default : error(E_MEASURE, (char)eval); break;
  }
  switch (aggm) {               /* check and translate agg. mode */
    case 'x': case 0: aggm = IST_NONE;      break;
    case 'm': aggm = IST_MIN;               break;
    case 'n': aggm = IST_MAX;               break;
    case 'a': aggm = IST_AVG;               break;
    default : error(E_MEASURE, (char)aggm); break;
  }
  if ((target > TT_ALL)         /* if individual set counters needed */
  || ((eval > IST_NONE) && (eval < IST_LOGQ)))
    mode &= ~IST_PERFECT;       /* remove perfect extension pruning */
  if (target <= TT_MAXIMAL) {   /* remove rule specific settings */
    mode |= APP_BOTH; conf = 100; } 
  if ((filter <= -1) || (filter >= 1))
    filter = 0;                 /* check and adapt the filter option */
  if (dir)                      /* if to sort output by size, */
    mode &= ~IST_PERFECT;       /* do not use perfect ext. pruning */

  /* --- create item base --- */
  ibase = ib_create(0, 0);      /* create an item base and */
  if (!ibase) error(E_NOMEM);   /* set the special characters */
  ib_chars(ibase, blanks, fldseps, recseps, "", comment);
  MSG(stderr, "\n");            /* terminate the startup message */

  /* --- read item appearance indicators --- */
  if (fn_app) {                 /* if item appearances are given */
    t = clock();                /* start the timer for the reading */
    if (*fn_app)                /* if an app. file name is given, */
      in = fopen(fn_app, "r");  /* open the item appearances file */
    else {                      /* if no app. file name is given, */
      in = stdin; fn_app = "<stdin>"; }   /* read from std. input */
    MSG(stderr, "reading %s ... ", fn_app);
    if (!in) error(E_FOPEN, fn_app);
    k = ib_readapp(ibase, in);  /* read the item appearances */
    if (k  != 0) error(k, fn_app, RECCNT(ibase), BUFFER(ibase));
    if (in != stdin) fclose(in);/* if not read from standard input, */
    in = NULL;                  /* close the input file */
    MSG(stderr, "[%d item(s)]", ib_cnt(ibase));
    MSG(stderr, " done [%.2fs].\n", SEC_SINCE(t));
  }                             /* print a log message */

  /* --- read transactions --- */
  t = clock();                  /* start the timer for the reading */
  if (fn_in && *fn_in)          /* if an input file name is given, */
    in = fopen(fn_in, "r");     /* open input file for reading */
  else {                        /* if no input file name is given, */
    in = stdin; fn_in = "<stdin>"; }   /* read from standard input */
  MSG(stderr, "reading %s ... ", fn_in);
  if (!in) error(E_FOPEN, fn_in);
  tabag = tb_create(ibase, 0);  /* create a transaction bag/multiset */
  if (!tabag) error(E_NOMEM);   /* to store the transactions */
  while (1) {                   /* transaction read loop */
    k = ib_read(ibase, in);     /* read the next transaction */
    if (k) { if (k > 0) break;  /* check for error and end of file */
      error(k, fn_in, RECCNT(ibase), BUFFER(ibase)); }
    if (tb_add(tabag, NULL) != 0) error(E_NOMEM);
  }                             /* add transaction to bag/multiset */
  if (in != stdin) fclose(in);  /* if not read from standard input, */
  in  = NULL;                   /* close the input file */
  n   = ib_cnt(ibase);          /* get the number of items */
  k   = tb_cnt(tabag);          /* get the number of transactions */
  wgt = tb_wgt(tabag);          /* the total transaction weight */
  MSG(stderr, "[%d item(s), ", n);
  if (k == wgt) MSG(stderr,    "%d transaction(s)]", k);
  else          MSG(stderr, "%d/%d transaction(s)]", k, wgt);
  MSG(stderr, " done [%.2fs].", SEC_SINCE(t));
  if ((n <= 0) || (wgt <= 0))   /* check for at least one item */
    error(E_NOTRANS);           /* and at least one transaction */
  MSG(stderr, "\n");            /* terminate the log message */
  if (format == dflt) {         /* if default info. format is used */
    if (target != TT_RULE) format = (supp < 0) ? "  (%a)" : "  (%1S)";
    else format = (supp < 0) ? "  (%b, %1C)" : "  (%1X, %1C)";
  }                             /* set default according to target */
  supp  = ceil ((supp >= 0) ? 0.01 *supp *wgt : -supp);
  smax  = floor((smax >= 0) ? 0.01 *smax *wgt : -smax);
  conf *= 0.01;                 /* transform support and confidence */

  /* --- sort and recode items --- */
  t = clock();                  /* compute absolute support values */
  MSG(stderr, "filtering, sorting and recoding items ... ");
  map = (int*)malloc(n *sizeof(int));
  if (!map) error(E_NOMEM);     /* create an item identifier map */
  k = (int)((mode & APP_HEAD) ? supp : ceil(supp *conf));
  n = ib_recode(ibase, k, sort, map);
  tb_recode(tabag, map);        /* recode the items and transactions */
  tb_itsort(tabag, 1, heap);    /* and sort items in transactions */
  free(map); map = NULL;        /* delete the item identifier map */
  MSG(stderr, "[%d item(s)] done [%.2fs].", n, SEC_SINCE(t));
  if (n <= 0) error(E_NOFREQ);  /* print a log message and */
  MSG(stderr, "\n");            /* check the number of items */
  k   = tb_max(tabag);          /* clamp the set/rule length to */
  if (max > k) max = k;         /* the maximum transaction size */

  /* --- reduce transactions --- */
  t = clock();                  /* start the timer for the reduction */
  MSG(stderr, "reducing transactions ... ");
  tb_filter(tabag, min, NULL);  /* remove items of short transactions */
  tb_sort(tabag, 1, heap);      /* sort the trans. lexicographically */
  k = tb_reduce(tabag);         /* reduce transactions to unique ones */
  if (k == wgt) MSG(stderr,    "[%d transaction(s)]", k);
  else          MSG(stderr, "[%d/%d transaction(s)]", k, wgt);
  MSG(stderr, " done [%.2fs].\n", SEC_SINCE(t));

  /* --- create transaction tree --- */
  tt = 0;                       /* init. the tree construction time */
  if (tree) {                   /* if to use a transaction tree */
    t = clock();                /* start the timer for construction */
    MSG(stderr, "building transaction tree ... ");
    tatree = tt_create(tabag);  /* create a transaction tree */
    if (!tatree) error(E_NOMEM);
    if (filter == 0) {          /* if not to filter items, */
      tb_delete(tabag, 0);      /* delete the transaction bag */
      tabag = NULL;             /* (redundant data storage) */
    }
    MSG(stderr, "[%d node(s)]", tt_nodecnt(tatree));
    MSG(stderr, " done [%.2fs].\n", SEC_SINCE(t));
    tt = clock() -t;            /* note the time for the construction */
  }                             /* of the transaction tree */

  /* --- create item set tree --- */
  t = clock(); tc = 0;          /* start the timer for the search */
  istree = ist_create(ibase, mode, (int)supp, (int)smax, conf);
  if (!istree) error(E_NOMEM);  /* create an item set tree */
  ist_seteval(istree, eval|zero, aggm, 0.01*minval, prune);

  /* --- check item subsets --- */
  MSG(stderr, "checking subsets of size 1");
  map = (int*)malloc(n *sizeof(int));
  if (!map) error(E_NOMEM);     /* create a filter map */
  while (1) {                   /* traverse the item set sizes */
    size = ist_height(istree);  /* get the current item set size and */
    if (size >= max) break;     /* abort if maximal size is reached */
    if ((filter != 0)           /* if to filter w.r.t. item usage */
    &&  (ist_check(istree, map) <= size))
      break;                    /* check which items are still used */
    if (post)                   /* if a-posteriori pruning requested, */
      ist_prune(istree);        /* prune infrequent item sets */
    k = ist_addlvl(istree);     /* while max. height is not reached, */
    if (k) { if (k > 0) break;  /* add a level to the item set tree */
             error(E_NOMEM);  } /* if no level was added, abort */
    if (((filter < 0)           /* if to filter w.r.t. item usage */
    &&   (i < -filter *n))      /* and enough items were removed */
    ||  ((filter > 0)           /* or counting time is long enough */
    &&   (i < n) && (i *(double)tt < filter *n *tc))) {
      n = i;                    /* note the new number of items */
      x = clock();              /* start the timer for filtering */
      tb_filter(tabag, size+1, map);
      tb_sort(tabag, 0, heap);  /* remove unnec. items and trans. */
      tb_reduce(tabag);         /* and reduce trans. to unique ones */
      if (tatree) {             /* if a transaction tree was created */
        tt_delete(tatree, 0);   /* delete the transaction tree */
        tatree = tt_create(tabag);
        if (!tatree) error(E_NOMEM);
      }                         /* rebuild the transaction tree */
      tt = clock() -x;          /* note the filter/rebuild time */
    }
    MSG(stderr, " %d", ++size); /* print the current item set size */
    x = clock();                /* start the timer for counting */
    if (tatree) ist_countx(istree, tatree);
    else        ist_countb(istree, tabag);
    tc = clock() -x;            /* count the transaction tree/bag */
  }                             /* and compute the new counting time */
  free(map); map = NULL;        /* delete the filter map */
  MSG(stderr, " done [%.2fs].\n", SEC_SINCE(t));

  /* --- filter found item sets --- */
  if ((target == TT_CLOSED) || (target == TT_MAXIMAL)) {
    t = clock();                /* start the timer for filtering */
    MSG(stderr, "filtering for %s item sets ... ",
        (target == TT_MAXIMAL) ? "maximal" : "closed");
    k = target | ((prune < 0) ? IST_EVAL : 0);
    ist_mark(istree, k);        /* filter closed/maximal item sets */
    MSG(stderr, "done [%.2fs].\n", SEC_SINCE(t));
  }                             /* print a log message */

  /* --- print item sets/rules/hyperedges --- */
  t = clock();                  /* start the timer for the output */
  if (fn_out && *fn_out)        /* if an output file name is given, */
    out = fopen(fn_out, "w");   /* open the output file */
  else {                        /* if no output file name is given, */
    out = stdout; fn_out = "<stdout>"; }    /* write to std. output */
  MSG(stderr, "writing %s ... ", fn_out);
  if (!out) error(E_FOPEN, fn_out);
  if (eval == IST_LOGQ) report |= ISR_LOGS;
  if ((target == TT_CLOSED) || (target == TT_MAXIMAL))
    report |= ISR_NOEXP;        /* combine the report mode flags */
  isrep = isr_create(ibase, out, report, isep, impl);
  if (!isrep) error(E_NOMEM);   /* create an item set reporter */
  isr_setfmt (isrep, format);   /* and configure it */
  isr_setsize(isrep,  min, max);
  ist_setsize(istree, min, max, dir);
  ist_init   (istree);          /* initialize the extraction */
  items = t_items(ib_tract(ibase));
  if ((target <= TT_MAXIMAL)    /* if to find frequent item sets */
  &&  (dir == 0)) {             /* and not to sort them by size */
    if      (eval == IST_LOGQ)  /* if to compute an add. evaluation */
      isr_seteval(isrep, isr_logq,  NULL,   0.01*minval);
    else if (eval >  IST_NONE)  /* set the add. evaluation function */
      isr_seteval(isrep, ist_evalx, istree, 0.01*minval);
    n = ist_report(istree, isrep); } /* report the item sets */
  else if (target <= TT_MAXIMAL) { /* if to find frequent item sets */
    for (n = 0; 1; ) {          /* extract item sets from the tree */
      k = ist_set(istree, items, &frq, &minval);
      if (k < 0) break;         /* get the next frequent item set */
      if (k > 0) fputs(isr_name(isrep, items[0]), out);
      for (i = 0; ++i < k; ) {  /* print the item names */
        fputs(isep, out); fputs(isr_name(isrep, items[i]), out); }
      if (format)               /* if requested, print information */
        isr_sinfo(isrep, frq, minval);
      fputc('\n', out); n++;    /* terminate the output line and */
    } }                         /* count the reported item set */
  else if (target == TT_RULE) { /* if to find association rules, */
    for (n = 0; 1; ) {          /* extract rules from tree */
      k = ist_rule(istree, items, &frq, &body, &head, &minval);
      if (k < 0) break;         /* get the next association rule */
      fputs(isr_name(isrep, items[0]), out);
      fputs(impl, out);         /* print name of rule head item */
      if (k > 1) fputs(isr_name(isrep, items[1]), out);
      for (i = 1; ++i < k; ) {  /* print names of items in rule body */
        fputs(isep, out); fputs(isr_name(isrep, items[i]), out); }
      if (format)               /* if requested, print information */
        isr_rinfo(isrep, frq, body, head, minval);
      fputc('\n', out); n++;    /* terminate the output line and */
    }                           /* count the reported ass. rule */
  }  /* if (target <= TT_MAXIMAL) .. else .. */
  if (fflush(out) != 0) error(E_FWRITE, fn_out);
  if (out != stdout) fclose(out);
  out = NULL;                   /* close the output file */
  MSG(stderr, "[%d %s(s)] done ", n,
              (target == TT_RULE) ? "rule" : "set");
  MSG(stderr, "[%.2fs].\n", SEC_SINCE(t));
  #ifdef BENCH                  /* if benchmark version, */
  ist_stats(istree);            /* show the search statistics */
  #endif                        /* (especially memory usage) */

  /* --- clean up --- */
  #ifndef NDEBUG                /* if this is a debug version */
  isr_delete(isrep, 0);             /* the item set reporter, */
  ist_delete(istree);               /* the item set tree, */
  if (tatree) tt_delete(tatree, 0); /* the transaction tree, */
  if (tabag)  tb_delete(tabag,  0); /* the transaction bag, */
  ib_delete(ibase);                 /* and the item base */
  #endif
  #ifdef STORAGE                /* if storage debugging */
  showmem("at end of program"); /* check memory usage */
  #endif
  return 0;                     /* return 'ok' */
}  /* main() */
Ejemplo n.º 16
0
int		ManageSessionCMD(Host Relay, SessProp *SessionProposal, uchar **ResponseBuffer, SResponse Response, uint *BRSize)
{
	uint		Idx, Cmd, SessID;
	uchar		ResponseCMDDatas[0xFFF] = {0};
	ObjectDesc	*SoughtObj;
	ObjectDesc	ObjSid, ObjSeq, ObjBlob, ObjV, ObjPrevSid;
	SResponse	SessCMDDatas;
	Memory_U	Tmp;
	static uint	SeqNbr = 0;
	static uint	InitialHeaderID = 0;
	static char	*ChatPeerName = NULL;

	Idx = 0;
	printf("Session Cmd received..\n");

	SoughtObj = GetObjByID(Response, 0x01, -1, -1);
	if (SoughtObj == NULL)
		return (-1);

	SessID = SoughtObj->Value.Nbr;
	
	if ((SessionProposal->CreatedSID == 0) && (SessionProposal->LocalCreatedSID == 0))
	{
		SessionProposal->CreatedSID = Response.Objs[Idx].Value.Nbr;
		SessionProposal->LocalCreatedSID = BytesRandom();
		printf("Created Session SID : 0x%x(%u) {Local SID : 0x%x(%u)}\n\n", Response.Objs[Idx].Value.Nbr, Response.Objs[Idx].Value.Nbr, SessionProposal->LocalCreatedSID, SessionProposal->LocalCreatedSID);
	}
	else
		printf("Command's SID : 0x%x(%u)..\n\n", Response.Objs[Idx].Value.Nbr, Response.Objs[Idx].Value.Nbr);

	SoughtObj = GetObjByID(Response, 0x04, -1, -1);
	if (SoughtObj == NULL)
	{
		cprintf(FOREGROUND_BLUE, "No SessionCMD..\n\n");
		return (0);
	}

	SessCMDDatas.Objs = NULL;
	SessCMDDatas.NbObj = 0;

	Tmp = SoughtObj->Value.Memory;
	ManageObjects(&(Tmp.Memory), Tmp.MsZ, &SessCMDDatas);

	SoughtObj = GetObjByID(SessCMDDatas, 0x01, -1, -1);
	if (SoughtObj == NULL)
		return (-1);

	Cmd = SoughtObj->Value.Nbr;

	ObjectDesc	RCDObjNbr;
	uchar		*RCDBrowser;
	uchar		*RCDMark;
	uint		ObjListIdx;

	switch(Cmd)
	{
	case 0x0D: //LetBeSyncBuddies (-> SendMeCredentialsAndStuff (0x23))
		cprintf(FOREGROUND_BLUE, "LetBeSyncBuddies Received.. Response : SendMeCredentialsAndStuff..\n");

		SoughtObj = GetObjByID(SessCMDDatas, 0x02, -1, -1);
		if (SoughtObj == NULL)
		{
			printf("No String ID for created session..\n");
			return (-1);
		}

		SessionProposal->CreatedSStrID = _strdup((char *)SoughtObj->Value.Memory.Memory);
		printf("Created Session String ID : %s\n", SessionProposal->CreatedSStrID);

		ObjSid.Family = OBJ_FAMILY_NBR;
		ObjSid.Id = 0x01;
		ObjSid.Value.Nbr = SessionProposal->LocalCreatedSID;

		ObjSeq.Family = OBJ_FAMILY_NBR;
		ObjSeq.Id = 0x03;
		ObjSeq.Value.Nbr = SeqNbr;
		SeqNbr += 1;

		RCDBrowser = ResponseCMDDatas;
		RCDMark = RCDBrowser;

		*RCDBrowser++ = RAW_PARAMS;
		WriteValue(&RCDBrowser, 0x01);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x01;
		RCDObjNbr.Value.Nbr = 0x23;				//SendMeCredentialsAndStuff
		WriteObject(&RCDBrowser, RCDObjNbr);

		ObjBlob.Family = OBJ_FAMILY_BLOB;
		ObjBlob.Id = 0x04;
		ObjBlob.Value.Memory.Memory = RCDMark;
		ObjBlob.Value.Memory.MsZ = (uint)(RCDBrowser - RCDMark);

		ObjV.Family = OBJ_FAMILY_NBR;
		ObjV.Id = 0x07;
		ObjV.Value.Nbr = 0x08;

		ObjPrevSid.Family = OBJ_FAMILY_NBR;
		ObjPrevSid.Id = 0x02;
		ObjPrevSid.Value.Nbr = SessionProposal->CreatedSID;

		*BRSize += BuildUserPacket(Relay, ResponseBuffer, 0xFFFF, 0x6D, SessionProposal->AesStreamOut, 5, ObjSid, ObjSeq, ObjBlob, ObjV, ObjPrevSid);
		SessionProposal->AesStreamOut->IvecIdx = 0;

		break;
	case 0x2A: //HereAreMyCredentials
		cprintf(FOREGROUND_BLUE, "HereAreMyCredentials (FROM CRED) Received.. Response : [SESSIONCMDACK]..\n");

		printf("Skipping (FROM) Credentials Saving..\n");

		//SEND SESSION CMD ACK NOT INDISPENSABLE

		break;
	case 0x13: //HereAreSomeHeaders (-> SendMeBodies (0x15))
		uint		NbHeaders;
		ObjectDesc	*SObj9, *SObjA, *SObj;

		cprintf(FOREGROUND_BLUE, "HereAreSomeHeaders Received.. Response : SendMeBodies..\n");

		NbHeaders = 0;

		for (Idx = 0; Idx < SessCMDDatas.NbObj; Idx++)
		{
			if ((SessCMDDatas.Objs[Idx].Id == 0x0A) && (SessCMDDatas.Objs[Idx].ObjListInfos.Id == 0x14))
				NbHeaders++;
		}

		SoughtObj = GetObjByID(SessCMDDatas, 0x0F, -1, -1);
		if (SoughtObj == NULL)
		{
			printf("No ID for Headers List..\n");
			return (-1);
		}

		InitialHeaderID = SoughtObj->Value.Nbr;

		printf("Headers List (0x%x) Size : #%d..\n", SoughtObj->Value.Nbr, NbHeaders);

		ObjSid.Family = OBJ_FAMILY_NBR;
		ObjSid.Id = 0x01;
		ObjSid.Value.Nbr = SessionProposal->LocalCreatedSID;

		ObjSeq.Family = OBJ_FAMILY_NBR;
		ObjSeq.Id = 0x03;
		ObjSeq.Value.Nbr =  SeqNbr;
		SeqNbr += 1;

		RCDBrowser = ResponseCMDDatas;
		RCDMark = RCDBrowser;

		*RCDBrowser++ = RAW_PARAMS;
		WriteValue(&RCDBrowser, 0x01 + NbHeaders);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x01;
		RCDObjNbr.Value.Nbr = 0x15;				//SendMeBodies
		WriteObject(&RCDBrowser, RCDObjNbr);

		ObjListIdx = 1;
		SObj9 = SObjA = SObj = NULL;

		while (NbHeaders--)
		{
			RCDObjNbr.Family = OBJ_FAMILY_NBR;
			RCDObjNbr.Id = 0x0A;

			SObj9 = GetObjByID(SessCMDDatas, 0x09, 0x14, ObjListIdx);
			SObjA = GetObjByID(SessCMDDatas, 0x0A, 0x14, ObjListIdx);
			if ((SObj9 == NULL) && (SObjA == NULL))
			{
				printf("Error Getting Header's Body To Request ID..\n");
				return (-1);
			}
			SObj = (SObjA == NULL) ? SObjA : SObj9;

			RCDObjNbr.Value.Nbr = SObj->Value.Nbr;
			WriteObject(&RCDBrowser, RCDObjNbr);

			ObjListIdx += 1;
		}

		ObjBlob.Family = OBJ_FAMILY_BLOB;
		ObjBlob.Id = 0x04;
		ObjBlob.Value.Memory.Memory = RCDMark;
		ObjBlob.Value.Memory.MsZ = (uint)(RCDBrowser - RCDMark);

		*BRSize += BuildUserPacket(Relay, ResponseBuffer, 0xFFFF, 0x6D, SessionProposal->AesStreamOut, 3, ObjSid, ObjSeq, ObjBlob);
		SessionProposal->AesStreamOut->IvecIdx = 0;

		break;
	case 0x2B: //HereAreBodies (-> IAmSyncingHere(0x10))
		uint		NbBodies;

		cprintf(FOREGROUND_BLUE, "HereAreBodies Received.. Response : [SESSIONCMDACK]..\n");

		NbBodies = 0;

		for (Idx = 0; Idx < SessCMDDatas.NbObj; Idx++)
		{
			if ((SessCMDDatas.Objs[Idx].Id == 0x0A) && (SessCMDDatas.Objs[Idx].ObjListInfos.Id == 0x20))
				NbBodies++;
		}

		ObjListIdx = 1;
		while (NbBodies--)
		{
			uint	MId;

			MId = 0x00;

			printf("Message #%d Properties :\n", ObjListIdx);
			
			SoughtObj = GetObjByID(SessCMDDatas, 0x00, 0x20, ObjListIdx);
			if (SoughtObj == NULL)
				printf("No STORE_AGE..\n");
			else
				printf("STORE_AGE : 0x%x\n", SoughtObj->Value.Nbr);

			SoughtObj = GetObjByID(SessCMDDatas, 0x02, 0x20, ObjListIdx);
			if (SoughtObj == NULL)
				printf("No UID_CRC..\n");
			else
				printf("UID_CRC : 0x%x\n", SoughtObj->Value.Nbr);

			SoughtObj = GetObjByID(SessCMDDatas, 0x0A, 0x20, ObjListIdx);
			if (SoughtObj == NULL)
				printf("No MID..\n");
			else
			{
				printf("MID : 0x%x\n", SoughtObj->Value.Nbr);
				MId = SoughtObj->Value.Nbr;
			}

			SoughtObj = GetObjByID(SessCMDDatas, 0x03, 0x20, ObjListIdx);
			if (SoughtObj == NULL)
				printf("No Message Body (?!?)..\n");
			else
			{
				RSA				*SkypeRSA;
				uchar			UnRSA[0xFFF];
				uchar			*PostProcessed;
				uint			PPsZ, Save;
				int				Suite;

				printf("RSA PUB KEY FROM [HEREAREBODIES]\n");
				showmem(SessionProposal->PeerContact->RsaPubKey.Memory, SessionProposal->PeerContact->RsaPubKey.MsZ);
				printf("\n");

				SkypeRSA = RSA_new();
				BN_hex2bn(&(SkypeRSA->n), Bin2HexStr(SessionProposal->PeerContact->RsaPubKey.Memory, MODULUS_SZ));
				BN_hex2bn(&(SkypeRSA->e), "10001");
				PPsZ = SoughtObj->Value.Memory.MsZ;
				SoughtObj->Value.Memory.MsZ -= PPsZ;
				Save = PPsZ;
				PPsZ = 0x80;
				ZeroMemory(UnRSA, 0xFFF);
				PPsZ = RSA_public_decrypt(PPsZ, SoughtObj->Value.Memory.Memory, UnRSA, SkypeRSA, RSA_NO_PADDING);
				RSA_free(SkypeRSA);

				printf("UnRSA :\n");
				showmem(UnRSA, PPsZ);
				printf("\n");

				if (PPsZ == 0xFFFFFFFF)
				{
					printf("Unable To UnRSA Message Body..\n");
					goto UnRSAFailed;
				}

				Suite = Save - PPsZ;
				SoughtObj->Value.Memory.Memory += PPsZ;

				printf("Suite :\n");
				showmem(SoughtObj->Value.Memory.Memory, Suite);
				printf("\n");

				PostProcessed = FinalizeLoginDatas(UnRSA, &PPsZ, (Suite > 0) ? SoughtObj->Value.Memory.Memory : NULL, Suite);

				if (PostProcessed == NULL)
				{
					printf("Bad Datas [METADATAS] Finalization..\n");

					PPsZ = 0x80;
					PostProcessed = FinalizeLoginDatas(UnRSA, &PPsZ, (Suite > 0) ? SoughtObj->Value.Memory.Memory : NULL, Suite);

					goto UnRSAFailed;
				}

				PostProcessed += SHA_DIGEST_LENGTH;
				PPsZ -= SHA_DIGEST_LENGTH;

				PostProcessed += (uint)strlen(SessionProposal->CreatedSStrID);
				PPsZ -= (uint)strlen(SessionProposal->CreatedSStrID);

				showmem(PostProcessed, PPsZ);
				printf("\n");

				SResponse ChatMsgDatas;

				ChatMsgDatas.Objs = NULL;
				ChatMsgDatas.NbObj = 0;

				ManageObjects(&PostProcessed, PPsZ, &ChatMsgDatas);

				if (MId == InitialHeaderID)
				{
					ChatPeerName = _strdup((char *)SessionProposal->PeerContact->DisplayName);

					/*SoughtObj = GetObjByID(ChatMsgDatas, 0x01, -1, -1);
					if (SoughtObj == NULL)
					{
						printf("No ChatPeer Name Specified.. Using Peer DisplayName\n\n");
						ChatPeerName = _strdup((char *)SessionProposal->PeerContact->DisplayName);
					}
					else
						ChatPeerName = _strdup((char *)SoughtObj->Value.Memory.Memory);*/
				}
				else
				{
					SoughtObj = GetObjByID(ChatMsgDatas, 0x02, -1, -1);
					if (SoughtObj == NULL)
						printf("Empty Message..\n\n");
					else
					{
						cprintf(YELLOW, "%s says :\n", ChatPeerName);
						cprintf(YELLOW, "%s\n\n", SoughtObj->Value.Memory.Memory);
					}
				}

				if (MId != 0)
				{
					ObjSid.Family = OBJ_FAMILY_NBR;
					ObjSid.Id = 0x01;
					ObjSid.Value.Nbr = SessionProposal->LocalCreatedSID;

					ObjSeq.Family = OBJ_FAMILY_NBR;
					ObjSeq.Id = 0x03;
					ObjSeq.Value.Nbr =  SeqNbr;
					SeqNbr += 1;

					RCDBrowser = ResponseCMDDatas;
					RCDMark = RCDBrowser;

					*RCDBrowser++ = RAW_PARAMS;
					WriteValue(&RCDBrowser, 0x06);

					RCDObjNbr.Family = OBJ_FAMILY_NBR;
					RCDObjNbr.Id = 0x01;
					RCDObjNbr.Value.Nbr = 0x10;				//IAmSyncingHere
					WriteObject(&RCDBrowser, RCDObjNbr);

					RCDObjNbr.Family = OBJ_FAMILY_NBR;
					RCDObjNbr.Id = 0x0A;
					RCDObjNbr.Value.Nbr = MId;
					WriteObject(&RCDBrowser, RCDObjNbr);

					RCDObjNbr.Family = OBJ_FAMILY_NBR;
					RCDObjNbr.Id = 0x13;
					RCDObjNbr.Value.Nbr = 0x10;
					WriteObject(&RCDBrowser, RCDObjNbr);

					RCDObjNbr.Family = OBJ_FAMILY_NBR;
					RCDObjNbr.Id = 0x22;
					RCDObjNbr.Value.Nbr = 0x01;
					WriteObject(&RCDBrowser, RCDObjNbr);

					RCDObjNbr.Family = OBJ_FAMILY_NBR;
					RCDObjNbr.Id = 0x23;
					RCDObjNbr.Value.Nbr = 0x01;
					WriteObject(&RCDBrowser, RCDObjNbr);

					RCDObjNbr.Family = OBJ_FAMILY_NBR;
					RCDObjNbr.Id = 0x25;
					RCDObjNbr.Value.Nbr = 0x01;
					WriteObject(&RCDBrowser, RCDObjNbr);

					ObjBlob.Family = OBJ_FAMILY_BLOB;
					ObjBlob.Id = 0x04;
					ObjBlob.Value.Memory.Memory = RCDMark;
					ObjBlob.Value.Memory.MsZ = (uint)(RCDBrowser - RCDMark);

					//*BRSize += BuildUserPacket(Relay, ResponseBuffer, 0xFFFF, 0x6D, SessionProposal->AesStreamOut, 3, ObjSid, ObjSeq, ObjBlob);
					//SessionProposal->AesStreamOut->IvecIdx = 0;
				}
			}
UnRSAFailed:
			ObjListIdx += 1;
		}

		break;
	case 0x24: //HereAreCredentialsAndStuff (-> WeAreSyncBuddies (0x0F), SendYourCredentials(0x29), IAmSyncingHere(0x10))
		cprintf(FOREGROUND_BLUE, "HereAreCredentialsAndStuff (TO CRED) Received.. Response : WeAreSyncBuddies + SendYourCredentials + IAmSyncingHere..\n");

		printf("Skipping (TO) Credentials Saving..\n");

		ObjSid.Family = OBJ_FAMILY_NBR;
		ObjSid.Id = 0x01;
		ObjSid.Value.Nbr = SessionProposal->LocalCreatedSID;

		ObjSeq.Family = OBJ_FAMILY_NBR;
		ObjSeq.Id = 0x03;
		ObjSeq.Value.Nbr =  SeqNbr;
		SeqNbr += 1;

		RCDBrowser = ResponseCMDDatas;
		RCDMark = RCDBrowser;

		*RCDBrowser++ = RAW_PARAMS;
		WriteValue(&RCDBrowser, 0x03);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x01;
		RCDObjNbr.Value.Nbr = 0x0F;				//WeAreSyncBuddies
		WriteObject(&RCDBrowser, RCDObjNbr);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x1C;
		RCDObjNbr.Value.Nbr = 0x01;
		WriteObject(&RCDBrowser, RCDObjNbr);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x1D;
		RCDObjNbr.Value.Nbr = 0x01;
		WriteObject(&RCDBrowser, RCDObjNbr);

		ObjBlob.Family = OBJ_FAMILY_BLOB;
		ObjBlob.Id = 0x04;
		ObjBlob.Value.Memory.Memory = RCDMark;
		ObjBlob.Value.Memory.MsZ = (uint)(RCDBrowser - RCDMark);

		*BRSize += BuildUserPacket(Relay, ResponseBuffer, 0xFFFF, 0x6D, SessionProposal->AesStreamOut, 3, ObjSid, ObjSeq, ObjBlob);
		SessionProposal->AesStreamOut->IvecIdx = 0;

		ZeroMemory(ResponseCMDDatas, sizeof(ResponseCMDDatas));

		ObjSid.Family = OBJ_FAMILY_NBR;
		ObjSid.Id = 0x01;
		ObjSid.Value.Nbr = SessionProposal->LocalCreatedSID;

		ObjSeq.Family = OBJ_FAMILY_NBR;
		ObjSeq.Id = 0x03;
		ObjSeq.Value.Nbr =  SeqNbr;
		SeqNbr += 1;

		RCDBrowser = ResponseCMDDatas;
		RCDMark = RCDBrowser;

		*RCDBrowser++ = RAW_PARAMS;
		WriteValue(&RCDBrowser, 0x01);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x01;
		RCDObjNbr.Value.Nbr = 0x29;				//SendYourCredentials
		WriteObject(&RCDBrowser, RCDObjNbr);

		ObjBlob.Family = OBJ_FAMILY_BLOB;
		ObjBlob.Id = 0x04;
		ObjBlob.Value.Memory.Memory = RCDMark;
		ObjBlob.Value.Memory.MsZ = (uint)(RCDBrowser - RCDMark);

		*BRSize += BuildUserPacket(Relay, ResponseBuffer, 0xFFFF, 0x6D, SessionProposal->AesStreamOut, 3, ObjSid, ObjSeq, ObjBlob);
		SessionProposal->AesStreamOut->IvecIdx = 0;

		ZeroMemory(ResponseCMDDatas, sizeof(ResponseCMDDatas));

		ObjSid.Family = OBJ_FAMILY_NBR;
		ObjSid.Id = 0x01;
		ObjSid.Value.Nbr = SessionProposal->LocalCreatedSID;

		ObjSeq.Family = OBJ_FAMILY_NBR;
		ObjSeq.Id = 0x03;
		ObjSeq.Value.Nbr =  SeqNbr;
		SeqNbr += 1;

		RCDBrowser = ResponseCMDDatas;
		RCDMark = RCDBrowser;

		*RCDBrowser++ = RAW_PARAMS;
		WriteValue(&RCDBrowser, 0x06);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x01;
		RCDObjNbr.Value.Nbr = 0x10;				//IAmSyncingHere
		WriteObject(&RCDBrowser, RCDObjNbr);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x0A;
		RCDObjNbr.Value.Nbr = 0xFFFFFFFF;
		WriteObject(&RCDBrowser, RCDObjNbr);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x13;
		RCDObjNbr.Value.Nbr = 0x10;
		WriteObject(&RCDBrowser, RCDObjNbr);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x22;
		RCDObjNbr.Value.Nbr = 0x01;
		WriteObject(&RCDBrowser, RCDObjNbr);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x23;
		RCDObjNbr.Value.Nbr = 0x01;
		WriteObject(&RCDBrowser, RCDObjNbr);

		RCDObjNbr.Family = OBJ_FAMILY_NBR;
		RCDObjNbr.Id = 0x25;
		RCDObjNbr.Value.Nbr = 0x01;
		WriteObject(&RCDBrowser, RCDObjNbr);

		ObjBlob.Family = OBJ_FAMILY_BLOB;
		ObjBlob.Id = 0x04;
		ObjBlob.Value.Memory.Memory = RCDMark;
		ObjBlob.Value.Memory.MsZ = (uint)(RCDBrowser - RCDMark);

		*BRSize += BuildUserPacket(Relay, ResponseBuffer, 0xFFFF, 0x6D, SessionProposal->AesStreamOut, 3, ObjSid, ObjSeq, ObjBlob);
		SessionProposal->AesStreamOut->IvecIdx = 0;

		//SEND SESSION CMD ACK NOT INDISPENSABLE

		break;
	default :
		printf("UnManaged SessionCMD 0x%x..\n", Cmd);
		break;
	}
	return (1);
}