int MFAnyStrPtr(WYSIWYG *wn, CNTRLS *control, int frame, char *data, int to_ac)
{
	if (trace_misc)
		p_info(PI_TRACE, "entering MFAnyStrPtr(p%1d:%#x %s data:%#x)\n",
				  control->off_rel, *(&REL_DATA(frame) p0 + control-> off_rel),
				  to_ac ? "-->" : "<--", data);
	
	if (to_ac)
	{
		if (*(&REL_DATA(frame) p0 + control -> off_rel) && data)
			strcpy(data, *(&REL_DATA(frame) p0 + control -> off_rel));
	}
	else if (data)
	{
		if (*(&REL_DATA(frame) p0 + control -> off_rel))
			*(&REL_DATA(frame) p0 + control -> off_rel) =
				p_realloc(*(&REL_DATA(frame) p0	+ control -> off_rel),
						  strlen(data)+1);
		else
			*(&REL_DATA(frame) p0 + control -> off_rel) =
				p_alloc(strlen(data)+1);
		
		strcpy(*(&REL_DATA(frame) p0 + control -> off_rel), data);
	}
	
	if (trace_misc)
		p_info(PI_TRACE, "leaving MFAnyStrPtr(p%1d:%#x %s data:%#x (%s))\n",
				  control->off_rel, *(&REL_DATA(frame) p0 + control-> off_rel),
				  to_ac ? "-->" : "<--", data, data ? data : "NULL");
	return(0);					/* Just so it returns something */
}
static void clear_color_list()	/* clear list of colors */
{
    struct clr_lst *tp;			/* list-walking pointer */
    struct clr_lst *tnxt;		/* list-walking pointer */
    int i;
    
#ifdef TRACE
    if (debugger_trace)
		p_info(PI_TRACE, "clear_color_list\n");
    if (color_trace)
		p_info(PI_TRACE, "clear_color_list ()\n");
#endif
    for (i=0; i<MAX_CLRS; i++)
    {
		tp = clr_1st[i];
		clr_1st[i] = 0;
		while(tp != 0)			/* walk towards the end	*/
		{
			tnxt = tp->nxt;		/* save location of next one  */
			p_free((char *)tp); /* free the memory */
#ifdef TRACE
			if (color_trace)
				p_info(PI_TRACE, "Plate #%d, %x->%d,%d,%.2f,%f,%s,%x removed\n",
					   i,(unsigned)tp, tp->color, tp->freq, tp->density, 
					   tp->angle, tp->func, (unsigned)tp->nxt);
#endif
			tp = tnxt;			/* and point to 'next' */
		}						/* end while(tp != 0) */
    }							/* end  for(i=0; i<MAX_CLRS; i++) */
}								/* end function */
LIST_PT *lmt_AddPtToList(LIST_PT *list_pt, CLIP_POINTS *cur)
{
#ifdef TRACE
	if (trace_lmt)
		p_info(PI_TRACE, "lmt_AddPtToList: x: %d, y: %d\n", cur -> pt.x, cur -> pt.y);
#endif
	cur -> used = 1;
	if (cur -> twin)
		cur -> twin -> used = 1;
	if (!list_pt)
	{
		list_pt = (LIST_PT *)p_alloc(sizeof(LIST_PT));
		list_pt -> min_x = list_pt -> max_x = cur -> pt.x;
		list_pt -> min_y = list_pt -> max_y = cur -> pt.y;
	}
	if (list_pt -> pts_used == list_pt -> total_pts)
	{
		list_pt -> total_pts += NUM_PTS;
		list_pt -> points =
			(DRAW_POINT_X_Y *)p_remalloc((char *)list_pt -> points,
										 sizeof(DRAW_POINT_X_Y) *
										 (list_pt -> total_pts - NUM_PTS),
										 sizeof(DRAW_POINT_X_Y) *
										 list_pt -> total_pts);
	}
	/*
	  if (cur -> twin)
	  p_info(PI_TRACE, "cur -> pt.arc: %#X, cur -> twin -> pt.arc: %#X\n",
	  cur -> pt.arc, cur -> twin -> pt.arc);
	  if (cur -> twin && cur -> twin -> pt.arc)
	  */
	if (0 && cur -> twin)
	{
		p_info(PI_TRACE, "Writing twin\n");
		memcpy((char *)&list_pt -> points[list_pt -> pts_used++],
			   (char *)&cur -> twin -> pt, sizeof(DRAW_POINT_X_Y));
	}
	else
		memcpy((char *)&list_pt -> points[list_pt -> pts_used++],
			   (char *)&cur -> pt, sizeof(DRAW_POINT_X_Y));
	if (cur -> pt.x < list_pt -> min_x)
		list_pt -> min_x = cur -> pt.x;
	else if (cur -> pt.x > list_pt -> max_x)
		list_pt -> max_x = cur -> pt.x;
	if (cur -> pt.y < list_pt -> min_y)
		list_pt -> min_y = cur -> pt.y;
	else if (cur -> pt.y > list_pt -> max_y)
		list_pt -> max_y = cur -> pt.y;
	return(list_pt);
}
int color_check(int color, int def)
{								/* color - got it? def - use if not */
    int i;
    uint32 plate;
	uint32  loop_temp;
    struct clr_lst *tp = 0;
    
	if (color < 0)
	{
#ifdef TRACE
		if (color_trace)
			p_info(PI_TRACE, "color_check color %d unspecified ret(%d).\n",color,def);
#endif
		return(def);
	}
	if ( !KeyOutputType)
		tp = find_color(color, 0); /* plate zero for composite */
	else
	{							/* look for plate if not composite */
		for (i=0; i<MAX_CLRS-1; i++)
		{
			plate = (loop_temp= ( 1 << i )) & cc_mask;
			if (plate)
			{
				tp = find_color(color, i + 1);
				if (tp)
					break;
			}	    
			if(loop_temp >= cc_mask)
				break;
		}						/* end for (i=1; i<MAX_CLRS-1; i++) */
	}							/* end else not composite */
    if(tp == 0)					/* can't find it? */
	{
#ifdef TRACE
		if (color_trace)
			p_info(PI_TRACE, "color_check color %d unspecified ret(%d).\n",color,def);
#endif
		return(def);			/* use second choice */
	}
    else
	{
#ifdef TRACE
		if (color_trace)
			p_info(PI_TRACE, "color_check found color %d @ %x.\n",color,(unsigned)tp);
#endif
	}
	return(color);				/* ok, use it */
}
static void store_color(int reset_flag)
{								/* store color pass, if any */
    if( !cur_screen || !cur_pct)
		cur_reverse = 1;
	else
		cur_reverse = 0;
#ifdef TRACE
    if(color_trace)
		p_info(PI_TRACE, "store clr= %d, plate= %d, fn= %s, ang= %3.2f, scr= %d, pct= %3.3f\n",
			   cur_color_id,cur_plate,cur_shape,cur_angle,cur_screen,cur_pct);
#endif
	add_color();
	if (reset_flag)
	{
		cur_plate = -1;    
		strcpy(cur_shape, "dot");
		cur_angle = 45.;
		cur_screen = 72;
		cur_pct = 100.0;
		cur_reverse = 0;
		strcpy(cur_op, "false");
		strcpy(cur_color_name,"");
		strcpy(cur_type,"process");
	}
}								/* end store color */
Exemple #6
0
static void report_file_creation(struct ts *ts, char *text_prefix, char *filename) {
	char qdepth[32];
	qdepth[0] = '\0';
	if (ts->packet_queue->items)
		snprintf(qdepth, sizeof(qdepth), " (depth:%d)", ts->packet_queue->items);
	p_info("%s%s%s\n", text_prefix, filename, qdepth);
}
Exemple #7
0
static void create_output_directory(struct ts *ts) {
	if (!ts->create_dirs)
		return;
	if (!file_exists(ts->output_dirname)) {
		p_info(" = Create directory %s", ts->output_dirname);
		create_dir(ts->output_dirname, dir_perm);
	}
}
/*************************************************************************
 **  FIND_COLOR	find entry for & return pointer to a color entry of 	**
 **		the specified index. Return 0 if no such entry exists.	**
 *************************************************************************/
struct clr_lst *find_color(int color, uint32 plate_number)
{
    struct clr_lst *tp;			/* list-walking pointer */

	if (plate_number >= 32)
		plate_number=0;

	if (color < 0)
	{
#ifdef TRACE
		if (color_trace)
		{
			p_info(PI_TRACE, "find_color color unspecified %d, plate_number %lo.\n",
				   color, plate_number);
		}
#endif
		return(0);
	}
	if ( !KeyOutputType)
		plate_number = 0;
	tp = clr_1st[plate_number];
#ifdef TRACE
    if (color_trace)
		p_info(PI_TRACE, "find_color, look for color %d, plate %lo \n",
			   color, plate_number);
#endif
    while(tp != 0)				/* we're looking for the end  */
    {
		if(tp->color == color)	/* hey, we've seen this one! */
		{
#ifdef TRACE
			if (color_trace)
				p_info(PI_TRACE, "found it @ %x.\n",(unsigned)tp);
#endif
			return(tp);
		}
		tp = tp->nxt;			/* move to next one */
    }
#ifdef TRACE
    if (color_trace)
		p_info(PI_TRACE, "Color unspecified %d, plate_number %lo.\n",
			   color, plate_number);
#endif
	return(0);
}								/* end function */
  ReturnCode port_add_(const std::string &iface_name, port_t port_num,
                       const char *in_pcap, const char *out_pcap) override {
    if (bmi_port_interface_add(port_mgr, iface_name.c_str(), port_num, in_pcap,
                               out_pcap))
      return ReturnCode::ERROR;

    PortInfo p_info(port_num, iface_name);
    if (in_pcap) p_info.add_extra("in_pcap", std::string(in_pcap));
    if (out_pcap) p_info.add_extra("out_pcap", std::string(out_pcap));

    Lock lock(mutex);
    port_info.emplace(port_num, std::move(p_info));

    return ReturnCode::SUCCESS;
  }
static void set_traces(char *string)
{
    while(*string)
    {
		int c;
		c = *string++;
		switch (c)
		{
		  case 'a':
			color_trace = 1;
			debugger_trace = 1;
			trace_lmt = 1;
			trace_8 = 1;
			parse_trace = 1;
			text_trace = 1;
			break;
		  case 'c':
			color_trace = 1;
			break;
		  case 'd':
			debugger_trace = 1;
			break;
		  case 'e':
			trace_lmt = 1;
			break;
		  case 'l':
			trace_8 = 1;
			break;
		  case 'p':
			parse_trace = 1;
			break;
		  case 't':
			text_trace = 1;
			break;
		  case '0':
			color_trace = 0;
			debugger_trace = 0;
			trace_lmt = 0;
			trace_8 = 0;
			parse_trace = 0;
			text_trace = 0;
			break;
		  default:
			p_info(PI_WLOG, "bad field %c\n",c);
		}						/* end switch */
    }							/* end while */
}								/* end function */
void stop(char *s1, char *s2, int eror)
{
    char msgbuff[256];
    
    if (eror > 0 )
    	sprintf (msgbuff, "PostPrint Fatal ERROR : %d ", err);
	else
	    sprintf (msgbuff, "PostPrint Fatal ERROR : ");

    if (s1 && (*s1 > ' '))
		strcat (msgbuff, s1);
    if (s2 && (*s2 > ' '))
		strcat (msgbuff, s2);
    strcat(msgbuff, "\n");
    p_info(PI_ELOG, msgbuff);
    exit(1);
}
void clear_vlist(void)			/* clear vid_1st list of vid_box structs */
{
    struct vid_box *vp;			/* list-walking pointer */
    int i;
    
#ifdef TRACE
    if(debugger_trace)
		p_info(PI_TRACE, "clear_vlist\n");
    if(color_trace)
		p_info(PI_TRACE, "clear_vlist (");
#endif
    for (i=0; i<MAX_CLRS; i++)
    {
		vp = vid_1st[i];
		if(vp == 0)
			continue;
#ifdef TRACE
		if (color_trace)
			p_info(PI_TRACE, "clearing list %i (",i);
#endif
		while(vp != 0)			/* walk towards the end	*/
		{
			vid_1st[i] = vp->nxt; /* save location of next one */
#ifdef TRACE
			if(color_trace)				
				p_info(PI_TRACE, ".");	/* show a mark apiece */
#endif
			p_free((char *)vp);	/* free the memory */
			vp = vid_1st[i];	/* and point to 'next */
		}
		if(color_trace)
			p_info(PI_TRACE, ")\n");
    }							/* end for(i=0; i<MAX_CLRS; i++) */
#ifdef TRACE
	if(color_trace)
		p_info(PI_TRACE, ")\n");
#endif
}								/* end CLEAR_VLIST */
/*************************************************************************
 ** ADD_COLOR	add a specified index to the list. If it exists, gripe	**
 **  and change. Don't change index 0 or 1 **
 *************************************************************************/
void add_color(void)
{
	int temp_cur_tint;
	int ii;

    struct clr_lst *tp = clr_1st[cur_plate]; /* list-walking pointer */
    struct clr_lst *lp = clr_1st[cur_plate]; /* pointer to last link */
    int	not_end = FALSE;		/* never reached the end flag */
    
    if(spot_pass != 1)
		return;					/* built on 1st color pass */
    if( (cur_plate < 0) || (cur_plate >= MAX_CLRS) )
    {
		p_info(PI_WLOG, "Attempt to define an invalid color:(%d, %d, %d, %f, %f, %d)\n",
			   cur_color_id,cur_plate,cur_screen,cur_pct,cur_angle,cur_tint);
		return;					/* not the WORST POSSIBLE case	*/
    }
    while(tp != 0)				/* we're looking for the end  */
    {
#ifdef TRACE
		if (color_trace)
			p_info(PI_TRACE, ".");		/* one dot per entry */
#endif
		lp = tp;				/* save address of latest entry */
		if(tp->color == cur_color_id) /* hey, we've seen this one! */
		{
			if (cur_plate)
				p_info(PI_WLOG, "Redefine a valid color: %d, %d, %d, %f, %f, %d, %d\n",
					   cur_color_id,cur_plate,cur_screen,cur_pct,
					   cur_angle,cur_reverse, cur_tint);
			not_end = TRUE;
			break;
		}
		tp = tp->nxt;			/* move to next one */
    }							/* end while(tp != 0) */
#ifdef TRACE
    if (color_trace)
		p_info(PI_TRACE, ")ptr to last found @ %x\n",(unsigned)lp);
#endif
	if(not_end == FALSE)		/* don't allocate existing one	*/
		tp = (struct clr_lst *) p_alloc(sizeof(struct clr_lst));
	if(tp != 0)
	{
		if(not_end == FALSE)
		{
			if (lp == 0)		/* if this is the first entry */
				clr_1st[cur_plate] = tp; /*   set it up */
			else				/* else there was a previous entry */
				lp->nxt = tp;	/* point prev to new allocation */
			tp->nxt = 0;		/* next allocation hasn't been done yet  */
		}
		temp_cur_tint = cur_tint;
		if ( !temp_cur_tint)
			temp_cur_tint = 100;
		tp->tint = temp_cur_tint;
		tp->color = cur_color_id; /* fill the data in */
		if(cur_screen == 0)
			tp->freq = 6;
		else
			tp->freq = cur_screen;
		tp->density = 1.0 - ( (cur_pct * cur_tint) / 10000.);
		tp->angle = cur_angle;
		strcpy(tp->func, cur_shape);
		tp->reverse = cur_reverse;
		strcpy(tp->op,cur_op);
		strcpy(tp->type,cur_type);
		strcpy(tp->color_name,cur_color_name);

		for (ii=0; ii<4; ii++) {
			tp->cmyk[ii] = cur_cmyk[ii];
		}

		tp->tint = temp_cur_tint;
/*
		for (i=0; i<4; i++)
			tp->cmyk[i] = cur_cmyk[i] = ((cur_cmyk[i] * temp_cur_tint) / 100.);
*/
		if ( !cur_plate && cur_cmyk_flag)
		{
			tp->cmyk_flag = 1;	/* only used for plate 0 if input */
			if (cur_cmyk[3] == 1)
				tp->density = 0.0; /* all black */
			else if ( !cur_cmyk[0] && !cur_cmyk[1] && !cur_cmyk[2] &&
					  !cur_cmyk[3] )
				tp->density = 1.0; /* all white */
			else if ( !cur_cmyk[0] && !cur_cmyk[1] && !cur_cmyk[2] &&
					  cur_cmyk[3] )
				tp->density = 1.0 - cur_cmyk[3]; /* all gray */
			else
				tp->density = 1.0 - (((50 * cur_cmyk[0]) + (75 * cur_cmyk[1]) +
									  (30 * cur_cmyk[2]) +
									  (100 * cur_cmyk[3]) ) / 255.);
		}
		else
			tp->cmyk_flag = 0;
#ifdef TRACE
		if (color_trace)
		{
			p_info(PI_TRACE, "add_color #%d fr:%d, dn:%3.2f, an:%3.2f, fn:%s, rv:%d\n",
				   tp->color, tp->freq, tp->density, tp->angle,
				   tp->func,tp->reverse);
			if (tp->cmyk_flag)
				p_info(PI_TRACE, "add_color CMYK Tint:%d C:%.2f M:%.2f Y:%.2f K:%.2f\n",
					   temp_cur_tint, tp->cmyk[0], tp->cmyk[1],
					   tp->cmyk[2], tp->cmyk[3]);
		}
#endif
    }
    else
    {
#ifdef TRACE
		if (color_trace)
			p_info(PI_TRACE, "NO MEMORY FOR ENTRY\n");
#endif
    }
}								/* end function */
/*ARGSUSED*/
int MFSynPicas(WYSIWYG *wn, CNTRLS *control, int junk, char *data, int to_ac)
{
	REL_WORDS syntax;
	int error = 0;

	memset((char *)&syntax, 0, sizeof(REL_WORDS));
	if (to_ac)
    {
		char buffer[12];
		
		memset(buffer, 0, sizeof(buffer));
		switch (control->off_rel) 
		{
		  case 0:				/* Col Width */
			syntax.offset = COL_GUIDES(wn).col_width;
			break;
		  case 1:				/* Col Gutter */
			syntax.offset = COL_GUIDES(wn).col_gutter;
			break;
		  case 2:				/* Row Depth */
			syntax.offset = COL_GUIDES(wn).row_depth;
			break;
		  case 3:				/* Row Gutter */
			syntax.offset = COL_GUIDES(wn).row_gutter;
			break;
		  default:				/* Preference Gutters */
			p_info(PI_ELOG, "\n*****PROGRAMMING ERROR: gutters not in preferences\n");
			/*
			  syntax.offset = 
			  *(&wn->global_data.gutter_top + control->off_rel%10);
			  */
		}
		lmt_syntax_to_ascii(&syntax, 0, buffer);
		memcpy(data, buffer, control -> length);
    }
	else
    {
		if (strlen(data) > control -> length)
			data[control -> length] = 0;
		if (!(error = lmt_size_parser(&syntax, data, 0)))
			switch (control->off_rel) 
			{
			  case 0:			/* Col Width */
				COL_GUIDES(wn).col_width = syntax.offset;
				break;
			  case 1:			/* Col Gutter */
				COL_GUIDES(wn).col_gutter = syntax.offset;
				break;
			  case 2:			/* Row Depth */
				COL_GUIDES(wn).row_depth = syntax.offset;
				break;
			  case 3:			/* Row Gutter */
				COL_GUIDES(wn).row_gutter = syntax.offset;
				break;
			  default:			/* Preference Gutters */
				p_info(PI_ELOG, "\n*****PROGRAMMING ERROR: gutters not in preferences\n");
				/*
				 *(&wn->global_data.gutter_top + control->off_rel%10) =
				 syntax.offset;
				 */
				break;
			}
	}
	return(error);
}
/*************************************************************************
 ** VID_COLOR - do setup of gray (& whatever) for a color by index		**
 **		MUST BE WRAPPED IN GS/GR PAIR BY CALLER			**
 *************************************************************************/
void vid_color(int color, int shade, uint32 plate_number)
{
	float temp_dens[4];
        struct clr_lst *clr;
	int ii;
    
#ifdef TRACE
	if (color_trace)
		p_info(PI_TRACE, "start vid_color(%d, %d, %lo), Black= %lo, cc_mask= %lo\n",
			   color, shade, plate_number, BlackPaint_cc_mask, cc_mask);
#endif
	if (color < 0)
	{
		BlackPaint_cc_mask &= ~(1 << (plate_number-1));	/* turn off a plate */
#ifdef TRACE
		if (color_trace)
			p_info(PI_TRACE, "new BlackPaint_cc_mask= %lo\n", BlackPaint_cc_mask);
#endif
		return;
	}
	if ( !KeyOutputType)
		clr = find_color(color, 0); /* use color from plate 0 for composite */
	else						/* normal color */
		clr = find_color(color, plate_number); /* find the color structure */
	if(clr == 0)
	{
#ifdef TRACE
		if (color_trace)
			p_info(PI_TRACE, "color %d on plate= %lo not defined\n",
				   color, plate_number);
#endif
		BlackPaint_cc_mask &= ~(1 << (plate_number-1));	/* turn off a plate */
#ifdef TRACE
		if (color_trace)
			p_info(PI_TRACE, "new BlackPaint_cc_mask= %lo\n", BlackPaint_cc_mask);
#endif
		return;					/* not defined */
	}

#ifdef TRACE
		if (color_trace) {
		p_info(PI_TRACE, "color= %d, reverse= %d, freq= %d, cmyk_flag= %d\n",
			   clr->color, clr->reverse,clr->freq,clr->cmyk_flag);
		p_info(PI_TRACE, "  c= %f, m= %f, y= %f, k= %f, dens= %f, angle= %f, func= %s op=%s\n",
			   clr->cmyk[0],clr->cmyk[1],clr->cmyk[2],clr->cmyk[3],
			   clr->density,clr->angle,clr->func,clr->op);
		}

#endif

/*     if( (clr->density != 1.0) && */ /* need screen if not white or black */
/*        (clr->density != 0.0) )  */
/* always put out screen 7/20/92 -Enhancement 33P from Dee */

#ifdef TRACE
	if (color_trace)
	{
		p_info(PI_TRACE, "%s setoverprint\n",clr->op);
		p_info(PI_TRACE, "%d %f %s setscreen (note - density= %f)\n",
			   clr->freq, clr->angle + (double)Orient,
			   clr->func, clr->density);
		p_info(PI_TRACE, "%d %f %s %s\n",
			old_freq, old_angle, old_func, old_op);
	}
#endif
	/* setoverprint for composites only */
	if ( !strcmp(clr->op,"false") && (!KeyOutputType) )
		m_fprintf("false setoverprint\n");
	else if ( !strcmp(clr->op,"true") && (!KeyOutputType) )
		m_fprintf("true setoverprint\n");

	if ( IncludeScreens )
	{
		/* Use PP Keyword LPI for color frequency */
		/* If LPI = 0, use colortable frequency */

		if (LPI != 0)
			clr->freq = LPI;

		if ( (old_freq != clr->freq) || (old_angle != clr->angle)
			|| (strcmp(old_func, clr->func)) || firstscreen
			|| (strcmp(old_op, clr->op)) )
		{

			m_fprintf("%d %5.2f {%s} setscreen \n",
				  clr->freq, clr->angle + (double)Orient,
				  clr->func); /* set screen from structure */
			firstscreen = 0;
		}
		old_freq = clr->freq;
		old_angle = clr->angle;
		strcpy(old_func, clr->func);
		strcpy(old_op, clr->op);  

	}
	if ( !CMYK_Allowed)
	{							/* enhancement 59P - 7/28/92 */
		temp_dens[0] = 1.0 - (((1.0 - clr->density) * shade) / 100.);
		digi_print(temp_dens[0]); /* set density */
		m_fprintf("setgray\n");
		if ( temp_dens[0] == 1.0)
			BlackPaint_cc_mask &= ~(1 << (plate_number-1));	/* white */
		else
			BlackPaint_cc_mask |= (1 << (plate_number-1)); /* black */
#ifdef TRACE
		if (color_trace)
		{
			p_info(PI_TRACE, "CMYK_Allowed=0, %6.3f setgray (to .tp file)\n",
				   temp_dens[0]);
			p_info(PI_TRACE, "new BlackPaint_cc_mask= %lo\n", BlackPaint_cc_mask);
		}
#endif
	}
	if (clr -> cmyk_flag && !KeyOutputType && CMYK_Allowed)
	{							/* set the specified color */

		if ( !strcmp(clr->type, "process")) {
		/* Add in tint and then shade for process color only */
		   for (ii=0; ii<4; ii++)
			clr->out_cmyk[ii] = ((clr->cmyk[ii] * clr->tint) / 100.);
		   for (ii=0; ii<4; ii++)
			clr->out_cmyk[ii] = ((clr->cmyk[ii] * shade) / 100.);
		} else {
		   for (ii=0; ii<4; ii++)
			clr->out_cmyk[ii] = clr->cmyk[ii];

		}

		temp_dens[0] = clr->out_cmyk[0];
		digi_print(temp_dens[0]); /* set C */
		temp_dens[1] = clr->out_cmyk[1];
		digi_print(temp_dens[1]); /* set M */
		temp_dens[2] = clr->out_cmyk[2];
		digi_print(temp_dens[2]); /* set Y */
		temp_dens[3] = clr->out_cmyk[3];
		digi_print(temp_dens[3]); /* set K */



		if ( !strcmp(clr->type, "process")) {
			/* Add used colors to color list */
			if (temp_dens[0] != 0)
				colorsused[0]=1; /* Has Cyan */
			if (temp_dens[1] != 0)
				colorsused[1]=1; /* Has Magenta */
			if (temp_dens[2] != 0)
				colorsused[2]=1; /* Has Yellow */
			if (temp_dens[3] != 0)
				colorsused[3]=1; /* Has Black */
			m_fprintf(" setcmykcolor\n");
		} else	{
			for (ii=0; ii< 48; ii++) {
				if (strcmp(customused[ii],clr->color_name) == 0) 
					break; /* Already Loaded */
				if (customused[ii][0] ==  '\0')  {
					strcpy(customused[ii],clr->color_name); /* Found Blank Spot for new entry */
					sprintf(cmykcustomused[ii],"%.2f %.2f %.2f %.2f",temp_dens[0], temp_dens[1], temp_dens[2], temp_dens[3]);
					break;
				}
			}
			m_fprintf("%s %.2f pentacustomcolor\n",clr->color_name, ( (100 - clr->tint) + (100 - shade) ) / 100);
		}

		 if ( (temp_dens[0] == 0.0) && (temp_dens[1] == 0.0) &&
			  (temp_dens[2] == 0.0) && (temp_dens[3] == 0.0)) 
			 BlackPaint_cc_mask &= ~(1 << (plate_number-1)); /* white */
		 else
			BlackPaint_cc_mask |= (1 << (plate_number-1)); /* black */
#ifdef TRACE
		if (color_trace)
			p_info(PI_TRACE, "%f %f %f %f set CMYK, Black= %lo\n",
				   temp_dens[0], temp_dens[1], temp_dens[2], temp_dens[3],
				   BlackPaint_cc_mask);
#endif
	}
	else if (!clr -> cmyk_flag && CMYK_Allowed)
	{							/* default to black */
		digi_print(0.0);		/* set C */
		digi_print(0.0);		/* set M */
		digi_print(0.0);		/* set Y */
		temp_dens[0] = shade / 100.;
		if( clr->density != 1.0)
		{
			digi_print(temp_dens[0]); /* set K - black */
			BlackPaint_cc_mask = 1; /* black */
		}
		else
		{
			digi_print(0.0);		/* set K - white */
			BlackPaint_cc_mask = 0;	/* white */
			temp_dens[0] = 0.0;
		}

		/* Add used colors to color list */
		if (temp_dens[0] != 0)
			colorsused[3]=1; /* Has Black */

		m_fprintf(" setcmykcolor\n");

#ifdef TRACE
		if (color_trace)
			p_info(PI_TRACE, "0 0 0 %f set CMYK(black), Black= %lo\n",
				   temp_dens[0], BlackPaint_cc_mask);
#endif
	}
}								/* end VID_TINT */
/***********************************************************************
 **  VLIST_INTERSECT determine if a frame bb rectangle **
 **         intersects any vid_box. **
 **		list started at vid_1st. **
 **		return 0 or pointer to structure **
 ***********************************************************************/
struct vid_box *vlist_intersect(uint32 plate_number)
{
	struct vid_box *vptr;

	if( in_overflow) 
	{
		repeat_ele = 0;
		repeat_rel = 0;
		return(0);					/* no hits */
	}
	if ( !KeyOutputType)
		plate_number = 1;
	if (current_vid_box == 0)
		vptr = vid_1st[plate_number]; /* list-walking pointer, start at head */
	else
		vptr = current_vid_box ->nxt;	/* start with next frame */
#ifdef TRACE
    if(color_trace)
		p_info(PI_TRACE, "vlist_intersect(%.2f, %.2f, %.2f, %.2f) (plate %lo)\n",
				  bb_left, bb_top, bb_right, bb_bottom, plate_number);
#endif
    while(vptr != 0)			/* walk towards the end */
    {
#ifdef TRACE
		if(color_trace)
			p_info(PI_TRACE, "compare %.2f, %.2f, %.2f, %.2f",
					  vptr->x,vptr->y,vptr->x1,vptr->y1);
#endif
		if((					/* if the passed area ...     */
				(bb_top < vptr->y1 ) && /* starts above bottom edge */
				((bb_bottom) > vptr->y) && /* ends below top edge */
				( bb_left < vptr->x1 ) && /* starts right of left edge */
				((bb_right) > vptr->x) /* ends left of right edge */
				) == TRUE)		/* they overlap! */
		{
			if ( (CurrentFrame != vptr -> rel_index) || /* rel is frame nbr */
				 (vptr ->cmd_bf_flag && (CurrentFrame == vptr -> rel_index)) )
			{					/* not current frame or bf in cur, try it */
#ifdef TRACE
				if (color_trace)
					p_info(PI_TRACE, " HIT!!\n");
#endif
				repeat_rel = vptr -> rel_index;
				repeat_ele = vptr -> ele_index;
				return(vptr);	/* so we say so */
			}
		}
#ifdef TRACE
		if(color_trace)
			p_info(PI_TRACE, " miss!\n");
#endif
		vptr = vptr -> nxt;		/* point to 'next'  */
    }
#ifdef TRACE
    if(color_trace)
		p_info(PI_TRACE, "They all miss or at end.\n");
#endif
	repeat_ele = 0;
	repeat_rel = 0;
    return(0);					/* no hits */
}								/* end VLIST_INTERSECT */
void add_to_vlist(float x, float y, float x2, float y3, int fg, int fg_shd,
				  int bg, int bg_shd, uint32 vlist_plates, int bf_flag)
{
    int i;
    struct vid_box *vp;			/* our new entry's pointer */
	uint32 plates_hold;
	uint32  loop_temp;
    
	if ( !KeyOutputType)
		vlist_plates = 1;
#ifdef TRACE
    if(color_trace)
	{
		p_info(PI_TRACE, "add_to_vlist: x= %.2f, y= %.2f, x2= %.2f, y3= %.2f\n",
			   x, y, x2, y3);
		p_info(PI_TRACE, "pg_deg= %d, pg_rot_x= %d, pg_rot_y= %d\n",
			   PageRotationAngle, PageRotationX, PageRotationY);
		p_info(PI_TRACE, "fg= %d %d, bg= %d %d, plates= %lo, rel= %d, ele= %d\n",
			   fg, fg_shd, bg, bg_shd, vlist_plates, CurrentFrame, CurrentEle);
	}
#endif
    for (i=0; i<MAX_CLRS-1; i++)
    {
		plates_hold = ( loop_temp = (1 << i) ) & vlist_plates;
		if(loop_temp > vlist_plates)
			break;
		if ( !plates_hold)
			continue;
		/* allocate an entry */
		vp = (struct vid_box *) p_alloc(sizeof(struct vid_box));
		if(vp != 0)				/* fill in if it's good	*/
		{
			if(vid_1st[i+1] == 0)	/* if list was empty */
			{
				vid_last[i+1] = vid_1st[i+1] = vp; /* last is first also */
				vp->prv = 0;	/* there is no previous entry*/
			}
			else
			{
				vid_last[i+1]->nxt = vp; /* old last points here */
				vp->prv = vid_last[i+1]; /* and old last is there */
				vid_last[i+1] = vp; /* while this is new last */
			}
			vp->x = x;			/* fill the data in */
			vp->y = y;
			vp->x1 = x2;
			vp->y1 = y3;
			vp->page_rotation_angle = -PageRotationAngle;
			vp->rot_x = PageRotationX / HorizontalBase;
			vp->rot_y = (Imageheight - PageRotationY) / VerticalBase;
			vp->fg_color = fg;
			vp->fg_shade = fg_shd;
			vp->bg_color = bg;
			vp->bg_shade = bg_shd;
			vp->rel_index = CurrentFrame;
			vp->ele_index = CurrentEle;
			vp->elem = PsCurRec -> elem;
			vp->cmd_bf_flag = bf_flag;
			vp->nxt  = 0;	/* and re-terminate the list  */
#ifdef TRACE
			if(color_trace)
				p_info(PI_TRACE, "entry made @ %x in color %d\n", (unsigned)vp, i);
#endif
			continue;
		}
		else					/* what, malloc failed? */
			p_info(PI_ELOG, "add_to_vlist:NO MEMORY FOR ENTRY\n");
		return;
    }							/* end for (i=0; i<MAX_CLRS-1; i++)  */
}								/* end ADD_TO_VLIST */
static int job_setup(void)
{
    int length, i, c;    
    int16 stds_buff[240];
    Pfd sysfd;
	int temp_reg_length = 0;
	int temp_trim = 0;

	float fcolor;
	int ii;
	char pdfword[8192];
	char pdftmp[8192];
	char pdfc[5];
	char *p;

	PdfActive = 0;				/* Assume no PDF style given, thus 
									no PDF output desired.  */
	/* Clear PDF values - Set defaults for menu items left blank  */
	/*   (all assuming that PDF output is active).  */
	pdflinkctr = 0;
	pdflinkAtSOL = 0;

	job_link.btype=3; /* none */
	job_link.weight=1;
	job_link.bcolor=000000000; /* White */
	strcpy(job_link.ocolor,"0 0 0");
	job_link.dashlen=4;
	job_link.dashgap=4;
	job_link.radius=0;

	pdf_info.title[0] = '\0';
	pdf_info.auth[0] = '\0';
	pdf_info.subj[0] = '\0';
	pdf_info.keyw[0] = '\0';
	pdf_info.creator[0] = '\0';
	pdf_info.date1[0] = '\0';
	pdf_info.date2[0] = '\0';

	pdf_docview.initpage=1;
	pdf_docview.initdisp=2; /* page only */
	pdf_docview.initsize=2; /* fit zoom */
	pdf_docview.initzoom=0; /* full screen */

	pdf_note_disp=0;
	pdf_note_length=60;
	pdf_note_depth=60;
	pdf_note_color=255255255;
	strcpy(pdf_note_ocolor,"1 1 1");

	pdf_output_lev = 9; /* all levels */
	pdf_crop_cw = pdf_crop_cd = 0;	/* No crop box. */
	pdf_crop_dw = pdf_crop_dd = 0;
	pdf_crop_cox = pdf_crop_coy = pdf_crop_cex = pdf_crop_cey = 0;
	pdf_crop_dox = pdf_crop_doy = pdf_crop_dex = pdf_crop_dey = 0;

    set_traces(msg[7].answer);
#ifdef TRACE
    if(debugger_trace)
    {
		for (i=0; i<KEYWORD_COUNT; i++)
			p_info(PI_TRACE, "i= %d, Keyword %s, Value= %s \n",
				   i,msg[i].keyword,msg[i].answer);
    }
#endif
	if (msg[68].answer[0])
		LockFlag = 0;
	else
		LockFlag = 1;
	FirstGal = 0;
	LastGal = 1000000;
    if ( !msg[6].answer[0])
    {							/* no Tree name present */
		if( !msg[7].answer[0])
		{						/* no traces change */
			p_info(PI_ELOG, "ERROR - 'Tree' name missing, program exit \n");
			exit(1);
		}
		return(1);				/* change traces only */
    }
    length = strlen(msg[6].answer);
    if( length >= MAX_NAME) 
    {
		p_info(PI_ELOG, "ERROR- 'Tree' name '%s' exceeds %d characters, program exit.\n",
			   msg[6].answer, MAX_NAME - 1);
		exit(1);
    }
    strcpy(TreeName, msg[6].answer);
    if ( !msg[4].answer[0])
    {							/* sub-dir name missing */
		if( msg[2].answer[0] )
		{						/* need subdir name if it is a galley */
			p_info(PI_ELOG, "ERROR - 'Dir' name is missing, program exit \n");
			exit(1);
		}
		else
		{						/* create SubDirName if not present for unit */
			if( !msg[3].answer[0] )
			{					/* need subdir name if it is a galley */
				p_info(PI_ELOG, "ERROR - 'Dir' name is missing, program exit \n");
				exit(1);
			}
			else				/* use unit name for project */
				sprintf(SubDirName,"%s.prj",msg[3].answer);
		}
    }
    else
    {
		length = strlen(msg[4].answer);
		if( length >= MAX_NAME) 
		{
			p_info(PI_ELOG, "ERROR - 'Dir' name '%s' exceeds %d characters, program exit.\n",
				   msg[4].answer, MAX_NAME - 1);
			exit(1);
		}
		strcpy(SubDirName, msg[4].answer);
    }
    if ( p_get_data_name ( TreeName, SubDirName, UserdataPath, 0 ) )
    {
		p_info(PI_ELOG, "ERROR - missing file '/Penta/%s/desks/%s/.data', program exit.\n",
			   TreeName, SubDirName);
		exit(1);
    }
#ifdef TRACE
    if (debugger_trace)
		p_info(PI_TRACE, "path to userdata is '%s' \n",UserdataPath);
#endif
    if ((sysfd = p_open(TreeName,USERDATA,UserdataPath,"standards","r")) == 0)
    {
		p_info(PI_ELOG, "ERROR - file 'standards' is missing, program exit.\n");
		exit(1);
    }
    if ( !(p_read((char *)stds_buff, 240, 1, sysfd, 0, BS16) ) )
    {
		p_info(PI_ELOG, "ERROR - cannot read file 'standards', program exit.\n");
		exit(1);
    }
    p_close(sysfd);
    HorizontalBase = stds_buff[35];
    VerticalBase = stds_buff[74];
    Jrule = (int)stds_buff[95];
	if ( !Jrule)
		Jrule = 10;
	BookPrint = 0;
    if ( msg[2].answer[0])
    {							/* galley name */
		length = strlen(msg[2].answer);
		if( length >= MAX_NAME) 
		{
			p_info(PI_ELOG, "ERROR - 'Galley' name '%s' exceeds %d characters, program exit. \n",
				   msg[2].answer, MAX_NAME - 1);
			exit(1);
		}
		strcpy(JobName, msg[2].answer); /* we have a galley name */
		FileType = 0;			/* Galley output */
		FirstPage = 0;
    }							/* end galley name */
    else if ( msg[3].answer)
    {							/* use the unit name */
		length = strlen(msg[3].answer);
		if( length >= MAX_NAME) 
		{
			p_info(PI_ELOG, "ERROR - 'Unit' name '%s' exceeds %d characters, program exit.\n",
				   msg[3].answer, MAX_NAME);
			exit(1);
		}
		FileType = 1;			/* must be a unit name */
		strcpy(JobName, msg[3].answer);

		FirstPage = -1;			/* (assume no start/end pgs given)  */
		LastPage = -1;
		if (strstr(msg[8].answer, ".prj"))
		{						/* Child-project name is passed instead of first pg#.
									Store project name, set doing-book flag:  */
			strcpy (FirstProjofBook, msg[8].answer);
			strcpy (LastProjofBook, FirstProjofBook);
			BookPrint = 1;
			if (strstr(msg[9].answer, ".prj"))
				strcpy (LastProjofBook, msg[9].answer);
		}
		else if (msg[8].answer[0])	/* Regular starting page #  */
		{
			FirstPage = atol(msg[8].answer);
			if (msg[9].answer[0])		/* Regular ending page #  */
				LastPage = atol(msg[9].answer);
		}
		if ( msg[18].answer[0])
		{						/* only use for debugging */
			FirstPage = atol(msg[18].answer);
			if ( !msg[19].answer[0])
				LastPage = -1;
			else
				LastPage = atol(msg[19].answer);
		}
		if ( msg[33].answer[0])	/* Layout */
			strcpy (msg[21].answer, msg[33].answer);
		if ( msg[21].answer[0])	/* FirstMaster */
		{
			length = strlen(msg[21].answer);
			if( length >= MAX_NAME) 
			{
				p_info(PI_ELOG, "ERROR - 'FirstMaster' name '%s' exceeds %d characters, program exit. \n",
					   msg[21].answer, MAX_NAME - 1);
				exit(1);
			}
			strcpy(PageName, msg[21].answer); /* we have a layout name */
			MasterNameFlag = 1;
			FirstPage = 0;
			LastPage = 0;
		}
		else
		{
			MasterNameFlag = 0;
			PageName[0] = 0;
		}
		if(psinit())
			exit(1);
    }							/* end unit name */
    else
    {
		p_info (PI_ELOG, "ERROR - missing 'Galley' or 'Unit' name, program exit. \n");
		exit(1);
    }
	if (msg[5].answer[0])
	{							/* printer name */
		length = strlen(msg[5].answer);
		if( length >= MAX_NAME) 
		{
			p_info(PI_ELOG, "ERROR - 'PrinterName' '%s' exceeds %d characters, program exit. \n",
				   msg[5].answer, MAX_NAME - 1);
			exit(1);
		}
		strcpy(PrinterName, msg[5].answer);
    }
    else
		strcpy(PrinterName, "\0\0");

    lnumbers = atoi(msg[10].answer);
    suppresslp=0;

    if ( msg[11].answer[0])
    {
		length = strlen(msg[11].answer);
		if( length >= MAX_NAME) 
		{
			p_info(PI_ELOG, "ERROR - 'ColorTable' name '%s' exceeds %d characters, program exit. \n",
				   msg[11].answer, MAX_NAME - 1);
			exit(1);
		}
		strcpy(ColorTableName, msg[11].answer);
    }
    else
		strcpy(ColorTableName, "colortable");
    init_color();
    p_info(PI_INFO, "Postprint starting Tree: '%s', Dir: '%s', Job: '%s' \n",TreeName,SubDirName,JobName);
    if ( msg[12].answer[0])
		GalleySlugFlag = atoi(msg[12].answer); /* use keyword with 0 or 1 */
    else
    {							/* no keyword, use defaults */
		if ( FileType)
			GalleySlugFlag = 0;	/* default is no print slug if Unit */
		else
			GalleySlugFlag = 1;	/* default is print slug if Galley */
    }
	if ( msg[13].answer[0])
		strcpy(PsfTableName, msg[13].answer); /* name of PSFTABLE */
	else
		strcpy(PsfTableName, "psftable");
	Orient = 0;					/* portrait is default */
	if ( msg[14].answer[0])
	{							/* p or P = portrait, l or L = landscape */
		switch (msg[14].answer[0])
		{
		  case 'P':
		  case 'p':
			Orient = 0;			/* portrait */
			break;
		  case 'L':
		  case 'l':
			Orient = 90;		/* landscape */
			break;
		  default:
			p_info(PI_ELOG, "ERROR - Orient '%s' invalid, defaulting to portrait.\n",
				   msg[14].answer);
			break;
		}
	}
	if ( msg[15].answer[0])
	{							/* KeyScale */
		if ( (msg[15].answer[0] & 0xdf) == 'X')
			KeyScale = -1;		/* defined as 'X' */
		else
			KeyScale = atoi(msg[15].answer);
	}
	else
		KeyScale = -2;			/* not defined */
	if ( msg[16].answer[0])		/* KeyScaleX */
		KeyScaleX = atoi(msg[16].answer);
	else
		KeyScaleX = -1;
	if ( msg[17].answer[0])		/* KeyScaleY */
		KeyScaleY = atoi(msg[17].answer);
	else
		KeyScaleY = -1;
	KeyOutputType = 0;			/* default is composite */
	if ( msg[20].answer[0] == '1')
	{
#if LPMfloat
		if ( LPMK[LPM_PWS1] || LPMK[LPM_PWS2] )
#else
		if ( (LPMK & LPM_PWS1) || (LPMK & LPM_PWS2) )
#endif
			p_info(PI_ELOG, "ERROR - Color separation not allowed on a Personal Workstation.\n");
		else
#if ! LPMfloat
		if((LPMK & LPM_SpotColor))
#endif
			KeyOutputType = 1;	/* color separation */
	}
	if ( msg[23].answer[0])		/* Header */
		setpage_allowed =
			atoi(msg[23].answer); /* 1 means dump page width and height */
	else
		setpage_allowed = -1;
	MultiPagesUp = 0;			/* default is 1 up */
	MultiPagesOddEvenFlag = 0;
	MultiOddPage_cc_mask = 0;
	if ( msg[24].answer[0])		/* Multi - for 2 pages up */
	{							/* non-zero means 2-up */
		MultiPagesUp = atoi(msg[24].answer);
		if ( !FileType || (FirstPage < 0) ||
			 ( ( FirstPage >= 0) && !(FirstPage & 1) ) )
			MultiPagesOddEvenFlag = 0;
		else
			MultiPagesOddEvenFlag = 1; /* starting Unit on odd page */
	}
	if ( msg[25].answer[0])		/* PageW */
	{
		PageW = atoi(msg[25].answer);
		PageW_key_flag = 1;
	}
	else
	{
		PageW = -1;
		PageW_key_flag = 0;
	}
	if ( msg[26].answer[0])		/* PageD */
	{
		PageH = atoi(msg[26].answer);
		PageD_key_flag = 1;
	}
	else
	{
		PageH = -1;
		PageD_key_flag = 0;
	}
	if ( msg[27].answer[0])		/* Pofft */
	{
		OffT = atoi(msg[27].answer);
		Pofft_key_flag = 1;
	}
	else
	{
		OffT = -1;
		Pofft_key_flag = 0;
	}
	if ( msg[28].answer[0])		/* Poffb */
	{
		OffB = atoi(msg[28].answer);
		Poffb_key_flag = 1;
	}
	else
	{
		OffB = -1;
		Poffb_key_flag = 0;
	}
	if ( msg[29].answer[0])		/* Poffl */
	{
		OffL = atoi(msg[29].answer);
		Poffl_key_flag = 1;
	}
	else
	{
		OffL = -1;
		Poffl_key_flag = 0;
	}
	if ( msg[30].answer[0])		/* Poffr */
	{
		OffR = atoi(msg[30].answer);
		Poffr_key_flag = 1;
	}
	else
	{
		OffR = -1;
		Poffr_key_flag = 0;
	}
	if ( msg[31].answer[0])		/* Cmyk */
		CMYK_Allowed = atoi(msg[31].answer);
	else
		CMYK_Allowed = -1;
	if ( msg[32].answer[0])		/* Hdrup */
		header_offset = atoi(msg[32].answer); /* Pts to raise slug line */
	else
		header_offset = -32760;	/* -32760 means no Hdrup keyword */
	LYPrintFlag = 0;
	if ( msg[34].answer[0])		/* LYP -  layout print */
	{
		if ( !FileType)
		{
			p_info(PI_ELOG, "ERROR - Cannot do LYP (layout print) for galley, program exit.\n");
			exit(1);

		}
/* for LayoutPrint, kill other functions */
		for (i=0; i<10; i++)
		{
			if ( !msg[34].answer[i])
				break;
			if ( msg[34].answer[i] == 'a')
			{					/* a means all reports */
				LYPrintFlag = -1;
				break;
			}
			c = (msg[34].answer[i] - '0') & 0xf;
			if ( (c <= 0) || (c > 9) )
				continue;
			LYPrintFlag |= 1 << (c -1 );
		}
	}							/* end if(msg[34].answer[0]) */
	if (LYPrintFlag)
	{
		delay_records_flag = -1; /* no sorting for reporting */
		GalleySlugFlag = 0;
		KeyOutputType = 0;
		MultiPagesUp = 0;
		lnumbers = 0;
		if ( msg[35].answer[0])
		{						/* Report directory, used, or both */
			Reports = atoi( msg[35].answer);
			switch ( Reports)
			{
			  case -1:			/* all files in directory and all used */
			  case 0:			/* only those files in directory (default) */
			  case 1:			/* only those files used */
				break;
			  default:
				p_info(PI_ELOG, "ERROR - 'Report' Key Word option %s not available. Defaulting to reporting on data base in directory.\n", msg[35].answer);
				Reports = 0;
				break;
 			}						/* end switch(Reports) */
		}
		else
			Reports = 0;		/* default */
	}
	else
		delay_records_flag = 1;	/* normal postsript delay */
	if ( msg[37].answer[0] == '1')
		KeyTrimFlags = 1;		/* trim marks */
	else
		KeyTrimFlags = 0;
	if ( msg[36].answer[0] == '1')
		KeyTrimFlags |= 2;		/* register marks */
	if ( (KeyTrimFlags & 1) && !LYPrintFlag )
    {							/* set up trim marks */
		if ( msg[41].answer[0])
			temp_trim = atoi(msg[41].answer);
		if ( !temp_trim)
			temp_trim = 24;		/* default */
		trim_mark_width = temp_trim * HorizontalBase;
		trim_mark_depth = temp_trim * VerticalBase;
		KeyTrimLength = temp_trim;
		KeyTrimWeight = 0;
		if ( msg[40].answer[0])
			KeyTrimWeight = (int )(atof(msg[40].answer) * 20); /* in 1/20 pt */
		if ( KeyTrimWeight < 2)
			KeyTrimWeight = 2;
	}
	else
	{
		trim_mark_width = 0;
		trim_mark_depth = 0;
		KeyTrimWeight = 0;
		KeyTrimLength = 0;
	}
	if ( (KeyTrimFlags & 2) && !LYPrintFlag )
    {							/* set up register marks */
		if ( msg[39].answer[0])
			temp_reg_length = atoi(msg[39].answer);
		if ( !temp_reg_length)
			temp_reg_length = 12;		/* default */
		KeyRegisterLength = temp_reg_length; /* in points */
		KeyRegisterWt = 0;
		if ( msg[38].answer[0])
			KeyRegisterWt = atof(msg[38].answer);
		if ( KeyRegisterWt < 0.1)
			KeyRegisterWt = .1;
		if ( (2 * temp_reg_length) > temp_trim)
		{
			trim_mark_width = temp_reg_length * HorizontalBase * 2;
			trim_mark_depth = temp_reg_length * VerticalBase * 2;
		}
	}
	else
	{
		KeyRegisterLength = 0;
		KeyRegisterWt = 0;
	}
	if ( (KeyTrimFlags &3) && !LYPrintFlag )
	{							/* add 9 point offset */
		if (msg[72].answer[0])	/* ie. gap between trim-line & tick */
			KeyTrimRegGap = atoi(msg[72].answer);
		else
			KeyTrimRegGap = 9;
		trim_mark_width += (KeyTrimRegGap * HorizontalBase);
		trim_mark_depth += (KeyTrimRegGap * VerticalBase);
	}
	if (msg[73].answer[0])	
		EpsFlag = atoi(msg[73].answer);
	else
		EpsFlag=0;

	if (msg[74].answer[0])	
		strcpy(Uname,msg[74].answer);
	else
		strcpy(Uname,"penta");

	if (msg[75].answer[0])	
		DownLoadFont=1;
	else
		DownLoadFont=0;

	if (msg[76].answer[0])	
		ResolveOPI=1;
	else
		ResolveOPI=0;

	if (msg[77].answer[0])
		job_link.btype=atoi(msg[77].answer);

	if (msg[78].answer[0])
		job_link.weight=atoi(msg[78].answer);

	if (msg[79].answer[0]) {
		job_link.bcolor=atoi(msg[79].answer);
		strcpy(pdftmp,msg[79].answer);
		/* split into chunks of 3 digits */
		job_link.ocolor[0] = '\0';
		p=pdftmp;
                for (ii=1; ii <= 3; ii++) {
		     strncpy(pdfc,p,3);
		     fcolor=(atoi(pdfc)/255);
                     memset(pdfword,0,sizeof(pdfword));
                     sprintf(pdfword," %.2f",fcolor);
                     strcat(job_link.ocolor,pdfword);
		     p+=3;
                 }
	}

	if (msg[80].answer[0])
		job_link.dashlen=atoi(msg[80].answer);

	if (msg[81].answer[0])
		job_link.dashgap=atoi(msg[81].answer);

	if (msg[82].answer[0])
		job_link.radius=atoi(msg[82].answer);

	if (msg[83].answer[0])
		strcpy(pdf_info.title,msg[83].answer);

	if (msg[84].answer[0])
		strcpy(pdf_info.auth,msg[84].answer);

	if (msg[85].answer[0])
		strcpy(pdf_info.subj,msg[85].answer);

	if (msg[86].answer[0])
		strcpy(pdf_info.keyw,msg[86].answer);

	if (msg[87].answer[0])
		strcpy(pdf_info.creator,msg[87].answer);

	if (msg[88].answer[0])
		strcpy(pdf_info.date1,msg[88].answer);

	if (msg[89].answer[0])
		strcpy(pdf_info.date2,msg[89].answer);

	if (msg[90].answer[0])
		pdf_docview.initpage = atoi(msg[90].answer);

	if (msg[91].answer[0])	/* This is the switch, set by DM print menu:  */
	{						/*   There was a PDF style used in this request.  */
		PdfActive = 1;		/* PDF output is now active.  */
		pdf_docview.initdisp = atoi(msg[91].answer);
	}

	if (msg[92].answer[0])
		pdf_docview.initsize = atoi(msg[92].answer);

	if (msg[93].answer[0])
		pdf_docview.initzoom = atoi(msg[93].answer);

	if (msg[94].answer[0])
		pdf_note_disp = atoi(msg[94].answer);

	if (msg[95].answer[0])
		pdf_note_length = atoi(msg[95].answer);

	if (msg[96].answer[0])
		pdf_note_depth = atoi(msg[96].answer);

	if (msg[97].answer[0]) {
                pdf_note_color=atoi(msg[97].answer);
                strcpy(pdftmp,msg[97].answer);
                /* split into chunks of 3 digits */
                pdf_note_ocolor[0] = '\0';
                p=pdftmp;
                for (ii=1; ii <= 3; ii++) {
                     strncpy(pdfc,p,3);
                     fcolor=(atoi(pdfc)/255);
                     memset(pdfword,0,sizeof(pdfword));
                     sprintf(pdfword," %.2f",fcolor);
                     strcat(pdf_note_ocolor,pdfword);
                     p+=3;
                 }
	}

	if (msg[98].answer[0])
		pdf_output_lev = atoi(msg[98].answer);

	if (msg[99].answer[0])
		pdf_crop_dox = atoi(msg[99].answer);
	if (msg[100].answer[0])
		pdf_crop_doy = atoi(msg[100].answer);
	if (msg[101].answer[0])
		pdf_crop_dex = atoi(msg[101].answer);
	if (msg[102].answer[0])
		pdf_crop_dey = atoi(msg[102].answer);
	if (msg[103].answer[0])
		pdf_crop_cox = atoi(msg[103].answer);
	if (msg[104].answer[0])
		pdf_crop_coy = atoi(msg[104].answer);
	if (msg[105].answer[0])
		pdf_crop_cex = atoi(msg[105].answer);
	if (msg[106].answer[0])
		pdf_crop_cey = atoi(msg[106].answer);
	if (msg[107].answer[0])
		pdf_crop_cw = atoi(msg[107].answer);
	if (msg[108].answer[0])
		pdf_crop_cd = atoi(msg[108].answer);
	if (msg[109].answer[0])
		pdf_crop_dw = atoi(msg[109].answer);
	if (msg[110].answer[0])
		pdf_crop_dd = atoi(msg[110].answer);
	if (msg[111].answer[0])
		pdf_bead = atoi(msg[111].answer);
	else
		pdf_bead = 0;


	MultiPagesFirstIsOdd = MultiPagesOddEvenFlag;
	if ( !FileType)
	{							/* if galley, see if start & end galley */
		if ( msg[42].answer[0])
		{
			FirstGal = atoi(msg[42].answer);
			if (FirstGal < 0)
			{
				p_info(PI_ELOG, "ERROR - First galley number (%s) less than 0, defaulting to all galleys.\n",
						   msg[42].answer);
				FirstGal = 0;
				LastGal = 1000000;
			}
			else if ( msg[43].answer[0])
			{
				LastGal = atoi(msg[43].answer);
				if (LastGal < FirstGal)
				{
					p_info(PI_ELOG, "ERROR - Last galley number (%s) less than first galley number (%s), defaulting to all galleys.\n",
						   msg[43].answer, msg[42].answer);
					FirstGal = 0;
					LastGal = 1000000;
				}
			}
			else
			{
				FirstGal = 0;
				LastGal = 1000000;
			}
		}						/* end if(msg[42].answer[0])  */
		if (!FirstGal && !LastGal)
			LastGal = 1000000;
	}							/* end if(!FileType) */
	if ( msg[45].answer[0])
		Proof = atoi(msg[45].answer);
	else
		Proof = 0;
	if ( KeyOutputType && msg[46].answer[0])
		Plates = (uint32 )atoi(msg[46].answer);
	else
		Plates = 0xffffffff;
	if ( FileType && msg[47].answer[0] && !LYPrintFlag)
		SupressBlankPages = atoi(msg[47].answer);
	else
		SupressBlankPages = 0;
	if ( msg[48].answer[0])
		Neg = atoi(msg[48].answer);
	else
		Neg = 0;
	if ( msg[49].answer[0])
		Mirror = atoi(msg[49].answer);
	else
		Mirror = 0;
	if ( msg[50].answer[0] && !FileType) /* only allowed in galleys */
		BcEcFlag = atoi(msg[50].answer); /* non-zero: use BcEc */
	else
		BcEcFlag = 0;			/* Ignore BcEc for this job */
	if ( msg[51].answer[0])
	{
		EditTraceFlag = atoi(msg[51].answer);
		if ( (EditTraceFlag < 0) || (EditTraceFlag > 3) )
		{
			p_info(PI_ELOG, "ERROR - EditTrace '%s' invalid, defaulting to none.\n",
				   msg[51].answer);
			EditTraceFlag = 0;
		}
	}
	else
		EditTraceFlag = 0;
	EditTraceStarted = 0;
	if ( EditTraceFlag)
	{							/* only read parameters if needed. */
		if ( msg[52].answer[0])
			CurInsOffset = (int )(atof(msg[52].answer) * VerticalBase);
		else
			CurInsOffset = 1.25 * VerticalBase;
		if ( msg[53].answer[0])
			PreInsOffset = (int )(atof(msg[53].answer) * VerticalBase);
		else
			PreInsOffset = 2.75 * VerticalBase;
		if ( msg[54].answer[0])
			CurDelOffset = (int )(atof(msg[54].answer) * VerticalBase);
		else
			CurDelOffset = 2.25 * VerticalBase;
		if ( msg[55].answer[0])
			PreDelOffset = (int )(atof(msg[55].answer) * VerticalBase);
		else
			PreDelOffset = 3.75 * VerticalBase;
		if ( msg[56].answer[0])
		{
			CurInsClr = atoi(msg[56].answer);
			if(CurInsClr < -1)
				CurInsClr = -1;
		}
		else
			CurInsClr = 1;
		if ( msg[57].answer[0])
		{
			PreInsClr = atoi(msg[57].answer);
			if(PreInsClr < -1)
				PreInsClr = -1;
		}
		else
			PreInsClr = 1;
		if ( msg[58].answer[0])
		{
			CurDelClr = atoi(msg[58].answer);
			if(CurDelClr < -1)
				CurDelClr = -1;
		}
		else
			CurDelClr = 1;
		if ( msg[59].answer[0])
		{
			PreDelClr = atoi(msg[59].answer);
			if(PreDelClr < -1)
				PreDelClr = -1;
		}
		else
			PreDelClr = 1;
		if ( msg[60].answer[0])
		{
			CurInsWeight = (atof(msg[60].answer)  * VerticalBase);
			if(CurInsWeight <= 0)
				CurInsWeight = 1.; /* 1/10 point in VerticalBase units */
		}
		else
			CurInsWeight = .1 * VerticalBase;
		if ( msg[61].answer[0])
		{
			PreInsWeight = atof(msg[61].answer) * VerticalBase;
			if(PreInsWeight <= 0)
				PreInsWeight = 1.; /* 1/10 point in VerticalBase units */
		}
		else
			PreInsWeight = .1 * VerticalBase;
	}							/* end if(EditTraceFlag) */
	if ( msg[62].answer[0])
	{
		ChapterPage = atoi(msg[62].answer);
		ChapterPageSetFlag = 0;
	}
	else
	{
		ChapterPage = 0;
		ChapterPageSetFlag = 1;
	}
	if ( msg[63].answer[0])
		IncludeScreens = atoi(msg[63].answer);
	else
		IncludeScreens = 1; /* If no keyword, set IncludeScreens to 1 */

	if (msg[64].answer[0])
		LPI = atoi(msg[64].answer);
	else
		LPI = 0; /* Use ColorTable */

    if ( msg[65].answer[0]) /* Number of Copies */
        NumCopies = atoi(msg[65].answer);
    else
        NumCopies = 1;
    if ( msg[66].answer[0]) /* ClipPaths */
		ClipPathFlag = atoi(msg[66].answer);
	else
		ClipPathFlag = 0;
	if ( msg[67].answer[0]) /* Collate */
		CollateFlag = atoi(msg[67].answer);
	else
		CollateFlag = 0;
	if ( msg[69].answer[0]) /* Page width in inches */
		PageWInch = atoi(msg[69].answer);
	else
		PageWInch = 0;
	if ( msg[70].answer[0]) /* Page Depth in inches */
		PageDInch = atoi(msg[70].answer);
	else
		PageDInch = 0;
	if ( msg[71].answer[0]) /* Switch: Do galley breaks in pp/pq extracts */
		DoExtractBreaks = atoi(msg[71].answer);
	else
		DoExtractBreaks = 1;
	if ( msg[120].answer[0]) /* 1= Distill to PDF (done by .psh script)
								0= don't   */
		DistillFlag = atoi(msg[120].answer);
	else
		DistillFlag = 0;
	if ( msg[121].answer[0] && lnumbers)
							/* += Put out line stats w/ line# (galley md only)
								5+=Do so, and use val as their pt-size.
								0= don't   */
		LineStats = atoi(msg[121].answer);
	else
		LineStats = 0;
	return(0);
}								/* end function */
/***********************************************************************
 **  POST_PRINT.C mainline.	**
 ***********************************************************************/
void main(int argc, char *argv[])
{
    int num_read, i;
    int one_shot;
    int pipe_in, pipe_out;
    int result;
	char tp_extend[18];
	char *new_Psf_path_ptr;
    char *parse_buff_ptr;

	umask(0);
    set_sigs();					/* get all traces out at end */
    p_init(0);
	lc_init(1);
	memset ( (char *)&ObjPageWn.page_number[0], 0,
			 sizeof (struct obj_pg_wn) );
	obj_wn_count = 0;
    one_shot = 0;

	Current_FgColor = 1;			/*  BUG 594q Initialize current color to black     */
	Current_FgShade = 100;			/*  BUG 594q Initialize current shade to 100%   */
    msg_parse_args(argc, argv, KEYWORD_COUNT, msg);
    pipe_in = atoi(msg[0].answer);
    pipe_out = atoi(msg[1].answer);
    if((pipe_in == 0) && (pipe_out ==0))
		one_shot = 1;			/* don't read from pipe */
    p_info(PI_INFO, "Postprint Startup.\n"); /* log in first message. */
    strcpy (overflow_path,"overflow.pos1"); /* Build name of overflow-text
											   temp file, using ipc suffix.*/
	bmtop = 0;					/* Init dynamic PDF bookmark mem array.  */
	uidtop = 0;					/* Init dynamic PDF bookmark-idrid mem array.  */

/***************************** start of big loop ***************************/
    for(;;)
    {
		if (p_LogFd)
		{
			fclose (p_LogFd);
			p_LogFd = NULL;
		}
		if (TrailerName)
		{
		        fclose(TrailerName);
			TrailerName = NULL;
		}
		if (PrologName)
		{
		        fclose(PrologName);
			PrologName = NULL;
		}

		p_LogCnt = 0;
		if (Fofd)
			p_close(Fofd);
		FoName[0] = 0;
		parse_buff = p_alloc(2048);
		if ( !m_fprintf_size)
		{
			m_fprintf_size = 4096;
			m_fprintf_buff = p_alloc(m_fprintf_size);
		}
		if( !one_shot)
		{						/* read from the pipe */
			num_read = read(pipe_in, parse_buff, 2048);
			switch (num_read)
			{
			  case -1:
				p_info(PI_ELOG, "pipe read failed\n");
				exit(1);
			  case 0:
				p_info(PI_ELOG, "pipe_in EOF\n");
				exit(1);
			  default:
				break;
			}					/* end switch(num_read) */
#ifdef TRACE
			if(debugger_trace)
				p_info(PI_TRACE, "pipe num_read= %d, '%s' \n",num_read,parse_buff);
#endif
			msg_parse(parse_buff, num_read, KEYWORD_COUNT, msg);
        }						/* end of pipe read */
		else
		{						/* read from arg & argv or from file */
			if ((one_shot == 1) && !source_pfd)
			{
			    if ( msg[44].answer[0])
				{				/* KEYWORD 'source', read from file */
					one_shot = 2;
					if((source_pfd = p_open(NO_STRING, OTHER_FILE, NO_STRING,
											msg[44].answer, "r")) == 0)
					{			
						p_info(PI_ELOG, "Failed to open source '%s'\n",msg[44].answer);
						exit(2);
					}
				}
			}
			if ( source_pfd)
			{					/* get next job from source file */
				if (p_fgets(parse_buff, 2048, source_pfd) == 0)
				{
					p_info(PI_ELOG, "source file empty\n");
					exit(3);
				}
				parse_buff_ptr = parse_buff;
				while ( *parse_buff_ptr)
				{
					if ( *parse_buff_ptr == '\012')
					{
						*parse_buff_ptr = 0;
						break;
					}
					parse_buff_ptr++;
				}
				msg_parse (parse_buff, (int)(parse_buff_ptr - parse_buff + 1),
						   KEYWORD_COUNT, msg);
			}
		}
#if LPMfloat
		for (i = 0; i < LPM_MaxOption; i++)
			LPMK[i] = lpm_option(i);
#else
		LPMK = lpm_query(LPM_Options,LPM_CurrRev);
#endif
        result = job_setup();
        p_free(parse_buff);
        if(result)
        {						/* only if setting traces */
			if(!one_shot)
			{
				if((num_read = write(pipe_out, "0", 2))== -1)
				{
					p_info(PI_ELOG, "write to pipe failed\n");
					exit(1);
				}
				else
					continue;	/* traces only, get next pipe message */
			}
			exit(1);
        }
        strcpy(tpname, JobName); /* TP filename. */
		if ( FileType)
		{						/* layout */
			tp_extend[0] = 0;
			if (MasterNameFlag)
				sprintf (tp_extend, ".%s", PageName);
			if ( LYPrintFlag)
				strcat (tp_extend, ".lyp");
			strcat (tpname, tp_extend);
			if ( (FirstPage >= 0) && ( !MasterNameFlag) )
			{
				if (LastPage != FirstPage)
					sprintf(tp_extend, ".%d_%d",FirstPage,LastPage);
				else			/* if equal only use one page number */
					sprintf(tp_extend, ".%d",FirstPage);
				strcat(tpname,tp_extend);
			}
			else if (BookPrint)
			{
				if (LastParentIndex > ParentIndex)
					sprintf(tp_extend, ".u%d_u%d",ParentIndex,LastParentIndex);
				else
					sprintf(tp_extend, ".u%d",ParentIndex);
				strcat(tpname,tp_extend);
			}
		}
		if (EpsFlag)
		   strcpy (logname, p_path(TreeName, EPS_FILE, SubDirName, tpname));
		else if (BookPrint)
		   strcpy (logname, p_path(TreeName, OUTPUT_FILE, ParentDirName, tpname));
		else
		   strcpy (logname, p_path(TreeName, OUTPUT_FILE, SubDirName, tpname));
		strcpy (prologname, logname);
		strcpy (trailername, logname);

		strcat (logname, ".log");
		p_LogFd = fopen (logname, "w+");

		strcat (prologname, ".plog");
		PrologName = fopen(prologname, "w+");

		strcat (trailername,".ptrl");
		TrailerName = fopen(trailername, "w+");

		new_Psf_path_ptr = p_path(TreeName, USERDATA, UserdataPath,
								  PsfTableName);
		if ( strcmp( Psf_path_name, new_Psf_path_ptr) )
		{						/* no match, need a new name and Psftable */
			strcpy(Psf_path_name, new_Psf_path_ptr);
			if ( !Psftable_load_with_name(TreeName, SubDirName,
										  PsfTableName) )
			{					/* bad psftable load, abort */
				p_info(PI_ELOG, "Unable to open file '%s'",Psf_path_name);
				exit(101);
			}
			PsfNameIndex = 0;
			PsfCodeIndex = 0;
			HelveticaFontNumber = 0;
			for (i=0; i<MaxPentaFont; i++)
			{					/* find Helvetica */
				if ( PentaToPsf[i].name)
				{
					if ( !strcmp(PentaToPsf[i].name, "Helvetica") )
						HelveticaFontNumber  = i;
				}
			}
		}						/* psftable loaded */

		if (HdrPNamPrt)
			get_prt_name();  /*  Bug 367p get actual printer name from .psh file */
		else
			PrtNam[0] = 0;
	
		getpgsize();			/* Parse header lines */

		if(lnumbers & 1) {		/* Print line numbers?  */
			if (!FileType) {	/* In galley mode:  */
				OffL += 40;		/* =15pts space at left + 25 for big line number  */
				if (LineStats)
					OffL += 30;	/* =5pts at left + 25 line# + 40 for band & ls  */
			}
			else				/* In page mode:  */
				OffL += 10;		/* just 10 pts of room.  */
		}
/***********************************************************************
 **  Call the PostScript mainline processor.			      **
 ***********************************************************************/
		
		psmain();
		
/***********************************************************************
 **  Wrap it all up.						      **
 ***********************************************************************/
		if (EpsFlag)
		   strcpy (logname, p_path(TreeName, EPS_FILE, SubDirName, tpname));
		else if (BookPrint)
		   strcpy (logname, p_path(TreeName, OUTPUT_FILE, ParentDirName, tpname));
		else
		   strcpy (logname, p_path(TreeName, OUTPUT_FILE, SubDirName, tpname));
		if (PrinterName[0])
		{						/* output to the printer queue */
			fflush (p_LogFd);
			if( !GraphicsPresentFlag)
				result = 0;
			else
				result = 1;

			sprintf(shell_msg,"/usr/local/bin/%s.psh %s %d %d %s %s %d %d %d %d",
                PrinterName, logname, result, FileType, TreeName,
				SubDirName, FirstPage, LastPage, HNJ_LockFailureFlag,
				DistillFlag);
			system(shell_msg);
		}

		/* If user asked for "Distill to PDF" (and there's no H&J lock), then
			test to find the newest .tp, .eps or .ps in the .drawer, and see
			if it's newer than any .pdf file there.
			If so, this means the printer script did NOT create a .pdf, so
			distill the .tp to .pdf using ghostscript's ps2pdf script here.
		*/
		if (DistillFlag && !HNJ_LockFailureFlag)
		{
			struct stat tpstat, psstat, pdfstat;
			int tpind, psind, pdfind, buildpdf;
			char *dotptr;

			strcpy (prologname, logname);
			strcat (prologname, ".pdf");	/* Get stat of *.tp.pdf file:  */
			pdfind = stat(prologname, &pdfstat);
			if (pdfind)						/* If that doesn't exit, alt try:  */
			{
				strcpy (prologname, logname);
				dotptr = strrchr (prologname, '.');
				*dotptr = 0;				/* Strip whatever suffix we have,  */
				strcat (prologname, ".pdf");/*  replace with .pdf.  */
											/* Get stat of that pdf file:  */
				pdfind = stat(prologname, &pdfstat);
			}

			tpind = stat(logname, &tpstat);	/* Get stat of .tp (or .eps) file  */
			psind = 1;						/* (assume unused)  */
			if (!EpsFlag)					/* If we started with .tp file,  */
			{								/*  also get stat of .ps file:  */
				strcpy (prologname, logname);
				strcpy (&prologname[strlen(logname)-3], ".ps");
				psind = stat(prologname, &psstat);
			}

			buildpdf = 0;				/* Assume no need to build a .pdf  */
			if (!tpind &&				/* If .tp (or .eps) exists, and  */
				(psind ||				/*  .ps does not, or .tp is newer, then:  */
				 tpstat.st_mtime > psstat.st_mtime))
			{
				strcpy (prologname, logname);	/* (use .tp name)  */
										/*  if there's no .pdf or it's older,  */
				if (pdfind || tpstat.st_mtime > pdfstat.st_mtime)
					buildpdf = 1;		/*  set flag to distill the .tp file.  */
			}
			else 
			if (!psind &&				/* If .ps exists, and  */
				(tpind ||				/*  .tp does not, or .ps is newer, then:  */
				 tpstat.st_mtime <= psstat.st_mtime))
			{
				strcpy (logname, prologname);	/* (use .ps name)  */
										/*  if there's no .pdf or it's older,  */
				if (pdfind || psstat.st_mtime > pdfstat.st_mtime)
					buildpdf = 1;		/*  set flag to distill the .ps file.  */
			}
			else						/* Neither exist, forget it.   */
				;

			if (buildpdf)				/* If we decided to distill a .pdf, then  */
			{							/* build basename by stripping suffix,  */
				*(dotptr = strrchr (prologname, '.')) = 0;
										/* build little script calling ps2pdf,  */
			  	sprintf (shell_msg,
				"PATH=/usr/local/bin/ghostscript:$PATH; export PATH; ps2pdf  %s %s.pdf",
				logname, prologname);

				p_info(PI_INFO, "Executing distillation to PDF from Postprint\n");
				system(shell_msg);		/* and send it off, wait for done.  */
			}
		}					/* end if (DistillFlag && !HNJ_LockFailureFlag)  */

		p_free(m_fprintf_buff);
		m_fprintf_size = 0;
		if(!one_shot)
		{
			if((num_read =write(pipe_out, "0", 2))== -1)
			{
				p_info(PI_ERROR, "write to pipe failed\n");
				exit(1);
			}
			else
				p_info(PI_INFO, "Post completed for %s \n",tpname);
		}
		else
		{
			if (!source_pfd)
			{
				p_info(PI_INFO, "Post completed for %s, program exit. \n",JobName);
				break;
			}
			else
				p_info(PI_INFO, "Post completed for %s \n",JobName);
		}
    }							/* end of for(;;) */
    exit(ExitError);
}								/* end of PSMAIN */
void init_color(void)
{
#define CLRBUFSZ 256
    char clr_parse_buff[CLRBUFSZ];
    char clr_parse_buff_temp[CLRBUFSZ];
	char temp_name[128], temp_chap_dir[128];
	char chap_tree[64];
	char chap_dir[64];
	char *result_ptr;
	float temp;
    int length, i;
	int plate_name_input;
	int temp_plate;
	int screen_found_flag;
	int plate_zero_stored = 0;
    int endflag = 0;
	int parent_flag = 0;

	memset((char *)&plate_nm[0].name[0], 0, sizeof(struct plate_name) * 33);
    clear_vlist();              /* clear list of reverses */
    clear_color_list();			/* clear the non-standard colors */
	strcpy(clr_parse_buff, SubDirName);
	if ((result_ptr = strrchr(clr_parse_buff, '.')) != NULL)
		*result_ptr = '\0';
	colorfd = p_get_table1(TreeName, clr_parse_buff, ColorTableName,
						  default_color_name);
	if (colorfd <= 0)
	{							/* parent */
		if(lc_parent(TreeName, SubDirName, temp_name))
		{
			parent_flag++;
			p_parent_path(TreeName, clr_parse_buff, temp_name, chap_tree,
						  chap_dir);
			strcpy(temp_chap_dir, chap_dir);
			if ((result_ptr = strrchr(temp_chap_dir, '.')) != NULL)
				*result_ptr = '\0';
			colorfd = p_get_table1(chap_tree, temp_chap_dir, ColorTableName,
								   default_color_name);
		}
	}
	if (colorfd <= 0)			/* Tree/tables and .default/tables */
		colorfd = p_get_table2(TreeName, clr_parse_buff, ColorTableName,
						  default_color_name);
    if ( (colorfd <= 0) && strcmp(ColorTableName, "colortable") )
	{							/* try using colortable.ct */
		strcpy (clr_parse_buff_temp, "colortable");
		colorfd = p_get_table1(TreeName, clr_parse_buff, clr_parse_buff_temp,
							   default_color_name);
		if (colorfd <= 0)
		{
			if ( parent_flag)
				colorfd = p_get_table1(chap_tree, temp_chap_dir,
									   clr_parse_buff_temp,
									   default_color_name);
		}
		if (colorfd <= 0)		/* Tree/tables and .default/tables */
			colorfd = p_get_table2(TreeName, clr_parse_buff,
								   clr_parse_buff_temp, default_color_name);
		if (colorfd > 0)
			p_info(PI_WLOG, "Color table %s does not exist, using colortable.ct\n",
				   ColorTableName);
	}
    if ( colorfd <= 0 )
	{							/* no colortable, use black and white */
		colorfd = 0;
		store_white_and_black();
		sprintf(default_color_name, "Penta/%s/%s/???.ct",
				DEFAULT_DIR, TABLES_DIR);
		p_info(PI_WLOG, "No color table exists, only colors 0 (white) and 1 (black) are valid.\n");
		return;
	}
    spot_pass = 1;				/* 1st pass */
	cur_color_id = -1;
    while ( !endflag  )
    {
		memset(clr_parse_buff, 0, CLRBUFSZ);
		if ( p_fgets(clr_parse_buff, CLRBUFSZ,
					 colorfd) != clr_parse_buff)
			endflag++;			/* out of data */
		if ( (length = strlen (clr_parse_buff)) < 5 )
			continue;			/* not long enough for a valid string */
								/* OTOH, err if line fills buff completely: */
		if ( length >= (CLRBUFSZ-1) ) {
			p_info(PI_WLOG, "WARNING: Color table '%s' line too long, ignored after %d:\n '%s'\n",
				ColorTableName, CLRBUFSZ, clr_parse_buff);
			do {				/* Flush until EOL:  */
				*clr_parse_buff_temp = 0;
				if (p_fgets(clr_parse_buff_temp, CLRBUFSZ, colorfd)
					!= clr_parse_buff_temp) endflag++; /* out of data */
 			} while (strlen(clr_parse_buff_temp) >= (CLRBUFSZ-1));
		}
		if ( (clr_parse_buff[0] == '%') || (clr_parse_buff[0] == '!') ||
			 (clr_parse_buff[0] == '#') )
			continue;			/* skip command lines */
		strcpy (clr_parse_buff_temp, clr_parse_buff);
		if ( !strncmp(clr_parse_buff, "AI_Sep", 6) )
			continue;			/* ignore Separation Key Words */
		if ( !strncmp(clr_parse_buff, "CD_Sep", 6) )
			continue;			/* ignore Separation Key Words */
		if ( !strncmp(clr_parse_buff, "G_FG_Color", 10) )
			continue;			/* ignore default graphic color Key Words */
		if ( !strncmp(clr_parse_buff, "G_BG_Color", 10) )
			continue;			/* ignore default graphic color Key Words */
		if ( !strncmp(clr_parse_buff, "G_BW_Overprint", 14) )
			continue;			/* ignore default graphic color Key Words */
		if ( !strncmp(clr_parse_buff, "Plate_Name", 10) )
		{						/* Save Plate Name */
			plate_name_input = atoi((char *)&clr_parse_buff[11]);
			if ( (plate_name_input < 0) || (plate_name_input > 32))
				continue;		/* no number */
			memset((char *)&plate_nm[plate_name_input].name[0],
				   0, sizeof(struct plate_name));
/*
			p=(strstr((char *)&clr_parse_buff[11],"-"));
			p++;
			strncpy((char *)&plate_nm[plate_name_input], p, 30);
*/
			strncpy((char *)&plate_nm[plate_name_input],
					(char *)&clr_parse_buff[11], 30);
			plate_nm[plate_name_input].name[30] = 0;
			if ( (result_ptr = strrchr((char *)&plate_nm[plate_name_input],
									   '\n') ) )
				*result_ptr = 0; /* null out the new line */
			continue;
		}
		msg_parse(clr_parse_buff_temp, length, CLR_KEYWORD_COUNT, clr_msg);
		for (i=0; i<CLR_KEYWORD_COUNT; i++)
		{
		if ( clr_msg[i].answer[0] && (i != 72))
				break;			/* got an answer */
		}

		if (i >= 11)
			continue;			/* no valid message */
		if (i == 0)
		{						/* got a color id */
			if ( (cur_color_id > 0)  && !plate_zero_stored)
			{
				cur_plate = 0;
				store_color(0);	/* store plate zero for prev color */
			}
			plate_zero_stored = 0;
			cur_plate = -1;
			cur_screen = 72;
			cur_pct = 100;
			cur_tint = 100;
			strcpy(cur_shape, "dot");
			cur_angle = 45.;
			cur_reverse = 0;
			cur_cmyk_flag = 0;
			strcpy(cur_op, "false");
			strcpy(cur_color_name,"");
			strcpy(cur_type,"process");
			for (i=0; i<4; i++)
				cur_cmyk[i] = 0.0;
			cur_color_id = atoi(clr_msg[0].answer);
			if (cur_color_id < 0)
			{
				cur_color_id = 0;
				p_info(PI_ELOG, "ERROR - Negative color '%s' is invalid.\n",
					   clr_msg[0].answer);
				continue;
			}
			for (i=7; i<11; i++)
			{					/* look for CMYK values */
				if ( clr_msg[i].answer[0])
				{
					temp = atof(clr_msg[i].answer);
					if ( (temp < 0.0 ) || (temp > 1.0) )
						p_info(PI_ELOG, "ERROR - CMYK value on line '%s' does not lie between 0 and 1.0\n",clr_parse_buff);
					else
					{
#if LPMfloat
						if(LPMK[LPM_ColorMaster])
#else
						if((LPMK & LPM_ColorMaster))
#endif
						{
							cur_cmyk[i-7] = temp;
							cur_cmyk_flag = 1;
						}
					}
				}					
			}					/* end for(i=7;i<11;i++) */
			if ( clr_msg[6].answer[0])
			{					/* got a Tint */
				cur_tint = atoi(clr_msg[6].answer);
				if ( (cur_tint <= 0) || (cur_tint > 100) )
				{
					cur_tint = 100;
					p_info(PI_ELOG, "ERROR - color Tint must be above 0, below 100;\n");
					p_info(PI_ELOG, "     '%s' is not valid. \n",clr_msg[6].answer);
				}		     
			}
			if ( clr_msg[45].answer[0]) /* got Overprint */
			{
				strncpy(cur_op, clr_msg[45].answer, 5);
				*(cur_op+5) = 0;
				if ( strcmp(cur_op, "true") && strcmp(cur_op, "false"))
				{
					p_info(PI_ELOG, "ERROR - color op '%s' must be true or false, will use true.\n", cur_op);
					strcpy(cur_op, "true");
				}
			}
			else
				strcpy(cur_op,"false");

			if ( clr_msg[46].answer[0]) {
				strcpy(cur_type,(clr_msg[46].answer));
			} else
				strcpy(cur_type,"process");

			if ( clr_msg[47].answer[0]) {
				if (strlen(clr_msg[47].answer) > 31) {
					p_info(PI_ELOG, "ERROR - color name '%s' exceeds 31 characters.\n", clr_msg[47].answer);
					continue;
				}
				strcpy (cur_color_name,(clr_msg[47].answer));
			} else
				strcpy(cur_color_name,"");
			continue;
		}						/* end got a color id */
		if ( cur_color_id < 0)
		{
			p_info(PI_ELOG, "ERROR - color id missing before line '%s' \n",clr_parse_buff);
			continue;
		}
		if (i == 1)
		{						/* Plate being defined */
			cur_plate = atoi(clr_msg[1].answer);
			if ( (cur_plate < 0) || (cur_plate >= MAX_CLRS) )
			{
				p_info(PI_ELOG, "ERROR - Color '%d', Plate '%d' less than 0 or greater than 31 \n",cur_color_id,cur_plate);
				p_info(PI_ELOG, "     Line in error reads '%s'\n",clr_parse_buff);
				cur_plate = -1;
				continue;
			}
			continue;
		}						/* end define Plate */
		if ( cur_plate < 0)
		{
			p_info(PI_ELOG, "ERROR - color Plate is missing before line '%s' \n",
				   clr_parse_buff);
			continue;
		}
		screen_found_flag = 0;
		switch (i)
		{
		  case 2:				/* Shape */
			if ( clr_msg[2].answer[0])
				strcpy(cur_shape, clr_msg[2].answer);
			else
			{
				p_info(PI_ELOG, "ERROR - Shape '%s' is not supported.\n",
					   clr_msg[2].answer);
				strcpy(cur_shape, "dot");
			}
				
		  case 3:				/* Angle */
			if ( clr_msg[3].answer[0])
				cur_angle = atof(clr_msg[3].answer); /* got an Angle */
			
		  case 4:				/* Screen */
			if ( clr_msg[4].answer[0])
			{					/* got a Screen */
				cur_screen = atoi(clr_msg[4].answer);
				if (cur_screen < 0)
					cur_screen = 6;
			}
				
		  case 5:				/* Percent */
			if ( clr_msg[5].answer[0])
			{					/* got a Percent */
				cur_pct = atof(clr_msg[5].answer);
				if ( (cur_pct < 0.0) || (cur_pct > 100.) )
				{
					cur_pct = 0.0;
					p_info(PI_ELOG, "ERROR - color Percent must be between 0 and 100\n");
					p_info(PI_ELOG, "     '%s' is not valid. \n",clr_msg[5].answer);
				}		     
			}
			screen_found_flag++; /* set if any case 2 thru 6 found */
			break;

		  default:
			continue;
			
		}					/* end switch (i) */
		if (cur_plate && !plate_zero_stored && screen_found_flag)
		{					/* store Plate 0 first */
			temp_plate = cur_plate;
			cur_plate = 0;
			store_color(0);
			cur_plate = temp_plate;
		}
		if (screen_found_flag)
		{
			store_color(1);
			plate_zero_stored++;
		}
    }							/* end while( !endflag ) */
    p_close(colorfd);
	store_white_and_black();
	cur_cmyk_flag = 0;
	cur_tint = 100;
}								/* end of init_color */
/***********************************************************************
 **  PostScript mainline processor.				      **
 ***********************************************************************/
static void psmain(void)
{
    int color_done;			/* done doing colors */
	int i;
	
	ini_JOB();					/* init job stuff		*/
    ini_PAGE();					/* init %%Page: comment state */
	Fofd = 0;
    GraphicsPresentFlag = 0;
    NoFont = 0;
	width_open(); /* Open WIDTH for H&Js char-width round-off errors*/
	FontBase = 1000;
#ifdef TRACE
    if(debugger_trace)
		p_info(PI_TRACE, "Starting job:%s\n",JobName);
#endif
    cc_hit = 0;
	cc_mask = (1 & Plates); /* hit nothing, set all black */
	if ( !cc_mask) 
		m_fopen(tpname, "w+", 1); /* delete prev version of .tp */
    spot_pass = 1;				/* 1st pass */
    color_done = 0;				/* not done yet */
	PageRotationAngle = 0;
	frame_fg_attribute = 0;		/* default is opaque */
	prologue_output_flag = 0;
	PageNo1 = 1;
	underscore_min = 10;
	overflow_page_buff_count = 0;
	memset ( (char *)overflow_page_buff, 0, sizeof (overflow_page_buff) );
	ExitError = 0;
	HNJ_LockFailureFlag = 0;
    while(color_done != 1 )		/* until we get all colors */
    {
		FootnoteFrameFlag = 0;
		BlackPaint_cc_mask = cc_mask;
		PaintOnPage = 0;
		blend_flag = 0;
		BlendAngle = 0;
		BlendEndColor = 0;
		in_overflow = 0;
		was_overflow = 0;
		Linesub = -1;			/* clear text/escapement buffer	*/
		flagGlyph = 0;
		*GlyphName = 0;
		for(i=0; i<1999; i++)
		{
			Line[i] = 0;
			Kspace[i] = 0;
		}
		for(i=0; i<40; i++)
			bf_kmd80[i].active_flag = 0;
		fowrd =  256;
		Xmark =  0;
		y_max =  0;
		Oldfont = -1;
		Holdfont =  0;
		usw = 0;
		StrikeThruRuleStartFlag = 0;
		FlashOn = 1;
		CurrentFrame = 0;
		CurrentEle = 0;
		memset( (char *)&fo_line_def.FoStatusLength, 0, sizeof(LDEF) );
		DontPaintFlag = fo_line_def.MiscLineFlags & 0x10;
		not_lnum = 1;			/* Default: Put text font, not line-num font*/
		last_lnum = 0;
		jbl = 0;
		repeatno = 0;
		Obdegree = 0;
		Old_ob = 0;
		Hold_ob = 0;
		Holdss = 0;
		Holdps = 0;
		Oldss = 0;
		Oldps = 0;
		Ktabmode = 0;
		psend = 0;
		WidthOfNumeric = 0;
		memset ( page_number, 0, sizeof(page_number) );
		CurrentLineBcEc = 0;
		PrevLineBcEc = 0;
		BcEcExtraLeadNeeded = 0;
		BcEcExtraLead = 0;
		LastLinemaxErr = 0;
		cc_hit &= (Plates & ~1); /* only use plates to be output */
#ifdef TRACE
		if(debugger_trace)
		{
			p_info(PI_TRACE, "spot color pass %d, cc_mask: %lo , cc_hit: %lo\n",
				   spot_pass, cc_mask, cc_hit);
			p_info(PI_TRACE, "processing Tree: '%s', Dir: '%s',file: '%s', type= %d\n",
				   TreeName, SubDirName, JobName, FileType);
		}
#endif
		switch(FileType)
		{
		  case 0:				/* Galley output */
			if (spot_pass != 2)
				cc_hit = 0;
			if((err = dtext()) )
				error("processing FO file, err = ",JobName,err);
			if( (cc_hit < 2) ||	/* picked up no color(s) */
			   (spot_pass != 1) || /* or on second pass thru file */
				( !KeyOutputType) )	/* or composite */
				color_done = 1;	/* we are done */
			else
			{
				spot_pass = 2;	/* mark as 2nd pass thru file */
				cc_hit &= (Plates & ~1); /* mask off black */
				cc_mask = 0;	/* not the black we start with */
				galley_count = 0;
				MasterOutputSwitch = 1;
				if(Fofd)		/* if still open */
					foread(1);	/* rewind open FO file */
			}
			break;
			
		  case 1:				/* DesignMaster */
			if((err = dxy()) )
				p_info(PI_ELOG, "ERROR --processing Tree: '%s', Dir: '%s', Unit: %s\n",
					   TreeName,SubDirName,JobName);
			color_done = 1;		/* color loop inside dxy */
			break;
		}						/* end switch(FileType) */
		m_close(-1);			/* close all output */
    }							/* end while(color_done!=1) */
    if (wdfd)
    {
		p_close (wdfd);
		wdfd = 0;
    }
    if (Fofd)
    {
		p_close(Fofd);
		Fofd = 0;
		FoName[0] = 0;
    }
   if (TrailerName) {
		fclose(TrailerName);
		TrailerName = NULL;
    }
    if (PrologName)
    {
		fclose(PrologName);
		PrologName = NULL;

		if (EpsFlag)
		   strcpy (logname, p_path(TreeName, EPS_FILE, SubDirName, tpname));
		else if (BookPrint)
		   strcpy (logname, p_path(TreeName, OUTPUT_FILE, ParentDirName, tpname));
		else
		   strcpy (logname, p_path(TreeName, OUTPUT_FILE, SubDirName, tpname));

	  	sprintf(shell_msg,"cat %s >> %s \n mv %s %s \n cat %s >> %s \n mv %s %s",
			prologname, trailername,
			trailername, prologname,
			logname, prologname,
			prologname, logname);
		system(shell_msg);
    }
#ifdef TRACE
    if(debugger_trace)
		p_info(PI_TRACE, "Finished job, Tree: '%s', Dir: '%s', Name: '%s'.\n",
			   TreeName,SubDirName,JobName);
#endif
}
Exemple #22
0
/* ------------------------------------------------------------------------- */
int tx_zmodem(s_protinfo *pi, bool caller)
{
	int   startblk  = 64;  /* Initial Zmodem block size                  */
	int   minblk    = 64;  /* Minimal Z-protocol block size              */
	int   maxblk    = 1024;/* Maximal Z-protocol block size              */
	int   blocklen  = 0;   /* Length of transmitted blocks               */
	int   goodblk   = 0;   /* How many blocks we sent w/o ZRPOS'tion :)  */
	int   txwindow  = 0;   /* Tranmitter window size (0 means streaming) */
	int   newcnt    = 0;   /* Count free bytes in receiver's buffer      */
	int   rxbuflen  = 0;   /* Receiver's max buffer length               */
	int   rxlastpos = 0;   /* Receiver's last reported offset            */
	int   beenhere  = 0;   /* How many times we've been ZRPOS'd same place */
	long  bytescnt  = 0;   /* Received bytes(current offset)             */
	long  lastsync  = 0;   /* Last offset to which we got a ZRPOS        */
	char  zconv     = 0;   /* Local ZMODEM file conversion request       */
	char  zmanag    = 0;   /* Local ZMODEM file management request       */
	char  ztrans    = 0;   /* Local ZMODEM file translation request      */
	char  zexten    = 0;   /* Local ZMODEM file extended options         */
	char *txbuf     = NULL;/* Buffer with ZMAXBLOCKLEN size              */
	int   zrinitcnt = 0;   /* Count received ZRINITs                     */
	int   rxflags1  = 0;
	int   rxflags2  = 0;
	int   txtries   = 0;
	int   junkcnt   = 0;
	int   initacked = 0;   /* TRUE when at least one ZRQINIT was sent    */
	                       /* after first ZRINIT was received            */
	int   rc        = 0;   /* Our return code                            */
	int   dtype, n;
	int   ftype;
	char  c, *p;
	long unsigned crc32;
	enum  ztxstates txstate;
	time_t deadtimer;
	
	log("start %s send", Protocols[state.handshake->protocol]);
	DEB((D_PROT, "start %s send", Protocols[state.handshake->protocol]));
	
	/* Set time transfer started at */
	if( pi->start_time == 0 )
		pi->start_time = time(NULL);
	
	txbuf      = (char *)xmalloc(ZMAXBLOCKLEN+1);
	zconv      = ZCBIN;
	maxblk     = (state.handshake->protocol == PROT_ZMODEM) ? 1024 : 8192;
	
	/* Set initial block size (default is 128b) */
	if( (startblk = conf_number(cf_zmodem_start_block_size)) > 0 )
	{
		if( startblk%64 || startblk > maxblk || startblk < 64 )
			startblk = 256;
	} else 
		startblk = 256;
	
	blocklen  = startblk;
	txwindow  = conf_number(cf_zmodem_tx_window);
	Z_Rxwait  = ZWAITTIME;
	Z_Rxtout  = ZRXTIMEOUT;
	txstate   = ZTX_START;

	timer_set(&deadtimer, ZDEADTIMER);
	
	setalarm(Z_Rxtout);
	
	/*
	 * At zmodem batches send empty netmail packet
	 * if no real outgoing traffic available
	 */
	if( !pi->send_left_size && conf_boolean(cf_zmodem_send_dummy_pkt) )
		zmodem_add_empty_packet(pi);
	
	while(1)
	{
		if( timer_expired(deadtimer) )
		{
			log("brain dead! (abort)");
			gotoexit(PRC_LOCALABORTED);
		}
		
		if( txstate == ZTX_RQINIT || txstate == ZTX_FINFO
		 || txstate == ZTX_EOF    || txstate == ZTX_FIN )
		{
#ifdef DEBUG
			if( txtries ) DEB((D_PROT, "tx_zmodem: try #%d", txtries));
#endif			
			if( ++txtries > ZMAXTRIES )
			{
				log("out of tries");
				gotoexit(PRC_LOCALABORTED);
			}
		}
		
		switch(txstate) {
		case ZTX_START:
			DEB((D_PROT, "tx_zmodem: entering state ZTX_START"));
			if( PUTSTR("rz\r") < 0 )
				gotoexit(PRC_ERROR);
			txtries = 0;
			txstate = ZTX_RQINIT;
			break;
			
		case ZTX_RQINIT:
			DEB((D_PROT, "tx_zmodem: entering state ZTX_RQINIT"));
			stohdr(Z_Txhdr, 0L);
			if( zshhdr(ZRQINIT, Z_Txhdr) < 0 )
				gotoexit(PRC_ERROR);
			setalarm(Z_Rxtout);
			txstate = ZTX_RQINITACK;
			break;
			
		case ZTX_NEXTFILE:
			DEB((D_PROT, "tx_zmodem: entering state ZTX_NEXTFILE"));
			if (pi->send) p_tx_fclose(pi);
			txtries = 0;
			txstate = p_tx_fopen(pi, NULL) ? ZTX_FIN : ZTX_FINFO;
			log("nextfile next state: %d", txstate);
			break;

		case ZTX_FINFO:
			DEB((D_PROT, "tx_zmodem: entering state ZTX_FINFO"));
			
			zrinitcnt = 0;
			
			strnxcpy(txbuf, pi->send->net_name, ZMAXFNAME);
			
			p = txbuf + strlen(txbuf) + 1; 
			sprintf(p, "%ld %lo %lo 0 %ld %ld",
				(long)pi->send->bytes_total, (long)pi->send->mod_time,
				(long)pi->send->mode, (long)pi->send_left_num,
				(long)pi->send_left_size);
			
			DEB((D_PROT, "tx_zmodem: send \"%s\\000%s\"", txbuf, p));
			
			Z_Txhdr[ZF0] = zconv;	/* file conversion request */
			Z_Txhdr[ZF1] = zmanag;  /* file management request */
			Z_Txhdr[ZF2] = ztrans;  /* file transport request  */
			Z_Txhdr[ZF3] = zexten;
			
			if( zsbhdr(ZFILE, Z_Txhdr) < 0 )
				gotoexit(PRC_ERROR);
			if( zsdata(txbuf, (p - txbuf) + strlen(p), ZCRCW, 0) < 0 )
				gotoexit(PRC_ERROR);
			
			setalarm(Z_Rxtout);
			txstate = ZTX_FINFOACK;
			break;
			
		case ZTX_STARTDATA:
			DEB((D_PROT, "tx_zmodem: entering state ZTX_STARTDATA"));
			
			newcnt   = rxbuflen;
			junkcnt  = 0;
			
			stohdr(Z_Txhdr, pi->send->bytes_sent);
			if( zsbhdr(ZDATA, Z_Txhdr) < 0 )
				gotoexit(PRC_ERROR);
			
			txstate = ZTX_DATA;
			break;
			
		case ZTX_DATA:
			DEB((D_PROT, "tx_zmodem: entering state ZTX_DATA"));
			
			timer_set(&deadtimer, ZDEADTIMER);
			setalarm(Z_Rxtout); /* Remove annoing timeouts! */
			
			if( (n = p_tx_readfile(txbuf, blocklen, pi)) < 0 )
			{
				/* error occured, remote wait for DATA */
				/* so send null ZCRCE data subpacket   */
				if( zsdata(txbuf, 0, ZCRCE, 0) < 0 )
					gotoexit(PRC_ERROR);
				txstate = ZTX_NEXTFILE;
				break;
			}
		
			if( pi->send->eofseen )
				dtype = ZCRCE;
			else if( junkcnt > 6 )
				dtype = ZCRCW;
			else if( bytescnt == lastsync )
				dtype = ZCRCW;
			else if( rxbuflen && (newcnt -= n) <= 0 )
				dtype = ZCRCW;
			else if( txwindow && (bytescnt - rxlastpos + n) >= txwindow )
				dtype = ZCRCQ;
			else
				dtype = ZCRCG;

			if( (rc = p_info(pi, 0)) )
				gotoexit(rc);
			
			if( zsdata(txbuf, n, dtype, pi->send->bytes_sent) < 0 )
				gotoexit(PRC_ERROR);
			
			if( ++goodblk > 5 && blocklen*2 <= maxblk )
			{
				goodblk = 0;
				blocklen *= 2;
				DEB((D_PROT, "tx_zmodem: new blocklen = %ld byte(s)", blocklen));
			}
			
			bytescnt = pi->send->bytes_sent += n;
			
			if( dtype == ZCRCW )
			{
				junkcnt = 0;
				setalarm(Z_Rxtout);
				txstate = ZTX_CRCWACK;
				break;
			}
			else if( dtype == ZCRCQ )
			{
				junkcnt = 0;
				setalarm(Z_Rxtout);
				txstate = ZTX_CRCQACK;
				break;
			}
			else if( dtype == ZCRCE )
			{
				txtries = 0;
				txstate = ZTX_EOF;
				break;
			}
			
			if( CHARWAIT(0) )
			{
				while( (rc = GETCHAR(1)) != ZTIMER )
				{
					if( rc < 0 )
					{
						gotoexit(PRC_ERROR);
					}
					else if( rc == CAN || rc == ZPAD )
					{
						DEB((D_PROT, "tx_zmodem: got ZPAD or CAN!"));
						setalarm(Z_Rxtout);
						txstate = ZTX_READCHECK;
						break;
					}
					else if( rc == XOFF || rc == (XOFF|0200) )
					{
						DEB((D_PROT, "tx_zmodem: got XOFF"));
						if( GETCHAR(5) < 0 )
							gotoexit(PRC_ERROR);
						break;
					}
					else if( rc == XON  || rc == (XON|0200) )
					{
						DEB((D_PROT, "tx_zmodem: got XON"));
					}
					else
					{
						junkcnt++;
						DEB((D_PROT, "tx_zmodem: got JUNK = 0x%x (junkcnt = %d)",
							rc, junkcnt));
					}
				} /* end of while( rc != ZTIMER ) */
			} /* end of if( CHARWAIT(0) ) */
			break;
		
		case ZTX_EOF:
			DEB((D_PROT, "tx_zmodem: entering state ZTX_EOF"));
			
			stohdr(Z_Txhdr, pi->send->bytes_sent);
			if( zsbhdr(ZEOF, Z_Txhdr) < 0 )
				gotoexit(PRC_ERROR);
			
			setalarm(Z_Rxtout);
			txstate = ZTX_EOFACK;
			break;
			
		case ZTX_FIN:
			DEB((D_PROT, "tx_zmodem: entering state ZTX_FIN"));
			
			stohdr(Z_Txhdr, 0L);
			if( zshhdr(ZFIN, Z_Txhdr) < 0 )
				gotoexit(PRC_ERROR);
			
			setalarm(Z_Rxtout);
			txstate = ZTX_FINACK;
			break;
			
		default:
			/* Ignore them all */
			break;
		} /* end of switch(txstate) */
	
		if( txstate != ZTX_START  && txstate != ZTX_RQINIT
		 && txstate != ZTX_FINFO  && txstate != ZTX_DATA
		 && txstate != ZTX_EOF    && txstate != ZTX_FIN )
		{
			switch( ftype = zgethdr(Z_Rxhdr) ) {
			case ZCAN:
				gotoexit(PRC_REMOTEABORTED);
				break;
				
			case ZHANGUP:
			case ZEXIT:
				gotoexit(PRC_ERROR);
				break;
				
			case ZTIMER:
				log("time out");
				
				if( txstate == ZTX_READCHECK )
					zsdata(txbuf, 0, ZCRCE, 0);
				
				switch(txstate) {
				case ZTX_RQINITACK: txstate = ZTX_RQINIT;    break;
				case ZTX_FINFOACK:  txstate = ZTX_FINFO;     break;
				case ZTX_READCHECK: txstate = ZTX_STARTDATA; break;
				case ZTX_CRCWACK:   txstate = ZTX_STARTDATA; break;
				case ZTX_CRCQACK:   txstate = ZTX_STARTDATA; break;
				case ZTX_EOFACK:    txstate = ZTX_EOF;       break;
				case ZTX_FINACK:    txstate = ZTX_FIN;       break;
				default:            break;
				}
				break;
				
			case ZERROR:
			case ZCRCERR:
				/* NAK them all! */
				stohdr(Z_Txhdr, 0L);
				if( zshhdr(ZNAK, Z_Txhdr) < 0 )
					gotoexit(PRC_ERROR);
				break;
				
			case ZRQINIT:
				if( txstate == ZTX_RQINITACK )
				{
					if( Z_Rxhdr[0] == ZCOMMAND )
						break;
					
					stohdr(Z_Txhdr, 0L);
					if( zshhdr(ZNAK, Z_Txhdr) < 0 )
						gotoexit(PRC_ERROR);
					
					txstate = ZTX_RQINIT;
				}
				else if( txstate == ZTX_FINFOACK )
				{
					/* remote is sender - abort */
					log("zmodem: remote is sender");
					gotoexit(PRC_LOCALABORTED);
				}
				break;
				
			case ZRINIT:
				if( txstate == ZTX_RQINITACK )
				{
					if( initacked == 0 )
					{
						/* Be sure ack first ZRINIT */
						stohdr(Z_Txhdr, 0L);
						if( zshhdr(ZRQINIT, Z_Txhdr) < 0 )
							gotoexit(PRC_ERROR);
						initacked = 1;
					}
					
					/* Get receiver's options */
					rxflags1  = (0377 & Z_Rxhdr[ZF0]);
					rxflags2  = (0377 & Z_Rxhdr[ZF1]);
					Z_Txfcs32 = (rxflags1 & CANFC32);
					Z_Ctlesc |= (rxflags1 & TESCCTL);
					rxbuflen  = (0377 & Z_Rxhdr[ZP0]);
					rxbuflen += ((0377 & Z_Rxhdr[ZP1])<<8);
					
					/* No ZCRCQ if remote doesn't indicate */
					/* FDX ability                         */ 
					if( !(rxflags1 & CANFDX) )
						txwindow = 0;
				
					DEB((D_PROT, "tx_zmodem: Z_Txfcs32 = %d Z_Ctlesc = %d",
						Z_Txfcs32, Z_Ctlesc));
					DEB((D_PROT, "tx_zmodem: rxbuflen = %d blocklen = %d",
						rxbuflen, blocklen));
					DEB((D_PROT, "tx_zmodem: txwindow = %u",
						txwindow));
				
					txstate   = ZTX_NEXTFILE;
				}
				else if( txstate == ZTX_FINFOACK )
				{
					/* Possible they didn't see */
					/* our file information     */
					if( ++zrinitcnt > 2 )
						txstate = ZTX_FINFO;
				}
				else if( txstate == ZTX_READCHECK
				      || txstate == ZTX_CRCQACK
				      || txstate == ZTX_CRCWACK )
				{
					if( txstate == ZTX_READCHECK
					 || txstate == ZTX_CRCQACK )
						zsdata(txbuf, 0, ZCRCE, 0);
					
					/* Assume file normaly sent ? */
					log("assume file normaly sent");
					
					pi->send->status = FSTAT_SUCCESS;
					txstate = ZTX_NEXTFILE;
				}
				else if( txstate == ZTX_EOFACK )
				{
					/* ok, send next */
					pi->send->status = FSTAT_SUCCESS;
					txstate = ZTX_NEXTFILE;
				}
				else if( txstate == ZTX_FINACK )
				{
					/* Possible we should ignore  */
					/* first ZRINIT. Because they */
					/* didn't see our first ZFIN  */
					/* But I'm soo lazy .. :))    */
					txstate = ZTX_FIN;
				}
				break;
				
			case ZACK:
				if( txstate == ZTX_CRCWACK )
				{
					rxlastpos = Z_Rxpos;
					if( pi->send->bytes_sent == Z_Rxpos )
						txstate = ZTX_STARTDATA;
				}
				else if( txstate == ZTX_READCHECK
				      || txstate == ZTX_CRCQACK )
				{
					rxlastpos = Z_Rxpos;
					txstate   = ZTX_DATA;
				}
				break;
				
			case ZSKIP:
				if( txstate == ZTX_FINFOACK
				 || txstate == ZTX_READCHECK
				 || txstate == ZTX_CRCQACK
				 || txstate == ZTX_CRCWACK
				 || txstate == ZTX_EOFACK )
				{
					if( txstate == ZTX_READCHECK
					 || txstate == ZTX_CRCQACK )
						zsdata(txbuf, 0, ZCRCE, 0);
					
					if( txstate == ZTX_READCHECK )
						CLEAROUT();
					
					pi->send->status = FSTAT_SKIPPED;
					log("remote side skipped file");
					
					txstate = ZTX_NEXTFILE;
				}
				break;
				
			case ZFIN:
				/* BUG!BUG!BUG!BUG!BUG!BUG!BUG!BUG!BUG! */
				/* BUG!BUG!BUG!BUG!BUG!BUG!BUG!BUG!BUG! */
				log(" BUG!BUG!BUG!BUG!BUG!BUG!BUG!BUG!BUG! ");
				if( txstate == ZTX_FINACK )
				{
					if( PUTSTR("OO") == 0 )
						FLUSHOUT();
					gotoexit(PRC_NOERROR);
				}
				break;
				
			case ZRPOS:
				if( txstate == ZTX_FINFOACK
				 || txstate == ZTX_READCHECK
				 || txstate == ZTX_CRCQACK
				 || txstate == ZTX_CRCWACK
				 || txstate == ZTX_EOFACK )
				{
					rxlastpos = Z_Rxpos;
					
					/* Clear modem buffers */
					/* if( txstate != FINFOACK ) SENDBREAK(); */
					if( txstate == ZTX_READCHECK ) CLEAROUT();

					if( txstate == ZTX_READCHECK
					 || txstate == ZTX_CRCQACK )
					{
						if( zsdata(txbuf, 0, ZCRCE, 0) < 0 )
							gotoexit(PRC_ERROR);
					}
					
					/* Reset EOF flag! */
					pi->send->eofseen = FALSE;
					
					/* Check pos */
					if( (Z_Rxpos || txstate != ZTX_FINFOACK)
					 && p_tx_rewind(pi, Z_Rxpos) )
					{
						logerr("can't send file from requested position");
						/* Open next file for send */
						txstate = ZTX_NEXTFILE;
						break;
					}
					
					if( txstate == ZTX_FINFOACK )
					{
						if( Z_Rxpos )
						{
							log("resyncing at offset %d", Z_Rxpos);
							pi->send->bytes_skipped = Z_Rxpos;
						}
					}
					else if( txstate == ZTX_READCHECK
					      || txstate == ZTX_CRCWACK
					      || txstate == ZTX_CRCQACK )
					{
						goodblk = 0;
						if( lastsync >= Z_Rxpos && ++beenhere > 4 )
							if( blocklen > minblk )
							{
								blocklen /= 2;
								DEB((D_PROT, "tx_zmodem: falldown to %ld BlockLen", blocklen));
							}
					}
					
					lastsync = bytescnt = pi->send->bytes_sent = Z_Rxpos;
					
					if( txstate == ZTX_FINFOACK )
						--lastsync;
					
					txstate = ZTX_STARTDATA;
				}
				break;
				
			case ZNAK:
				switch(txstate) {
				case ZTX_RQINITACK: txstate = ZTX_RQINIT; break;
				case ZTX_FINFOACK:  txstate = ZTX_FINFO;  break;
				case ZTX_EOFACK:    txstate = ZTX_EOF;    break;
				case ZTX_FINACK:    txstate = ZTX_FIN;    break;
				default:            break;
				}
				break;
				
			case ZCRC:
				if( txstate == ZTX_FINFOACK )
				{
					log(" Send file's CRC-32 ");
					crc32 = 0xFFFFFFFFL;
					
					while( ((c = getc(pi->send->fp)) != EOF) && --Z_Rxpos )
						crc32 = updcrc32(c, crc32);
					
					crc32 = ~crc32;
					
					clearerr(pi->send->fp); /* Clear EOF */
					fseek(pi->send->fp, 0L, 0);
					
					stohdr(Z_Txhdr, crc32);
					if( zsbhdr(ZCRC, Z_Txhdr) < 0 )
						gotoexit(PRC_ERROR);
				}
				break;
				
			case ZCHALLENGE:
				if( txstate == ZTX_RQINITACK )
				{
					/* Echo receiver's challenge number */
					stohdr(Z_Txhdr, Z_Rxpos);
					if( zshhdr(ZACK, Z_Txhdr) < 0 )
						gotoexit(PRC_ERROR);
					txstate = ZTX_RQINIT;
				}
				break;
				
			case ZCOMMAND:
				if( txstate == ZTX_RQINITACK )
				{
					txstate = ZTX_RQINIT;
				}
				break;

			case ZABORT:
				log("remote requested for session abort");
				stohdr(Z_Txhdr, 0L);
				if( zshhdr(ZFIN, Z_Txhdr) < 0 )
					gotoexit(PRC_ERROR);
				gotoexit(PRC_REMOTEABORTED);
				break;
				
			case ZFERR:
				if( txstate == ZTX_FINFOACK
				 || txstate == ZTX_READCHECK
				 || txstate == ZTX_CRCWACK
				 || txstate == ZTX_CRCQACK
				 || txstate == ZTX_EOFACK )
				{
					if( txstate == ZTX_READCHECK
					 || txstate == ZTX_CRCQACK )
					{
						if( zsdata(txbuf, 0, ZCRCE, 0) < 0 )
							gotoexit(PRC_ERROR);
					}

					pi->send->status = FSTAT_REFUSED;
					log("remote side refused file");
					
					txstate = ZTX_NEXTFILE;
				}
				break;
				
			default:
				log("got unexpected frame %d", ftype);
				break;
			} /* end of switch(hdr) */
		} /* end of if */
	} /* end of while */
	
exit:
	DEB((D_PROT, "tx_zmodem: SEND exit = %d", rc));
	
	setalarm(0);
	
	if (pi->send) p_tx_fclose(pi);
	
	if( txbuf ) {
		free(txbuf);
		txbuf = NULL;
	}
	
	
	return(rc);
}
Exemple #23
0
int main (int argc, char **argv){
	int rank =0, size =0;
	int NX = 0;
	double *t = NULL;
	// this is an array we expect as a reference array
	double *t_ref = NULL;
	MPI_Comm comm = MPI_COMM_WORLD;
	diag_t diag = DIAG_OK;  // to store the diagnostic information
	struct test_info test_result = {TEST_PASSED, "1D_arr_global_noxml"};
	struct err_counts err = { 0, 0};
	struct adios_tsprt_opts adios_opts;

	GET_ENTRY_OPTIONS(adios_opts,  "Runs readers. It is recommended to run as many readers as writers.");

	// adios read initialization
	MPI_Init( &argc, &argv);
	MPI_Comm_rank (comm, &rank);

	// depending on the method
	SET_ERROR_IF_NOT_ZERO(adios_read_init_method(adios_opts.method, comm, adios_opts.adios_options), err.adios);
	RET_IF_ERROR(err.adios, rank);


	// I will be working with streams so the lock mode is necessary,
	// return immediately if the stream unavailable
	ADIOS_FILE *adios_handle = adios_read_open(FILE_NAME, adios_opts.method, comm, ADIOS_LOCKMODE_NONE, 0.0);
	if ( !adios_handle){
		p_error("Quitting ... (%d) %s\n", adios_errno, adios_errmsg());
		return DIAG_ERR;
	}

	// define portions of data how they will be read
	ADIOS_SELECTION *sel = NULL;
	ADIOS_VARINFO *avi = NULL;


	// for storing the variables
	char buf[STR_BUFFER_SIZE];

	int step = 0;

	// read how many processors wrote that array
	avi = adios_inq_var (adios_handle, "size");
	if (!avi){
		p_error("rank %d: Quitting ... (%d) %s\n", rank, adios_errno, adios_errmsg());
		diag = DIAG_ERR;
		goto close_adios;
	}
	size = *((int*)avi->value);
	adios_free_varinfo(avi);
	avi = NULL;

	// if I run the more readers than writers; just release
	// the excessive readers
	if (rank >= size){
		p_info("rank %d: I am an excessive rank. Nothing to read ...\n", rank);
		diag = DIAG_OK;
		goto close_adios;
	}

	// read the size of the array
	avi = adios_inq_var (adios_handle, "NX");
	if (!avi){
		p_error("rank %d: Quitting ... (%d) %s\n", rank, adios_errno, adios_errmsg());
		diag = DIAG_ERR;
		goto close_adios;
	}

	// I expect a scalar that will tell me the size of an array
	assert(0 == avi->ndim);
	assert(adios_integer == avi->type);
	NX = *((int*)avi->value);
	// I don't need that variable any more
	adios_free_varinfo(avi);
	assert(NX_DIM == NX);
	avi = NULL;


	// this will define the slice that we want to read; each rank should
	// read its own slice written by a corresponding writer rank
	uint64_t count[1] = { NX };
	uint64_t start[1] = { 0 };
	start[0] = rank*NX;

	sel = adios_selection_boundingbox(1,start, count);
	if( !sel ){
		p_error("rank %d: Quitting ... (%d) %s\n", rank, adios_errno, adios_errmsg());
		diag = DIAG_ERR;
		goto close_adios;
	}

	// make the reference array with reference values I expect to get
	t_ref = calloc(NX, sizeof(double));
	if (gen_1D_array(t_ref, NX, rank) == DIAG_ERR){
		p_error("Generating 1D array. Quitting ...\n");
		diag = DIAG_ERR;
		goto close_adios;
	}

	// allocate the memory for the actual array to be read
	t = calloc(NX, sizeof(double));

	if (adios_schedule_read(adios_handle, sel, "var_1d_array",0,1,t) != 0){
		p_error("rank %d: Quitting ...(%d) %s\n", rank, adios_errno, adios_errmsg());
		diag = DIAG_ERR;
		goto just_clean;
	}

	// not sure if this assumption is correct; difficult to find in the ADIOS sources
	if (adios_perform_reads(adios_handle, 1) != 0){
		p_error("rank %d: Quitting ...(%d) %s\n", rank, adios_errno, adios_errmsg());
		diag = DIAG_ERR;
		goto just_clean;
	}

	sprintf(buf, "Rank %d: var_1d_array: step %d: t: ", rank, step);

	int i = 0;
	for(i=0; i < NX; ++i){
		if( t[i] != t_ref[i] ){
			p_test_failed("%s: rank %d: for t[%d] (expected %.1f, got %.1f)\n", test_result.name, rank,  i, t_ref[i], t[i] );
			test_result.result = TEST_FAILED;
			break;
		}
	}

	if (TEST_PASSED == test_result.result)
		p_test_passed("%s: rank %d\n", test_result.name, rank);

just_clean:
	// clean everything
	adios_selection_delete(sel);
	sel = NULL;
	free(t);
	t = NULL;
	free(t_ref);
	t_ref = NULL;

close_adios:
	CLOSE_ADIOS_READER(adios_handle, adios_opts.method);

	if ((DIAG_OK == diag) && (TEST_PASSED == test_result.result)) {
		return 0;
	} else {
		return 1;
	}
}
void print_member(LLD item, int index)
{
	p_info(PI_TRACE, "Trace item %d -- Index: %d, filename: %s\n",
			  index, ((LC_MEMB_REC *)item)->index, 
			  ((LC_MEMB_REC *)item)->filename);
}
Exemple #25
0
void* handle_req(void* p)
{
    conn_t * pConn = (conn_t*)p;
    // Network state
	// FIXME cuda_bridge_request_t == cuda_packet_t == rpkt_t, this is rediculous
	strm_hdr_t *hdr         = NULL;
	rpkt_t *rpkts           = NULL; // array of cuda packets

        
        // CLOSE the listen connection
        //    conn_close(pConnListen);
        
        // Connection-related structures
        hdr = &pConn->strm.hdr;
        rpkts = pConn->strm.rpkts;   // an array of packets (MAX_REMOTE_BATCH_SIZE)
        // these are buffers for extra data transferred as
        pConn->pReqBuffer = NULL;
        pConn->pRspBuffer = NULL;
        
        while(1) {
            
            p_debug("------------------New RPC--------------------\n");
            
            memset(hdr, 0, sizeof(strm_hdr_t));
            memset(rpkts, 0, MAX_REMOTE_BATCH_SIZE * sizeof(rpkt_t));
            pConn->request_data_size = 0;
            pConn->response_data_size = 0;
            
            pConn->pReqBuffer = freeBuffer(pConn->pReqBuffer);
            pConn->pRspBuffer = freeBuffer(pConn->pRspBuffer);
            
            //recv the header describing the batch of remote requests
            if (1 != get(pConn, hdr, sizeof(strm_hdr_t))) {
                break;
            }
            p_debug(" received request header. Expecting  %d packets. And extra request buffer of data size %d\n",
                    hdr->num_cuda_pkts, hdr->data_size);
            
            if (hdr->num_cuda_pkts <= 0) {
                p_warn("Received header specifying zero packets, ignoring\n");
                continue;
            }
            
            // Receive the entire batch.
            // first the packets, then the extra data (reqbuf)
            //
            // let's assume that we have enough space. otherwise we have a problem
            // pConn allocates the buffers for incoming cuda packets
            // so we should be fine
            if(1 != get(pConn, rpkts, hdr->num_cuda_pkts * sizeof(rpkt_t))) {
                break;
            }
            p_info("Received %d packets, each of size of (%lu) bytes\n",
                   hdr->num_cuda_pkts, sizeof(rpkt_t));
            
            p_info( "Received method %s (method_id %d) from Thr_id: %lu.\n",
                   methodIdToString(rpkts[0].method_id), rpkts[0].method_id, rpkts[0].thr_id);
            
            // receiving the request buffer if any
            if(hdr->data_size > 0){
                p_info("Expecting data size/Buffer: %u, %d.\n",
                       hdr->data_size, pConn->request_data_size);
                // let's assume that the expected amount of data will fit into
                // the buffer we have (size of pConn->request_data_buffer
                
                // allocate the right amount of memory for the request buffer
                pConn->pReqBuffer = malloc(hdr->data_size);
                if( mallocCheck(pConn->pReqBuffer, __FUNCTION__, NULL) == ERROR ){
                    break;
                }
                
                //assert(hdr->data_size <= TOTAL_XFER_MAX);
                if(1 != get(pConn, pConn->pReqBuffer, hdr->data_size)){
                    pConn->pReqBuffer = freeBuffer(pConn->pReqBuffer);
                    break;
                }
                pConn->request_data_size = hdr->data_size;
                p_info( "Received request buffer (%d bytes)\n", pConn->request_data_size);
            }
            
            // execute the request
            pkt_execute(&rpkts[0], pConn);
            
            // we need to send the one response packet + response_buffer if any
            
            // @todo you need to check if he method needs to send
            // and extended response - you need to provide the right
            // data_size
            
            if( strm_expects_response(&pConn->strm) ){
                
                // send the header about response
                p_debug( "pConn->response_data_size %d\n", pConn->response_data_size);
                if (conn_sendCudaPktHdr(&*pConn, 1, pConn->response_data_size) == ERROR) {
                    p_info( "__ERROR__ after : Sending the CUDA packet response header: Quitting ... \n");
                    break;
                }
                
                // send the standard response (with cuda_error_t, and simple arguments etc)
                if (1 != put(pConn, rpkts, sizeof(rpkt_t))) {
                    p_info("__ERROR__ after : Sending CUDA response packet: Quitting ... \n");
                    break;
                }
                p_info("Response packet sent.\n");
                
                // send the extra data if you have anything to send
                if( pConn->response_data_size > 0 ){
                    if (1 != put(pConn, pConn->pRspBuffer, pConn->response_data_size)) {
                        p_info("__ERROR__ after: Sending accompanying response buffer: Quitting ... \n"
                               );
                        break;
                    }
                    p_info( "Response buffer sent (%d) bytes.\n", pConn->response_data_size);
                }
            }
        }//while(1)
    
    
    dec_thread_count_per_device();
        
        freeBuffer(pConn->pReqBuffer);
        freeBuffer(pConn->pRspBuffer);
        //conn_close(pConnListen);
        conn_close(pConn);
        
        //free(pConnListen);
        free(pConn);
        
        return NULL;
        
    
}
Exemple #26
0
void * backend_thread(){
	// connection for listening on a port
	// 2 conn_t cannot be allocated on stack (see comment on conn_t)
	// since cause a seg faults
	conn_t * pConnListen;
	conn_t * pConn;
    pid_t childpid, childpid2;
    int status;

	//int retval = 0;

	// Network state
	// FIXME cuda_bridge_request_t == cuda_packet_t == rpkt_t, this is rediculous
	strm_hdr_t *hdr         = NULL;
	rpkt_t *rpkts           = NULL; // array of cuda packets

	if( (pConnListen = conn_malloc(__FUNCTION__, NULL)) == NULL ) return NULL;
	// this allocates memory for the strm.rpkts, i.e., the array of packets
	if( (pConn = conn_malloc(__FUNCTION__, NULL)) == NULL ) return NULL;


	fprintf(stderr, "**************************************\n");
	fprintf(stderr, "%s.%d: hey, here server thread!\n", __FUNCTION__, __LINE__);
	fprintf(stderr, "**************************************\n");

	// set up the connection
	conn_localbind(pConnListen);
    
    for(;;)
    {
	conn_accept(pConnListen, pConn);   // blocking

    printf("ACCEPTED A CONN***********\n");    
    if((childpid = fork()) == 0)
    {
        
    if((childpid2 = fork()) == 0)
    {    
    // CLOSE the listen connection
    //    conn_close(pConnListen);
        
	// Connection-related structures
	hdr = &pConn->strm.hdr;
	rpkts = pConn->strm.rpkts;   // an array of packets (MAX_REMOTE_BATCH_SIZE)
	// these are buffers for extra data transferred as
	pConn->pReqBuffer = NULL;
	pConn->pRspBuffer = NULL;

    while(1) {

    	p_debug("------------------New RPC--------------------\n");

		memset(hdr, 0, sizeof(strm_hdr_t));
		memset(rpkts, 0, MAX_REMOTE_BATCH_SIZE * sizeof(rpkt_t));
		pConn->request_data_size = 0;
		pConn->response_data_size = 0;

		pConn->pReqBuffer = freeBuffer(pConn->pReqBuffer);
		pConn->pRspBuffer = freeBuffer(pConn->pRspBuffer);

		//recv the header describing the batch of remote requests
		if (1 != get(pConn, hdr, sizeof(strm_hdr_t))) {
			break;
		}
		p_debug(" received request header. Expecting  %d packets. And extra request buffer of data size %d\n",
				hdr->num_cuda_pkts, hdr->data_size);

		if (hdr->num_cuda_pkts <= 0) {
			p_warn("Received header specifying zero packets, ignoring\n");
			continue;
		}

        // Receive the entire batch.
		// first the packets, then the extra data (reqbuf)
		//
		// let's assume that we have enough space. otherwise we have a problem
		// pConn allocates the buffers for incoming cuda packets
		// so we should be fine
		if(1 != get(pConn, rpkts, hdr->num_cuda_pkts * sizeof(rpkt_t))) {
			break;
		}
		p_info("Received %d packets, each of size of (%lu) bytes\n",
				hdr->num_cuda_pkts, sizeof(rpkt_t));

		p_info( "Received method %s (method_id %d) from Thr_id: %lu.\n",
		 methodIdToString(rpkts[0].method_id), rpkts[0].method_id, rpkts[0].thr_id);

		// receiving the request buffer if any
		if(hdr->data_size > 0){
			p_info("Expecting data size/Buffer: %u, %d.\n",
					hdr->data_size, pConn->request_data_size);
			// let's assume that the expected amount of data will fit into
			// the buffer we have (size of pConn->request_data_buffer

			// allocate the right amount of memory for the request buffer
			pConn->pReqBuffer = malloc(hdr->data_size);
			if( mallocCheck(pConn->pReqBuffer, __FUNCTION__, NULL) == ERROR ){
				break;
			}

			//assert(hdr->data_size <= TOTAL_XFER_MAX);
			if(1 != get(pConn, pConn->pReqBuffer, hdr->data_size)){
				pConn->pReqBuffer = freeBuffer(pConn->pReqBuffer);
				break;
			}
			pConn->request_data_size = hdr->data_size;
			p_info( "Received request buffer (%d bytes)\n", pConn->request_data_size);
		}

		// execute the request
		pkt_execute(&rpkts[0], pConn);

		// we need to send the one response packet + response_buffer if any

		// @todo you need to check if he method needs to send
		// and extended response - you need to provide the right
		// data_size

		if( strm_expects_response(&pConn->strm) ){

			// send the header about response
			p_debug( "pConn->response_data_size %d\n", pConn->response_data_size);
			if (conn_sendCudaPktHdr(&*pConn, 1, pConn->response_data_size) == ERROR) {
				p_info( "__ERROR__ after : Sending the CUDA packet response header: Quitting ... \n");
				break;
			}

			// send the standard response (with cuda_error_t, and simple arguments etc)
			if (1 != put(pConn, rpkts, sizeof(rpkt_t))) {
				p_info("__ERROR__ after : Sending CUDA response packet: Quitting ... \n");
				break;
			}
			p_info("Response packet sent.\n");

			// send the extra data if you have anything to send
			if( pConn->response_data_size > 0 ){
				if (1 != put(pConn, pConn->pRspBuffer, pConn->response_data_size)) {
					p_info("__ERROR__ after: Sending accompanying response buffer: Quitting ... \n"
							);
					break;
				}
				p_info( "Response buffer sent (%d) bytes.\n", pConn->response_data_size);
			}
		}
    }

    freeBuffer(pConn->pReqBuffer);
    freeBuffer(pConn->pRspBuffer);
	conn_close(pConnListen);
	conn_close(pConn);

	free(pConnListen);
	free(pConn);

	return NULL;
    } //if(childpid2==0)   
    else
        exit(0);
        
        
    
    } //if(childpid==0)

        //CLOSE THE other conn
        conn_close(pConn);
        waitpid(childpid, &status, NULL);
    }//for(;;)
}
int MFPrefSynPts(WYSIWYG *wn, CNTRLS *control,int frame, char *data, int to_ac)
{								/* 0 = picas, 1 = points for lmt_size_parser */
	REL_WORDS syntax;
	int error = 0;

	memset ((char*)&syntax, 0, sizeof(REL_WORDS));
	if (to_ac)
    {
		char buffer[12];

		memset(buffer, 0, sizeof(buffer));
		switch (control->off_rel)
		{
		  case -1:
			syntax.offset = CUR_LOCKS(wn).v_lines;
			break;
		  case 0:
		  case 1:
		  case 6:
		  case 7:
		  case 8:
		  case 9:
			if (frame)
				syntax.offset = *(&REL_DATA(frame) d0 + control->off_rel);
			else
				syntax.offset = *(&wn->preferences.rule_weight +
								  control->off_rel);
			break;
		  default:
			p_info(PI_ELOG, "MFPrefSynPts Illegal control->off_rel: %d\n", 
					  control->off_rel);
			return(0);
		}
		if (control -> off_rel <= 1)
			lmt_syntax_to_ascii_pts(&syntax, buffer);
		else
			lmt_syntax_to_ascii(&syntax, 0, buffer);
		memcpy(data, buffer, control -> length);
    }
	else
    {
		if (strlen(data) > control -> length)
			data[control -> length] = 0;
		if(!(error = lmt_size_parser(&syntax, data,
									 control->off_rel <= 1 ? 1 : 0)))
			switch (control->off_rel)
			{
			  case -1:
				CUR_LOCKS(wn).v_lines = syntax.offset;
				break;
			  case 0:
			  case 1:
			  case 6:
			  case 7:
			  case 8:
			  case 9:
				if (frame)
					*(&REL_DATA(frame) d0 + control -> off_rel)
						= syntax.offset;
				else
					*(&wn->preferences.rule_weight+control->off_rel)
						= syntax.offset;
				break;
			  default:
				p_info(PI_ELOG, "MFPrefSynPts Illegal control->off_rel: %d\n",
						  control->off_rel);
				break;
			}
    }
	return(error);
}