Beispiel #1
0
static int
display_deltacast_reconfigure(void *state, struct video_desc desc)
{
        struct state_deltacast            *s = (struct state_deltacast *)state;
        int VideoStandard;
        int i;
        ULONG Result;
        
        if(s->initialized) {
                if(s->SlotHandle)
                        VHD_UnlockSlotHandle(s->SlotHandle);
                VHD_StopStream(s->StreamHandle);
                VHD_CloseStreamHandle(s->StreamHandle);
        }

        assert(desc.tile_count == 1);

        s->tile->width = desc.width;
        s->tile->height = desc.height;
        s->frame->color_spec = desc.color_spec;
        s->frame->interlacing = desc.interlacing;
        s->frame->fps = desc.fps;
        
        for (i = 0; i < deltacast_frame_modes_count; ++i)
        {
                if(fabs(desc.fps - deltacast_frame_modes[i].fps) < 0.01 &&
                                desc.interlacing == deltacast_frame_modes[i].interlacing &&
                                desc.width == deltacast_frame_modes[i].width &&
                                desc.height == deltacast_frame_modes[i].height) {
                        VideoStandard = deltacast_frame_modes[i].mode;
                        fprintf(stderr, "[DELTACAST] %s mode selected.\n", deltacast_frame_modes[i].name);
                        break;
                }
        }
        if(i == deltacast_frame_modes_count) {
                fprintf(stderr, "[DELTACAST] Failed to obtain video format for incoming video: %dx%d @ %2.2f %s\n", desc.width, desc.height,
                                                                        (double) desc.fps, get_interlacing_description(desc.interlacing));

                goto error;
        }
        
        if(desc.color_spec == RAW) {
                Result = VHD_OpenStreamHandle(s->BoardHandle,VHD_ST_TX0,VHD_SDI_STPROC_RAW,NULL,&s->StreamHandle,NULL);
        } else if (s->play_audio == TRUE) {
                Result = VHD_OpenStreamHandle(s->BoardHandle,VHD_ST_TX0,VHD_SDI_STPROC_JOINED,NULL,&s->StreamHandle,NULL);
        } else {
                Result = VHD_OpenStreamHandle(s->BoardHandle,VHD_ST_TX0,VHD_SDI_STPROC_DISJOINED_VIDEO,NULL,&s->StreamHandle,NULL);
        }
        
        if (Result != VHDERR_NOERROR) {
                fprintf(stderr, "[DELTACAST] Failed to open stream handle.\n");
                goto error;
        }
        
        VHD_SetStreamProperty(s->StreamHandle,VHD_SDI_SP_VIDEO_STANDARD,VideoStandard);
        VHD_SetStreamProperty(s->StreamHandle,VHD_CORE_SP_BUFFERQUEUE_DEPTH,2);
        VHD_SetStreamProperty(s->StreamHandle,VHD_CORE_SP_BUFFERQUEUE_PRELOAD,0);

        Result = VHD_StartStream(s->StreamHandle);
        if (Result != VHDERR_NOERROR) {
                fprintf(stderr, "[DELTACAST] Unable to start stream.\n");  
                goto error;
        }
        
        s->initialized = TRUE;
        return TRUE;

error:
        return FALSE;
}
Beispiel #2
0
void fork_process(char *proc_name, char *ctrl_addr, pid_t *pid, int num_tokens, char *token[2], int argc, char **argv)
{
#ifdef WIN32
        int                      i;
        char			 args[1024];
        LPSTARTUPINFO		 startup_info;
        LPPROCESS_INFORMATION	 proc_info;

        startup_info = (LPSTARTUPINFO) xmalloc(sizeof(STARTUPINFO));
        startup_info->cb              = sizeof(STARTUPINFO);
        startup_info->lpReserved      = 0;
        startup_info->lpDesktop       = 0;
        startup_info->lpTitle         = 0;
        startup_info->dwX             = 0;
        startup_info->dwY             = 0;
        startup_info->dwXSize         = 0;
        startup_info->dwYSize         = 0;
        startup_info->dwXCountChars   = 0;
        startup_info->dwYCountChars   = 0;
        startup_info->dwFillAttribute = 0;
        startup_info->dwFlags         = 0;
        startup_info->wShowWindow     = 0;
        startup_info->cbReserved2     = 0;
        startup_info->lpReserved2     = 0;
        startup_info->hStdInput       = 0;
        startup_info->hStdOutput      = 0;
        startup_info->hStdError       = 0;

        proc_info = (LPPROCESS_INFORMATION) xmalloc(sizeof(PROCESS_INFORMATION));

	if (num_tokens == 1) {
		_snprintf(args, sizeof(args), "%s -ctrl \"%s\" -token %s", proc_name, ctrl_addr, token[0]);
	} else {
		_snprintf(args, sizeof(args), "%s -T -ctrl \"%s\" -token %s -token %s", proc_name, ctrl_addr, token[0], token[1]);
	}
        for(i=0;i<argc;i++) {
                _snprintf(args, sizeof(args), "%s %s", args, argv[i]);
        }

        if (!CreateProcess(NULL, args, NULL, NULL, TRUE, 0, NULL, NULL, startup_info, proc_info)) {
                perror("Couldn't create process");
                abort();
        }
        *pid = (pid_t) proc_info->hProcess;	/* Sigh, hope a HANDLE fits into 32 bits... */
        debug_msg("Forked %s\n", proc_name);
#else /* ...we're on unix */
	char *path, *path_env;
	int i;
#ifdef DEBUG_FORK
	if (num_tokens == 1) {
        	debug_msg("%s -ctrl '%s' -token %s\n", proc_name, ctrl_addr, token[0]);
	} else {
        	debug_msg("%s -T -ctrl '%s' -token %s -token %s\n", proc_name, ctrl_addr, token[0], token[1]);
	}
        UNUSED(pid);
#else
	if ((getuid() != 0) && (geteuid() != 0)) {
		/* Ensure that the current directory is in the PATH. This is a security */
		/* problem, but reduces the number of support calls we get...           */
		path = getenv("PATH");
		if (path == NULL) {
			path_env = (char *) xmalloc(8);
			sprintf(path_env, "PATH=.");
		} else {
			path_env = (char *) xmalloc(strlen(path) + 8);
			sprintf(path_env, "PATH=%s:.", path);
		}
		debug_msg("%s\n", path_env);
		putenv(path_env);
		/* NOTE: we MUST NOT free the memory allocated to path_env. In some    */
		/* cases the string passed to putenv() becomes part of the environment */
		/* and hence freeing the memory removes PATH from the environment.     */
	} else {
		debug_msg("Running as root? PATH unmodified\n");
	}
        /* some glibc versions have issues with malloc/free when used inside or
           in some cases outside a fork/exec, so we now use a args[64] array instead of
           xmalloc'ing it. In the unlikely event the array needs to hold more
           command-line arguments, print a error message */
        if ((2 * num_tokens) + argc + 4 >= 64) {
                fprintf(stderr, "Exceeded max of %i command-line arguments\n",
                        64 - (2 * num_tokens) + 4);
                exit(1);
        }
        /* Fork off the sub-process... */
        *pid = fork();
        if (*pid == -1) {
                perror("Cannot fork");
                abort();
        } else if (*pid == 0) {
                char *args[64];
                int numargs=0;

                args[numargs++] = proc_name;
                args[numargs++] = "-ctrl";
                args[numargs++] = ctrl_addr;
                for(i=0;i<num_tokens;i++) {
                        args[numargs++] = "-token";
                        args[numargs++] = token[i];
                }
                for(i=0;i<argc;i++) {
                        args[numargs++] = argv[i];
                }
                args[numargs++] = NULL;
                execvp( proc_name, args );

                perror("Cannot execute subprocess");
                /* Note: this MUST NOT be exit() or abort(), since they affect the standard */
                /* IO channels in the parent process (fork duplicates file descriptors, but */
                /* they still point to the same underlying file).                           */
                _exit(1);
        }
#endif
#endif
}
Beispiel #3
0
void	DrawWatermazeTrack( FILE *fp, TRACK *t, char *Label, int PointsPerPixel, int OriginX, int OriginY, INFO I, int DrawEvents, int frame, FILEINFO FileInfo, float Scale)
{
	RGBCOLOR	rgb[N_COLORS];

	int		i,j, FirstGoodPosition = 1, NewEvent;
	float		x, y;
	float		CenterX, CenterY, ArenaRadiusPix;
	double		asin(), acos(), atan2();
	double 		Y, X, ang, rad, RoomFrameIncrease;

    	SetRGBColors(rgb);
	
	ArenaRadiusPix = (float)DEFAULT_ARENA_RADIUS / Scale;	// iTrack sets the radius to be 127

	(void) fprintf(fp, "gsave\n");

	// Set coordinate system to arena center
	CenterX = (float)(OriginX);
	CenterY = (float)(OriginY - I.Arena.CenterY * PointsPerPixel - 20);
	(void) fprintf(fp, "%0.2f %0.2f translate\n", CenterX, CenterY);

	RoomFrameIncrease = (ROOM_FRAME_INCREASE / Scale);

	if(strcmp(Label,"")){
		// label the Figure
		(void) fprintf(fp, "/Times-Roman findfont\n");
		(void) fprintf(fp, "0.5 cm scalefont\n");
		(void) fprintf(fp, "setfont\n");

		(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", (0.0 - ArenaRadiusPix), (ArenaRadiusPix + 35.0));
		(void) fprintf(fp, "( %s %s ) show\n", I.Paradigm, Label);
	}

	// label the picture
	(void) fprintf(fp, "/Times-Roman findfont\n");
	(void) fprintf(fp, "0.3 cm scalefont\n");
	(void) fprintf(fp, "setfont\n");

	(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", (0.0 - ArenaRadiusPix), (ArenaRadiusPix + 20.0));
	(void) fprintf(fp, "( Subject: %d Trial %d) show\n", I.TrialSubjectId, I.TrialNumber);
	(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", (0.0 - ArenaRadiusPix), (ArenaRadiusPix + 10.0));
	(void) fprintf(fp, "( Start: %s) show\nnewpath\n", I.TrialStartLabel);

	// draw the arena in a thin line
	(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n1.0 setlinewidth\n", rgb[BLACK].r, rgb[BLACK].g, rgb[BLACK].b);

	switch(I.Arena.Type){
		case ARENA_TYPE_CIRCLE:
			/* draw a circle for the arena */
			(void) fprintf(fp, "%0.2f pix %0.2f pix %0.2f pix 0 360 arc\n", 0.0, 0.0, ArenaRadiusPix);
			(void) fprintf(fp, "closepath\nstroke\n");
			break;

		default:
			break;
	}

	/* draw a square for the room */
	(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n1.0 setlinewidth\n", rgb[GRAY].r, rgb[GRAY].g, rgb[GRAY].b);
	(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", 0.0 - (ArenaRadiusPix + RoomFrameIncrease) , 0.0 - (ArenaRadiusPix + RoomFrameIncrease));
	(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", (ArenaRadiusPix + RoomFrameIncrease), 0.0 - (ArenaRadiusPix + RoomFrameIncrease));
	(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", (ArenaRadiusPix + RoomFrameIncrease) , (ArenaRadiusPix + RoomFrameIncrease));
	(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", 0.0 - (ArenaRadiusPix + RoomFrameIncrease) , (ArenaRadiusPix + RoomFrameIncrease));
	(void) fprintf(fp, "closepath\nstroke\n");	
		
	/* draw the reinforced area */
	if(I.Target[frame].Show){
		switch(I.Target[frame].Type){
			case REINFORCED_CIRCLE:
				(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n0.5 setlinewidth\n", rgb[RED].r, rgb[RED].g, rgb[RED].b);
			
				// draw the same regardless of the defining frame
				// original target
				X = I.Target[frame].Circle.X - I.Arena.CenterX, 
				Y = I.Arena.CenterY - I.Target[frame].Circle.Y;
				X /= Scale;
				Y /= Scale;

				(void) fprintf(fp, "%0.2f pix %0.2f pix %0.2f pix 0 360 arc\n", X, Y, I.Target[frame].Circle.Rad/Scale);
				(void) fprintf(fp, "closepath\nstroke\n");
				rad = hypot(Y, X);
				ang = atan2(Y, X);

				// draw corresponding targets in the other quadrants
				(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n1.0 setlinewidth\n", rgb[GRAY].r, rgb[GRAY].g, rgb[GRAY].b);
					
				for(j = 1; j < 4; j++){
					X = cos(ang + j * (M_PI / 2.0)) * rad; 
					Y = sin(ang + j * (M_PI / 2.0)) * rad; 
					(void) fprintf(fp, "%0.2f pix %0.2f pix %0.2f pix 0 360 arc\n", X, Y, I.Target[frame].Circle.Rad/Scale);
					(void) fprintf(fp, "closepath\nstroke\n");
				}
				break;
			default:
				break;
		}
	}

	// draw track
	(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n1.0 setlinewidth\n", rgb[BLACK].r, rgb[BLACK].g, rgb[BLACK].b);
	FirstGoodPosition = 1;
	NewEvent = 1;
	for(i = 0; i < I.NumberOfSamps; i ++){
		// Was the object detected?
		if((!t[i].x) || (!t[i].y)){
			if(!FirstGoodPosition)
				(void) fprintf(fp, "stroke\n");
			FirstGoodPosition = 1;
			continue;
		}

		// Transform from tracker to Cartesian coordinates
		x = (float)(t[i].x - I.Arena.CenterX);
		y = (float)(I.Arena.CenterY - t[i].y);

		x /= Scale;
		y /= Scale;

		if(FirstGoodPosition){
			(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
			if(t[i].event){
				if((I.FileFormat == TRACKER_FORMAT) || (I.FileFormat == ITRACK_FORMAT)){ // Event is coded as a state
					if((NewEvent) && (t[i].event == PP_STATE_Feed)){
						(void) fprintf(fp, "stroke\n");
						DrawAnEvent(fp, x, y, rgb, PointsPerPixel, RED);
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
						NewEvent = 0;
					}else{
						if(t[i].event != PP_STATE_Feed)
							NewEvent = 1;
					}
				}else{
					(void) fprintf(fp, "stroke\n");
					DrawAnEvent(fp, x, y, rgb, PointsPerPixel, RED);
					(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
					NewEvent = 0;
				}
			}	
			FirstGoodPosition = 0;
			continue;
		}
		(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", x,y);
		if(t[i].event){
			if((I.FileFormat == TRACKER_FORMAT) || (I.FileFormat == ITRACK_FORMAT)){ // Event is coded as a state
				if((NewEvent) && (t[i].event == PP_STATE_Feed)){
					(void) fprintf(fp, "stroke\n");
					DrawAnEvent(fp, x, y, rgb, PointsPerPixel, RED);
				}
				(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
				NewEvent = 0;
			}else{
				if(t[i].event != PP_STATE_Feed)
				NewEvent = 1;
			}
		}
	}
	if(!FirstGoodPosition)
		(void) fprintf(fp, "stroke\n");

	// reset coordinate system upon return
	(void) fprintf(fp, "grestore\n");

	return;
}
Beispiel #4
0
void
usage_which(void)
{
	fprintf(stderr, "usage: pkg which <file>\n\n");
	fprintf(stderr, "For more information see 'pkg help which'.\n");
}
Beispiel #5
0
void draw_grid_line_matlab(FILE * ff, const grid_line * line, const d_grid * grd, const char * color, short thick) 
{
#ifndef DEBUG
	return;
#endif

	if (line == NULL)
		return;
	if (grd == NULL)
		return;

	size_t fl_size = line->size();
	size_t i;
	size_t J1, J2;
	size_t pos_i, pos_j;
	size_t NN = grd->getCountX();
	size_t MM = grd->getCountY();
	for (i = 0; i < fl_size; i++) {
		J1 = line->get_first_cell(i);
		J2 = line->get_second_cell(i);
		
		one2two(J1, pos_i, pos_j, NN+2, MM+2);
		pos_i--;
		pos_j--;
		
		REAL x, y;
		
		REAL stepX2 = grd->stepX/REAL(2);
		REAL stepY2 = grd->stepY/REAL(2);
		grd->getCoordNode(pos_i,pos_j,x,y);
		
		int diff = (J2-J1);
		
		// right line
		if (diff == 1) {
			fprintf(ff,"plot([%lf  %lf],[%lf %lf],'color','%s','LineWidth',%d);\n", 
				x+stepX2, x+stepX2, y-stepY2, y+stepY2, color, thick);
		}
		
		// left line
		if (diff == -1) {
			fprintf(ff,"plot([%lf  %lf],[%lf %lf],'color','%s','LineWidth',%d);\n", 
				x-stepX2, x-stepX2, y-stepY2, y+stepY2, color, thick);
		}
		
		// up line 
		if (diff == NN+2) {
			fprintf(ff,"plot([%lf  %lf],[%lf %lf],'color','%s','LineWidth',%d);\n", 
				x-stepX2, x+stepX2, y+stepY2, y+stepY2, color, thick);
		}
		
		// down line
		if (-diff == NN+2) { // diff == -NN-2
			fprintf(ff,"plot([%lf  %lf],[%lf %lf],'color','%s','LineWidth',%d);\n", 
				x-stepX2, x+stepX2, y-stepY2, y-stepY2, color, thick);
		}
		
	}
	
	fflush(ff);
};
Beispiel #6
0
/* This is a strange function. What we do is fit a polynomial to the
 * curve, of degree $polydegree, and then evaluate it at the points
 * in the time scale.  What we do is this: for every set of points that
 * we fit a polynomial to, fill in as much of the new vector as we can
 * (i.e, between the last value of the old scale we went from to this
 * one). At the ends we just use what we have...  We have to detect
 * badness here too...
 *
 * Note that we pass arguments differently for this one cx_ function...  */
void *
cx_interpolate(void *data, short int type, int length, int *newlength, short int *newtype, struct plot *pl, struct plot *newpl, int grouping)
{
    struct dvec *ns, *os;
    double *d;
    int degree;
    register int i, oincreasing = 1, nincreasing = 1;
    int base;

    if (grouping == 0)
	grouping = length;

    /* First do some sanity checks. */
    if (!pl || !pl->pl_scale || !newpl || !newpl->pl_scale) {
        fprintf(cp_err, "Internal error: cx_interpolate: bad scale\n");
        return (NULL);
    }
    ns = newpl->pl_scale;
    os = pl->pl_scale;
    if (iscomplex(ns)) {
        fprintf(cp_err, "Error: new scale has complex data\n");
        return (NULL);
    }
    if (iscomplex(os)) {
        fprintf(cp_err, "Error: old scale has complex data\n");
        return (NULL);
    }

    if (length != os->v_length) {
        fprintf(cp_err, "Error: lengths don't match\n");
        return (NULL);
    }
    if (type != VF_REAL) {
        fprintf(cp_err, "Error: argument has complex data\n");
        return (NULL);
    }

    /* Now make sure that either both scales are strictly increasing
     * or both are strictly decreasing.  */
    if (os->v_realdata[0] < os->v_realdata[1])
        oincreasing = TRUE;
    else
        oincreasing = FALSE;
    for (i = 0; i < os->v_length - 1; i++)
        if ((os->v_realdata[i] < os->v_realdata[i + 1])
                != oincreasing) {
            fprintf(cp_err, "Error: old scale not monotonic\n");
            return (NULL);
        }
    if (ns->v_realdata[0] < ns->v_realdata[1])
        nincreasing = TRUE;
    else
        nincreasing = FALSE;
    for (i = 0; i < ns->v_length - 1; i++)
        if ((ns->v_realdata[i] < ns->v_realdata[i + 1])
                != nincreasing) {
            fprintf(cp_err, "Error: new scale not monotonic\n");
            return (NULL);
        }

    *newtype = VF_REAL;
    *newlength = ns->v_length;
    d = alloc_d(ns->v_length);

    if (!cp_getvar("polydegree", CP_NUM, (void *) &degree))
        degree = 1;

    for (base = 0; base < length; base += grouping) {
	if (!ft_interpolate((double *) data + base, d + base,
	    os->v_realdata + base, grouping,
            ns->v_realdata + base, grouping, degree))
	{
	    tfree(d);
	    return (NULL);
	}
    }

    return ((void *) d);
}
Beispiel #7
0
void *
cx_group_delay(void *data, short int type, int length, int *newlength, short int *newtype, struct plot *pl, struct plot *newpl, int grouping)
{
    complex *cc = (complex *) data;
    double *v_phase = alloc_d(length);
    double *datos,adjust_final;
    double *group_delay = alloc_d(length);
    int i;
    /* char *datos_aux; */

    /* Check to see if we have the frequency vector for the derivative */
    if (!eq(pl->pl_scale->v_name, "frequency"))
    {
      fprintf(cp_err, "Internal error: cx_group_delay: need frequency based complex vector.\n");
      return (NULL);
    }


    if (type == VF_COMPLEX)
     for (i = 0; i < length; i++)
     {
      v_phase[i] = radtodeg(cph(&cc[i]));
     }
    else
    {
      fprintf(cp_err, "Signal must be complex to calculate group delay\n");
      return (NULL);
    }


    type = VF_REAL;

    /* datos_aux = (char *)cx_deriv((char *)v_phase, type, length, newlength, newtype, pl, newpl, grouping);
     * datos = (double *) datos_aux;
     */
    datos = (double *)cx_deriv((char *)v_phase, type, length, newlength, newtype, pl, newpl, grouping);
    
    /* With this global variable I will change how to obtain the group delay because
     * it is defined as:
     *
     *  gd()=-dphase[rad]/dw[rad/s]
     *
     * if you have degrees in phase and frequency in Hz, must be taken into account
     *
     *  gd()=-dphase[deg]/df[Hz]/360
     *  gd()=-dphase[rad]/df[Hz]/(2*pi)
     */

    if(cx_degrees)
     {
       adjust_final=1.0/360;
     }
     else
     {
       adjust_final=1.0/(2*M_PI);
     }


    for (i = 0; i < length; i++)
    {
     group_delay[i] = -datos[i]*adjust_final;
    }

    /* Adjust to Real because the result is Real */
    *newtype = VF_REAL;

    	
    /* Set the type of Vector to "Time" because the speed of group units' s'
     * The different types of vectors are INCLUDE \ Fte_cons.h
     */
    pl->pl_dvecs->v_type= SV_TIME;

   return ((char *) group_delay);

}
static int
add_del_route6(const struct rt_entry *rt, int add)
{
  struct rt_msghdr *rtm;
  unsigned char buff[512];
  unsigned char *walker;
  struct sockaddr_in6 sin6;
  struct sockaddr_dl sdl;
  const struct rt_nexthop *nexthop;
  int sin_size, sdl_size;
  int len;

  if (add) {
    OLSR_PRINTF(2, "KERN: Adding %s\n", olsr_rtp_to_string(rt->rt_best));
  } else {
    OLSR_PRINTF(2, "KERN: Deleting %s\n", olsr_rt_to_string(rt));
  }

  memset(buff, 0, sizeof(buff));
  memset(&sin6, 0, sizeof(sin6));
  memset(&sdl, 0, sizeof(sdl));

  sin6.sin6_len = sizeof(sin6);
  sin6.sin6_family = AF_INET6;
  sdl.sdl_len = sizeof(sdl);
  sdl.sdl_family = AF_LINK;

  sin_size = 1 + ((sizeof(struct sockaddr_in6) - 1) | (sizeof(long) - 1));
  sdl_size = 1 + ((sizeof(struct sockaddr_dl) - 1) | (sizeof(long) - 1));

  /**********************************************************************
   *                  FILL THE ROUTING MESSAGE HEADER
   **********************************************************************/

  /* position header to the beginning of the buffer */
  rtm = (struct rt_msghdr *)buff;
  rtm->rtm_version = RTM_VERSION;
  rtm->rtm_type = (add != 0) ? RTM_ADD : RTM_DELETE;
  rtm->rtm_index = 0;
  rtm->rtm_flags = olsr_rt_flags(rt);
  rtm->rtm_pid = OLSR_PID;
  rtm->rtm_seq = ++seq;

  /* walk to the end of the header */
  walker = buff + sizeof(struct rt_msghdr);

  /**********************************************************************
   *                  SET  DESTINATION OF THE ROUTE
   **********************************************************************/

  memcpy(&sin6.sin6_addr.s6_addr, &rt->rt_dst.prefix.v6, sizeof(struct in6_addr));
  memcpy(walker, &sin6, sizeof(sin6));
  walker += sin_size;
  rtm->rtm_addrs = RTA_DST;

  /**********************************************************************
   *                  SET GATEWAY OF THE ROUTE
   **********************************************************************/

  nexthop = olsr_get_nh(rt);
  if (0 != (rtm->rtm_flags & RTF_GATEWAY)) {
    memcpy(&sin6.sin6_addr.s6_addr, &nexthop->gateway.v6, sizeof(struct in6_addr));
    memset(&sin6.sin6_addr.s6_addr, 0, 8);
    sin6.sin6_addr.s6_addr[0] = 0xfe;
    sin6.sin6_addr.s6_addr[1] = 0x80;
    sin6.sin6_scope_id = nexthop->iif_index;
#ifdef __KAME__
    *(u_int16_t *) & sin6.sin6_addr.s6_addr[2] = htons(sin6.sin6_scope_id);
    sin6.sin6_scope_id = 0;
#endif
    memcpy(walker, &sin6, sizeof(sin6));
    walker += sin_size;
    rtm->rtm_addrs |= RTA_GATEWAY;
  }
  else {
    /*
     * Host is directly reachable, so add
     * the output interface MAC address.
     */
    memcpy(&sin6.sin6_addr.s6_addr, &rt->rt_dst.prefix.v6, sizeof(struct in6_addr));
    memset(&sin6.sin6_addr.s6_addr, 0, 8);
    sin6.sin6_addr.s6_addr[0] = 0xfe;
    sin6.sin6_addr.s6_addr[1] = 0x80;
    sin6.sin6_scope_id = nexthop->iif_index;
#ifdef __KAME__
    *(u_int16_t *) & sin6.sin6_addr.s6_addr[2] = htons(sin6.sin6_scope_id);
    sin6.sin6_scope_id = 0;
#endif
    memcpy(walker, &sin6, sizeof(sin6));
    walker += sin_size;
    rtm->rtm_addrs |= RTA_GATEWAY;
    rtm->rtm_flags |= RTF_GATEWAY;
  }

  /**********************************************************************
   *                         SET  NETMASK
   **********************************************************************/

  if (0 == (rtm->rtm_flags & RTF_HOST)) {
    olsr_prefix_to_netmask((union olsr_ip_addr *)&sin6.sin6_addr, rt->rt_dst.prefix_len);
    memcpy(walker, &sin6, sizeof(sin6));
    walker += sin_size;
    rtm->rtm_addrs |= RTA_NETMASK;
  }

  /**********************************************************************
   *           WRITE CONFIGURATION MESSAGE TO THE ROUTING SOCKET
   **********************************************************************/

  rtm->rtm_msglen = (unsigned short)(walker - buff);
  len = write(olsr_cnf->rts, buff, rtm->rtm_msglen);
  if (len < 0 && !(errno == EEXIST || errno == ESRCH)) {
    fprintf(stderr, "cannot write to routing socket: %s\n", strerror(errno));
  }

  /*
   * If we get an EEXIST error while adding, delete and retry.
   */
  if (len < 0 && errno == EEXIST && rtm->rtm_type == RTM_ADD) {
    struct rt_msghdr *drtm;
    unsigned char dbuff[512];

    memset(dbuff, 0, sizeof(dbuff));
    drtm = (struct rt_msghdr *)dbuff;
    drtm->rtm_version = RTM_VERSION;
    drtm->rtm_type = RTM_DELETE;
    drtm->rtm_index = 0;
    drtm->rtm_flags = olsr_rt_flags(rt);
    drtm->rtm_seq = ++seq;

    walker = dbuff + sizeof(struct rt_msghdr);
    memcpy(&sin6.sin6_addr.s6_addr, &rt->rt_dst.prefix.v6, sizeof(struct in6_addr));
    memcpy(walker, &sin6, sizeof(sin6));
    walker += sin_size;
    drtm->rtm_addrs = RTA_DST;
    drtm->rtm_msglen = (unsigned short)(walker - dbuff);
    len = write(olsr_cnf->rts, dbuff, drtm->rtm_msglen);
    if (len < 0) {
      fprintf(stderr, "cannot delete route: %s\n", strerror(errno));
    }
    rtm->rtm_seq = ++seq;
    len = write(olsr_cnf->rts, buff, rtm->rtm_msglen);
    if (len < 0) {
      fprintf(stderr, "still cannot add route: %s\n", strerror(errno));
    }
  }
  return 0;
}
/*
 * Sends an add or delete message via the routing socket.
 * The message consists of:
 *  - a header i.e. struct rt_msghdr
 *  - 0-8 socket address structures
 */
static int
add_del_route(const struct rt_entry *rt, int add)
{
  struct rt_msghdr *rtm;               /* message to send to the routing socket */
  unsigned char buff[512];
  unsigned char *walker;               /* points within the buffer */
  struct sockaddr_in sin4;             /* internet style sockaddr */
  struct sockaddr_dl *sdl;             /* link level sockaddr */
  struct ifaddrs *addrs;
  struct ifaddrs *awalker;
  const struct rt_nexthop *nexthop;
  union olsr_ip_addr mask;             /* netmask as ip address */
  int sin_size, sdl_size;              /* payload of the message */
  int len;                             /* message size written to routing socket */

  if (add) {
    OLSR_PRINTF(2, "KERN: Adding %s\n", olsr_rtp_to_string(rt->rt_best));
  } else {
    OLSR_PRINTF(2, "KERN: Deleting %s\n", olsr_rt_to_string(rt));
  }

  memset(buff, 0, sizeof(buff));
  memset(&sin4, 0, sizeof(sin4));

  sin4.sin_len = sizeof(sin4);
  sin4.sin_family = AF_INET;

  sin_size = 1 + ((sizeof(struct sockaddr_in) - 1) | (sizeof(long) - 1));
  sdl_size = 1 + ((sizeof(struct sockaddr_dl) - 1) | (sizeof(long) - 1));

  /**********************************************************************
   *                  FILL THE ROUTING MESSAGE HEADER
   **********************************************************************/

  /* position header to the beginning of the buffer */
  rtm = (struct rt_msghdr *)buff;

  rtm->rtm_version = RTM_VERSION;
  rtm->rtm_type = add ? RTM_ADD : RTM_DELETE;
  rtm->rtm_index = 0;           /* is ignored in outgoing messages */
  rtm->rtm_flags = olsr_rt_flags(rt);
  rtm->rtm_pid = OLSR_PID;
  rtm->rtm_seq = ++seq;

  /* walk to the end of the header */
  walker = buff + sizeof(struct rt_msghdr);

  /**********************************************************************
   *                  SET  DESTINATION OF THE ROUTE
   **********************************************************************/

#ifdef _WRS_KERNEL
  /*
   * vxWorks: change proto or tos
   */
  OLSR_PRINTF(8, "\t- Setting Protocol: 0\n");
  ((struct sockaddr_rt *)(&sin4))->srt_proto = 0;
  OLSR_PRINTF(8, "\t- Setting TOS: 0\n");
  ((struct sockaddr_rt *)(&sin4))->srt_tos = 0;
#endif

  sin4.sin_addr = rt->rt_dst.prefix.v4;
  memcpy(walker, &sin4, sizeof(sin4));
  walker += sin_size;
  rtm->rtm_addrs = RTA_DST;

  /**********************************************************************
   *                  SET GATEWAY OF THE ROUTE
   **********************************************************************/

#ifdef _WRS_KERNEL
  /*
   * vxWorks: Route with no gateway is deleted
   */
  if (add) {
#endif
    nexthop = olsr_get_nh(rt);
    if (0 != (rtm->rtm_flags & RTF_GATEWAY)) {
      sin4.sin_addr = nexthop->gateway.v4;
      memcpy(walker, &sin4, sizeof(sin4));
      walker += sin_size;
      rtm->rtm_addrs |= RTA_GATEWAY;
    }
    else {
      /*
       * Host is directly reachable, so add
       * the output interface MAC address.
       */
      if (getifaddrs(&addrs)) {
        fprintf(stderr, "\ngetifaddrs() failed\n");
        return -1;
      }

      for (awalker = addrs; awalker != NULL; awalker = awalker->ifa_next)
        if (awalker->ifa_addr->sa_family == AF_LINK && strcmp(awalker->ifa_name, if_ifwithindex_name(nexthop->iif_index)) == 0)
          break;

      if (awalker == NULL) {
        fprintf(stderr, "\nInterface %s not found\n", if_ifwithindex_name(nexthop->iif_index));
        freeifaddrs(addrs);
        return -1;
      }

      /* sdl is "struct sockaddr_dl" */
      sdl = (struct sockaddr_dl *)awalker->ifa_addr;
      memcpy(walker, sdl, sdl->sdl_len);
      walker += sdl_size;
      rtm->rtm_addrs |= RTA_GATEWAY;
#ifdef RTF_CLONING
      rtm->rtm_flags |= RTF_CLONING;
#endif
#ifndef _WRS_KERNEL
      rtm->rtm_flags &= ~RTF_HOST;
#endif
      freeifaddrs(addrs);
    }
#ifdef _WRS_KERNEL
  }
#endif

  /**********************************************************************
   *                         SET  NETMASK
   **********************************************************************/

  if (0 == (rtm->rtm_flags & RTF_HOST)) {
    olsr_prefix_to_netmask(&mask, rt->rt_dst.prefix_len);
    sin4.sin_addr = mask.v4;
    memcpy(walker, &sin4, sizeof(sin4));
    walker += sin_size;
    rtm->rtm_addrs |= RTA_NETMASK;
  }

  /**********************************************************************
   *           WRITE CONFIGURATION MESSAGE TO THE ROUTING SOCKET
   **********************************************************************/

  rtm->rtm_msglen = (unsigned short)(walker - buff);
  len = write(olsr_cnf->rts, buff, rtm->rtm_msglen);
  if (0 != rtm->rtm_errno || len < rtm->rtm_msglen) {
    fprintf(stderr, "\nCannot write to routing socket: (rtm_errno= 0x%x) (last error message: %s)\n",
              rtm->rtm_errno,strerror(errno));
    if (add) {
      fprintf(stderr, " Failed on Adding %s\n", olsr_rtp_to_string(rt->rt_best));
    } else {
      fprintf(stderr, " Failed on Deleting %s\n",olsr_rt_to_string(rt));
    }
  }
  return 0;
}
Beispiel #10
0
void* metis_receive_thread(void* arg) {
    struct sockaddr_in addr;
    unsigned int length;
    int bytes_read;

    length=sizeof(addr);
    while(1) {
   	bytes_read=recvfrom(discovery_socket,input_buffer,sizeof(input_buffer),0,(struct sockaddr*)&addr,&length);
        if(bytes_read<0) {
            perror("recvfrom socket failed for metis_receive_thread");
            exit(1);
        }

        if(input_buffer[0]==0xEF && input_buffer[1]==0xFE) {
            switch(input_buffer[2]) {
                case 1:
                    if(!discovering) {
                        // get the end point
                        ep=input_buffer[3]&0xFF;

                        // get the sequence number
                        sequence=((input_buffer[4]&0xFF)<<24)+((input_buffer[5]&0xFF)<<16)+((input_buffer[6]&0xFF)<<8)+(input_buffer[7]&0xFF);
                        //fprintf(stderr,"received data ep=%d sequence=%ld\n",ep,sequence);

                        switch(ep) {
                            case 6:
                                // process the data
                                process_ozy_input_buffer(&input_buffer[8]);
                                process_ozy_input_buffer(&input_buffer[520]);
                                break;
                            case 4:
                                //fprintf(stderr,"EP4 data\n");
                                break;
                            default:
                                fprintf(stderr,"unexpected EP %d length=%d\n",ep,bytes_read);
                                break;
                        }
                    } else {
                        fprintf(stderr,"unexpected data packet when in discovery mode\n");
                    }
                    break;
                case 2:  // response to a discovery packet - hardware is not yet sending
                case 3:  // response to a discovery packet - hardware is already sending
                    if(discovering) {
                        if(found<MAX_METIS_CARDS) {
                            // get MAC address from reply
                            sprintf(metis_cards[found].mac_address,"%02X:%02X:%02X:%02X:%02X:%02X",
                                       input_buffer[3]&0xFF,input_buffer[4]&0xFF,input_buffer[5]&0xFF,input_buffer[6]&0xFF,input_buffer[7]&0xFF,input_buffer[8]&0xFF);
                            fprintf(stderr,"Metis MAC address %s\n",metis_cards[found].mac_address);
    
                            // get ip address from packet header
                            sprintf(metis_cards[found].ip_address,"%d.%d.%d.%d",
                                       addr.sin_addr.s_addr&0xFF,
                                       (addr.sin_addr.s_addr>>8)&0xFF,
                                       (addr.sin_addr.s_addr>>16)&0xFF,
                                       (addr.sin_addr.s_addr>>24)&0xFF);
                            fprintf(stderr,"Metis IP address %s\n",metis_cards[found].ip_address);
                            metis_cards[found].code_version = input_buffer[9];
                            switch (input_buffer[10]) {
                               case 0x00:
                                  metis_cards[found].board_id = "Metis";
                                  break;
                               case 0x01:
                                  metis_cards[found].board_id = "Hermes";
                                  break;
                               case 0x02:
                                  metis_cards[found].board_id = "Griffin";
                                  break;
                               default: 
                                  metis_cards[found].board_id = "unknown";
                                  break;
                            }       
                            fprintf(stderr,"Board id: %s",metis_cards[found].board_id);
                            fprintf(stderr," version:  %1.2F\n",metis_cards[found].code_version /10.0);

                            found++;
                            if(input_buffer[2]==3) {
                                fprintf(stderr,"Metis is sending\n");
                            }
                        } else {
                            fprintf(stderr,"too many metis cards!\n");
                        }
                    } else {
                        fprintf(stderr,"unexepected discovery response when not in discovery mode\n");
                    }
                    break;
                default:
                    fprintf(stderr,"unexpected packet type: 0x%02X\n",input_buffer[2]);
                    break;
            }
Beispiel #11
0
int
gageDeconvolve(Nrrd *_nout, double *lastDiffP,
               const Nrrd *nin, const gageKind *kind,
               const NrrdKernelSpec *ksp, int typeOut,
               unsigned int maxIter, int saveAnyway,
               double step, double epsilon, int verbose) {
  char me[]="gageDeconvolve", err[BIFF_STRLEN];
  gageContext *ctx[2];
  gagePerVolume *pvl[2];
  double *out[2], *val[2], alpha, (*lup)(const void *, size_t), meandiff=0;
  const double *ans[2];
  Nrrd *nout[2];
  airArray *mop;
  unsigned int sx, sy, sz, xi, yi, zi, anslen, this, last, inIdx, iter;
  int E, valItem;

  if (!(_nout && lastDiffP && nin && kind && ksp)) {
    sprintf(err, "%s: got NULL pointer", me);
    biffAdd(GAGE, err); return 1;
  }
  if (!(nrrdTypeDefault == typeOut
        || !airEnumValCheck(nrrdType, typeOut))) {
    sprintf(err, "%s: typeOut %d not valid", me, typeOut);
    biffAdd(GAGE, err); return 1;
  }
  if (!( maxIter >= 1 )) {
    sprintf(err, "%s: need maxIter >= 1 (not %u)", me, maxIter);
    biffAdd(GAGE, err); return 1;
  }
  if (!( epsilon >= 0 )) {
    sprintf(err, "%s: need epsilon >= 0.0 (not %g)", me, epsilon);
    biffAdd(GAGE, err); return 1;
  }

  /* this once changed from 0 to 1, but is unlikely to change again */
  valItem = 1;

  mop = airMopNew();
  for (iter=0; iter<2; iter++) {
    nout[iter] = nrrdNew();
    airMopAdd(mop, nout[iter], (airMopper)nrrdNuke, airMopAlways);
    if (nrrdConvert(nout[iter], nin, nrrdTypeDouble)) {
      sprintf(err, "%s: couldn't allocate working buffer %u", me, iter);
      biffMove(GAGE, err, NRRD); airMopError(mop); return 1;
    }
    ctx[iter] = gageContextNew();
    airMopAdd(mop, ctx[iter], (airMopper)gageContextNix, airMopAlways);
    E = 0;
    if (!E) E |= !(pvl[iter] = gagePerVolumeNew(ctx[iter], nout[iter], kind));
    if (!E) E |= gagePerVolumeAttach(ctx[iter], pvl[iter]);
    if (!E) E |= gageKernelSet(ctx[iter], gageKernel00,
                               ksp->kernel, ksp->parm);
    if (!E) E |= gageQueryItemOn(ctx[iter], pvl[iter], valItem);
    if (!E) E |= gageUpdate(ctx[iter]);
    if (E) {
      sprintf(err, "%s: trouble setting up context %u", me, iter);
      biffAdd(GAGE, err); airMopError(mop); return 1;
    }
    out[iter] = AIR_CAST(double*, nout[iter]->data);
    ans[iter] = gageAnswerPointer(ctx[iter], pvl[iter], valItem);
  }
  
  anslen = kind->table[valItem].answerLength;
  lup = nrrdDLookup[nin->type];

  alpha = ksp->kernel->eval1_d(0.0, ksp->parm);
  sx = ctx[0]->shape->size[0];
  sy = ctx[0]->shape->size[1];
  sz = ctx[0]->shape->size[2];
  
  for (iter=0; iter<maxIter; iter++) {
    this = (iter+1) % 2;
    last = (iter+0) % 2;
    val[this] = out[this];
    val[last] = out[last];
    inIdx = 0;
    meandiff = 0;
    for (zi=0; zi<sz; zi++) {
      for (yi=0; yi<sy; yi++) {
        for (xi=0; xi<sx; xi++) {
          unsigned int ai;
          double in, aa;
          gageProbe(ctx[last], xi, yi, zi);
          for (ai=0; ai<anslen; ai++) {
            in = lup(nin->data, ai + anslen*inIdx);
            aa = ans[last][ai];
            val[this][ai] = val[last][ai] + step*(in - aa)/alpha;
            meandiff += 2*(in - aa)*(in - aa)/(DBL_EPSILON + in*in + aa*aa);
          }
          val[this] += anslen;
          val[last] += anslen;
          ++inIdx;
        }
      }
    }
    meandiff /= sx*sy*sz;
    if (verbose) {
      fprintf(stderr, "%s: iter %u meandiff = %g\n", me, iter, meandiff);
    }
    if (meandiff < epsilon) {
      /* we have indeed converged while iter < maxIter */
      break;
    }
  }
  if (iter == maxIter) {
    if (!saveAnyway) {
      sprintf(err, "%s: failed to converge in %u iterations, meandiff = %g",
              me, maxIter, meandiff);
      biffAdd(GAGE, err); airMopError(mop); return 1;
    } else {
      if (verbose) {
        fprintf(stderr, "%s: at maxIter %u; err %g still > thresh %g\n", me,
                iter, meandiff, epsilon);
      }
    }
  }

  if (nrrdClampConvert(_nout, nout[this], (nrrdTypeDefault == typeOut
                                           ? nin->type
                                           : typeOut))) {
    sprintf(err, "%s: couldn't create output", me);
    biffAdd(GAGE, err); airMopError(mop); return 1;
  }
  *lastDiffP = meandiff;

  airMopOkay(mop);
  return 0;
}
Beispiel #12
0
void metis_discover(char* interface,char* metisip) {
    int rc;
    int i;
    int on=1;
    //struct ifreq ifr;

    fprintf(stderr,"Looking for Metis card on interface %s\n",interface);

    discovering=1;
    
    // send a broadcast to locate metis boards on the network
    discovery_socket=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
    if(discovery_socket<0) {
        perror("create socket failed for discovery_socket\n");
        exit(1);
    }

    // get my MAC address and IP address
    if(get_addr(discovery_socket,interface)<0) {
        exit(1);
    }

    printf("%s IP Address: %ld.%ld.%ld.%ld\n",
              interface,
              ip_address&0xFF,
              (ip_address>>8)&0xFF,
              (ip_address>>16)&0xFF,
              (ip_address>>24)&0xFF);

    printf("%s MAC Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
         interface,
         hw_address[0], hw_address[1], hw_address[2], hw_address[3], hw_address[4], hw_address[5]);


    // start a receive thread to get discovery responses
    rc=pthread_create(&receive_thread_id,NULL,metis_receive_thread,NULL);
    if(rc != 0) {
        fprintf(stderr,"pthread_create failed on metis_receive_thread: rc=%d\n", rc);
        exit(1);
    }

    // bind to this interface
    struct sockaddr_in name={0};
    name.sin_family = AF_INET;
    name.sin_addr.s_addr = ip_address;
    name.sin_port = htons(DISCOVERY_SEND_PORT);
    bind(discovery_socket,(struct sockaddr*)&name,sizeof(name));


    // allow broadcast on the socket
    rc=setsockopt(discovery_socket, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));
    if(rc != 0) {
        fprintf(stderr,"cannot set SO_BROADCAST: rc=%d\n", rc);
        exit(1);
    }

    discovery_length=sizeof(discovery_addr);
    memset(&discovery_addr,0,discovery_length);
    discovery_addr.sin_family=AF_INET;
    discovery_addr.sin_port=htons(DISCOVERY_SEND_PORT);
    discovery_addr.sin_addr.s_addr=htonl(INADDR_BROADCAST);

    buffer[0]=0xEF;
    buffer[1]=0xFE;
    buffer[2]=0x02;
    for(i=0;i<60;i++) {
        buffer[i+3]=0x00;
    }

    if(sendto(discovery_socket,buffer,63,0,(struct sockaddr*)&discovery_addr,discovery_length)<0) {
        perror("sendto socket failed for discovery_socket\n");
        exit(1);
    }
}
Beispiel #13
0
/*
 * Computes entropy from integer frequencies for various encoding methods and
 * picks the best encoding.
 *
 * FIXME: we could reuse some of the code here for the actual encoding
 * parameters too. Eg the best 'k' for SUBEXP or the code lengths for huffman.
 *
 * Returns the best codec to use.
 */
enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) {
    enum cram_encoding best_encoding = E_NULL;
    int best_size = INT_MAX, bits;
    int nvals, i, ntot = 0, max_val = 0, min_val = INT_MAX, k;
    int *vals = NULL, *freqs = NULL, vals_alloc = 0, *codes;

    //cram_stats_dump(st);

    /* Count number of unique symbols */
    for (nvals = i = 0; i < MAX_STAT_VAL; i++) {
	if (!st->freqs[i])
	    continue;
	if (nvals >= vals_alloc) {
	    vals_alloc = vals_alloc ? vals_alloc*2 : 1024;
	    vals  = realloc(vals,  vals_alloc * sizeof(int));
	    freqs = realloc(freqs, vals_alloc * sizeof(int));
	    if (!vals || !freqs) {
		if (vals)  free(vals);
		if (freqs) free(freqs);
		return E_HUFFMAN; // Cannot do much else atm
	    }
	}
	vals[nvals] = i;
	freqs[nvals] = st->freqs[i];
	ntot += freqs[nvals];
	if (max_val < i) max_val = i;
	if (min_val > i) min_val = i;
	nvals++;
    }
    if (st->h) {
	HashIter *iter=  HashTableIterCreate();
	HashItem *hi;
	int i;

	while ((hi = HashTableIterNext(st->h, iter))) {
	    if (nvals >= vals_alloc) {
		vals_alloc = vals_alloc ? vals_alloc*2 : 1024;
		vals  = realloc(vals,  vals_alloc * sizeof(int));
		freqs = realloc(freqs, vals_alloc * sizeof(int));
		if (!vals || !freqs)
		    return E_HUFFMAN; // Cannot do much else atm
	    }
	    i = (size_t)hi->key;
	    vals[nvals]=i;
	    freqs[nvals] = hi->data.i;
	    ntot += freqs[nvals];
	    if (max_val < i) max_val = i;
	    if (min_val > i) min_val = i;
	    nvals++;
	}
	HashTableIterDestroy(iter);
    }

    st->nvals = nvals;
    assert(ntot == st->nsamp);

#if 0
    // RANDOMISER
    switch(random()%10) {
    case 0:  return E_HUFFMAN;
    case 1:  return E_HUFFMAN;
    //case 1:  return E_BETA; // Java doesn't support E_BETA for BYTE vals
    default: return E_EXTERNAL;
    }
#endif

    if (nvals <= 1) {
	free(vals);
	free(freqs);

	if (fd->verbose > 1)
	    fprintf(stderr, "0 values => 0 bits\n");

	return E_HUFFMAN;
    }

    if (fd->verbose > 1)
	fprintf(stderr, "Range = %d..%d, nvals=%d, ntot=%d\n",
		min_val, max_val, nvals, ntot);

    /* Theoretical entropy */
    if (fd->verbose > 1) {
	double dbits = 0;
	for (i = 0; i < nvals; i++) {
	    dbits += freqs[i] * log((double)freqs[i]/ntot);
	}
	dbits /= -log(2);
	if (fd->verbose > 1)
	    fprintf(stderr, "Entropy = %f\n", dbits);
    }

    if (nvals > 1 && ntot > 256) {
#if 0
	/*
	 * CRUDE huffman estimator. Round to closest and round up from 0
	 * to 1 bit.
	 *
	 * With and without ITF8 incase we have a few discrete values but with
	 * large magnitude.
	 *
	 * Note rans0/arith0 and Z_HUFFMAN_ONLY vs internal huffman can be
	 * compared in this way, but order-1 (eg rans1) or maybe LZ77 modes
	 * may detect the correlation of high bytes to low bytes in multi-
	 * byte values. So this predictor breaks down.
	 */
	double dbits = 0;  // entropy + ~huffman
	double dbitsH = 0;
	double dbitsE = 0; // external entropy + ~huffman
	double dbitsEH = 0;
	int F[256] = {0}, n = 0;
	double e = 0; // accumulated error bits
	for (i = 0; i < nvals; i++) {
	    double x; int X;
	    unsigned int v = vals[i];

	    //Better encoding would cope with sign.
	    //v = ABS(vals[i])*2+(vals[i]<0);

	    if (!(v & ~0x7f)) {
		F[v]             += freqs[i], n+=freqs[i];
	    } else if (!(v & ~0x3fff)) {
		F[(v>>8) |0x80] += freqs[i];
		F[ v     &0xff] += freqs[i], n+=2*freqs[i];
	    } else if (!(v & ~0x1fffff)) {
Beispiel #14
0
static void *display_deltacast_init(struct module *parent, const char *fmt, unsigned int flags)
{
        UNUSED(parent);
        struct state_deltacast *s;
        ULONG             Result,DllVersion,NbBoards,ChnType;
        ULONG             BrdId = 0;

        s = (struct state_deltacast *)calloc(1, sizeof(struct state_deltacast));
        s->magic = DELTACAST_MAGIC;
        
        s->frame = vf_alloc(1);
        s->tile = vf_get_tile(s->frame, 0);
        s->frames = 0;
        
        gettimeofday(&s->tv, NULL);
        
        s->initialized = FALSE;
        if(flags & DISPLAY_FLAG_AUDIO_EMBEDDED) {
                s->play_audio = TRUE;
        } else {
                s->play_audio = FALSE;
        }
        
        s->BoardHandle = s->StreamHandle = s->SlotHandle = NULL;
        s->audio_configured = FALSE;

        if(fmt && strcmp(fmt, "help") == 0) {
                show_help();
                vf_free(s->frame);
                free(s);
                return &display_init_noerr;
        }
        
        if(fmt)
        {
                char *tmp = strdup(fmt);
                char *save_ptr = NULL;
                char *tok;
                
                tok = strtok_r(tmp, ":", &save_ptr);
                if(!tok)
                {
                        free(tmp);
                        show_help();
                        goto error;
                }
                if (strncasecmp(tok, "board=", strlen("board=")) == 0) {
                        BrdId = atoi(tok + strlen("board="));
                } else {
                        fprintf(stderr, "Unknown option: %s\n\n", tok);
                        free(tmp);
                        show_help();
                        goto error;
                }
                free(tmp);
        }

        /* Query VideoMasterHD information */
        Result = VHD_GetApiInfo(&DllVersion,&NbBoards);
        if (Result != VHDERR_NOERROR) {
                fprintf(stderr, "[DELTACAST] ERROR : Cannot query VideoMasterHD"
                                " information. Result = 0x%08X\n",
                                Result);
                goto error;
        }
        if (NbBoards == 0) {
                fprintf(stderr, "[DELTACAST] No DELTA board detected, exiting...\n");
                goto error;
        }
        
        if(BrdId >= NbBoards) {
                fprintf(stderr, "[DELTACAST] Wrong index %d. Found %d cards.\n", BrdId, NbBoards);
                goto error;
        }

        /* Open a handle on first DELTA-hd/sdi/codec board */
        Result = VHD_OpenBoardHandle(BrdId,&s->BoardHandle,NULL,0);
        if (Result != VHDERR_NOERROR)
        {
                fprintf(stderr, "[DELTACAST] ERROR : Cannot open DELTA board %u handle. Result = 0x%08X\n",BrdId,Result);
                goto error;
        }
        VHD_GetBoardProperty(s->BoardHandle, VHD_CORE_BP_TX0_TYPE, &ChnType);
        if((ChnType!=VHD_CHNTYPE_SDSDI)&&(ChnType!=VHD_CHNTYPE_HDSDI)&&(ChnType!=VHD_CHNTYPE_3GSDI)) {
                fprintf(stderr, "[DELTACAST] ERROR : The selected channel is not an SDI one\n");
                goto bad_channel;
        }
        
        /* Disable RX0-TX0 by-pass relay loopthrough */
        VHD_SetBoardProperty(s->BoardHandle,VHD_CORE_BP_BYPASS_RELAY_0,FALSE);
        
        /* Select a 1/1 clock system */
        VHD_SetBoardProperty(s->BoardHandle,VHD_SDI_BP_CLOCK_SYSTEM,VHD_CLOCKDIV_1);

        pthread_mutex_init(&s->lock, NULL);
                  
	return s;

bad_channel:
        VHD_CloseBoardHandle(s->BoardHandle);
error:
        vf_free(s->frame);
        free(s);
        return NULL;
}
int main(int argc, char* argv[])
{
  /*define variables*/
  int nx,nx1,nt;
  int n1,n2;
  float d1,o1,d2,o2;
  int padt,padx;
  int ntfft,*n,nw,nk;
  float **d,*wavelet,**shot,**ds,**vel,**vmig,**M,v_ave;
  float *kx,*omega,dkx,dw;
  sf_complex **m,**ms,**mr,*in2a,*in2b,*cs,*cr,*c,czero;
  sf_complex Ls;
  float fmin,fmax,f_low,f_high;
  int if_low,if_high;
  int ix,iw,ik;
  float dt,dx,ox,dz,zmax;
  fftwf_plan p2a,p2b;
  sf_file in,out,velfile,source_wavelet;
  int iz,nz;
  int ishot,max_num_shot,ig,ng,it,index;
  int iswavelet;
  /*define sf input output*/
  sf_init (argc,argv);
  in = sf_input("in");
  out = sf_output("out");
  velfile = sf_input("velfile");
  if (!sf_histint(in,"n1",&n1)) sf_error("No n1= in input");
  if (!sf_histfloat(in,"d1",&d1)) sf_error("No d1= in input");
  if (!sf_histfloat(in,"o1",&o1)) o1=0.;
  if (!sf_histint(in,"n2",&n2)) sf_error("No n2= in vel");
  if (!sf_histfloat(in,"d2",&d2)) sf_error("No d2= in input");
  if (!sf_histfloat(in,"o2",&o2)) o2=0.;

  dt = d1;
  dx = d2;
  ox = o2;
  nx1 = n2;
  nt = n1;
  if (!sf_histint(velfile,"n1",&nz)) sf_error("No n1= in vel");
  if (!sf_histfloat(velfile,"d1",&dz)) sf_error("No n1= in vel");
  if (!sf_histint(velfile,"n2",&n2)) sf_error("No n2= in vel");	
   if (!sf_getint("iswavelet",&iswavelet)) iswavelet = 0;
  source_wavelet=sf_input("source_wavelet");

  max_num_shot=100;
  ng=700;
  nx=n2;
  padt = 2;
  padx = 2;
  ntfft = padt*nt;
  nw=ntfft/2+1;
  nk = padx*nx;
  dw = 2*PI/ntfft/dt;
  dkx = 2*PI/nk/dx;

  sf_putint(out,"n1",nz);
  sf_putint(out,"n2",nx);
  sf_putfloat(out,"d1",dz);
  sf_putstring(out,"label1","z");
  sf_putstring(out,"unit1","m");
  sf_putstring(out,"title","migrated");

  if (!sf_getfloat("fmax",&fmax)) fmax = 0.5/d1; /* max frequency to process */
  if (fmax > 0.5/d1) fmax = 0.5/d1;
  if (!sf_getfloat("fmin",&fmin)) fmin = 0.1; /* min frequency to process */
  if (!sf_getfloat("Zmax",&zmax)) zmax = (nz-1)*dz; /* max Depth to migrate */

  
  /*define axis variables*/
 
  dkx=(float) 2*PI/nk/dx;
  dw=(float) 2*PI/ntfft/dt;
  /*allocate memory to dynamic arrays*/
  d = sf_floatalloc2(nt,nx1);
  shot=sf_floatalloc2(nt,ng);
  ds=sf_floatalloc2(nt,nx);
  vel = sf_floatalloc2(nz,nx);
  wavelet=sf_floatalloc(nt);
  vmig = sf_floatalloc2(nz,nx);
  m = sf_complexalloc2(nw,nx);
  ms = sf_complexalloc2(nw,nx);
  mr = sf_complexalloc2(nw,nx);
  kx= sf_floatalloc (nk);
  omega= sf_floatalloc (nw);
  in2a = sf_complexalloc(nk);
  in2b = sf_complexalloc(nk);
  n = sf_intalloc(1);
  M= sf_floatalloc2(nz,nx);
  c = sf_complexalloc(nx);
  cs = sf_complexalloc(nx);
  cr = sf_complexalloc(nx);
  /*read input files*/ 
  sf_floatread(d[0],nx1*nt,in);
  sf_floatread(vel[0],nx*nz,velfile);
/* If there is no wavelet use delta as default
If there is a wavelet use it*/
   if (iswavelet==0) {
	for (it=0; it<nt; it++) wavelet[it] = 0.0;
	wavelet[0]=1;
 	 }

   if (iswavelet==1) sf_floatread(wavelet,nt,source_wavelet);

  /* This part is important: we need to define the horizontal wavenumber and frequency axes right.*/

dw = 2*PI/ntfft/dt;

 dkx = 2*PI/nk/dx;

for (iw=0;iw<nw;iw++){

    omega[iw] = dw*iw;

}
for (ik=0;ik<nk;ik++){ 

  if (ik<nk/2) kx[ik] = dkx*ik;

  else         kx[ik] = -(dkx*nk - dkx*ik);

}

  /* Define minimum and maximum frequency index to process*/   
  
  f_low = fmin;   /* min frequency to process */
  f_high = fmax;  /* max frequency to process */
  
  if(f_low>0){
  	if_low = trunc(f_low*dt*ntfft);
  }	
  else{ 
  	if_low = 0;
  }
  if(f_high*dt*ntfft+1<nw){
  	if_high = trunc(f_high*dt*ntfft)+1;
  }
  else{
 	 if_high = nw;
  }
  
  
  __real__ czero = 0;
  __imag__ czero = 0;
  n[0] = nk;
  p2a = fftwf_plan_dft(1, n, (fftwf_complex*)in2a, (fftwf_complex*)in2a, FFTW_FORWARD, FFTW_ESTIMATE);
  p2b = fftwf_plan_dft(1, n, (fftwf_complex*)in2b, (fftwf_complex*)in2b, FFTW_BACKWARD, FFTW_ESTIMATE);

fftwf_execute(p2a); /* FFT x to k */
fftwf_execute(p2b); /* FFT x to k */

  /* Define initial migrated model and source field as zeros*/
 
  for (iz=0; iz<nz; iz++) {	
    for (ix=0; ix<nx; ix++) M[ix][iz] = 0.0;
  }

   for (it=0; it<nt; it++) {	
    for (ix=0; ix<nx; ix++) ds[ix][it] = 0.0;
  }

  for (iz=0; iz<nz;iz++){
    for (ix=0;ix<nx;ix++) vmig[ix][iz]=vel[ix][iz];
    }
  
  /* loop over shots*/
for (ishot=0;ishot<max_num_shot;ishot++){
	for (ig=0;ig<ng;ig++){
		for (it=0; it<nt; it++)
		shot[ig][it]=d[ishot*ng+ig][it];
	}
	 for (it=0; it<nt; it++) {	
    		for (ix=0; ix<nx; ix++) ds[ix][it] = 0.0;
 	 }
	index=ishot*nx/max_num_shot;
	for (it=0; it<nt; it++) ds[index][it]=wavelet[it];
/* apply fourier transform in time direction t-x ---> w-x*/
  my_forward_fft(ms,mr,shot,ds,nt,dt,nx,padt);

  for (iw=if_low;iw<if_high;iw++){
     for (iz=0; iz<nz;iz++){
		v_ave=vmig[0][iz];	
	        my_v_ave (v_ave,vmig,iz,nx);
/*Apply phase shift to source side*/
	        my_phase_shift(ms,czero,iw,iz,omega,kx,nk,nx,v_ave,in2a,in2b,p2a,p2b,dz,0);
			for (ix=0;ix<nx;ix++) {
					cs[ix]= in2b[ix];
					}
/*Apply phase shift to receiver side*/
		 my_phase_shift(mr,czero,iw,iz,omega,kx,nk,nx,v_ave,in2a,in2b,p2a,p2b,dz,1);
			for (ix=0;ix<nx;ix++) {
					cr[ix]= in2b[ix];
					}
/*Apply split step correction to source and receiver side wavefields*/
         	my_split_step_correction (ms,cs,vmig,v_ave,iz,dz,iw,dw,nx,0);
		my_split_step_correction (mr,cr,vmig,v_ave,iz,dz,iw,dw,nx,1);
	/* Apply cross corrolation as an imaging condition*/
		for (ix=0;ix<nx;ix++){
		__real__ Ls=crealf(ms[ix][iw]);
		__imag__ Ls=- cimagf(ms[ix][iw]);
		m[ix][iw]=mr[ix][iw]*Ls;
		}
   			/* Update migrated model by stacking*/	
		for (ix=0;ix<nx;ix++) M[ix][iz]=M[ix][iz]+2*crealf(m[ix][iw]);
      }
   }
fprintf(stderr,"\r progress = %6.2f%%",(float) 100*(ishot)/(max_num_shot));
  }


  sf_floatwrite(M[0],nz*nx,out);

  
  fftwf_destroy_plan(p2a);
  fftwf_free(in2a); 
  fftwf_destroy_plan(p2b);
  fftwf_free(in2b);	
  
  exit (0);
}
Beispiel #16
0
/*!
  Takes pointers to the two bodies in contact, and the set of contacts returned
  from the collision detection system, and adds a contact to each body for each
  contact in the set.
 */
void
addContacts(Body *body1, Body *body2, ContactReport &contactSet, bool softContactsOn )
{
	ContactReport::iterator cp;
	Contact *c1,*c2;
	int i;

	if ( softContactsOn && ( body1->isElastic() || body2->isElastic() ) ) {
		findSoftNeighborhoods( body1, body2, contactSet);
		DBGP("Before merge: " << contactSet.size());
		mergeSoftNeighborhoods( body1, body2, contactSet);
		DBGP("After merge: " << contactSet.size());
	}

	for (i=0,cp=contactSet.begin();cp!=contactSet.end();cp++,i++) {

		DBGP( body1->getName().latin1() << " - " << body2->getName().latin1() << " contact: " <<
		cp->b1_pos << " " <<  cp->b1_normal );

		//this is an attempt to check if the contact normals point in the right direction
		//based on the distance between the bodies. It is meant to help with bad geometry with ill-defined
		//normals. Can be removed completely - should never come up for good geometry
		if (! checkContactNormals(body1, body2, &(*cp)) ) {
			DBGP("Wrong normals detected!");
		}
		if ( softContactsOn && ( body1->isElastic() || body2->isElastic() ) ) {
			c1 = new SoftContact( body1, body2, cp->b1_pos, cp->b1_normal, &(cp->nghbd1) );
			c2 = new SoftContact( body2, body1, cp->b2_pos, cp->b2_normal, &(cp->nghbd2) );
			c1->setMate(c2);
			c2->setMate(c1);

			((SoftContact *)c1)->setUpFrictionEdges();
			((SoftContact *)c2)->setUpFrictionEdges();
		} else {
			c1 = new PointContact(body1,body2,cp->b1_pos,cp->b1_normal);
			c2 = new PointContact(body2,body1,cp->b2_pos,cp->b2_normal);
			c1->setMate(c2);
			c2->setMate(c1);
		}

		body1->addContact(c1);
		body2->addContact(c2);

		//check if the new contacts inherit two contacts from previous time step
		//if so, remove ancestors so nobody else inherits them
		Contact *ancestor = body1->checkContactInheritance(c1);
		if (ancestor) {
			c1->inherit(ancestor);
			if (!ancestor->getMate()) 
				fprintf(stderr,"No mate for inherited contact!!\n");
			else
				c2->inherit(ancestor->getMate());
			//careful: this also deletes the removed contact so remove the mate first
			if (ancestor->getMate()) body2->removePrevContact( ancestor->getMate() );
			body1->removePrevContact( ancestor );
		} else {
			ancestor = body2->checkContactInheritance(c2);
			if (ancestor){
				if (!ancestor->getMate())
					fprintf(stderr,"No mate for inherited contact!!\n");
				else		
					c1->inherit(ancestor->getMate());
				c2->inherit(ancestor);
				if (ancestor->getMate()) body1->removePrevContact( ancestor->getMate() );
				body2->removePrevContact( ancestor );
			} else {
//				fprintf(stderr,"New contact between %s and %s\n",body1->getName().latin1(), body2->getName().latin1() );
			}
		}
	}
}
Beispiel #17
0
int main(int argc, char *argv[])
{
setbuf(stdout,NULL);
     int sockfd, newsockfd,play_n,hops,i;
char ip_arr[MAX][255];
long int portno;
     socklen_t clilen;
     char buffer[256];
     struct sockaddr_in serv_addr, cli_addr;
     int n;
struct hostent *out_h;
     if (argc < 4) {
         fprintf(stderr,"ERROR, no port provided\n");
         exit(1);
     }
play_n=atoi(argv[2]);
hops=atoi(argv[3]);

char hostn[255];
gethostname(hostn,sizeof(hostn));
printf("Potato Master on %s \nPlayers = %d\nHops = %d\n",hostn,play_n,hops);

if(play_n<=1)
{
printf("ERROR: Enter Valid values for Players \n");
if(hops<0)
printf("ERROR: Enter Valid values for hops \n");

exit(EXIT_SUCCESS);
}
if(hops<0)
{
printf("ERROR: Enter Valid values for hops \n");
exit(EXIT_SUCCESS);
}
    
///

 sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0) 
        error("ERROR opening socket");
     bzero((char *) &serv_addr, sizeof(serv_addr));
     portno = atoi(argv[1]);
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(portno);
     if (bind(sockfd, (struct sockaddr *) &serv_addr,
              sizeof(serv_addr)) < 0) 
              error("ERROR on binding");
     listen(sockfd,play_n);
     clilen = sizeof(cli_addr);

int count=0;
while(count!=play_n)
{
count++;
     newsockfd = accept(sockfd, 
                 (struct sockaddr *) &cli_addr, 
                 &clilen);
     if (newsockfd < 0) 
          error("ERROR on accept");
     bzero(buffer,256);
int port_n;
     n = recv(newsockfd,&port_n,sizeof(int),0);
     if (n < 0) error("ERROR reading from socket");
     


     n = send(newsockfd,"I got your message",18,0);
     if (n < 0) error("ERROR writing to socket");


    struct hostent *server;
int sockc;
    
   
        sockc = socket(AF_INET, SOCK_STREAM, 0);
    if (sockc < 0) 
        error("ERROR opening socket");
char *ip;
ip=inet_ntoa(cli_addr.sin_addr);

    server = gethostbyname(ip);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(port_n);
    while(connect(sockc,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0);
        
sockf = socket(AF_INET, SOCK_STREAM, 0);
     if (sockf< 0) 
        error("ERROR opening socket");
int cli_port;
Play_list[count].mast_port=make_socket(sockf,fserver);


    
   n = send(sockc,&Play_list[count].mast_port,sizeof(int),0);
    if (n < 0) 
         error("ERROR writing to socket");
    bzero(buffer,256);
    n = recv(sockc,buffer,255,0);
    if (n < 0) 
         error("ERROR reading from socket");
   
    close(sockc);
   // return 0;
listen(sockf,play_n);
     clilen = sizeof(cli_addr);
Play_list[count].fd = accept(sockf, 
                 (struct sockaddr *) &cli_addr, 
                 &clilen);
     if (Play_list[count].fd < 0) 
          error("ERROR on accept");


out_h = gethostbyaddr((char *)&cli_addr.sin_addr,sizeof(struct in_addr), AF_INET);

printf("player %d is on %s\n",count,out_h->h_name);

n = send(Play_list[count].fd,&count,sizeof(int),0);
    if (n < 0) 
         error("ERROR writing to socket");
int left;
n = recv(Play_list[count].fd,&Play_list[count].left_port,sizeof(int),0);
     if (n < 0) error("ERROR reading from socket");


char *ipcpy=(char *)malloc(255);
ipcpy=inet_ntoa(cli_addr.sin_addr);
strcpy(ip_arr[count],ipcpy);


n = send(Play_list[count].fd,&play_n,sizeof(int),0);
     if (n < 0) error("ERROR writing to socket");

n = send(Play_list[count].fd,&hops,sizeof(int),0);
     if (n < 0) error("ERROR writing to socket");
}

if(play_n==1)
exit(1);


//left port array creation

for(i=1;i<=play_n;i++)
{
left_arr[i]=Play_list[i].left_port;
}

for(i=1;i<=play_n;i++)
{
int j;
for(j=1;j<=play_n;j++)
n=send(Play_list[i].fd,&left_arr[j],sizeof(int),0);
if (n < 0) error("ERROR writing to socket");
}


for(i=1;i<=play_n;i++)
{
int j;
for(j=1;j<=play_n;j++)
n=send(Play_list[i].fd,&ip_arr[j],256*sizeof(char),0);
if (n < 0) error("ERROR writing to socket");
}
char check_ring;
n = recv(Play_list[1].fd,&check_ring,sizeof(char),0);

int rand_no;
time_t seco;
time(&seco);

srand(seco);
rand_no=rand();
i=(rand_no%play_n)+1;

if(hops==0)
{
printf("All players present, not sending potato\n");
for(i=1;i<=play_n;i++)
{
char last_m='f';
n=send(Play_list[i].fd,&last_m,sizeof(char),0);
if (n < 0) error("ERROR writing to socket");
}
for(i=1;i<=play_n;i++)
close(Play_list[i].fd);
exit(EXIT_SUCCESS);
}
char p='p';
printf("All players present, sending potato to player %d\n" ,i);
n=send(Play_list[i].fd,&p,sizeof(char),0);
if (n < 0) error("ERROR writing to socket");

//get potato from player....




while(1)
{
fd_set monito;
int readsock;
int highfd=0;
FD_ZERO(&monito);

for(i=1;i<=play_n;i++)
{
FD_SET(Play_list[i].fd,&monito);

if(Play_list[i].fd>highfd)
highfd=Play_list[i].fd;

}

struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
readsock = select(highfd+1, &monito, (fd_set *) 0,(fd_set *) 0, &timeout);
if (readsock < 0) {
			perror("select");
			exit(EXIT_FAILURE);
		}
		 else if(readsock>0)
{
		
		
		for(i=1;i<=play_n;i++)
{
if (FD_ISSET(Play_list[i].fd,&monito))
			{
char fini;
int l,val;
n = recv(Play_list[i].fd,&fini,sizeof(char),0);
if (n < 0) error("ERROR writing to socket");
		if(n>0 && fini=='f')
		{
	n = recv(Play_list[i].fd,&l,sizeof(int),0);
if (n < 0) error("ERROR writing to socket");

if(n>0)
{
int j;
printf("Trace of potato:\n");
for(j=1;j<=l;j++)
		{
		n = recv(Play_list[i].fd,&val,sizeof(int),0);
     		if (n < 0) error("ERROR writing to socket");
		if(n>0)	
		{
		printf("%d",val);
			}
		if(j!=l)
		printf(",");
		else
		printf("\n");
		}
//sleep(1);
for(i=1;i<=play_n;i++)
{
char last_m='f';
n=send(Play_list[i].fd,&last_m,sizeof(char),0);
if (n < 0) error("ERROR writing to socket");
}
for(i=1;i<=play_n;i++)
close(Play_list[i].fd);
exit(EXIT_SUCCESS);
}
}
}
}	
}
}
}
Beispiel #18
0
int nfs_mount(const char *pathname, const char *hostname,
	      uint32_t server, const char *rem_path, const char *path,
	      struct nfs_mount_data *data)
{
	struct client *clnt = NULL;
	struct sockaddr_in addr;
	char mounted = 0;
	int sock = -1;
	int ret = 0;
	int mountflags;

	if (get_ports(server, data) != 0)
		goto bail;

	dump_params(server, rem_path, data);

	if (data->flags & NFS_MOUNT_TCP)
		clnt = tcp_client(server, mount_port, CLI_RESVPORT);
	else
		clnt = udp_client(server, mount_port, CLI_RESVPORT);

	if (clnt == NULL)
		goto bail;

	if (data->flags & NFS_MOUNT_VER3)
		ret = mount_v3(rem_path, data, clnt);
	else
		ret = mount_v2(rem_path, data, clnt);

	if (ret == -1)
		goto bail;
	mounted = 1;

	if (data->flags & NFS_MOUNT_TCP)
		sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	else
		sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);

	if (sock == -1) {
		perror("socket");
		goto bail;
	}

	if (bindresvport(sock, 0) == -1) {
		perror("bindresvport");
		goto bail;
	}

	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = server;
	addr.sin_port = htons(nfs_port);
	memcpy(&data->addr, &addr, sizeof(data->addr));

	strncpy(data->hostname, hostname, sizeof(data->hostname));

	data->fd = sock;

	mountflags = (data->flags & NFS_MOUNT_KLIBC_RONLY) ? MS_RDONLY : 0;
	data->flags = data->flags & NFS_MOUNT_FLAGMASK;
	ret = mount(pathname, path, "nfs", mountflags, data);

	if (ret == -1) {
		if (errno == ENODEV) {
			fprintf(stderr, "mount: the kernel lacks NFS v%d "
				"support\n",
				(data->flags & NFS_MOUNT_VER3) ? 3 : 2);
		} else {
			perror("mount");
		}
		goto bail;
	}

	dprintf("Mounted %s on %s\n", pathname, path);

	goto done;

bail:
	if (mounted) {
		if (data->flags & NFS_MOUNT_VER3)
			umount_v3(path, clnt);
		else
			umount_v2(path, clnt);
	}

	ret = -1;

done:
	if (clnt)
		client_free(clnt);

	if (sock != -1)
		close(sock);

	return ret;
}
Beispiel #19
0
void *
cx_deriv(void *data, short int type, int length, int *newlength, short int *newtype, struct plot *pl, struct plot *newpl, int grouping)
{
    double *scratch;
    double *spare;
    double x;
    int i, j, k;
    int	degree;
    int n, base;

    if (grouping == 0)
	grouping = length;
    /* First do some sanity checks. */
    if (!pl || !pl->pl_scale || !newpl || !newpl->pl_scale) {
        fprintf(cp_err, "Internal error: cx_deriv: bad scale\n");
        return (NULL);
    }

    if (!cp_getvar("dpolydegree", CP_NUM, (void *) &degree))
	degree = 2; /* default quadratic */

    n = degree +  1;

    spare = alloc_d(n);
    scratch = alloc_d(n * (n + 1));

    *newlength = length;
    *newtype = type;

    if (type == VF_COMPLEX) {
	complex *c_outdata, *c_indata;
	double *r_coefs, *i_coefs;
	double *scale;

	r_coefs = alloc_d(n);
	i_coefs = alloc_d(n);
	c_indata = (complex *) data;
	c_outdata = alloc_c(length);
	scale = alloc_d(length);	/* XXX */
	if (pl->pl_scale->v_type == VF_COMPLEX)
	    /* Not ideal */
	  for (i = 0; i < length; i++)
		   scale[i] = realpart(&pl->pl_scale->v_compdata[i]);
	 else
	    for (i = 0; i < length; i++)
		   scale[i] = pl->pl_scale->v_realdata[i];

	 for (base = 0; base < length; base += grouping)
    {
	    k = 0;
	    for (i = degree; i < grouping; i += 1)
       {

		  /* real */
		  for (j = 0; j < n; j++)
		    spare[j] = c_indata[j + i + base].cx_real;
		  if (!ft_polyfit(scale + i + base - degree,
		    spare, r_coefs, degree, scratch))
		   {
		    fprintf(stderr, "ft_polyfit @ %d failed\n", i);
		   }
		  ft_polyderiv(r_coefs, degree);

		  /* for loop gets the beginning part */
		  for (j = k; j <= i + degree / 2; j++)
        {
		    x = scale[j + base];
		    c_outdata[j + base].cx_real =
			ft_peval(x, r_coefs, degree - 1);
		  }

		  /* imag */
		  for (j = 0; j < n; j++)
		    spare[j] = c_indata[j + i + base].cx_imag;
		  if (!ft_polyfit(scale + i - degree + base,
		    spare, i_coefs, degree, scratch))
		  {
		    fprintf(stderr, "ft_polyfit @ %d failed\n", i);
		  }
		  ft_polyderiv(i_coefs, degree);

		  /* for loop gets the beginning part */
        for (j = k; j <= i - degree / 2; j++)
        {
		    x = scale[j + base];
		    c_outdata[j + base].cx_imag =
		    ft_peval(x, i_coefs, degree - 1);
		  }
		 k = j;
	   }

	    /* get the tail */
	    for (j = k; j < length; j++)
       {
		  x = scale[j + base];
		  /* real */
		  c_outdata[j + base].cx_real = ft_peval(x, r_coefs, degree - 1);
		  /* imag */
		  c_outdata[j + base].cx_imag = ft_peval(x, i_coefs, degree - 1);
	    }
    }

	tfree(r_coefs);
	tfree(i_coefs);
	tfree(scale);
	return (void *) c_outdata;

  }
  else
  {
	/* all-real case */
	double *coefs;

	double *outdata, *indata;
	double *scale;

	coefs = alloc_d(n);
	indata = (double *) data;
	outdata = alloc_d(length);
	scale = alloc_d(length);	/* XXX */

   /* Here I encountered a problem because when we issue an instruction like this:
    * plot -deriv(vp(3)) to calculate something similar to the group delay, the code
    * detects that vector vp(3) is real and it is believed that the frequency is also 
    * real. The frequency is COMPLEX and the program aborts so I'm going to put the 
    * check that the frequency is complex vector not to abort.
    */


   /* Original problematic code
	* for (i = 0; i < length; i++)
	*    scale[i] = pl->pl_scale->v_realdata[i];
    */

   /* Modified to deal with complex frequency vector */
   if (pl->pl_scale->v_type == VF_COMPLEX)
	  for (i = 0; i < length; i++)
		   scale[i] = realpart(&pl->pl_scale->v_compdata[i]);
	else
	    for (i = 0; i < length; i++)
		   scale[i] = pl->pl_scale->v_realdata[i];



	for (base = 0; base < length; base += grouping)
   {
	    k = 0;
	    for (i = degree; i < grouping; i += 1)
       {
		  if (!ft_polyfit(scale + i - degree + base,
		    indata + i - degree + base, coefs, degree, scratch))
		   {
		    fprintf(stderr, "ft_polyfit @ %d failed\n", i + base);
	    	}
        ft_polyderiv(coefs, degree);

		  /* for loop gets the beginning part */
		  for (j = k; j <= i - degree / 2; j++)
        {
          /* Seems the same problem because the frequency vector is complex
           * and the real part of the complex should be accessed because if we 
           * run x = pl-> pl_scale-> v_realdata [base + j]; the execution will 
           * abort.
           */

          if (pl->pl_scale->v_type == VF_COMPLEX)
            x = realpart(&pl->pl_scale->v_compdata[j+base]);  /* For complex scale vector */
          else
            x = pl->pl_scale->v_realdata[j + base];           /* For real scale vector */

		    outdata[j + base] = ft_peval(x, coefs, degree - 1);
		  }
	    	k = j;
	    }

	    for (j = k; j < length; j++)
       {
          /* Again the same error */
		  /* x = pl->pl_scale->v_realdata[j + base]; */
          if (pl->pl_scale->v_type == VF_COMPLEX)
            x = realpart(&pl->pl_scale->v_compdata[j+base]);  /* For complex scale vector */
          else
            x = pl->pl_scale->v_realdata[j + base];           /* For real scale vector */

		    outdata[j + base] = ft_peval(x, coefs, degree - 1);
	    }
   }


	tfree(coefs);
	tfree(scale);	/* XXX */
	return (char *) outdata;
 }

}
Beispiel #20
0
int pad_front(int start_index, int buff_step, short* outbuf,
   int outbuf_index, int* sub_from_start) {
   /* Pad the start of the runs with F0F0 if there are missing data
   bins before the start of good data */

   int pad_cnt=0;    /* number of bytes encoded (return value)          */
   int F0_bins;      /* number of bins to fill                          */ 
   int F0_runs;      /* number of 2-byte F0F0 words stuffed in outbuf   */
   int odd_bins;     /* number of odd bins between 0 and 30             */
   short pad_run;    /* holds value from the odd_run_table              */
   int i;            /* loop iteration variable                         */
   short F0F0=(short)0xF0F0; /* holds hex 0xF0F0 (30 bins worth of 0's) */
   short odd_run_table[]={
      (short)0x0000, (short)0x1000,(short)0x1010,(short)0x2010,
      (short)0x3010, (short)0x4010,(short)0x5010,(short)0x6010,
      (short)0x7010, (short)0x8010,(short)0x9010,(short)0xA010,
      (short)0xB010, (short)0xC010,(short)0xD010,(short)0xE010,
      (short)0xF010, (short)0xF020,(short)0xF030,(short)0xF040,
      (short)0xF050, (short)0xF060,(short)0xF070,(short)0xF080,
      (short)0xF090, (short)0xF0A0,(short)0xF0B0,(short)0xF0C0,
      (short)0xF0D0, (short)0xF0E0};
   int TEST=FALSE; /* boolean test flag                                 */

   *sub_from_start=0;  /* initialize value to subtract from the start   */

   /* display input parameters before processing                        */
   if(TEST) {
      fprintf(stderr,"Padfront Input Parameter Diagnostics:\n");
      fprintf(stderr,"  start_index:           %i\n",start_index);
      fprintf(stderr,"  buff_step:             %i\n",buff_step);
      fprintf(stderr,"  outbuf_index:          %i\n",outbuf_index);
      }

   /* calculate number of runs of 30 and the odd bins of missing data   */

   /* note that work is done in the function ONLY if missing data is    */
   /* located at the beginning of a radial. if the start_index (which   */
   /* points to the first bin with GOOD data is not coincident with an  */
   /* index of 1, then "missing" data exists                            */
   if(start_index!=1) {
      /* set the number of missing bins equal to F0_bins. Subtract 1 from
      the count to not include the first good bin as missing            */
      F0_bins=start_index-1;
      if(TEST) 
         fprintf(stderr,"  Total number of missing bins: F0_bins=%i\n",F0_bins);

      /* calculate the number of groups depending upon buff_step. buff_step
      is the storage increment value. Hence, to store every bin, then
      buff_step would have a value of 1, etc. The 'fmod' library call is
      equivalent to the FORTRAN MOD function to calculate the modulus of
      two values. The return is the whole number remainder of the division
      between the two parameters. Hence mod(31,7)=3 or (31 - int(31/7))=7 */
      *sub_from_start=fmod(F0_bins,buff_step);
      if(TEST) fprintf(stderr,"  mod(F0_bins(%i),buff_step(%i))=%i\n",F0_bins,
         buff_step,*sub_from_start);

      /* next, calculate how many bins would be left given the input 
         buff_step increment value                                      */
      F0_bins=F0_bins/buff_step;
      if(TEST) fprintf(stderr,"  F0_bins/buff_step=%i\n",F0_bins);

      /* Once the increment value has been taken care of, determine how 
         many multiples of 30 bins remain. Store this value in F0_runs  */
      F0_runs=F0_bins/30;
      if(TEST) fprintf(stderr,"  F0_bins/30=%i\n",F0_runs);

      /* if there was not an even multiple of bins, then copy the 
         remaining number of bins (in excess of a multiple of 30) into 
         odd_bins                                                       */
      odd_bins=fmod(F0_bins,30);
      if(TEST) fprintf(stderr,"  mod(F0_bins,30)=%i\n",odd_bins);

      /* initialize pad_run to 0 before stuffing outbuf with data. this
         variable will eventually hold the total number of stuffed 2-byte
         words within outbuf */
      pad_run=0;

      /* if the number of "odd_bins" is greater than 0 (but less than 30),
      then we need to handle this condition for stuffing a word other than
      F0F0 into outbuf */
      if(odd_bins>0) {
         /* Not sure why the upcoming decrementation takes place if odd_bins=1 */
         if(TEST) fprintf(stderr,"  enter odd_bins processing\n");
         if(odd_bins==1) {
            /* set flag for caller to decrement starting bin by 1
            to make an even number of runs of 30 of missing data */
            *sub_from_start=*sub_from_start + (odd_bins * buff_step);
            if(TEST) fprintf(stderr,"  odd_bins=1 sub_from_start=%i\n",*sub_from_start);
            }
          else {
            /* if odd_bins >1 and <30 then access the correct hex value for
            stuffing into outbuf by using the odd_run_table. Each value within
            this table is a hex/rle representation of the same number
            (i.e. 0x1010=2 bins, 0xF010=16 bins and 0xF0E0=29 bins   */
            pad_run=odd_run_table[odd_bins];
            if(TEST) fprintf(stderr,"  pad_run value=%02x\n",(unsigned short)pad_run);
            } /* end if(odd_bins==1) */
         } /* end if(odd_bins>0) */

      /* F0_runs contains the number of 2-byte words of F0F0 to stuff into
      the output buffer. stuff the groups of 30 missing bins now */
      for(i=1;i<=F0_runs;i++) {
         outbuf[outbuf_index+i-1]=F0F0;
         } /* end for i loop */

      /* pad_count will now contain the number of 2-bytes that were stuffed
      into outbuf and the amount that the buffer index will have to be
      incremented back in the calling procedure */
      pad_cnt=F0_runs;

      /* finally, we need to add the odd hex value that was stored in pad_run
      if there was not an even multiple of 30 bins designated as missing */
      if(pad_run!=0) {
         /* store odd runs and increment count */
         outbuf[outbuf_index+F0_runs]=pad_run;
         /* final incrementing of pad_count. it now contains the total number
         of 'padded' words in the output buffer */
         pad_cnt=pad_cnt+1;
         } /* end of if(pad_run) */
      if(TEST) fprintf(stderr,"  final pad_cnt value=%i\n",pad_cnt);
      } /* end of if start_index */

   return(pad_cnt);
   }  /* end of pad_front */
Beispiel #21
0
// Compile shaders
void PrepareShader(GLint shaderNum)
{
    char fullFileName[255];
    GLchar *shString;
    const GLchar *shStringPtr[1];
    GLint success;

    // Create shader objects and specify shader text
    sprintf(fullFileName, "./shaders/%s.vs", shaderNames[shaderNum]);
    shString = LoadShaderText(fullFileName);
    if (!shString)
    {
        fprintf(stderr, "Unable to load \"%s\"\n", fullFileName);
        Sleep(5000);
        exit(0);
    }
    vShader[shaderNum] = glCreateShader(GL_VERTEX_SHADER);
    shStringPtr[0] = shString;
    glShaderSource(vShader[shaderNum], 1, shStringPtr, NULL);
    free(shString);

    // Compile shaders and check for any errors
    glCompileShader(vShader[shaderNum]);
    glGetShaderiv(vShader[shaderNum], GL_COMPILE_STATUS, &success);
    if (!success)
    {
        GLchar infoLog[MAX_INFO_LOG_SIZE];
        glGetShaderInfoLog(vShader[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
        fprintf(stderr, "Error in vertex shader #%d compilation!\n", shaderNum);
        fprintf(stderr, "Info log: %s\n", infoLog);
        Sleep(10000);
        exit(0);
    }

    sprintf(fullFileName, "./shaders/%s.fs", shaderNames[shaderNum]);
    shString = LoadShaderText(fullFileName);
    if (!shString)
    {
        fprintf(stderr, "Unable to load \"%s\"\n", fullFileName);
        Sleep(5000);
        exit(0);
    }
    fShader[shaderNum] = glCreateShader(GL_FRAGMENT_SHADER);
    shStringPtr[0] = shString;
    glShaderSource(fShader[shaderNum], 1, shStringPtr, NULL);
    free(shString);

    // Compile shaders and check for any errors
    glCompileShader(fShader[shaderNum]);
    glGetShaderiv(fShader[shaderNum], GL_COMPILE_STATUS, &success);
    if (!success)
    {
        GLchar infoLog[MAX_INFO_LOG_SIZE];
        glGetShaderInfoLog(fShader[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
        fprintf(stderr, "Error in fragment shader #%d compilation!\n", shaderNum);
        fprintf(stderr, "Info log: %s\n", infoLog);
        Sleep(10000);
        exit(0);
    }
    else
    {
        GLchar infoLog[MAX_INFO_LOG_SIZE];
        glGetShaderInfoLog(fShader[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
        //fprintf(stderr, "Fragment shader #%d info log: %s\n", shaderNum, infoLog);
    }

    // Create program object, attach shader, then link
    progObj[shaderNum] = glCreateProgram();
    glAttachShader(progObj[shaderNum], vShader[shaderNum]);
    glAttachShader(progObj[shaderNum], fShader[shaderNum]);

    glLinkProgram(progObj[shaderNum]);
    glGetProgramiv(progObj[shaderNum], GL_LINK_STATUS, &success);
    if (!success)
    {
        GLchar infoLog[MAX_INFO_LOG_SIZE];
        glGetProgramInfoLog(progObj[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
        fprintf(stderr, "Error in program #%d linkage!\n", shaderNum);
        fprintf(stderr, "Info log: %s\n", infoLog);
        Sleep(10000);
        exit(0);
    }
    else
    {
        GLchar infoLog[MAX_INFO_LOG_SIZE];
        glGetProgramInfoLog(progObj[shaderNum], MAX_INFO_LOG_SIZE, NULL, infoLog);
        //fprintf(stderr, "Program #%d info log: %s\n", shaderNum, infoLog);
    }

    // Program object has changed, so we should revalidate
    needsValidation[shaderNum] = GL_TRUE;
}
Beispiel #22
0
int
poll(struct pollfd *ufds, nfds_t nfds, int timeout)
{
    static void             *libc_handle;
    int                      retval;
    static poll_handle       orig_poll = NULL;
    struct pollfd           *p;
    int                      i;
    int                      fd;
    int                      begin = 0;
    int                      elapsed = 0;

    dd("calling my poll");

    init_libc_handle();

    if (orig_poll == NULL) {
        orig_poll = dlsym(libc_handle, "poll");
        if (orig_poll == NULL) {
            fprintf(stderr, "mockeagain: could not find the underlying poll: "
                    "%s\n", dlerror());
            exit(1);
        }
    }

    init_matchbufs();

    dd("calling the original poll");

    if (pattern) {
        begin = now();
    }

    retval = (*orig_poll)(ufds, nfds, timeout);

    if (pattern) {
        elapsed = now() - begin;
    }

    if (retval > 0) {
        struct timeval  tm;

        p = ufds;
        for (i = 0; i < nfds; i++, p++) {
            fd = p->fd;
            if (fd > MAX_FD || weird_fds[fd]) {
                dd("skipping fd %d", fd);
                continue;
            }

            if (pattern && (p->revents & POLLOUT) && snd_timeout_fds[fd]) {

                if (get_verbose_level()) {
                    fprintf(stderr, "mockeagain: poll: should suppress write "
                            "event on fd %d.\n", fd);
                }

                p->revents &= ~POLLOUT;

                if (p->revents == 0) {
                    retval--;
                    continue;
                }
            }

            active_fds[fd] = p->revents;
            polled_fds[fd] = 1;

            if (get_verbose_level()) {
                fprintf(stderr, "mockeagain: poll: fd %d polled with events "
                        "%d\n", fd, p->revents);
            }
        }

        if (retval == 0) {
            if (get_verbose_level()) {
                fprintf(stderr, "mockeagain: poll: emulating timeout on "
                        "fd %d.\n", fd);
            }

            if (timeout < 0) {
                tm.tv_sec = 3600 * 24;
                tm.tv_usec = 0;

                if (get_verbose_level()) {
                    fprintf(stderr, "mockeagain: poll: sleeping 1 day "
                            "on fd %d.\n", fd);
                }

                select(0, NULL, NULL, NULL, &tm);

            } else {

                if (elapsed < timeout) {
                    int     diff;

                    diff = timeout - elapsed;

                    tm.tv_sec = diff / 1000;
                    tm.tv_usec = diff % 1000 * 1000;

                    if (get_verbose_level()) {
                        fprintf(stderr, "mockeagain: poll: sleeping %d ms "
                                "on fd %d.\n", diff, fd);
                    }

                    select(0, NULL, NULL, NULL, &tm);
                }
            }
        }
    }

    return retval;
}
int main(){
	
	int numPeaks=0,numPits=0,numRows=0,numLetters=0,row=0,col=0,count=0,loc=-1,maxCols=0,i=0;
	char encrypted[10000],decrypted[10000];
	FILE* in= fopen("input.txt","r");
	FILE* out= fopen("output.txt","w");
	
	if(in==NULL){//Checks to see if the input file exist
		printf("Input File Invalid");
		fprintf(out,"INPUT FILE INVALID");
		return 1;
	}
	
	fscanf(in,"%d",&numRows); //Stores the number of rows
	fscanf(in,"%s",&encrypted); //Stores the encrypted message
	fclose(in);
	
	numLetters= strlen(encrypted); //Gets the length of the encrypted message
	
	if(numLetters<=0 || numRows <=0){//Checks to see if the input in the input file is fairly valid
		printf("This input can not be deciphered or there is no input to be deciphered");
		return 1;	
	}
	
	if(numLetters <= numRows){//All characters fall in first column therefore may be printed directly without deciphering
		fprintf(out,"%s",encrypted);
		fclose(out);
		printf("CHECK OUTPUT.TXT FOR RESULTS");
		return 0;
	}
	
	numPeaks=1+(numLetters/(2*numRows-2)); //Number of peaks in the encrypted message
	numPits=1+((numLetters-numRows)/(2*numRows-2)); //Number of pits in the encrypted message
	
	row=1;
	while(row <= numRows){ //Loops from current row to number of rows
		
		col=1;
		maxCols=getMax(numPeaks,numPits,row,numLetters,numRows); //Retrieves maximum number of columns/characters in row
		
		while(col <= maxCols){
			//loc is the location the character belongs in, in the deciphered array
			//Places characters row by row into their correct position in deciphered array
			
			if(col==1){ //Characters in first column is automatically has correct loc index
				loc=row;
			}
			
			else if(row == 1 || row == numRows){ //Row is first or final row
				loc=(col-1)*(2*numRows -2) +row;
			}
					
			else if(col%2==0){ //Column is even and has 1 more large gaps between characters than small ones
				loc=(col/2)*((2*numRows) - (2*row)) + (col/2 -1)*((2*numRows) - (2*(numRows-row +1))) + row ;
			}
				
			else{//Column is odd and has the same number of large and small gaps before the current character
				loc = (col/2)* (((2*numRows) - (2*row)) + ((2*numRows) - 2*(numRows-row +1))) + row;
			}
			
			loc-=1; //To accommodate for array location starting at 0 
			decrypted[loc]=encrypted[count++];
			col++;		
		}
		row++;
	}
	decrypted[numLetters]='\0'; //Adds end of string character at the end of array to make it a string
	fprintf(out,"%s",decrypted);
	
	printf("CHECK OUTPUT.TXT FOR RESULTS");
	fclose(out);
	return 0;
}
Beispiel #24
0
ssize_t
writev(int fd, const struct iovec *iov, int iovcnt)
{
    ssize_t                  retval;
    static writev_handle     orig_writev = NULL;
    struct iovec             new_iov[1] = { {NULL, 0} };
    const struct iovec      *p;
    int                      i;
    size_t                   len;

    if ((get_mocking_type() & MOCKING_WRITES)
        && fd <= MAX_FD
        && polled_fds[fd]
        && written_fds[fd]
        && !(active_fds[fd] & POLLOUT))
    {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"writev\" on fd %d to "
                    "signal EAGAIN.\n", fd);
        }

        errno = EAGAIN;
        return -1;
    }

    written_fds[fd] = 1;

    init_libc_handle();

    if (orig_writev == NULL) {
        orig_writev = dlsym(libc_handle, "writev");
        if (orig_writev == NULL) {
            fprintf(stderr, "mockeagain: could not find the underlying writev: "
                    "%s\n", dlerror());
            exit(1);
        }
    }

    if (!(get_mocking_type() & MOCKING_WRITES)) {
        return (*orig_writev)(fd, iov, iovcnt);
    }

    if (fd <= MAX_FD && polled_fds[fd]) {
        p = iov;
        for (i = 0; i < iovcnt; i++, p++) {
            if (p->iov_base == NULL || p->iov_len == 0) {
                continue;
            }

            new_iov[0].iov_base = p->iov_base;
            new_iov[0].iov_len = 1;
            break;
        }

        len = 0;
        p = iov;
        for (i = 0; i < iovcnt; i++, p++) {
            len += p->iov_len;
        }
    }

    if (new_iov[0].iov_base == NULL) {
        retval = (*orig_writev)(fd, iov, iovcnt);

    } else {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"writev\" on fd %d to emit "
                    "1 of %llu bytes.\n", fd, (unsigned long long) len);
        }

        if (pattern && new_iov[0].iov_len) {
            char          *p;
            size_t         len;
            char           c;

            c = *(char *) new_iov[0].iov_base;

            if (matchbufs[fd] == NULL) {

                matchbufs[fd] = malloc(matchbuf_len);
                if (matchbufs[fd] == NULL) {
                    fprintf(stderr, "mockeagain: ERROR: failed to allocate memory.\n");
                }

                p = matchbufs[fd];
                memset(p, 0, matchbuf_len);

                p[0] = c;

                len = 1;

            } else {
                p = matchbufs[fd];

                len = strlen(p);

                if (len < matchbuf_len - 1) {
                    p[len] = c;
                    len++;

                } else {
                    memmove(p, p + 1, matchbuf_len - 2);

                    p[matchbuf_len - 2] = c;
                }
            }

            /* test if the pattern matches the matchbuf */

            dd("matchbuf: %.*s (len: %d)", (int) len, p,
                    (int) matchbuf_len - 1);

            if (len == matchbuf_len - 1 && strncmp(p, pattern, len) == 0) {
                if (get_verbose_level()) {
                    fprintf(stderr, "mockeagain: \"writev\" has found a match for "
                            "the timeout pattern \"%s\" on fd %d.\n", pattern, fd);
                }

                snd_timeout_fds[fd] = 1;
            }
        }

        dd("calling the original writev on fd %d", fd);
        retval = (*orig_writev)(fd, new_iov, 1);
        active_fds[fd] &= ~POLLOUT;
    }

    return retval;
}
Beispiel #25
0
int main(int argc, char **argv)
{
	char inbuf[4096];
	struct addr_range vmlinux;
	FILE *ramDisk;
	FILE *inputVmlinux;
	FILE *outputVmlinux;

	char *rd_name, *lx_name, *out_name;

	size_t i;
	unsigned long ramFileLen;
	unsigned long ramLen;
	unsigned long roundR;
	unsigned long offset_end;

	unsigned long kernelLen;
	unsigned long actualKernelLen;
	unsigned long round;
	unsigned long roundedKernelLen;
	unsigned long ramStartOffs;
	unsigned long ramPages;
	unsigned long roundedKernelPages;
	unsigned long hvReleaseData;
	u_int32_t eyeCatcher = 0xc8a5d9c4;
	unsigned long naca;
	unsigned long xRamDisk;
	unsigned long xRamDiskSize;
	long padPages;
  
  
	if (argc < 2) {
		fprintf(stderr, "Name of RAM disk file missing.\n");
		exit(1);
	}
	rd_name = argv[1];

	if (argc < 3) {
		fprintf(stderr, "Name of vmlinux file missing.\n");
		exit(1);
	}
	lx_name = argv[2];

	if (argc < 4) {
		fprintf(stderr, "Name of vmlinux output file missing.\n");
		exit(1);
	}
	out_name = argv[3];


	ramDisk = fopen(rd_name, "r");
	if ( ! ramDisk ) {
		fprintf(stderr, "RAM disk file \"%s\" failed to open.\n", rd_name);
		exit(1);
	}

	inputVmlinux = fopen(lx_name, "r");
	if ( ! inputVmlinux ) {
		fprintf(stderr, "vmlinux file \"%s\" failed to open.\n", lx_name);
		exit(1);
	}
  
	outputVmlinux = fopen(out_name, "w+");
	if ( ! outputVmlinux ) {
		fprintf(stderr, "output vmlinux file \"%s\" failed to open.\n", out_name);
		exit(1);
	}

	i = fread(inbuf, 1, sizeof(inbuf), inputVmlinux);
	if (i != sizeof(inbuf)) {
		fprintf(stderr, "can not read vmlinux file %s: %u\n", lx_name, i);
		exit(1);
	}

	i = check_elf64(inbuf, sizeof(inbuf), &vmlinux);
	if (i == 0) {
		fprintf(stderr, "You must have a linux kernel specified as argv[2]\n");
		exit(1);
	}

	/* Input Vmlinux file */
	fseek(inputVmlinux, 0, SEEK_END);
	kernelLen = ftell(inputVmlinux);
	fseek(inputVmlinux, 0, SEEK_SET);
	printf("kernel file size = %lu\n", kernelLen);

	actualKernelLen = kernelLen - ElfHeaderSize;

	printf("actual kernel length (minus ELF header) = %lu\n", actualKernelLen);

	round = actualKernelLen % 4096;
	roundedKernelLen = actualKernelLen;
	if ( round )
		roundedKernelLen += (4096 - round);
	printf("Vmlinux length rounded up to a 4k multiple = %ld/0x%lx \n", roundedKernelLen, roundedKernelLen);
	roundedKernelPages = roundedKernelLen / 4096;
	printf("Vmlinux pages to copy = %ld/0x%lx \n", roundedKernelPages, roundedKernelPages);

	offset_end = _ALIGN_UP(vmlinux.memsize, 4096);
	/* calc how many pages we need to insert between the vmlinux and the start of the ram disk */
	padPages = offset_end/4096 - roundedKernelPages;

	/* Check and see if the vmlinux is already larger than _end in System.map */
	if (padPages < 0) {
		/* vmlinux is larger than _end - adjust the offset to the start of the embedded ram disk */ 
		offset_end = roundedKernelLen;
		printf("vmlinux is larger than _end indicates it needs to be - offset_end = %lx \n", offset_end);
		padPages = 0;
		printf("will insert %lx pages between the vmlinux and the start of the ram disk \n", padPages);
	}
	else {
		/* _end is larger than vmlinux - use the offset to _end that we calculated from the system map */
		printf("vmlinux is smaller than _end indicates is needed - offset_end = %lx \n", offset_end);
		printf("will insert %lx pages between the vmlinux and the start of the ram disk \n", padPages);
	}



	/* Input Ram Disk file */
	// Set the offset that the ram disk will be started at.
	ramStartOffs = offset_end;  /* determined from the input vmlinux file and the system map */
	printf("Ram Disk will start at offset = 0x%lx \n", ramStartOffs);
  
	fseek(ramDisk, 0, SEEK_END);
	ramFileLen = ftell(ramDisk);
	fseek(ramDisk, 0, SEEK_SET);
	printf("%s file size = %ld/0x%lx \n", rd_name, ramFileLen, ramFileLen);

	ramLen = ramFileLen;

	roundR = 4096 - (ramLen % 4096);
	if ( roundR ) {
		printf("Rounding RAM disk file up to a multiple of 4096, adding %ld/0x%lx \n", roundR, roundR);
		ramLen += roundR;
	}

	printf("Rounded RAM disk size is %ld/0x%lx \n", ramLen, ramLen);
	ramPages = ramLen / 4096;
	printf("RAM disk pages to copy = %ld/0x%lx\n", ramPages, ramPages);



  // Copy 64K ELF header
	for (i=0; i<(ElfPages); ++i) {
		get4k( inputVmlinux, inbuf );
		put4k( outputVmlinux, inbuf );
	}

	/* Copy the vmlinux (as full pages). */
	fseek(inputVmlinux, ElfHeaderSize, SEEK_SET);
	for ( i=0; i<roundedKernelPages; ++i ) {
		get4k( inputVmlinux, inbuf );
		put4k( outputVmlinux, inbuf );
	}
  
	/* Insert pad pages (if appropriate) that are needed between */
	/* | the end of the vmlinux and the ram disk. */
	for (i=0; i<padPages; ++i) {
		memset(inbuf, 0, 4096);
		put4k(outputVmlinux, inbuf);
	}

	/* Copy the ram disk (as full pages). */
	for ( i=0; i<ramPages; ++i ) {
		get4k( ramDisk, inbuf );
		put4k( outputVmlinux, inbuf );
	}

	/* Close the input files */
	fclose(ramDisk);
	fclose(inputVmlinux);
	/* And flush the written output file */
	fflush(outputVmlinux);



	/* Fixup the new vmlinux to contain the ram disk starting offset (xRamDisk) and the ram disk size (xRamDiskSize) */
	/* fseek to the hvReleaseData pointer */
	fseek(outputVmlinux, ElfHeaderSize + 0x24, SEEK_SET);
	if (fread(&hvReleaseData, 4, 1, outputVmlinux) != 1) {
		death("Could not read hvReleaseData pointer\n", outputVmlinux, out_name);
	}
	hvReleaseData = ntohl(hvReleaseData); /* Convert to native int */
	printf("hvReleaseData is at %08lx\n", hvReleaseData);

	/* fseek to the hvReleaseData */
	fseek(outputVmlinux, ElfHeaderSize + hvReleaseData, SEEK_SET);
	if (fread(inbuf, 0x40, 1, outputVmlinux) != 1) {
		death("Could not read hvReleaseData\n", outputVmlinux, out_name);
	}
	/* Check hvReleaseData sanity */
	if (memcmp(inbuf, &eyeCatcher, 4) != 0) {
		death("hvReleaseData is invalid\n", outputVmlinux, out_name);
	}
	/* Get the naca pointer */
	naca = ntohl(*((u_int32_t*) &inbuf[0x0C])) - KERNELBASE;
	printf("Naca is at offset 0x%lx \n", naca);

	/* fseek to the naca */
	fseek(outputVmlinux, ElfHeaderSize + naca, SEEK_SET);
	if (fread(inbuf, 0x18, 1, outputVmlinux) != 1) {
		death("Could not read naca\n", outputVmlinux, out_name);
	}
	xRamDisk = ntohl(*((u_int32_t *) &inbuf[0x0c]));
	xRamDiskSize = ntohl(*((u_int32_t *) &inbuf[0x14]));
	/* Make sure a RAM disk isn't already present */
	if ((xRamDisk != 0) || (xRamDiskSize != 0)) {
		death("RAM disk is already attached to this kernel\n", outputVmlinux, out_name);
	}
	/* Fill in the values */
	*((u_int32_t *) &inbuf[0x0c]) = htonl(ramStartOffs);
	*((u_int32_t *) &inbuf[0x14]) = htonl(ramPages);

	/* Write out the new naca */
	fflush(outputVmlinux);
	fseek(outputVmlinux, ElfHeaderSize + naca, SEEK_SET);
	if (fwrite(inbuf, 0x18, 1, outputVmlinux) != 1) {
		death("Could not write naca\n", outputVmlinux, out_name);
	}
	printf("Ram Disk of 0x%lx pages is attached to the kernel at offset 0x%08lx\n",
	       ramPages, ramStartOffs);

	/* Done */
	fclose(outputVmlinux);
	/* Set permission to executable */
	chmod(out_name, S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);

	return 0;
}
Beispiel #26
0
ssize_t
send(int fd, const void *buf, size_t len, int flags)
{
    ssize_t                  retval;
    static send_handle       orig_send = NULL;

    dd("calling my send");

    if ((get_mocking_type() & MOCKING_WRITES)
        && fd <= MAX_FD
        && polled_fds[fd]
        && written_fds[fd]
        && !(active_fds[fd] & POLLOUT))
    {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"send\" on fd %d to "
                    "signal EAGAIN\n", fd);
        }

        errno = EAGAIN;
        return -1;
    }

    written_fds[fd] = 1;

    init_libc_handle();

    if (orig_send == NULL) {
        orig_send = dlsym(libc_handle, "send");
        if (orig_send == NULL) {
            fprintf(stderr, "mockeagain: could not find the underlying send: "
                    "%s\n", dlerror());
            exit(1);
        }
    }

    if ((get_mocking_type() & MOCKING_WRITES)
        && fd <= MAX_FD
        && polled_fds[fd]
        && len)
    {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"send\" on fd %d to emit "
                    "1 byte data only\n", fd);
        }

        if (pattern && len) {
            char          *p;
            size_t         len;
            char           c;

            c = *(char *) buf;

            if (matchbufs[fd] == NULL) {

                matchbufs[fd] = malloc(matchbuf_len);
                if (matchbufs[fd] == NULL) {
                    fprintf(stderr, "mockeagain: ERROR: failed to allocate memory.\n");
                }

                p = matchbufs[fd];
                memset(p, 0, matchbuf_len);

                p[0] = c;

                len = 1;

            } else {
                p = matchbufs[fd];

                len = strlen(p);

                if (len < matchbuf_len - 1) {
                    p[len] = c;
                    len++;

                } else {
                    memmove(p, p + 1, matchbuf_len - 2);

                    p[matchbuf_len - 2] = c;
                }
            }

            /* test if the pattern matches the matchbuf */

            dd("matchbuf: %.*s (len: %d)", (int) len, p,
                    (int) matchbuf_len - 1);

            if (len == matchbuf_len - 1 && strncmp(p, pattern, len) == 0) {
                if (get_verbose_level()) {
                    fprintf(stderr, "mockeagain: \"writev\" has found a match for "
                            "the timeout pattern \"%s\" on fd %d.\n", pattern, fd);
                }

                snd_timeout_fds[fd] = 1;
            }
        }

        retval = (*orig_send)(fd, buf, 1, flags);
        active_fds[fd] &= ~POLLOUT;

    } else {

        dd("calling the original send on fd %d", fd);

        retval = (*orig_send)(fd, buf, len, flags);
    }

    return retval;
}
Beispiel #27
0
void	DrawTrack(FILE *fp, TRACK *t, char *Label, int PointsPerPixel, int OriginX, int OriginY, INFO I, int DrawEvents, int frame, FILEINFO FileInfo)
{
	RGBCOLOR	rgb[N_COLORS];

	int			i,j, FirstGoodPosition = 1, NewEvent;
	float		x, y;
	float		CenterX, CenterY, ArenaRadiusPix;
	float		MinShockAng, MaxShockAng, MinShockRad, MaxShockRad;
	double		asin(), acos(), atan2();
	double 		Y, X, ang, rad;
	unsigned char	**ReinforcedMap;

	SetRGBColors(rgb);
	
	// ArenaRadiusPix = (float)(I.Arena.Radius * I.PixelsPerCM);
	ArenaRadiusPix = (float)DEFAULT_ARENA_RADIUS;	// iTrack sets the radius to be 127

	(void) fprintf(fp, "gsave\n");

	// Set coordinate system to arena center
	CenterX = (float)(I.Arena.CenterX * PointsPerPixel + OriginX);
	CenterY = (float)(OriginY - I.Arena.CenterY * PointsPerPixel - 20);
	(void) fprintf(fp, "%0.2f %0.2f translate\n", CenterX, CenterY);

	// label the picture
	(void) fprintf(fp, "/Times-Roman findfont\n");
	(void) fprintf(fp, "0.5 cm scalefont\n");
	(void) fprintf(fp, "setfont\n");

	(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", (0.0 - ArenaRadiusPix), (ArenaRadiusPix + 10.0));
	// (void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", (0.0 - ArenaRadiusPix - ROOM_FRAME_INCREASE), (ArenaRadiusPix + 10.0));
	(void) fprintf(fp, "( Paradigm: %s ) show\n", I.Paradigm);

	(void) fprintf(fp, "%d pix %d pix mt\n", 0 - strlen(Label) / 2, 0 - (int)(ArenaRadiusPix + 20));
	(void) fprintf(fp, "( %s ) center show\nnewpath\n", Label);

	// draw the arena in a thin line
	(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n1.0 setlinewidth\n", rgb[BLACK].r, rgb[BLACK].g, rgb[BLACK].b);

	switch(I.Arena.Type){
		case ARENA_TYPE_CIRCLE:
			/* draw a circle for the arena */
			(void) fprintf(fp, "%0.2f pix %0.2f pix %0.2f pix 0 360 arc\n", 0.0, 0.0, ArenaRadiusPix);
			(void) fprintf(fp, "closepath\nstroke\n");

		break;

		default:
		break;
	}

	for(i = 0; i < I.NumberOfCoordFrames; i++){
		// draw the Coordinate frame in a thick line
		(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n3.0 setlinewidth\n", rgb[BLACK].r, rgb[BLACK].g, rgb[BLACK].b);
		switch(I.Target[i].CoordFrame){
			case ROOM_FRAME:
				/* draw a square for the room */
				(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", 0.0 - (ArenaRadiusPix + ROOM_FRAME_INCREASE) , 0.0 - (ArenaRadiusPix + ROOM_FRAME_INCREASE));
				(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", (ArenaRadiusPix + ROOM_FRAME_INCREASE), 0.0 - (ArenaRadiusPix + ROOM_FRAME_INCREASE));
				(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", (ArenaRadiusPix + ROOM_FRAME_INCREASE) , (ArenaRadiusPix + ROOM_FRAME_INCREASE));
				(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", 0.0 - (ArenaRadiusPix + ROOM_FRAME_INCREASE) , (ArenaRadiusPix + ROOM_FRAME_INCREASE));
				(void) fprintf(fp, "closepath\nstroke\n");	
			break;

			case ARENA_FRAME:
				switch(I.Arena.Type){
					case ARENA_TYPE_CIRCLE:
						/* draw a circle for the arena */	
						(void) fprintf(fp, "%0.2f pix %0.2f pix %0.2f pix 0 360 arc\n", 0.0, 0.0, ArenaRadiusPix);
						(void) fprintf(fp, "closepath\nstroke\n");
					break;
					
					default:
					break;
				}
			break;

			case ROOM_AND_ARENA_FRAME:
				/* draw a square for the room */
				(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", 0.0 - (ArenaRadiusPix + ROOM_FRAME_INCREASE) , 0.0 - (ArenaRadiusPix + ROOM_FRAME_INCREASE));
				(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", (ArenaRadiusPix + ROOM_FRAME_INCREASE), 0.0 - (ArenaRadiusPix + ROOM_FRAME_INCREASE));
				(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", (ArenaRadiusPix + ROOM_FRAME_INCREASE) , (ArenaRadiusPix + ROOM_FRAME_INCREASE));
				(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", 0.0 - (ArenaRadiusPix + ROOM_FRAME_INCREASE) , (ArenaRadiusPix + ROOM_FRAME_INCREASE));
				(void) fprintf(fp, "closepath\nstroke\n");
			
				switch(I.Arena.Type){
					case ARENA_TYPE_CIRCLE:
						/* draw a circle for the arena */	
						(void) fprintf(fp, "%0.2f pix %0.2f pix %0.2f pix 0 360 arc\n", 0.0, 0.0, ArenaRadiusPix);
						(void) fprintf(fp, "closepath\nstroke\n");
					break;

					default:
					break;
				}
			
			break;

			default:
			break;
		}
		
		/* draw the reinforced area */
		if(I.Target[i].Show && (i == frame)){

			switch(I.Target[i].Type){
				case REINFORCED_CIRCLE:
					(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n1.0 setlinewidth\n", rgb[RED].r, rgb[RED].g, rgb[RED].b);
				
					// draw the same regardless of the defining frame
					// original target
					X = I.Target[i].Circle.X - I.Arena.CenterX, 
					Y = I.Arena.CenterY - I.Target[i].Circle.Y;
					(void) fprintf(fp, "%0.2f pix %0.2f pix %0.2f pix 0 360 arc\n", X, Y, I.Target[i].Circle.Rad);
					(void) fprintf(fp, "closepath\nstroke\n");
					rad = hypot(Y, X);
					ang = atan2(Y, X);

					// draw corresponding targets in the other quadrants
					(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n1.0 setlinewidth\n", rgb[BLACK].r, rgb[BLACK].g, rgb[BLACK].b);
					
					for(j = 1; j < 4; j++){
						X = cos(ang + j * (M_PI / 2.0)) * rad; 
						Y = sin(ang + j * (M_PI / 2.0)) * rad; 
						(void) fprintf(fp, "%0.2f pix %0.2f pix %0.2f pix 0 360 arc\n", X, Y, I.Target[i].Circle.Rad);
						(void) fprintf(fp, "closepath\nstroke\n");
					}
				break;

				case REINFORCED_SECTOR:
					(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n3.0 setlinewidth\n", rgb[RED].r, rgb[RED].g, rgb[RED].b);
				
					MinShockAng = (float)(I.Target[i].Sector.Ang - (I.Target[i].Sector.Width / (float)2.0)) / (float)DEG_PER_RAD;
					MaxShockAng = (float)(I.Target[i].Sector.Ang + (I.Target[i].Sector.Width / (float)2.0)) / (float)DEG_PER_RAD;
					MinShockRad = (float)(I.Target[i].Sector.InRad);
					MaxShockRad = (float)(I.Target[i].Sector.OutRad);

					// draw according to the defining frame
					if((I.Target[i].CoordFrame == ROOM_FRAME) || (I.Target[i].CoordFrame == ROOM_AND_ARENA_FRAME)){
						double RoomRadius, WallRadius;

						RoomRadius = ArenaRadiusPix + ROOM_FRAME_INCREASE;
						// max ang: line in to out
						x = (float)(cos(MaxShockAng) * MinShockRad);
						y = (float)(sin(MaxShockAng) * MinShockRad);
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);

						if(((MaxShockAng > (45.0 / DEG_PER_RAD)) && (MaxShockAng < (135.0 / DEG_PER_RAD))) ||
							((MaxShockAng > (225.0 / DEG_PER_RAD)) && (MaxShockAng < (315.0 / DEG_PER_RAD))))
							WallRadius = sqrt((double)(RoomRadius * RoomRadius) / (1.0 - cos(MaxShockAng) * cos(MaxShockAng)));
						else
							WallRadius = sqrt((double)(RoomRadius * RoomRadius) / (1.0 - sin(MaxShockAng) * sin(MaxShockAng)));
					
						x = (float)(cos(MaxShockAng) * WallRadius);
						y = (float)(sin(MaxShockAng) * WallRadius);
						(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", x,y);
				
						// max ang outer to min ang outer
						if(((MinShockAng > (45.0 / DEG_PER_RAD)) && (MinShockAng < (135.0 / DEG_PER_RAD))) ||
							((MinShockAng > (225.0 / DEG_PER_RAD)) && (MinShockAng < (315.0 / DEG_PER_RAD))))
							WallRadius = sqrt((double)(RoomRadius * RoomRadius) / (1.0 - cos(MinShockAng) * cos(MinShockAng)));
						else
							WallRadius = sqrt((double)(RoomRadius * RoomRadius) / (1.0 - sin(MinShockAng) * sin(MinShockAng)));

						x = (float)(cos(MinShockAng) * WallRadius);
						y = (float)(sin(MinShockAng) * WallRadius);
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);

						// min ang: outer to inner
						x = (float)(cos(MinShockAng) * MinShockRad);
						y = (float)(sin(MinShockAng) * MinShockRad);
						(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", x,y);
		
						// inner arc
						x = (float)(cos(MinShockAng) * MinShockRad);
						y = (float)(sin(MinShockAng) * MinShockRad);
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
						x = 0.0;
						y = 0.0;
						(void) fprintf(fp, "%0.2f pix %0.2f pix %0.2f pix %0.2f %0.2f arc\n", x, y, MinShockRad, MinShockAng * DEG_PER_RAD, MaxShockAng * DEG_PER_RAD);
						x = (float)(cos(MaxShockAng) * MinShockRad);
						y = (float)(sin(MaxShockAng) * MinShockRad);
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);

						(void) fprintf(fp, "closepath\nstroke\n");
					}
					if((I.Target[i].CoordFrame == ARENA_FRAME) || (I.Target[i].CoordFrame == ROOM_AND_ARENA_FRAME)){

						// max ang: line in to out
						x = (float)(cos(MaxShockAng) * MinShockRad);
						y = (float)(sin(MaxShockAng) * MinShockRad);
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
						x = (float)(cos(MaxShockAng) * MaxShockRad);
						y = (float)(sin(MaxShockAng) * MaxShockRad);
						(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", x,y);

						// outer arc
						x = (float)(cos(MinShockAng) * MaxShockRad);
						y = (float)(sin(MinShockAng) * MaxShockRad);
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
						x = 0.0;
						y = 0.0;
						(void) fprintf(fp, "%0.2f pix %0.2f pix %0.2f pix %0.2f %0.2f arc\n", x, y, MaxShockRad, MinShockAng * DEG_PER_RAD, MaxShockAng * DEG_PER_RAD);
						
						// min ang: line out to in
						x = (float)(cos(MinShockAng) * MaxShockRad);
						y = (float)(sin(MinShockAng) * MaxShockRad);
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
						x = (float)(cos(MinShockAng) * MinShockRad);
						y = (float)(sin(MinShockAng) * MinShockRad);
						(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", x,y);

						// inner arc
						x = (float)(cos(MinShockAng) * MinShockRad);
						y = (float)(sin(MinShockAng) * MinShockRad);
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
						x = 0.0;
						y = 0.0;
						(void) fprintf(fp, "%0.2f pix %0.2f pix %0.2f pix %0.2f %0.2f arc\n", x, y, MinShockRad, MinShockAng * DEG_PER_RAD, MaxShockAng * DEG_PER_RAD);
						x = (float)(cos(MaxShockAng) * MinShockRad);
						y = (float)(sin(MaxShockAng) * MinShockRad);
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);

						(void) fprintf(fp, "closepath\nstroke\n");
					}
				break;

				default:
				break;

			}	
		}
	}

	//  draw quadrant lines
	if(I.ParadigmType == OPEN_FIELD || I.ParadigmType == TRACKER){
		double RoomRadius, QuadAng;

		RoomRadius = ArenaRadiusPix + ROOM_FRAME_INCREASE;

		(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n0.5 setlinewidth\n", rgb[BLACK].r, rgb[BLACK].g, rgb[BLACK].b);

		QuadAng = 135.0 / (double)DEG_PER_RAD; // NW point
		x = (float)(cos(QuadAng) * RoomRadius);
		y = (float)(sin(QuadAng) * RoomRadius);
		(void) fprintf(fp, "newpath\n%0.2f pix %0.2f pix mt\n", x,y);

		QuadAng = 315.0 / (double)DEG_PER_RAD; // SE point
		x = (float)(cos(QuadAng) * RoomRadius);
		y = (float)(sin(QuadAng) * RoomRadius);
		(void) fprintf(fp, "%0.2f pix %0.2f pix lt\nclosepath\nstroke\n", x,y);

		QuadAng = 45.0 / (double)DEG_PER_RAD; // NE point
		x = (float)(cos(QuadAng) * RoomRadius);
		y = (float)(sin(QuadAng) * RoomRadius);
		(void) fprintf(fp, "newpath\n%0.2f pix %0.2f pix mt\n", x,y);

		QuadAng = 225.0 / (double)DEG_PER_RAD; // SW point
		x = (float)(cos(QuadAng) * RoomRadius);
		y = (float)(sin(QuadAng) * RoomRadius);
		(void) fprintf(fp, "%0.2f pix %0.2f pix lt\nclosepath\nstroke\n", x,y);

	}

	//  draw grid lines
	if(I.ParadigmType == OPEN_FIELD){
		double RoomRadius;
		int	OFPixelSize;
		float  point;

		RoomRadius = ArenaRadiusPix + ROOM_FRAME_INCREASE;
		OFPixelSize = (int)(TRACKER_XY_RESOLUTION / I.Options.OpenFieldDimension);

		(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n0.5 setlinewidth\n", rgb[BLACK].r, rgb[BLACK].g, rgb[BLACK].b);

		for(i = 0; i <= TRACKER_XY_RESOLUTION; i += OFPixelSize){
			point = (float)(i - (TRACKER_XY_RESOLUTION / 2));
			// vertical lines
			(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", point, RoomRadius);
			(void) fprintf(fp, "%0.2f pix %0.2f pix lt\nstroke\n", point, -1.0 * RoomRadius);
			// horizontal lines
			(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", -1.0 * RoomRadius, point);
			(void) fprintf(fp, "%0.2f pix %0.2f pix lt\nstroke\n", RoomRadius, point);
		}
	}

	// draw track

	// define the Reinforced sector for avoidance since this was not set in Tracker
	if(I.ParadigmType == PLACE_AVOIDANCE){
		if(I.Target[frame].Type == REINFORCED_SECTOR){
                	MakeAvoidSectorMap(&ReinforcedMap, I, I.Target[frame].Sector);
                }else if(I.Target[frame].Type == REINFORCED_CIRCLE){
                	MakeAvoidCircleMap(&ReinforcedMap, I, I.Target[frame].Circle, 1);
		}
	}

	(void) fprintf(fp, "%0.2f %0.2f %0.2f setrgbcolor\n0.5 setlinewidth\n", rgb[GRAY].r, rgb[GRAY].g, rgb[GRAY].b);
	FirstGoodPosition = 1;
	NewEvent = 1;
	for(i = 0; i < I.NumberOfSamps; i ++){
		// Was the object detected?
		if((!t[i].x) || (!t[i].y)){
			if(!FirstGoodPosition)
				(void) fprintf(fp, "stroke\n");
			FirstGoodPosition = 1;
			continue;
		}

		// Transform from tracker to Cartesian coordinates
		x = (float)(t[i].x - I.Arena.CenterX);
		y = (float)(I.Arena.CenterY - t[i].y);
		if(FirstGoodPosition){
			(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
			if(t[i].event){
				switch(DrawEvents){
					case 0: break;		/* don't draw anything */

					case 1: 		/* draw one mark per event */
						if((I.FileFormat == TRACKER_FORMAT) || (I.FileFormat == ITRACK_FORMAT) || (I.FileFormat == FGX_FORMAT)){ // Event is coded as a state
							if(t[i].event == SHOCK_STATE){
								if(NewEvent){
									(void) fprintf(fp, "stroke\n");
									if(I.Target[frame].Show){
										if(ReinforcedMap[t[i].y][t[i].x] == TARGET){	// make frame specific events
											DrawAnEvent(fp, x, y, rgb, PointsPerPixel, RED);
										}else{
											DrawAnEvent(fp, x, y, rgb, PointsPerPixel, BLUE);
										}
									}else{
										DrawAnEvent(fp, x, y, rgb, PointsPerPixel, BLUE);
									}
									(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
									NewEvent = 0;
								}
							}else{
								if(t[i].event != BAD_SPOT_STATE){	// Use the BadSpot flag introduced by Tracker
									NewEvent = 1;
								}
							}
						}else{
							(void) fprintf(fp, "stroke\n");
							if(I.Target[frame].Show){
								DrawAnEvent(fp, x, y, rgb, PointsPerPixel, RED);
							}else{
								DrawAnEvent(fp, x, y, rgb, PointsPerPixel, BLUE);
							}
							(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
						}
						break;

					case 2:
						(void) fprintf(fp, "stroke\n");
						if(I.Target[frame].Show){
							for(j = 0; j < t[i].event; j++){
								DrawAnEvent(fp, (float)(x + (j * 0.1)), (float)(y + (j * 0.1)), rgb, PointsPerPixel, RED);
							}
						}else{
							for(j = 0; j < t[i].event; j++){
								DrawAnEvent(fp, (float)(x + (j * 0.1)), (float)(y + (j * 0.1)), rgb, PointsPerPixel, BLUE);
							}
						}
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
						break;
					default:	
						break;
				}
			}else{
				if(t[i].event != BAD_SPOT_STATE){	// Use the BadSpot flag introduced by Tracker
					NewEvent = 1;
				}
			}	
			FirstGoodPosition = 0;
			continue;
		}
		(void) fprintf(fp, "%0.2f pix %0.2f pix lt\n", x,y);
		if(t[i].event){
			switch(DrawEvents){
				case 0: break;		/* don't draw anything */

				case 1: 		/* draw one mark per event */
					if((I.FileFormat == TRACKER_FORMAT) || (I.FileFormat == ITRACK_FORMAT) || (I.FileFormat == FGX_FORMAT)){ // Event is coded as a state
						if(t[i].event == SHOCK_STATE){
							if(NewEvent){
								(void) fprintf(fp, "stroke\n");
								if(I.Target[frame].Show){
									if(ReinforcedMap[t[i].y][t[i].x] == TARGET){	// make frame specific events
										// DEBUG(-1 * i)
										DrawAnEvent(fp, x, y, rgb, PointsPerPixel, RED);
									}else{
										DrawAnEvent(fp, x, y, rgb, PointsPerPixel, BLUE);
									}
								}else{
									DrawAnEvent(fp, x, y, rgb, PointsPerPixel, BLUE);
								}
								(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
								NewEvent = 0;
							}
						}else{
							if(t[i].event != BAD_SPOT_STATE){       // Use the BadSpot flag introduced by Tracker	
								NewEvent = 1;
							}
						}
					}else{
						(void) fprintf(fp, "stroke\n");
						if(I.Target[frame].Show){
							DrawAnEvent(fp, x, y, rgb, PointsPerPixel, RED);
						}else{
							DrawAnEvent(fp, x, y, rgb, PointsPerPixel, BLUE);
						}
						(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
					}
					break;

				case 2:
					(void) fprintf(fp, "stroke\n");
					if(I.Target[frame].Show){
						for(j = 0; j < t[i].event; j++){
							DrawAnEvent(fp, (float)(x + (j * 0.1)), (float)(y + (j * 0.1)), rgb, PointsPerPixel, RED);
						}
					}else{
						for(j = 0; j < t[i].event; j++){
							DrawAnEvent(fp, (float)(x + (j * 0.1)), (float)(y + (j * 0.1)), rgb, PointsPerPixel, BLUE);
						}
					}
					(void) fprintf(fp, "%0.2f pix %0.2f pix mt\n", x,y);
					break;

				default:	
					break;
			}
		}else{
			NewEvent = 1;
		}
	}
	if(!FirstGoodPosition)
		(void) fprintf(fp, "stroke\n");

	// reset coordinate system upon return
	(void) fprintf(fp, "grestore\n");

	return;
	
}
int main(void)
{
  double y[EQ_N][2];
  double (*func[EQ_N])();
  double parameter[PARTICLE_N][PARA_N], parameter_memory[PARA_N], resampled_parameter[PARTICLE_N][PARA_N];
  double ref_parameter[PARA_N];
  double time_point[TIME_POINT_N];
  double ref_time_point[TIME_POINT_N];

  int i, j, k, l, m;
  int mcmc_num, pa_num, integral_num, particle_num, rk_num, timepoint_num, parameter_num, equation_num;
  
  int x_flag = 0;
  double dt;

  double probability_before, probability_after, probability_ratio;
  int move_count = 0;

  double weight[PARTICLE_N], weight_tmp[PARTICLE_N];
  double total_weight = 0, power_total_weight, partial_total_weight, upper_weight, lower_weight;
  double log_weight[PARTICLE_N], log_weight_tmp[PARTICLE_N];
  double total_likelihood[PARTICLE_N], total_likelihood_previous[PARTICLE_N];
  double log_likelihood[PARTICLE_N], total_log_likelihood;
  double epsilon[POPULATION_N] = {1.5, 1.0, 0.75, 0.5, 0.25, 0.1, 0.09, 0.08, 0.07, 0.06, 0.05, 0.04, 0.03, 0.02, 0.01};
  double ess;
  int sampling_num;
  int resampling_count = 0;
  int weighten_particle_num[POPULATION_N] = {0, 0, 0, 0, 0}, last_weighten_particle_num = 0;
  int resampling_flag[POPULATION_N] = {0, 0, 0, 0, 0};

  double effective_particle_num = 0, total_effective_particle_num = 0;
  double weighten_particle_multiplier = 1;

  int mcmc_step;

  double unit_r, chosen_num;

  FILE *fp1, *fp2, *fp3, *fp4, *fp5, *fp6, *fp7, *fin;

  clock_t start, end;

  dt = 0.001;


  function_set(func);


/*** 計算開始 **********************************************************************************************************************************/

  /* 時間を計る */
  start = clock();
  
  /* 乱数の初期化 */
  init_genrand(2);

  /* ファイル設定 */
  fp1 = fopen("information2.data","w");

  /* 実験データの読み込み */
  fin = fopen("ref_time_point.data","r");

  for(timepoint_num=0;timepoint_num<TIME_POINT_N;timepoint_num++){
    fscanf(fin, "%lf", &ref_time_point[timepoint_num]);
  }

  fclose(fin);
  /* 実験データの読み込み終了 */


  /* 参照パラメータ値設定 */
  parameter_set(ref_parameter);

  /* サンプル番号初期化 */
  sampling_num = 0;

  printf("0 th population\n");

  /* ランダムサンプリングによる 粒子数個のパラメータセットの発生 **************************************************************************************/
  for( ; ; ){
    /* パラメータを発生させる */
    parameter_set(parameter[sampling_num]);
    parameter_generation(parameter[sampling_num], ref_parameter);

    sampling_num++;
    
    if(sampling_num == PARTICLE_N) break; 
  }


  /* 重みを初期化 正規化 */
  for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
    weight[particle_num] = 1.0/PARTICLE_N;
  }
  /* ランダムサンプリングによる初期パラメータ発生 終了 ************************************************************************************************/









  
  /* Population annealing 開始 *****************************************************************************************************************/
  for(pa_num=0;pa_num<POPULATION_N;pa_num++){

    printf("%d th population\n", pa_num+1);
    
    /* 各粒子ごとに尤度の計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      total_likelihood[particle_num] = 0; /* 初期化 */
      total_likelihood_previous[particle_num] = 0; /* 初期化 */
    }


    /* 中間分布の計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){

      /* time point データの発生 */
      initial_condition_set(y);
      rk_search(1, dt, func, y, parameter[particle_num], time_point);

      /* 尤度の計算 */
      total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]);

      if(pa_num==0){
        total_likelihood_previous[particle_num] = 1;
      }
      else{
        total_likelihood_previous[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num-1]);
      }

    }
    /* 中間分布の計算終了 */


    /* 重みの計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      weight[particle_num] = weight[particle_num] * total_likelihood[particle_num]/total_likelihood_previous[particle_num];
      if(total_likelihood[particle_num]==0 || total_likelihood_previous[particle_num]==0) weight[particle_num] = 0.0;
    }

    total_weight = 0.0;

    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      total_weight = total_weight + weight[particle_num];
    }
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      weight[particle_num] = weight[particle_num]/total_weight;
    }


    /* 重みを持つ粒子数の計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      if(weight[particle_num]!=0) weighten_particle_num[pa_num]++;
    }
    fprintf(fp1, "weighten particle num = %d\n", weighten_particle_num[pa_num]);





    /* 各粒子ごとに */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){

      /* 重みが0なら飛ばす */
      if(weight[particle_num]==0) continue;

      /* フラグの初期化 */
      x_flag = 0;


      /* MCMC 計算 */
      for(mcmc_num=0;mcmc_num<MCMC_MAX_STEP;mcmc_num++){
 
        /* 許容されなければ、元のままのパラメータ */
        if(x_flag == 1){
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
        }


        /* 確率の初期化 */
        probability_before = 1.0;
        probability_after = 1.0;
    

        /* フラグの初期化 */
        x_flag = 0;


        /* 新候補の計算前の値を記憶 */
        for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
          parameter_memory[parameter_num] = parameter[particle_num][parameter_num];
        }


        /* 移動前の確率を計算 */
        probability_before = probability_before*pdf_uniform_parameter(parameter[particle_num], ref_parameter); /* 事前分布を乗じる */

        
        total_likelihood[particle_num] = 0.0; /* 初期化 */

        /* time point データの発生 */
        initial_condition_set(y);
        rk_search(1, dt, func, y, parameter[particle_num], time_point);

        /* 尤度の計算 */
        total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]);

        probability_before = probability_before * total_likelihood[particle_num]; /* 移動前の確率 */  


        /* 新候補を計算 パラメータの中から1つだけ動かす */
        parameter_sampler(parameter[particle_num]);


        /* 移動後の確率を計算 : 一様事前分布を乗じる */
        probability_after = probability_after*pdf_uniform_parameter(parameter[particle_num], ref_parameter); /* 事前分布を乗じる */
        

        if(probability_after == 0.0){
          x_flag = 1;
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
          continue;
        }



        /* 移動後の確率を計算 */
        total_likelihood[particle_num] = 0.0; /* 初期化 */

        /* time point データの発生 */
        initial_condition_set(y);
        rk_search(1, dt, func, y, parameter[particle_num], time_point);

        /* 尤度の計算 */
        total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]);

        probability_after = probability_after * total_likelihood[particle_num]; /* 移動後の確率 */


        if(probability_after == 0.0){
          x_flag = 1;
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
          continue;
        }



        /* 移動前と移動後の確率の比の計算 */
        probability_ratio = probability_after/probability_before;

        /* [0,1) 単位乱数の発生 */
        unit_r = genrand_real2();   


        /* 移動の判定 */
        if(probability_ratio > unit_r){ 
          move_count++;
        }
        else{
          x_flag = 1;
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
          continue;
        }
    
      }
      /* particle_num 番目の粒子の MCMC 終了 */
    }
    /* 全粒子の MCMC 終了 */
 




 
    /* リサンプリング ********************************************************/
    power_total_weight = 0.0;
    ess = 0.0;

    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      power_total_weight = power_total_weight + pow(weight[particle_num], 2);
    }


    /* Effective Sample Size の計算 */
    ess = 1.0/power_total_weight;
    //if(pa_num==4) ess = 0.0;

    fprintf(fp1, "%d th population", pa_num);
    fprintf(fp1, "ESS = %f\t particle_num/2 = %f\n\n", ess, PARTICLE_N/2.0);
    

    /* リサンプリングの判定と実行 */
    if(ess < PARTICLE_N/2){

      fprintf(fp1, "resampling\n");
      resampling_count++;
      resampling_flag[pa_num] = 1;
      fprintf(fp1, "resampling flag = %d\n", resampling_flag[pa_num]);
      
      /* 粒子数個リサンプリングする 重複可 */
      for(m=0;m<PARTICLE_N;m++){

        /* [0,1) 乱数発生 */
        unit_r = genrand_real2();

        partial_total_weight = 0.0;

        /* l 番目の粒子が選ばれる */
        for(l=0;l<PARTICLE_N;l++){
          partial_total_weight = partial_total_weight + weight[l];

          upper_weight = partial_total_weight;
          lower_weight = partial_total_weight - weight[l];

          if((unit_r >= lower_weight) && (unit_r < upper_weight)){
            for(i=0;i<PARA_N;i++){
              resampled_parameter[m][i] = parameter[l][i];
            }
            break;
          }
        }

      }
      /* 粒子数個リサンプリング終了 */



      /* リサンプル後のパラメータと活性化時間の再設定 */
      for(l=0;l<PARTICLE_N;l++){
        for(i=0;i<PARA_N;i++){
          parameter[l][i] = resampled_parameter[l][i];
        }
      }



      /* リサンプル後の重みを初期化 正規化 */
      for(l=0;l<PARTICLE_N;l++){
        weight[l] = 1.0/PARTICLE_N;
      }


    }
    /* リサンプリングの判定と実行 終了 */
    /* リサンプリング終了 ****************************************************/

  }
  /* Population annealing 終了 *****************************************************************************************************************/
  

  for(pa_num=0;pa_num<POPULATION_N;pa_num++){
    if(resampling_flag[pa_num]==1){
      weighten_particle_multiplier = weighten_particle_multiplier * weighten_particle_num[pa_num]/PARTICLE_N;
    }
  }

  /* 重みを持つ粒子数の計算 */
  last_weighten_particle_num = 0;
  for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
    if(weight[particle_num]!=0) last_weighten_particle_num++;
  }
  effective_particle_num = last_weighten_particle_num*weighten_particle_multiplier;
  
  fprintf(fp1, "effective particle number = %f\n", effective_particle_num);



  /* 移動回数、 リサンプリング回数、 モデル数を出力 */
  fprintf(fp1, "%d times move\n", move_count);
  fprintf(fp1, "%d times resampling\n", resampling_count);
  end = clock();
  /* 計算時間の出力 */
  fprintf(fp1, "%f min\n", (double)(end - start)/CLOCKS_PER_SEC/60.0);



  fclose(fp1);

  return 0;
}
Beispiel #29
0
static int
tiffcmp(TIFF* tif1, TIFF* tif2)
{
	uint16 config1, config2;
	tsize_t size1;
	uint32 s, row;
	unsigned char *buf1, *buf2;

	if (!CheckShortTag(tif1, tif2, TIFFTAG_BITSPERSAMPLE, "BitsPerSample"))
		return (0);
	if (!CheckShortTag(tif1, tif2, TIFFTAG_SAMPLESPERPIXEL, "SamplesPerPixel"))
		return (0);
	if (!CheckLongTag(tif1, tif2, TIFFTAG_IMAGEWIDTH, "ImageWidth"))
		return (0);
	if (!cmptags(tif1, tif2))
		return (1);
	(void) TIFFGetField(tif1, TIFFTAG_BITSPERSAMPLE, &bitspersample);
	(void) TIFFGetField(tif1, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
	(void) TIFFGetField(tif1, TIFFTAG_IMAGEWIDTH, &imagewidth);
	(void) TIFFGetField(tif1, TIFFTAG_IMAGELENGTH, &imagelength);
	(void) TIFFGetField(tif1, TIFFTAG_PLANARCONFIG, &config1);
	(void) TIFFGetField(tif2, TIFFTAG_PLANARCONFIG, &config2);
	buf1 = (unsigned char *)_TIFFmalloc(size1 = TIFFScanlineSize(tif1));
	buf2 = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif2));
	if (buf1 == NULL || buf2 == NULL) {
		fprintf(stderr, "No space for scanline buffers\n");
		exit(-1);
	}
	if (config1 != config2 && bitspersample != 8 && samplesperpixel > 1) {
		fprintf(stderr,
"Can't handle different planar configuration w/ different bits/sample\n");
		goto bad;
	}
#define	pack(a,b)	((a)<<8)|(b)
	switch (pack(config1, config2)) {
	case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG):
		for (row = 0; row < imagelength; row++) {
			if (TIFFReadScanline(tif2, buf2, row, 0) < 0)
				checkEOF(tif2, row, -1)
			for (s = 0; s < samplesperpixel; s++) {
				if (TIFFReadScanline(tif1, buf1, row, s) < 0)
					checkEOF(tif1, row, s)
				SeparateCompare(1, s, row, buf2, buf1);
			}
		}
		break;
	case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE):
		for (row = 0; row < imagelength; row++) {
			if (TIFFReadScanline(tif1, buf1, row, 0) < 0)
				checkEOF(tif1, row, -1)
			for (s = 0; s < samplesperpixel; s++) {
				if (TIFFReadScanline(tif2, buf2, row, s) < 0)
					checkEOF(tif2, row, s)
				SeparateCompare(0, s, row, buf1, buf2);
			}
		}
		break;
	case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE):
		for (s = 0; s < samplesperpixel; s++)
			for (row = 0; row < imagelength; row++) {
				if (TIFFReadScanline(tif1, buf1, row, s) < 0)
					checkEOF(tif1, row, s)
				if (TIFFReadScanline(tif2, buf2, row, s) < 0)
					checkEOF(tif2, row, s)
				ContigCompare(s, row, buf1, buf2, size1);
			}
		break;
	case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG):
		for (row = 0; row < imagelength; row++) {
			if (TIFFReadScanline(tif1, buf1, row, 0) < 0)
				checkEOF(tif1, row, -1)
			if (TIFFReadScanline(tif2, buf2, row, 0) < 0)
				checkEOF(tif2, row, -1)
			ContigCompare(-1, row, buf1, buf2, size1);
		}
		break;
	}
	if (buf1) _TIFFfree(buf1);
	if (buf2) _TIFFfree(buf2);
	return (1);
bad:
	if (stopondiff)
		exit(1);
	if (buf1) _TIFFfree(buf1);
	if (buf2) _TIFFfree(buf2);
	return (0);
}
Beispiel #30
0
void error(void)
{
	fprintf(stderr, "%s\n", "bad command\n"
		"syntax: [command] [optional recipient] [optional msg]");
}