void
BAG_putpair (long first, long second)
{
  long junk;

  if (BAG_getfirst (&junk, second) != NO_SUCH_PAIR)
    BAG_killpair_bysecond (second);
  addtolist (&lookupbyfirst[hash (first)], first, second);
  addtolist (&lookupbysecond[hash (second)], first, second);
}
Ejemplo n.º 2
0
Archivo: cfg.c Proyecto: berkus/lang-e
/* bb_linklbl: make p the predecessor of the basic block starting with 
   label l: if the block does not exist, create a forward reference that
   will be resolved later. */
static inline void bb_linklbl (i_bb_t p, i_label_t l) {
     i_bb_t s = label2bb(l);
     assert(p);
     if (!s) {
	  fwdrefs[fwdref_cur].src = p;
	  fwdrefs[fwdref_cur].dst = l;
	  fwdref_cur++;
     } else {
	  addtolist(i_bb_t, p->n, s, p->nn, p->ln, 4);
	  addtolist(i_bb_t, s->p, p, s->np, s->lp, 4);
     }
}
Ejemplo n.º 3
0
/* Steps in program: determine the number of iterations of desired
 * function required to get a measurement interval of the desired
 * length, allocate vectors of that size, initialize to appropriate
 * values for both the related and random scenarios, make the runs,
 * output the results. */
main()
{
    int i,itercount;
    unsigned ccount;
    
    /* The next two lines are just a sanity check -- particularly
       useful when trying on a new platform. Can comment out when
       doing repeated runs thereafter. */
    /* display_CPUspeed();
    printf("Cycle threshold for measurements: %.2f (millions)\n\n", 
    (double) CMIN / 1e6);  */

    itercount = measurecnt();
    printf("Measuring using %d iterations\n",itercount);

    /* allocate arrays for both scenarios */
    allocarrays(itercount);
    
    /* initialize arrays for scenario 1: valA[i] < valB[i] */
    initarrays1(itercount);
    
    /* do multiple runs for this scenario, recording each */
    clearlist();
    for (i = 0; i < MEASMAX; i++)
    {
	ccount = measure(itercount);
	addtolist(ccount);
    }

    /* test and output best */
    printf("Cycles per function call, predictable branches\n");
    testbest();

    /* initialize arrays for scenario 2: valA[i] ? valB[i] */
    initarrays2(itercount);
    
    /* do multiple runs for this scenario, recording each */
    clearlist();
    for (i = 0; i < MEASMAX; i++)
    {
	ccount = measure(itercount);
	addtolist(ccount);
    }

    /* test and output best */
    printf("Cycles per function call, unpredictable branches\n");
    testbest();
}
Ejemplo n.º 4
0
data_t *_dalloc(const size_t size, const char *file, const int line) {
	data_t *memory;
	size_t newsize = mem_allocated + size;
	alloclist_t *newentry;

	if(newsize > mem_lim_hard) {
		if(thread_running)
			for(;;);
		return NULL;
	} else if(!warned && (newsize > mem_lim_soft)) {
		if(mem_verbosity == MEM_VERBOSE)
			fprintf(stderr, "-- WARNING: Soft memory limit reached.\n");
		warned = 1;
	} else if(warned && (newsize < mem_lim_soft))
		warned = 0;

	memory = (data_t*)malloc(size);

	if(memory) {
		if((newentry = make_entry(memory, file, line, size))) {
			addtolist(newentry);

			mem_allocated += size;
			if(mem_allocated > n_bytes_peak)
				n_bytes_peak = mem_allocated;

			n_allocs++;
		} else {
			fprintf(stderr, "ERROR: malloc() failed for new memory list entry.\n");
			free(memory);
			return NULL;
		}
	}
	return memory;
}
Ejemplo n.º 5
0
lisp_data_t *lisp_dalloc(const size_t size, const char *file, const int line, lisp_ctx_t *context) {
	lisp_data_t *memory;
	size_t newsize = context->mem_allocated + size;
	alloclist_t *newentry;

	if(newsize > context->mem_lim_hard) {
		if(context->thread_running)
			for(;;);
		return NULL;
	} else if(!(context->warned) && (newsize > context->mem_lim_soft)) {
		if(context->mem_verbosity == LISP_GC_VERBOSE)
			fprintf(stderr, "-- WARNING: Soft memory limit reached.\n");
		context->warned = 1;
	} else if((context->warned) && (newsize < context->mem_lim_soft))
		context->warned = 0;

	memory = malloc(size);

	if(memory) {
		if((newentry = make_entry(memory, file, line, size))) {
			addtolist(newentry, context);

			context->mem_allocated += size;
			if(context->mem_allocated > context->n_bytes_peak)
				context->n_bytes_peak = context->mem_allocated;

			context->n_allocs++;
		} else {
			fprintf(stderr, "ERROR: malloc() failed for new memory list entry.\n");
			free(memory);
			return NULL;
		}
	}
	return memory;
}
Ejemplo n.º 6
0
/* driver for everything: for current vector and operation types,
 * run through entire range of vector lengths, making repeated
 * measurements of each, then determine slope of line that best
 * matches data, and finally output results as CPE. */
main()
{
    int i,j;
    unsigned ccount;
    
    /* The next two lines are just a sanity check -- particularly
       useful when trying on a new platform. Can comment out when
       doing repeated runs thereafter. */
    /* display_CPUspeed();
    printf("Cycle threshold for measurements: %.2f (millions)\n\n", 
    (double) CMIN / 1e6);  */

    clearmaster();
    initvlen();
    for (i = 2; i <= VECMAX; i = i << 1)
    {
	/* printf("Vector length: %d\n",i);  for debugging */
	setupvectors(i);
	clearlist();
	/* do multiple runs for this vector length, recording each */
	for (j = 0; j < MEASMAX; j++)
	{
	    ccount = measure();
	    addtolist(ccount);
	}
	testbest();
	addtomaster();  /* record best time in master list */
    }
    /* dumpmaster();      for debugging */
    lsfit();	       /* do linear fit */
}
Ejemplo n.º 7
0
void parseHTML(WebPage *currpage, List *currlist, HashTable *currhash, int initdepth){
  int position = 0;
  char* newurl;// = NULL;
  char *end;
  //Parsed through the HTML file and gets every URL
  while((position=GetNextURL(currpage->html, position, currpage->url, &newurl)) > 0 ){
    //Normalized the URL and if it is bad, it will be freed right away
    if (NormalizeURL(newurl)){
      //Deals with internal references
      if((end=strchr(newurl,'#'))){
	*end='\0';
      }
      // checks to make sure that the URL has the defined domain
      if( strstr(newurl,URL_PREFIX) != NULL ){
	if ( insertHashTable(currhash,newurl) == 0 ){
	  //Creates a new webpage for the found url and adds it to the our List if it successfully adds to the hashtable
	  char* dummyurl = (char *)malloc(strlen(newurl)+1);
	  strcpy(dummyurl,newurl);
	  WebPage *newpage=createWebPage(dummyurl, initdepth);
	  addtolist(currlist,newpage);
	  free(newurl);
	} else free(newurl);
      } else free(newurl);
    } else free(newurl);
  } 
  free(end);
}
Ejemplo n.º 8
0
/** recursedirs()
 *  Recursively go througn the directories with the HTML files and memory
 *	map them
 */
void recursedirs(char *name) {
   
   DIR *dp;
   struct dirent *ep;
   struct stat finfo;
   char *path;
   
   if (((req_data > 0) && (data_size < req_data)) || (req_data <= 0)) {
      dp = opendir (name);
      if (dp != NULL)      // it's a directory
      {
         while ((ep = readdir (dp)) != NULL) {
            if (strcmp(ep->d_name, ".") == 0) continue;
            if (strcmp(ep->d_name, "..") == 0) continue;
            
            path = (char *)malloc(strlen(ep->d_name) + strlen(name) + 2);
            sprintf(path, "%s/%s",name,ep->d_name);
            
            recursedirs(path);
            free(path);
         }
         (void) closedir (dp);
      }
      else  // it's not a directory, mmap file and add it to the list
      {
         filelist_t *file;
         CHECK_ERROR((file = (filelist_t *)malloc(sizeof(filelist_t))) == NULL);
         file->fd = open(name, O_RDONLY);
         if (file->fd < 0) {
            free(file);   
         }
         else {
            int ret = fstat(file->fd, &finfo);
            if (ret < 0) {
               free(file);
            }
            else {
               file->size = finfo.st_size;
               char *f_data = mmap(0, file->size + 1, PROT_READ | PROT_WRITE, 
                                                       MAP_PRIVATE, file->fd, 0);
               if (f_data == NULL) {
                  free(file);
               }
               else {
                  CHECK_ERROR((file->name = (char *)malloc(strlen(name) + 1)) == NULL);
                  data_size += finfo.st_size;
                  strcpy(file->name, name);
                  file->data = (char *)malloc(finfo.st_size + 1);
                  memcpy(file->data, f_data, finfo.st_size);
                  addtolist(file);
                  munmap(f_data, file->size + 1);
                  close(file->fd);
               }
            }
         }
      }
   }
   return;
}
Ejemplo n.º 9
0
void	*xmalloc(t_mal **list, size_t size, int i)
{
  void	*tomalloc;

  tomalloc = NULL;
  if ((tomalloc = malloc(size * i)) == NULL)
    return (NULL);
  addtolist(tomalloc, list);
  return (tomalloc);
}
Ejemplo n.º 10
0
void
draw_wire(ModeInfo * mi)
{
	int         offset, i, j, found = 0;
	unsigned char *z, *znew;
	circuitstruct *wp;

	if (circuits == NULL)
		return;
	wp = &circuits[MI_SCREEN(mi)];
	if (wp->newcells == NULL)
		return;

	MI_IS_DRAWN(mi) = True;

	/* wires do not grow so min max stuff does not change */
	for (j = wp->minrow; j <= wp->maxrow; j++) {
		for (i = wp->mincol; i <= wp->maxcol; i++) {
			offset = j * wp->bncols + i;
			z = wp->oldcells + offset;
			znew = wp->newcells + offset;
			if (*z != *znew) {	/* Counting on once a space always a space */
				found = 1;
				*z = *znew;
				if (!addtolist(mi, i - 2, j - 2, *znew - 1)) {
					free_wire(MI_DISPLAY(mi), wp);
					return;
				}
			}
		}
	}
	for (i = 0; i < COLORS - 1; i++)
		if (!draw_state(mi, i)) {
			free_wire(MI_DISPLAY(mi), wp);
			return;
		}
	if (++wp->generation > MI_CYCLES(mi) || !found) {
		init_wire(mi);
		return;
	} else
		do_gen(wp);

	if (wp->redrawing) {
		for (i = 0; i < REDRAWSTEP; i++) {
			if ((*(wp->oldcells + wp->redrawpos))) {
				drawCell(mi, wp->redrawpos % wp->bncols - 2,
					 wp->redrawpos / wp->bncols - 2, *(wp->oldcells + wp->redrawpos) - 1);
			}
			if (++(wp->redrawpos) >= wp->bncols * (wp->bnrows - 2)) {
				wp->redrawing = 0;
				break;
			}
		}
	}
}
Ejemplo n.º 11
0
void osiedl(long x,long y)
{
	long h=gethash(x,y);
	rycerz[r].x=x;
	rycerz[r].y=y;
	addtolist(hash[h],r);
	j[r].miny=y;
	j[r].maxy=y;
	coxadd(r);
	r++;
	rc++;
}
Ejemplo n.º 12
0
void GLPatch::paramSurfaces(BezierPatch G, float res[])
{ 

glm::mat4x4 M(glm::vec4(-1.0f,  3.0f, -3.0f, 1.0f),
              glm::vec4( 3.0f, -6.0f,  3.0f, 0.0f),
              glm::vec4(-3.0f,  3.0f,  0.0f, 0.0f),
              glm::vec4( 1.0f,  0.0f,  0.0f, 0.0f));

for (float s = 0.f; s < 5.f; s += 1.f){
    for (float t = 0.f; t < 5.f; t += 1.f){
        glm::vec4 S(s * s * s, s * s, s, 1.0f);
        glm::vec4 T(t * t * t, t * t, t, 1.0f);

        glm::mat4x4 DLB(glm::vec4(8.0f, 0.0f, 0.0f, 0.0f),
                        glm::vec4(4.0f, 4.0f, 0.0f, 0.0f),
                        glm::vec4(2.0f, 4.0f, 2.0f, 0.0f),
                        glm::vec4(1.0f, 3.0f, 3.0f, 1.0f));
        DLB /= 8.0f;

        glm::mat4x4 DRB(glm::vec4(1.0f, 3.0f, 3.0f, 1.0f),
                        glm::vec4(0.0f, 2.0f, 4.0f, 2.0f),
                        glm::vec4(0.0f, 0.0f, 4.0f, 4.0f),
                        glm::vec4(0.0f, 0.0f, 0.0f, 8.0f));
        DRB /= 8.0f;

        BezierPatch G11 = glm::transpose(DLB) * G * DLB;
        addtolist(G11, res, 0);
        BezierPatch G12 = glm::transpose(DRB) * G * DLB;
        addtolist(G11, res, 47);
        BezierPatch G21 = glm::transpose(DLB) * G * DRB;
        addtolist(G11, res, 95);
        BezierPatch G22 = glm::transpose(DRB) * G * DRB;
        addtolist(G11, res, 143);
        }
    }
}
Ejemplo n.º 13
0
static void
RandomSoup(ModeInfo * mi)
{
	demonstruct *dp = &demons[MI_SCREEN(mi)];
	int         row, col, mrow = 0;

	for (row = 0; row < dp->nrows; ++row) {
		for (col = 0; col < dp->ncols; ++col) {
			dp->oldcell[col + mrow] =
				(unsigned char) LRAND() % ((unsigned char) dp->states);
			if (!addtolist(mi, col, row, dp->oldcell[col + mrow]))
				return; /* sparse soup */
		}
		mrow += dp->ncols;
	}
}
Ejemplo n.º 14
0
static Bool
SetSoup(ModeInfo * mi)
{
	dragonstruct *dp = &dragons[MI_SCREEN(mi)];
	int         row, col, mrow = 0;

	for (row = dp->nrows - 1; row >= 0; --row) {
		for (col = dp->ncols - 1; col >= 0; --col) {
			if (!addtolist(mi, col, row))
				return False;
		}
		mrow += dp->ncols;
	}
	dp->addlist = !dp->addlist;
	return True;
}
Ejemplo n.º 15
0
int main(){
    int result;
    pos = 0;
    
    fgets(buffer,40,stdin);
    while(buffer[0] != '\n'){
        addtolist(buffer);
        fgets(buffer,40,stdin);
    }
    
    fgets(buffer,40,stdin);
    while(!feof(stdin)){
        result = query(buffer);
        if(result != -1){
            printf("%s\n",english[result]);
        } else {
            printf("eh\n");
        }
        fgets(buffer,40,stdin);
    }    
        
    return 0;
}
Ejemplo n.º 16
0
CWindowPtr
createdirwindow (CInfoPBRec *dir, Rect *r, char **path, short volume)
{
  CWindowPeek wp;
  short i;
  OSErr e;
  Str255 s;
  opendirinfo **infoh;
  ControlHandle c;

  if (executor_p ())
    {
      CInfoPBRec cpb;
      OSErr e2;

      cpb = *dir;
      e2 = unixmount (&cpb);
      if (e2 == noErr)
	volume = cpb.hFileInfo.ioVRefNum;
    }
  tail (*path, s);
  wp = (CWindowPeek) NewPtr (sizeof (CWindowRecord));
  wp = (CWindowPeek) NewCWindow (wp, r, s, false, documentProc, (WindowPtr) 0, true, 0);
  wp->refCon = (long) NewHandle (sizeof (opendirinfo));

  infoh = (opendirinfo **) wp->refCon;
#if 1
/* This handle should be unlocked later, but it isn't for Executor 1.99m */
  HLock ((Handle) infoh);
#endif /* 0 */
  (*infoh)->sortorder = ALPHABETIC;
  (*infoh)->items = (ControlHandle (**)[])
    NewHandle (BANDARRAYSIZE * sizeof (ControlHandle));
  (*infoh)->path = path;
  (*infoh)->iodirid = dir->dirInfo.ioDrDirID;
  (*infoh)->vrefnum = volume;
  (*infoh)->numitems = 0;
  (*infoh)->view = ICONVIEW;

/* NOTE: r is the wrong rectangle, but it gets fixed before it's used. */
  (*infoh)->sbar = NewControl ((WindowPtr) wp, r, (StringPtr) "\p", false, 0, 0, 0,
			       scrollBarProc, 0);
  MoveControl ((*infoh)->sbar, wp->port.portRect.right - SCROLLBARWIDTH, 0);

  dir->hFileInfo.ioNamePtr = s;
  dir->hFileInfo.ioVRefNum = volume;
  e = noErr;
  for (i = 1; e == noErr; i++)
    {
      checkgrowitemarray (i, (*infoh)->items);
      dir->hFileInfo.ioDirID = (*infoh)->iodirid;
      dir->hFileInfo.ioFDirIndex = i;
      e = PBGetCatInfo (dir, false);
      if (e == noErr && !(dir->hFileInfo.ioFlFndrInfo.fdFlags & fInvisible))
	{
	  c = addtolist ((WindowPeek) wp, s, dir->hFileInfo.ioFlParID, volume);
	  if (dir->hFileInfo.ioFlFndrInfo.fdType == 'APPL' ||
	      dir->hFileInfo.ioFlFndrInfo.fdType == 'dfil')
	    hashicons (c);
	}
    }
  setwindowicons (wp);
  straightenwindow ((WindowPtr) wp);
  return (CWindowPtr) wp;
}
Ejemplo n.º 17
0
int granted(const char* newgrpname, struct passwd** ppwd)
{
	uid_t	ruid;
	gid_t	newgrp;
	struct group  *grp;

	/*
	 * Initialization.
	 */
	*ppwd = getpwuid(ruid = getuid());

	/*
	 * The following are implementation defined security restrictions.
	 * If euid is not root then reject -- need a setuid-root exectuable.
 	 * If ruid is not root and not in /etc/passwd then reject.
	 */
	if (geteuid() || (ruid && (*ppwd == NULL))) {
		fprintf(stderr, "%s: Who are you?\n", PROGNAME);
		errno = EPERM;
		return -1;
	}

	/*
	 * No operands -- change back to /etc/passwd defaults.
	 */
	if (newgrpname == NULL) {
		/* change group(s) back to original "login fresh" values */
#if (NGROUPS_MAX > 1)
		initgroups((*ppwd)->pw_name, (*ppwd)->pw_gid);
#endif
		/* success */
		return (*ppwd)->pw_gid;
	}

	/*
	 * If given group name exists in /etc/group, then use it,
	 * else assume given group name is really the numeric group id.
	 */
	newgrp = -1;
	if ((grp = getgrnam(newgrpname)) == NULL) {
		char *temp;

		/* if a non-negative numeric group id was given, then use it */
		newgrp = (gid_t) strtol(newgrpname, &temp, 0);
		if ((newgrpname[0] == '\0') || (temp == NULL) ||
			(*temp != '\0') || (newgrp < 0) ||
			(((grp = getgrgid(newgrp)) == NULL) && ruid)) {
			fprintf(stderr, "%s: Unknown group %s\n", PROGNAME, newgrpname);
			errno = EINVAL;
			return -1;
		}
	}
	newgrp = (grp) ? grp->gr_gid : newgrp;

	/*
	 * If one of the following conditions are true, we can skip any
	 * additional security mechanisms:
	 *     - real user id is root
	 *     - new group id matches group id listed in /etc/passwd for user
	 */
	if ((ruid) && (newgrp != (*ppwd)->pw_gid)) {
		int rc;
		char **m, *temp;

		/* Check if the user listed as member of group */
		for (m = grp->gr_mem; *m && strcmp(*m, (*ppwd)->pw_name); m++);

		/* if not member, perform yet another security check */
		if (*m == NULL) {
			/* if no group passwd exists then reject */
			/* else prompt for passwd */
			if (grp->gr_passwd && (grp->gr_passwd[0] != '\0') &&
				(grp->gr_passwd[0] != '*')) {
				temp = getpass("Password:"******"%s: Sorry\n", PROGNAME);
#ifndef DONTUSESYSLOG
					syslog(LOG_AUTH|LOG_WARNING, "BAD NEWGRP by %s to %s%s",
						(*ppwd)->pw_name, newgrpname, ontty());
#endif
					errno = EPERM;
					return -1;
				}
			} else {
				fprintf(stderr, "%s: Sorry\n", PROGNAME);
				errno = EINVAL;
				return -1;
			}
		}
	}

#if (NGROUPS_MAX > 1) /* Does this system support supplemental groups */
	{	
		int gnum;
		gid_t glist[NGROUPS_MAX+1];
#ifdef FRUGAL
		int x;
#endif

		if ((gnum = getgroups(NGROUPS_MAX, glist)) != -1) {

#ifdef FRUGAL /* egid should not be in the sup. group list */
			/* if new gid is in list, remove it */
			for (x = 0; x < gnum; x++) {
				if (glist[x] == newgrp) {
					for (gnum--; x < gnum; x++) {
						glist[x] = glist[x+1];
					}
					break;
				}
			}

#else /* This system normally stores the egid in the sup. group list */

			/* if there is room, add new gid to list */
			gnum = addtolist(newgrp, gnum, &glist[0]);
#endif
			/* if there is room, add old gid to list */
			gnum = addtolist(getegid(), gnum, &glist[0]);

			setgroups(gnum, glist);
		}
	}
#endif

	/* success */
	return newgrp;
}
Ejemplo n.º 18
0
ENTRYPOINT void
draw_demon (ModeInfo * mi)
{
	int         i, j, k, l, mj = 0, ml;
	demonstruct *dp;

	if (demons == NULL)
		return;
	dp = &demons[MI_SCREEN(mi)];
	if (dp->cellList == NULL)
		return;

	MI_IS_DRAWN(mi) = True;
	if (dp->state >= dp->states) {
		(void) memcpy((char *) dp->newcell, (char *) dp->oldcell,
			      dp->ncols * dp->nrows * sizeof (unsigned char));

		if (dp->neighbors == 6) {
			for (j = 0; j < dp->nrows; j++) {
				for (i = 0; i < dp->ncols; i++) {
					/* NE */
					if (!(j & 1))
						k = (i + 1 == dp->ncols) ? 0 : i + 1;
					else
						k = i;
					l = (!j) ? dp->nrows - 1 : j - 1;
					ml = l * dp->ncols;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
					/* E */
					k = (i + 1 == dp->ncols) ? 0 : i + 1;
					ml = mj;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
					/* SE */
					if (!(j & 1))
						k = (i + 1 == dp->ncols) ? 0 : i + 1;
					else
						k = i;
					l = (j + 1 == dp->nrows) ? 0 : j + 1;
					ml = l * dp->ncols;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
					/* SW */
					if (j & 1)
						k = (!i) ? dp->ncols - 1 : i - 1;
					else
						k = i;
					l = (j + 1 == dp->nrows) ? 0 : j + 1;
					ml = l * dp->ncols;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
					/* W */
					k = (!i) ? dp->ncols - 1 : i - 1;
					ml = mj;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
					/* NW */
					if (j & 1)
						k = (!i) ? dp->ncols - 1 : i - 1;
					else
						k = i;
					l = (!j) ? dp->nrows - 1 : j - 1;
					ml = l * dp->ncols;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
				}
				mj += dp->ncols;
			}
		} else if (dp->neighbors == 4 || dp->neighbors == 8) {
			for (j = 0; j < dp->nrows; j++) {
				for (i = 0; i < dp->ncols; i++) {
					/* N */
					k = i;
					l = (!j) ? dp->nrows - 1 : j - 1;
					ml = l * dp->ncols;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
					/* E */
					k = (i + 1 == dp->ncols) ? 0 : i + 1;
					ml = mj;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
					/* S */
					k = i;
					l = (j + 1 == dp->nrows) ? 0 : j + 1;
					ml = l * dp->ncols;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
					/* W */
					k = (!i) ? dp->ncols - 1 : i - 1;
					l = j;
					ml = mj;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
				}
				mj += dp->ncols;
			}
			if (dp->neighbors == 8) {
				mj = 0;
				for (j = 0; j < dp->nrows; j++) {
					for (i = 0; i < dp->ncols; i++) {
						/* NE */
						k = (i + 1 == dp->ncols) ? 0 : i + 1;
						l = (!j) ? dp->nrows - 1 : j - 1;
						ml = l * dp->ncols;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
						/* SE */
						k = (i + 1 == dp->ncols) ? 0 : i + 1;
						l = (j + 1 == dp->nrows) ? 0 : j + 1;
						ml = l * dp->ncols;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
						/* SW */
						k = (!i) ? dp->ncols - 1 : i - 1;
						l = (j + 1 == dp->nrows) ? 0 : j + 1;
						ml = l * dp->ncols;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
						/* NW */
						k = (!i) ? dp->ncols - 1 : i - 1;
						l = (!j) ? dp->nrows - 1 : j - 1;
						ml = l * dp->ncols;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
					}
					mj += dp->ncols;
				}
			}
		} else if (dp->neighbors == 3 || dp->neighbors == 9 ||
			   dp->neighbors == 12) {
			for (j = 0; j < dp->nrows; j++) {
				for (i = 0; i < dp->ncols; i++) {
					if ((i + j) % 2) {	/* right */
						/* W */
						k = (!i) ? dp->ncols - 1 : i - 1;
						ml = mj;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
					} else {	/* left */
						/* E */
						k = (i + 1 == dp->ncols) ? 0 : i + 1;
						ml = mj;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
					}
					/* N */
					k = i;
					l = (!j) ? dp->nrows - 1 : j - 1;
					ml = l * dp->ncols;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
					/* S */
					k = i;
					l = (j + 1 == dp->nrows) ? 0 : j + 1;
					ml = l * dp->ncols;
					if (dp->oldcell[k + ml] ==
					    (int) (dp->oldcell[i + mj] + 1) % dp->states)
						dp->newcell[i + mj] = dp->oldcell[k + ml];
				}
				mj += dp->ncols;
			}
			if (dp->neighbors == 9 || dp->neighbors == 12) {
				mj = 0;
				for (j = 0; j < dp->nrows; j++) {
					for (i = 0; i < dp->ncols; i++) {
						/* NN */
						k = i;
						if (!j)
							l = dp->nrows - 2;
						else if (!(j - 1))
							l = dp->nrows - 1;
						else
							l = j - 2;
						ml = l * dp->ncols;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
						/* SS */
						k = i;
						if (j + 1 == dp->nrows)
							l = 1;
						else if (j + 2 == dp->nrows)
							l = 0;
						else
							l = j + 2;
						ml = l * dp->ncols;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
						/* NW */
						k = (!i) ? dp->ncols - 1 : i - 1;
						l = (!j) ? dp->nrows - 1 : j - 1;
						ml = l * dp->ncols;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
						/* NE */
						k = (i + 1 == dp->ncols) ? 0 : i + 1;
						l = (!j) ? dp->nrows - 1 : j - 1;
						ml = l * dp->ncols;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
						/* SW */
						k = (!i) ? dp->ncols - 1 : i - 1;
						l = (j + 1 == dp->nrows) ? 0 : j + 1;
						ml = l * dp->ncols;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
						/* SE */
						k = (i + 1 == dp->ncols) ? 0 : i + 1;
						l = (j + 1 == dp->nrows) ? 0 : j + 1;
						ml = l * dp->ncols;
						if (dp->oldcell[k + ml] ==
						    (int) (dp->oldcell[i + mj] + 1) % dp->states)
							dp->newcell[i + mj] = dp->oldcell[k + ml];
					}
					mj += dp->ncols;
				}
				if (dp->neighbors == 12) {
					mj = 0;
					for (j = 0; j < dp->nrows; j++) {
						for (i = 0; i < dp->ncols; i++) {
							if ((i + j) % 2) {	/* right */
								/* NNW */
								k = (!i) ? dp->ncols - 1 : i - 1;
								if (!j)
									l = dp->nrows - 2;
								else if (!(j - 1))
									l = dp->nrows - 1;
								else
									l = j - 2;
								ml = l * dp->ncols;
								if (dp->oldcell[k + ml] ==
								    (int) (dp->oldcell[i + mj] + 1) % dp->states)
									dp->newcell[i + mj] = dp->oldcell[k + ml];
								/* SSW */
								k = (!i) ? dp->ncols - 1 : i - 1;
								if (j + 1 == dp->nrows)
									l = 1;
								else if (j + 2 == dp->nrows)
									l = 0;
								else
									l = j + 2;
								ml = l * dp->ncols;
								if (dp->oldcell[k + ml] ==
								    (int) (dp->oldcell[i + mj] + 1) % dp->states)
									dp->newcell[i + mj] = dp->oldcell[k + ml];
								/* EE */
								k = (i + 1 == dp->ncols) ? 0 : i + 1;
								l = j;
								ml = mj;
								if (dp->oldcell[k + ml] ==
								    (int) (dp->oldcell[i + mj] + 1) % dp->states)
									dp->newcell[i + mj] = dp->oldcell[k + ml];
							} else {	/* left */
								/* NNE */
								k = (i + 1 == dp->ncols) ? 0 : i + 1;
								if (!j)
									l = dp->nrows - 2;
								else if (!(j - 1))
									l = dp->nrows - 1;
								else
									l = j - 2;
								ml = l * dp->ncols;
								if (dp->oldcell[k + ml] ==
								    (int) (dp->oldcell[i + mj] + 1) % dp->states)
									dp->newcell[i + mj] = dp->oldcell[k + ml];
								/* SSE */
								k = (i + 1 == dp->ncols) ? 0 : i + 1;
								if (j + 1 == dp->nrows)
									l = 1;
								else if (j + 2 == dp->nrows)
									l = 0;
								else
									l = j + 2;
								ml = l * dp->ncols;
								if (dp->oldcell[k + ml] ==
								    (int) (dp->oldcell[i + mj] + 1) % dp->states)
									dp->newcell[i + mj] = dp->oldcell[k + ml];
								/* WW */
								k = (!i) ? dp->ncols - 1 : i - 1;
								l = j;
								ml = mj;
								if (dp->oldcell[k + ml] ==
								    (int) (dp->oldcell[i + mj] + 1) % dp->states)
									dp->newcell[i + mj] = dp->oldcell[k + ml];
							}
						}
						mj += dp->ncols;
					}
				}
			}
		}
		mj = 0;
		for (j = 0; j < dp->nrows; j++) {
			for (i = 0; i < dp->ncols; i++)
				if (dp->oldcell[i + mj] != dp->newcell[i + mj]) {
					dp->oldcell[i + mj] = dp->newcell[i + mj];
					if (!addtolist(mi, i, j, dp->oldcell[i + mj])) {
						free_demon(MI_DISPLAY(mi), dp);
						return;
					}
				}
			mj += dp->ncols;
		}
		if (++dp->generation > MI_CYCLES(mi))
			init_demon(mi);
		dp->state = 0;
	} else {
		if (dp->ncells[dp->state])
			if (!draw_state(mi, dp->state)) {
				free_demon(MI_DISPLAY(mi), dp);
				return;
			}
		dp->state++;
	}
	if (dp->redrawing) {
		for (i = 0; i < REDRAWSTEP; i++) {
			if (dp->oldcell[dp->redrawpos]) {
				drawcell(mi, dp->redrawpos % dp->ncols, dp->redrawpos / dp->ncols,
					 dp->oldcell[dp->redrawpos]);
			}
			if (++(dp->redrawpos) >= dp->ncols * dp->nrows) {
				dp->redrawing = 0;
				break;
			}
		}
	}
}
Ejemplo n.º 19
0
int main (int argc, char *argv[]){
  //Check to make sure that the arguments are valid
  if( argcheck(argc,argv) == 1 ){
    exit(1);
  }
  //Keep asking the user for inputs unless they choose to quit
  while(1){
    char userInput[MAX_INPUT];
    wordList *currlist;

    printf("Please enter the words that you want to search for:");

    //Getting the words and passing them into a list only if the input is not ctrl + d
    if((fgets(userInput,MAX_INPUT,stdin)) != NULL ){
    List *inputList=malloc(sizeof(List));
    inputList->head=NULL;
    inputList->tail=NULL;
    char *tok;
    tok=strtok(userInput," ");
    while( tok != NULL ){
      char *newword = malloc((strlen(tok)+1)*sizeof(char));
      strcpy(newword,tok);
      addtolist(inputList,newword);
      tok=strtok(NULL," ");
    }

    //Making sure that our last word doesn't contain "\n"
    ListNode *fixingnode = inputList->head;
    while( fixingnode->next != NULL ){
      fixingnode=fixingnode->next;
    }
    fixingnode->word[strlen(fixingnode->word)-1]='\0';

    //Initialize our wordlist
    currlist=initializeList();
    wordListNode *newWordListnode = malloc(sizeof(wordListNode));
    newWordListnode->wnode=NULL;
    newWordListnode->next=NULL;
    currlist->head=newWordListnode;
    WNode *newWnode = malloc(sizeof(WNode));
    newWnode->next = NULL;
    newWnode->word=NULL;
    newWordListnode->wnode = newWnode;

    //Go through each word in the line and add it to our list of words
    wordListNode *currWordListNode=currlist->head;
    WNode *currWnode=currlist->head->wnode;

    ListNode *workingnode = inputList->head;
    while( workingnode != NULL ){
      char *word=workingnode->word;

      if( strcmp(word,"OR") == 0 ){
        WNode *freshWnode = malloc(sizeof(WNode));
        freshWnode->next=NULL;
        freshWnode->word=NULL;
        wordListNode *freshWordListNode = malloc(sizeof(wordListNode));
        freshWordListNode->next=NULL;
        freshWordListNode->wnode=NULL;

	currWordListNode->next=freshWordListNode;
        currWordListNode=currWordListNode->next;
        currWordListNode->wnode=freshWnode;
        currWnode=currWordListNode->wnode;
      } else if (strcmp(word," ") == 0){
      } else if ( strcmp(word,"AND") != 0 ){

        //Normalize all of the words before adding them
        for(int j=0;word[j];j++){
          word[j]=tolower(word[j]);
        }

        WNode *freshWnode = malloc(sizeof(WNode));
        freshWnode->next=NULL;
        freshWnode->word=NULL;
        currWnode->word=word;
        currWnode->next=freshWnode;
        currWnode=currWnode->next;
      }
      workingnode=workingnode->next;
    }
  
    //Take the inverted index and load it into a hashtable
    HashTable *newHash;
    newHash=initializeIndexHash();
    
    FILE *origfile=fopen(argv[1],"r");
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    if (origfile == NULL ){
      printf("Make sure your fourth argument is valid.  Please try again");
      exit(EXIT_FAILURE);
    }
    char *token, *word;
    while ((read = getline(&line,&len,origfile)) != -1 ){
      int wordflag,totflag,IDflag,freqflag;
      wordflag=totflag=IDflag=freqflag=0;
      int IDdoc,freq;
      
      token = strtok(line," ");
      while ( token != NULL ){
	if(wordflag==0){
	  word=token;
	  wordflag=1;
	  token=strtok(NULL," ");
	}
	if(totflag==0){
	  totflag=1;
	  token=strtok(NULL," ");
	}
	if(IDflag==0){
	  IDflag=1;
	  freqflag=1;
	  IDdoc=atoi(token);
	  token=strtok(NULL," ");
	}
	if(freqflag==1){
	  freqflag=0;
	  IDflag=0;
	  freq=atoi(token);
	}
	char *dummy = malloc((strlen(word)+1)*sizeof(char));
	strncpy(dummy,word,strlen(word)+1);
	insertIndexHash(newHash,dummy,IDdoc,freq);
	token = strtok (NULL, " ");
      }
    }
    free(token);
    free(word);
    fclose(origfile);

    //Initialize a list of docnodes
    docList *finalDocs = malloc(sizeof(docList));
    finalDocs->head=NULL;
    
    //Enter a while loop in order to create our list of docnodes
    wordListNode *searchNode=currlist->head;
    int check = 0;
    //For every wordlist node...
    while( searchNode != NULL ){
      docList *newDocs = malloc(sizeof(docList));
      newDocs->head=NULL;
      WNode *findWNode=searchNode->wnode;
      empty = 0;

      //For every wordnode...
      while( findWNode->word != NULL ){
	char *searchWord=findWNode->word;
	if ( check == 0 ){
	  finalDocs=insertDocList(newHash,searchWord,finalDocs);
	} else {
	  newDocs=insertDocList(newHash,searchWord,newDocs);
	} 
	findWNode=findWNode->next;
      }
    
      //If it is the first time going through, then do nothing, but if this is the second pass, compare the temporary docList with the master docList to see if there are any similarities, in which case you would want to combine them, or if there are any differences, in which case you would want to add them to the back of the mast docList.
      if( check == 0 ){
	check = 1;
      } else {
	docNode *combineNode = newDocs->head;
	while(combineNode != NULL ){
	  int flick = 0;
	  docNode *fixNode=finalDocs->head;

	  //Combining frequencies if the doc_id's are the same
	  while(fixNode != NULL ){
	    if( fixNode->doc_id == combineNode->doc_id){
	      fixNode->freq+=combineNode->freq;
	      flick = 1;
	    }
	    fixNode=fixNode->next;
	  }
	  if(flick == 0){
	    //Adding docNodes to the docList if the doc_id's don't match up
	    docNode *newDocNode=malloc(sizeof(docNode));
	    newDocNode->doc_id=combineNode->doc_id;
	    newDocNode->freq=combineNode->freq;
	    newDocNode->next=NULL;
	    docNode *dummyNode;
	    docNode *endNode=finalDocs->head;
	    while(endNode != NULL ){
	      dummyNode=endNode;
	      endNode=endNode->next;
	    }
	    if (finalDocs->head == NULL ){
	      finalDocs->head=newDocNode;
	    } else {
	      dummyNode->next=newDocNode;
	    }
	  }
	  combineNode=combineNode->next;
	}
      }
      searchNode=searchNode->next;
      freeDocList(newDocs);
    }
      
    //Sort the docs based on frequency scores
     int docCount=0;
    docNode *countnode = finalDocs->head;
    while(countnode != NULL){
      docCount++;
      countnode=countnode->next;
      }
    sortDocList(finalDocs,docCount);
    
    //Print out the results
    char *targetdir = argv[2];
    printDocList(finalDocs,targetdir);

    //clean and free everything
    freeDocList(finalDocs);
    freewordlist(currlist);   
    freeIndexHash(newHash);
    } else { 
      return 0;
    }
  }
}
Ejemplo n.º 20
0
Archivo: cfg.c Proyecto: berkus/lang-e
/* bb_linkbb: make p the predecessor of s and s the successor of p */
static inline void bb_linkbb (i_bb_t p, i_bb_t s) {
     assert(p && s);
     addtolist(i_bb_t, p->n, s, p->nn, p->ln, 4);
     addtolist(i_bb_t, s->p, p, s->np, s->lp, 4);
}
Ejemplo n.º 21
0
int
main(int argc, char *argv[])
{
	int	index;
	struct	sigaction sa;
	int	c;
	char	*p = strrchr(argv[0], '/');

	if (p == NULL)
		p = argv[0];
	else
		p++;

	pname = p;

	(void) setlocale(LC_ALL, "");
#if	!defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
#define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
#endif
	(void) textdomain(TEXT_DOMAIN);

	if (getuid() != 0)
		die(gettext("must be root to run this program\n"));

	/*
	 * Handle normal termination signals that may be received.
	 */
	sa.sa_handler = SIG_IGN;
	sa.sa_flags = 0;
	(void) sigemptyset(&sa.sa_mask);
	(void) sigaction(SIGHUP, &sa, NULL);
	(void) sigaction(SIGINT, &sa, NULL);
	(void) sigaction(SIGQUIT, &sa, NULL);
	(void) sigaction(SIGTERM, &sa, NULL);

	/*
	 * To make sure persistent state gets removed.
	 */
	sa.sa_handler = cleanup_on_exit;
	sa.sa_flags = 0;
	(void) sigemptyset(&sa.sa_mask);
	(void) sigaction(SIGSEGV, &sa, NULL);
	(void) sigaction(SIGILL, &sa, NULL);
	(void) sigaction(SIGABRT, &sa, NULL);
	(void) sigaction(SIGBUS, &sa, NULL);

	if (strcmp(pname, CONSDAEMON) == 0) {
		fallbackdaemon();
		return (E_SUCCESS);
	}

	if (argc == 1)
		display++;
	else {
		while ((c = getopt(argc, argv, "adp")) != EOF)  {
			switch (c) {
			case 'a':
				addflag++;
				break;
			case 'd':
				deleteflag++;
				break;
			case 'p':
				persist++;
				break;
			default:
				(void) fprintf(stderr, gettext(usage));
				exit(E_USAGE);
				/*NOTREACHED*/
			}
		}
	}

	if (display) {
		getconsole();
		return (E_SUCCESS);
	}
	if (addflag && deleteflag) {
		(void) fprintf(stderr, gettext(usage));
		return (E_ERROR);
	}
	if (addflag) {
		if (optind == argc) {
			(void) fprintf(stderr, gettext(usage));
			return (E_ERROR);
		}
		/* separately check every device path specified */
		for (index = optind; index < argc; index++) {
			if (verifyarg(argv[index], addflag))
				return (E_ERROR);
		}

		for (index = optind; index < argc; index++) {
			setaux(argv[index]);
			if (persist)
				addtolist(argv[index]);
		}

		/*
		 * start/restart daemon based on the auxilary
		 * consoles at this time.
		 */
		setfallback(argv);
		return (E_SUCCESS);
	} else if (deleteflag) {
		if (optind == argc) {
			(void) fprintf(stderr, gettext(usage));
			return (E_ERROR);
		}
		/* separately check every device path specified */
		for (index = optind; index < argc; index++) {
			if (verifyarg(argv[index], 0))
				return (E_ERROR);
		}

		for (index = optind; index < argc; index++) {
			unsetaux(argv[index]);
			if (persist && deleteflag)
				removefromlist(argv[index]);
		}

		/*
		 * kill off daemon and restart with
		 * new list of auxiliary consoles
		 */
		setfallback(argv);
		return (E_SUCCESS);
	} else if (persist) {
		if (optind < argc) {
			(void) fprintf(stderr, gettext(usage));
			return (E_ERROR);
		}

		persistlist();
		return (E_SUCCESS);
	} else {
		(void) fprintf(stderr, gettext(usage));
		return (E_ERROR);
	}
} /* main */
Ejemplo n.º 22
0
void TUserList::addtolist(string word)
{
	addtolist (word,"");
}
Ejemplo n.º 23
0
void
draw_dilemma(ModeInfo * mi)
{
	int         col, row, mrow, colrow, n, i;
	dilemmastruct *dp;

	if (dilemmas == NULL)
		return;
	dp = &dilemmas[MI_SCREEN(mi)];
	if (dp->s == NULL)
		return;

	MI_IS_DRAWN(mi) = True;

	if (dp->state >= 2 * COLORS) {

		for (col = 0; col < dp->ncols; col++) {
			for (row = 0; row < dp->nrows; row++) {
				colrow = col + row * dp->ncols;
				if (conscious)
					dp->payoff[colrow] =
						dp->pm[(int) dp->s[colrow]][(int) dp->s[colrow]];
				else
					dp->payoff[colrow] = 0.0;
				for (n = 0; n < dp->neighbors; n++)
					dp->payoff[colrow] +=
						dp->pm[(int) dp->s[colrow]][(int)
						  dp->s[neighbor_position(dp,
					col, row, n * 360 / dp->neighbors)]];

			}
		}
		for (row = 0; row < dp->nrows; row++) {
			for (col = 0; col < dp->ncols; col++) {
				float       hp;
				int         position;

				colrow = col + row * dp->ncols;
				hp = dp->payoff[colrow];
				dp->sn[colrow] = dp->s[colrow];
				for (n = 0; n < dp->neighbors; n++) {
					position = neighbor_position(dp, col, row, n * 360 / dp->neighbors);
					if (ROUND_FLOAT(dp->payoff[position], 0.001) >
					    ROUND_FLOAT(hp, 0.001)) {
						hp = dp->payoff[position];
						dp->sn[colrow] = dp->s[position];
					}
				}
			}
		}
		mrow = 0;
		for (row = 0; row < dp->nrows; row++) {
			for (col = 0; col < dp->ncols; col++) {
				addtolist(mi, col, row,
					  dp->sn[col + mrow] * BITMAPS + dp->s[col + mrow]);
			}
			mrow += dp->ncols;
		}

		if (++dp->generation > MI_CYCLES(mi) ||
		    dp->defectors == dp->npositions || dp->defectors == 0)
			init_dilemma(mi);
		dp->state = 0;
	} else {
		if (dp->state < COLORS) {
			draw_state(mi, dp->state);
		}
		dp->state++;
	}
#if 1
	if (dp->redrawing) {
		for (i = 0; i < REDRAWSTEP; i++) {
			drawcell(mi, dp->redrawpos % dp->ncols, dp->redrawpos / dp->ncols,
				 dp->colors[(int) dp->sn[dp->redrawpos]][(int) dp->s[dp->redrawpos]],
				 dp->sn[dp->redrawpos], False);
			if (++(dp->redrawpos) >= dp->npositions) {
				dp->redrawing = 0;
				break;
			}
		}
	}
#endif
}
Ejemplo n.º 24
0
double shake(int nb, char** seq, char** seqname, char* ctree, options opt, char** eval_input, int nb_eval_input){

  int nb2, i, j, ii, jj, k, l, *ttree[MAXNSP], **curtree, **newtree, **evaltree, nbbi, nbdclade, nbgclade, print1, print2;
  int nochange, pres_grossiere=-1, l1, l2, restart_d, restart_g, oldmovedist;
  int **dclade, **gclade, **newdclade, **newgclade, **ddist, **gdist, movedist, maxmovedist;
  int **list_tree, lliste, *solid;
  long nblist, nblistmax;
  double *lgbp, *sortedlgbp, *lgbi, *bootvals, fracroot1, lkh, maxlkh, maxlcrossedbranch;
  char *nom[MAXNSP], *nom2[MAXNSP], **dcladename, **gcladename, **list1, **list2, racine, *ctreenew, *ctreenew_nobl, *treedeb, *ctree1, *ctree2;
  FILE* outfile1, *outfile2;
  print_option trueprint, noprint;


  print1=opt->print->PRINT1;
  print2=opt->print->PRINT2;
  noprint=check_alloc(1, sizeof(struct print_option));
  noprint->PRINT3=0;
  if(opt->print->PRINT2)
    noprint->PRINT1=noprint->PRINT2=1;
  else
    noprint->PRINT1=noprint->PRINT2=0;
  if(print1) noprint->PRINT0=1; else noprint->PRINT0=0;
  trueprint=opt->print;
  opt->print=noprint;
  maxlcrossedbranch=opt->SH_MAXLCROSSED;



		/* READ TREE STRING */

  lgbp=(double*)check_alloc(nb+1, sizeof(double));
  sortedlgbp=(double*)check_alloc(nb+1, sizeof(double));
  lgbi=(double*)check_alloc(nb+1, sizeof(double));
  for(i=0;i<nb+1;i++)
    lgbp[i]=lgbi[i]=-1.;

  solid=(int*)check_alloc(nb+1, sizeof(int));
  bootvals=(double*)check_alloc(nb+1, sizeof(double));
  if(nb>=MAXNSP) {printf("Too many sequences\n"); exit(EXIT_FAILURE);}
  for(i=0;i<=nb;i++){
    nom[i]=(char*)check_alloc(MAXLNAME+1, sizeof(char));
    nom2[i]=(char*)check_alloc(MAXLNAME+1, sizeof(char));
    ttree[i]=(int*)check_alloc(nb, sizeof(int));
  }
  list1=check_alloc(nb, sizeof(char*));
  list2=check_alloc(nb, sizeof(char*));
  curtree=(int**)check_alloc(nb+1, sizeof(int*));
  newtree=(int**)check_alloc(nb+1, sizeof(int*));
  evaltree=(int**)check_alloc(nb+1, sizeof(int*));
  for(i=0;i<nb+1;i++) newtree[i]=(int*)check_alloc(nb-2, sizeof(int));
  ctreenew=(char*)check_alloc(2*MAXLNAME*nb, sizeof(char));
  ctree1=(char*)check_alloc(2*MAXLNAME*nb, sizeof(char));
  ctree2=(char*)check_alloc(2*MAXLNAME*nb, sizeof(char));
  ctreenew_nobl=(char*)check_alloc(2*MAXLNAME*nb, sizeof(char));


  nb2=ctot(ctree, ttree, lgbi, lgbp, bootvals, nom, &racine, &nbbi);

  if(nb2<nb){
    printf("More species in sequence file than in tree file\n");
    exit(EXIT_FAILURE);
  }
  if(nb2>nb){
    printf("More species in tree file than in sequence file\n");
    exit(EXIT_FAILURE);
  }


	/* PREPARE TREE : UNROOT, SET LEFT and RIGHT LISTS, SORT TAXA */

  if(racine=='r'){
    unroot(ttree, nb, lgbi, lgbp, bootvals, nom, list1, list2, &l1, &l2, &fracroot1);
  }
  else{
    printf("Tree must be rooted\n");
    exit(EXIT_FAILURE);
  }
  nbbi--;
  if(nbbi!=nb-3){
    printf("Tree must be bifurcating\n");
    exit(EXIT_FAILURE);
  }

  for(i=0;i<nb;i++){
    for(j=0;j<nb;j++){
      if(samename(seqname[i], nom[j])){
	curtree[i]=ttree[j];
	sortedlgbp[i]=lgbp[j];
	break;
      }
    }
  }

  for(i=0;i<nb-3;i++) if(bootvals[i]>opt->SH_MAXBOOTCROSSED) solid[i]=1;

  ctree_noblbs(ctree, ctreenew_nobl, strlen(ctree));

	/* EVALUATE INITIAL TREE */

  if(print1)
    printf("\nEvaluating initial tree : \n%s\n", ctreenew_nobl);
  if(print2)
    printf("\n");

  maxlkh=maxlike(nb, seq, seqname, curtree, lgbi, sortedlgbp, nbbi, l1, list1, l2, list2, opt, NULL, NULL, NULL);
  if(opt->SH_RESTART) save_current_best("current_best_tree", ctreenew_nobl, maxlkh, 1);
  if(opt->SH_RESTART) save_evaluated("evaluated_trees", ctreenew_nobl, maxlkh, 1);

	/* ALLOCATE SHAKE VARIABLES */

  nbdclade=2*l1-1;
  nbgclade=2*l2-1;
  dclade=(int**)check_alloc(nbdclade, sizeof(int*));
  for(i=0;i<nbdclade;i++)
    dclade[i]=(int*)check_alloc(nb, sizeof(int));
  gclade=(int**)check_alloc(2*nb, sizeof(int*));
  for(i=0;i<nbgclade;i++)
    gclade[i]=(int*)check_alloc(nb, sizeof(int));
  newdclade=(int**)check_alloc(nbdclade, sizeof(int*));
  for(i=0;i<nbdclade;i++)
    newdclade[i]=(int*)check_alloc(nb, sizeof(int));
  newgclade=(int**)check_alloc(nbgclade, sizeof(int*));
  for(i=0;i<nbgclade;i++)
    newgclade[i]=(int*)check_alloc(nb, sizeof(int));
  ddist=(int**)check_alloc(nbdclade, sizeof(int*));
  gdist=(int**)check_alloc(nbgclade, sizeof(int*));
  for(i=0;i<nbdclade;i++) ddist[i]=(int*)check_alloc(nbdclade, sizeof(int));
  for(i=0;i<nbgclade;i++) gdist[i]=(int*)check_alloc(nbgclade, sizeof(int));
  dcladename=(char**)check_alloc(nbdclade, sizeof(char*));
  gcladename=(char**)check_alloc(nbgclade, sizeof(char*));
  for(i=0;i<nbdclade;i++)
    dcladename[i]=(char*)check_alloc(nb*(MAXLNAME+3)+1, sizeof(char));
  for(i=0;i<nbgclade;i++)
    gcladename[i]=(char*)check_alloc(nb*(MAXLNAME+3)+1, sizeof(char));
  nblistmax=nb*nb;
  if(nblistmax<MIN_NBLISTMAX) nblistmax=MIN_NBLISTMAX;
  if(nblistmax<nb_eval_input) nblistmax=nb_eval_input;
  if(nblistmax>MAX_NBLISTMAX) nblistmax=MAX_NBLISTMAX;
  while(1){
    lliste=(nblistmax*(nb-3)+lmot-1)/lmot;
    list_tree=(int**)check_alloc(nb, sizeof(int*));
    for(i=0;i<nb;i++)
      list_tree[i]=(int*)calloc(lliste, sizeof(int));
    if(list_tree[nb-1]) break;
    nblistmax/=2;
    if(nblistmax==0){
      printf("Not enough memory\n");
      exit(EXIT_FAILURE);
    }
  }


	/* SET LIST OF EVALUATED TREES */

  if(eval_input){
    nblist=0;
    for(k=0;k<nb_eval_input;k++){
      for(i=0;i<=nb;i++) ttree[i]=check_alloc(nb, sizeof(int));
      nb2=ctot(eval_input[k], ttree, NULL, NULL, NULL, nom2, &racine, NULL);
      if(racine=='r')
        unroot(ttree, nb, NULL, NULL, NULL, nom2, NULL, NULL, NULL, NULL, NULL);
      else{ printf("Evaluated trees must be rooted\n"); exit(EXIT_FAILURE);}
      for(i=0;i<nb;i++){
        for(j=0;j<nb;j++){
          if(samename(seqname[i], nom2[j])){
	    evaltree[i]=ttree[j];
	    break;
          }
        }
      }
      if(deja_evalue(evaltree, nb, list_tree, nblist, nblistmax)) continue;
      addtolist(evaltree, nb, list_tree, nblist, nblistmax);
      nblist++;
    }
    printf("%d already evaluated topologies loaded\n", nblist);
  }
  else{
    addtolist(curtree, nb, list_tree, 0, nblistmax);
    nblist=1;
  }


	/* SHAKE */

  treedeb=ctreenew;
  nochange=1; movedist=0; 
  if(opt->SH_G>0 && opt->SH_G<nb-3) 
    maxmovedist=opt->SH_G;
  else
    maxmovedist=nb-3;

  if(print1)
    printf("\nStarting rearrangements\n");
  
  do{

    oldmovedist=movedist;

    if(nochange==1) movedist++;
    else movedist=1;

    if(print1 && !(nochange==0 && oldmovedist==1)){
      printf("\nCrossing %d internal branch", movedist);
      if(movedist>1) printf("es");
      printf("\n");
    }

    nochange=1;





    while(1){
      setclades(curtree, nb, seqname, l1, list1, l2, list2, dclade, gclade, ddist, gdist, nbdclade, nbgclade, dcladename, gcladename);
      restart_d=0;
      for(i=0;i<nbdclade;i++){
        for(j=0;j<nbdclade;j++){
	  if(abs(ddist[i][j])!=movedist) continue; 
	  if(ddist[i][j]<0) continue;
	  moveclade(dclade, newdclade, nbdclade, nb, ddist, i, j);
	  settree(newdclade, nbdclade, gclade, nbgclade, nb, newtree);

	  if(deja_evalue(newtree, nb, list_tree, nblist, nblistmax))
	    continue;
          if(solid_branch_crossed(newtree, curtree, nb, solid))
	    continue;

	  addtolist(newtree, nb, list_tree, nblist, nblistmax);
  	  nblist++;
	  if(print1){
	    printf("\nMoving %s toward %s\n", dcladename[i], dcladename[j]);
          }
	  if(print2)
	    printf("\n");
	  lkh=maxlike(nb, seq, seqname, newtree, NULL, NULL, nbbi, l1, list1, l2, list2, opt, ctreenew, NULL, NULL);

	  if(lkh>maxlkh){
  	    ctree_noblbs(ctreenew, ctreenew_nobl, strlen(ctreenew));
	    if(print1)
	      printf("New tree is optimal : \n%s\n\nRestarting rearrangements\n", ctreenew_nobl);
	    maxlkh=lkh;
	    copytree(newtree, curtree, nb);
            if(opt->SH_RESTART) save_current_best("current_best_tree", ctreenew_nobl, lkh, 0);
            if(opt->SH_RESTART) save_evaluated("evaluated_trees", ctreenew_nobl, lkh, 0);
	    restart_d=1;
	    nochange=0;
	    ctreenew=treedeb;
	    while(*ctreenew) {*ctreenew=0; ctreenew++; }
	    ctreenew=treedeb;
	    break;
	  }
	  else{
	    if(print1)
	      printf("No improvement:\n");
            ctree_noblbs(ctreenew, ctreenew_nobl, strlen(ctreenew));
            if(print1)
              printf("%s\n", ctreenew_nobl);
            if(opt->SH_RESTART) save_evaluated("evaluated_trees", ctreenew_nobl, lkh, 0);
	  }
	  ctreenew=treedeb;
	  while(*ctreenew) {*ctreenew=0; ctreenew++; }
	  ctreenew=treedeb;
        }
      if(restart_d) break;
      }
      if(!restart_d || movedist>1) break;
    }

    if(restart_d && movedist>1) continue;

    while(1){
      setclades(curtree, nb, seqname, l1, list1, l2, list2, dclade, gclade, ddist, gdist, nbdclade, nbgclade, dcladename, gcladename);
      restart_g=0;
      for(i=0;i<nbgclade;i++){
        for(j=0;j<nbgclade;j++){
	  if(abs(gdist[i][j])!=movedist) continue;
	  if(gdist[i][j]<0) continue;

	  moveclade(gclade, newgclade, nbgclade, nb, gdist, i, j);
	  settree(dclade, nbdclade, newgclade, nbgclade, nb, newtree);

	  if(deja_evalue(newtree, nb, list_tree, nblist, nblistmax))
	    continue;
          if(solid_branch_crossed(newtree, curtree, nb, solid))
	    continue;
	  addtolist(newtree, nb, list_tree, nblist, nblistmax);
	  nblist++;
	  if(print1){
	    printf("\nMoving %s toward %s\n", gcladename[i], gcladename[j]);
          }
	  if(print2){
	    printf("\n");
          }

	  lkh=maxlike(nb, seq, seqname, newtree, NULL, NULL, nbbi, l1, list1, l2, list2, opt, ctreenew, NULL, NULL);

	  if(lkh>maxlkh){
  	    ctree_noblbs(ctreenew, ctreenew_nobl, strlen(ctreenew));
	    if(print1)
	      printf("New tree is optimal : \n%s\n\nRestarting rearrangements\n", ctreenew_nobl);
	    maxlkh=lkh;
	    copytree(newtree, curtree, nb);
	    if(opt->SH_RESTART) save_current_best("current_best_tree", ctreenew_nobl, lkh, 0);
            if(opt->SH_RESTART) save_evaluated("evaluated_trees", ctreenew_nobl, lkh, 0);
            restart_g=1;
	    nochange=0;
	    ctreenew=treedeb;
	    while(*ctreenew) {*ctreenew=0; ctreenew++; }
	    ctreenew=treedeb;
	    break;
	  }
	  else{
	    if(print1)
	      printf("No improvement:\n");
            ctree_noblbs(ctreenew, ctreenew_nobl, strlen(ctreenew));
            if(print1)
              printf("%s\n", ctreenew_nobl);
            if(opt->SH_RESTART) save_evaluated("evaluated_trees", ctreenew_nobl, lkh, 0);
	  }
	  ctreenew=treedeb;
	  while(*ctreenew) {*ctreenew=0; ctreenew++; }
	  ctreenew=treedeb;
        }
      if(restart_g) break;
      }
      if(!restart_g || movedist>1) break;
    }
  } while(nochange==0 || movedist!=maxmovedist);



  	/* FINAL EVALUATION */

  if(print1)
    printf("\nFinal evaluation\n");
  if(print2)
    printf("\n");
  opt->print=trueprint;

  maxlkh=maxlike(nb, seq, seqname, curtree, NULL, NULL, nbbi, l1, list1, l2, list2, opt, NULL, ctree1, ctree2);

  if(ctree1){
    outfile1=fopen("treefile.eqgc", "w");
    outfile2=fopen("treefile.ndgc", "w");
    if(outfile1==NULL || outfile2==NULL){ printf("Cannot write tree file\n"); exit(EXIT_FAILURE); }
    fprintf(outfile1, "%s\n", ctree1);
    fprintf(outfile2, "%s\n", ctree2);
    if(print1){
      printf("Tree is written into files : treefile.eqgc (equilibrium G+C content)\n");
      printf("                             treefile.ndgc (G+C content at each node)\n\n");
    }
  }


  free(lgbp); free(sortedlgbp); free(lgbi);
  free(bootvals);
  for(i=0;i<nb;i++){ free(nom[i]); free(ttree[i]); }
  free(list1); free(list2); free(curtree);

  
  return maxlkh;
}
Ejemplo n.º 25
0
static void listexternal(void *arg, char *key, void *value) {
	if ((((Var *) value)->flags & var_isinternal) == 0 && !specialvar(key))
		addtolist(arg, key, value);
}
Ejemplo n.º 26
0
void
draw_dragon(ModeInfo * mi)
{
	int white, black;
	int         choose_layer, factor, orient, l;
	dragonstruct *dp;
	CellList *locallist;
	Bool detour = False;

	if (dragons == NULL)
		return;
	dp = &dragons[MI_SCREEN(mi)];
	if (dp->cellList == NULL)
		return;

	MI_IS_DRAWN(mi) = True;
	choose_layer= NRAND(6);
	if (dp->ncells[!dp->addlist] == 1) {
		/* Since the maze is infinite, it may not get to this last
		 * spot for a while.  Force it to do it right away so it
		 * does not appear to be stuck. */
		detour = True;
		white = black = 0; /* not used but make -Wall happy */
	} else {
		white = (choose_layer / 2);
		black = (choose_layer % 2) ?
			((white + 2) % 3) : ((white + 1) % 3);
		/* gray = (choose_layer % 2) ?
			((white + 1) % 3) : ((white + 2) % 3); */
	}
	locallist = dp->cellList[!dp->addlist];
	orient = dp->generation % 2;
	factor = 1;
	for (l = 0; l < dp->generation / 2; l++) {
		factor *= 3;
	}
	if (!locallist && dp->generation >= MI_CYCLES(mi)) {
		init_dragon(mi);
		return;
	}

	while (locallist) {
		int i, j, k;

		i = locallist->pt.x;
		j = locallist->pt.y;
		if (orient) {
			k = (j / factor) % 3;
		} else {
		 	if (j % 2) {
				/* Had trouble with this line... */
				k = ((i + factor / 2) / factor + 1) % 3;
			} else {
				k = (i / factor) % 3;
			}
		}
		if (detour) {
			k = (LRAND() & 1) + 1;
			dp->oldcell[j * dp->ncols + i] = k;
			drawcell(mi, i, j, k);
		} if (white == k) {
			dp->oldcell[j * dp->ncols + i] = 0;
			drawcell(mi, i, j, 0);
			if (!addtolist(mi, i, j)) {
				free_dragon(MI_DISPLAY(mi), dp);
				return;
			}
		} else if (black == k) {
			dp->oldcell[j * dp->ncols + i] = 1;
			drawcell(mi, i, j, 1);
		} else /* if (gray == k) */ {
			dp->oldcell[j * dp->ncols + i] = 2;
			drawcell(mi, i, j, 2);
		}
		dp->cellList[!dp->addlist] = dp->cellList[!dp->addlist]->next;
		free(locallist);
		dp->ncells[!dp->addlist]--;
		locallist = dp->cellList[!dp->addlist];
		if ((dp->cellList[!dp->addlist] == NULL) &&
		    (dp->cellList[dp->addlist] == NULL))
			dp->generation = 0;
	}
	dp->addlist = !dp->addlist;
	if (dp->redrawing) {
		int i;

		for (i = 0; i < REDRAWSTEP; i++) {
			if (dp->oldcell[dp->redrawpos] != 1) {
				drawcell(mi, dp->redrawpos % dp->ncols, dp->redrawpos / dp->ncols,
					 dp->oldcell[dp->redrawpos]);
			}
			if (++(dp->redrawpos) >= dp->ncols * dp->nrows) {
				dp->redrawing = 0;
				break;
			}
		}
	}
	dp->generation++;
}
Ejemplo n.º 27
0
static void listinternal(void *arg, char *key, void *value) {
	if (((Var *) value)->flags & var_isinternal)
		addtolist(arg, key, value);
}
Ejemplo n.º 28
0
void
init_dilemma(ModeInfo * mi)
{
	int         size = MI_SIZE(mi);
	int         i, col, row, colrow, mrow;
	dilemmastruct *dp;

	if (dilemmas == NULL) {
		if ((dilemmas = (dilemmastruct *) calloc(MI_NUM_SCREENS(mi),
					    sizeof (dilemmastruct))) == NULL)
			return;
	}
	dp = &dilemmas[MI_SCREEN(mi)];

	dp->generation = 0;
	dp->redrawing = 0;
	dp->state = 0;
	free_dilemma(dp);

	if (!dp->initialized) {	/* Genesis */
		icon_width = cooperat_width;
		icon_height = cooperat_height;
		dp->initialized = 1;
		for (i = 0; i < BITMAPS; i++) {
			logo[i].width = icon_width;
			logo[i].height = icon_height;
			logo[i].bytes_per_line = (icon_width + 7) / 8;
		}
	}
	if (MI_IS_FULLRANDOM(mi)) {
		dp->vertical = (Bool) (LRAND() & 1);
	} else {
		dp->vertical = vertical;
	}
	dp->width = MI_WIDTH(mi);
	dp->height = MI_HEIGHT(mi);

	for (i = 0; i < NEIGHBORKINDS; i++) {
		if (neighbors == plots[i]) {
			dp->neighbors = neighbors;
			break;
		}
		if (i == NEIGHBORKINDS - 1) {
#if 0
			dp->neighbors = plots[NRAND(NEIGHBORKINDS)];
			dp->neighbors = (LRAND() & 1) ? 4 : 8;
#else
			dp->neighbors = 8;
#endif
			break;
		}
	}

	if (dp->neighbors == 6) {
		int nccols, ncrows, sides;

		if (!dp->vertical) {
			dp->height = MI_WIDTH(mi);
			dp->width = MI_HEIGHT(mi);
		}
		if (dp->width < 2)
			dp->width = 2;
		if (dp->height < 4)
			dp->height = 4;
		if (size < -MINSIZE)
			dp->ys = NRAND(MIN(-size, MAX(MINSIZE, MIN(dp->width, dp->height) /
				      MINGRIDSIZE)) - MINSIZE + 1) + MINSIZE;
		else if (size < MINSIZE) {
			if (!size)
				dp->ys = MAX(MINSIZE, MIN(dp->width, dp->height) / MINGRIDSIZE);
			else
				dp->ys = MINSIZE;
		} else
			dp->ys = MIN(size, MAX(MINSIZE, MIN(dp->width, dp->height) /
					       MINGRIDSIZE));
		dp->xs = dp->ys;
		dp->pixelmode = True;
		nccols = MAX(dp->width / dp->xs - 2, 2);
		ncrows = MAX(dp->height / dp->ys - 1, 2);
		dp->ncols = nccols / 2;
		dp->nrows = 2 * (ncrows / 4);
		dp->xb = (dp->width - dp->xs * nccols) / 2 + dp->xs / 2;
		dp->yb = (dp->height - dp->ys * (ncrows / 2) * 2) / 2 +
			dp->ys - 2;
		for (sides = 0; sides < 6; sides++) {
			if (dp->vertical) {
				dp->shape.hexagon[sides].x =
					(dp->xs - 1) * hexagonUnit[sides].x;
				dp->shape.hexagon[sides].y =
					((dp->ys - 1) * hexagonUnit[sides].y /
					2) * 4 / 3;
			} else {
				dp->shape.hexagon[sides].y =
					(dp->xs - 1) * hexagonUnit[sides].x;
				dp->shape.hexagon[sides].x =
					((dp->ys - 1) * hexagonUnit[sides].y /
					2) * 4 / 3;
			}
		}
	} else if (dp->neighbors == 4 || dp->neighbors == 8) {
		if (dp->width < 2)
			dp->width = 2;
		if (dp->height < 2)
			dp->height = 2;
		if (size == 0 ||
		    MINGRIDSIZE * size > dp->width || MINGRIDSIZE * size > dp->height) {
			if (dp->width > MINGRIDSIZE * icon_width &&
			    dp->height > MINGRIDSIZE * icon_height) {
				dp->pixelmode = False;
				dp->xs = icon_width;
				dp->ys = icon_height;
			} else {
				dp->pixelmode = True;
				dp->xs = dp->ys = MAX(MINSIZE, MIN(dp->width, dp->height) /
						      MINGRIDSIZE);
			}
		} else {
			dp->pixelmode = True;
			if (size < -MINSIZE)
				dp->ys = NRAND(MIN(-size, MAX(MINSIZE, MIN(dp->width, dp->height) /
				      MINGRIDSIZE)) - MINSIZE + 1) + MINSIZE;
			else if (size < MINSIZE)
				dp->ys = MINSIZE;
			else
				dp->ys = MIN(size, MAX(MINSIZE, MIN(dp->width, dp->height) /
						       MINGRIDSIZE));
			dp->xs = dp->ys;
		}
		dp->ncols = MAX(dp->width / dp->xs, 2);
		dp->nrows = MAX(dp->height / dp->ys, 2);
		dp->xb = (dp->width - dp->xs * dp->ncols) / 2;
		dp->yb = (dp->height - dp->ys * dp->nrows) / 2;
	} else {		/* TRI */
		int orient;

		if (!dp->vertical) {
			dp->height = MI_WIDTH(mi);
			dp->width = MI_HEIGHT(mi);
		}
		if (dp->width < 2)
			dp->width = 2;
		if (dp->height < 2)
			dp->height = 2;
		if (size < -MINSIZE)
			dp->ys = NRAND(MIN(-size, MAX(MINSIZE, MIN(dp->width, dp->height) /
				      MINGRIDSIZE)) - MINSIZE + 1) + MINSIZE;
		else if (size < MINSIZE) {
			if (!size)
				dp->ys = MAX(MINSIZE, MIN(dp->width, dp->height) / MINGRIDSIZE);
			else
				dp->ys = MINSIZE;
		} else
			dp->ys = MIN(size, MAX(MINSIZE, MIN(dp->width, dp->height) /
					       MINGRIDSIZE));
		dp->xs = (int) (1.52 * dp->ys);
		dp->pixelmode = True;
		dp->ncols = (MAX(dp->width / dp->xs - 1, 2) / 2) * 2;
		dp->nrows = (MAX(dp->height / dp->ys - 1, 2) / 2) * 2;
		dp->xb = (dp->width - dp->xs * dp->ncols) / 2 + dp->xs / 2;
		dp->yb = (dp->height - dp->ys * dp->nrows) / 2 + dp->ys / 2;
		for (orient = 0; orient < 2; orient++) {
			for (i = 0; i < 3; i++) {
				if (dp->vertical) {
					dp->shape.triangle[orient][i].x =
						(dp->xs - 2) * triangleUnit[orient][i].x;
					dp->shape.triangle[orient][i].y =
						(dp->ys - 2) * triangleUnit[orient][i].y;
				} else {
					dp->shape.triangle[orient][i].y =
						(dp->xs - 2) * triangleUnit[orient][i].x;
					dp->shape.triangle[orient][i].x =
						(dp->ys - 2) * triangleUnit[orient][i].y;
				}
			}
		}
	}

	dp->npositions = dp->ncols * dp->nrows;

	dp->pm[0][0] = 1, dp->pm[0][1] = 0;
	if (bonus < 1.0 || bonus > 4.0)
		dp->pm[1][0] = 1.85;
	else
		dp->pm[1][0] = bonus;
	dp->pm[1][1] = 0;

	if (MI_NPIXELS(mi) >= COLORS) {

		dp->colors[0][0] = MI_PIXEL(mi, BLUE);	/* COOPERATING, was cooperating */
		dp->colors[0][1] = MI_PIXEL(mi, GREEN);		/* COOPERATING, was defecting */
		dp->colors[1][0] = MI_PIXEL(mi, YELLOW);	/* DEFECTING, was cooperating */
		dp->colors[1][1] = MI_PIXEL(mi, RED);	/* DEFECTING, was defecting */
	} else {
		dp->colors[0][0] = MI_WHITE_PIXEL(mi);
		dp->colors[0][1] = MI_WHITE_PIXEL(mi);
		dp->colors[1][0] = MI_WHITE_PIXEL(mi);
		dp->colors[1][1] = MI_WHITE_PIXEL(mi);
	}
	alloc_dilemma(dp);
	if (dp->s == NULL)
		return;
	MI_CLEARWINDOW(mi);

	dp->defectors = MI_COUNT(mi);
	if (dp->defectors < -MINDEFECT) {
		dp->defectors = NRAND(-dp->defectors - MINDEFECT + 1) + MINDEFECT;
	} else if (dp->defectors < MINDEFECT)
		dp->defectors = MINDEFECT;
	if (dp->defectors > dp->npositions)
		dp->defectors = dp->npositions;

	for (i = 0; i < dp->defectors; i++) {
		do {
			colrow = NRAND(dp->npositions);
		} while (dp->sn[colrow]);
		dp->sn[colrow] = 1;
	}
#if 0				/* if p was a float... */
	mrow = 0;
	for (row = 0; row < dp->nrows; row++) {
		for (col = 0; col < dp->ncols; col++) {
			dp->sn[col + mrow] = ((float) LRAND() / MAXRAND < dp->p);
		}
		mrow += dp->ncols;
	}
#endif

	dp->defectors = 0;

	/* Show initial state... real important for debugging */
	mrow = 0;
	for (row = 0; row < dp->nrows; ++row) {
		for (col = 0; col < dp->ncols; ++col) {
			addtolist(mi, col, row,
			   dp->sn[col + mrow] * BITMAPS + dp->s[col + mrow]);
		}
		mrow += dp->ncols;
	}
}