#define MMCOPYRIGHT	"by   M. Mittelbach"
/*
 *        Copyright (C) 1992,...,1995  Marc Mittelbach, Joerg Koerber
 *                    All rights reserved.
 *          Notice of copyright on this source code 
 *          product does not indicate publication. 
 * 
 */


#include "xtexshell.h"

static int	i,iptest,
		filenumber,
		build_pathname(),
		build_whole_pathname();

static long int	displayTool_buf_len=0;

static Boolean 	rainbow = TRUE, landscape = FALSE, all_select = FALSE,
		tex_select = TRUE, dvi_select = FALSE;

static char     *filename,
		*pathname,
		*swstring,           /* Scroll Window string       */
		scrolldir[500],
		scrollfile[256];

static char	inp_disp[16]  = "File  ...      ",
                edi1_disp[16] = "Edit 1 ...     ",
                edi2_disp[16] = "Edit 2 ...     ",
                edi3_disp[16] = "Edit 3 ...     ",
                edi4_disp[16] = "Edit 4 ...     ",
                eig_resolution[10],
                eig_tex[8];

static char	errormsg[256], *papersize[2] = { "a4","a4r" },
		inp_path[300]  = "",	  dvi_inp_path[300]  = "",
		edi1_path[300]  = "",	  edi2_path[300] = "",
		edi3_path[300]  = "",	  edi4_path[300] = "",
		dpi[6],		home_x[6],	home_y[6],	b_Dvi[6],
		b_Edi[6],	h_Edi[6],	x_Edi[6],	y_Edi[6],
		SOUNDS[30] = "",  PWD[100],
		shrink_factor[6],begin_pageno[6], p_begin_pageno[6],
		end_pageno[6], leaves[6],
		number_of_copies[6] = "1",
		h_offset[6] = "0", v_offset[6] = "0",
		x_offset[6] = "0", y_offset[6] = "0",
		print_PCL_tool_path[200], 
		TextEditorTitel[200];

static int	Edit_id = 0,	Tex_id = 0,	Dvi_id = 0,	
		Play_id = 0,    XFig_id = 0,    Print_id = 0,
		Err_in,		Out_in,
		to_Child,	from_TeX;

float		X_offset, Y_offset;

static void	parameters(),
		OpenPopup(),
		menuSelect_cb(),
		rainbow_cb(),
		DrawAndPrint(),
		StubEventHandler(),
		scrollbar_cb(),
		FooterMessage(),
		GetColors(),
		SetPosition(),
		SetStubCursor(),
		setfilenumber1_callback(),
		setfilenumber2_callback(),
		modify_callback(),
		motion_callback(),
		TeX_callback(),
		Preview_callback(),
		Print_callback(),
		Edit_callback(),
		Editor_callback(),
		DismissPopup(),
		notice_cb1(),
		notice_cb2(),
		par_translate(),
		play_sound(),
		TeXruns(),
		Printruns();

void		initList(),
		clearList();
void		get_from_prog(),
		get_from_others(),
		send_to_prog(),
		reset_displayTool(),
		insert_string(),
		redirect_input();

int		finde_Element(),
		suffix_ident(),
		RowOfPosition();
void		vertausche_Elemente();

unsigned	long Dlswstring=1;

static short    item_count = 0,
		newFcount;

static Widget   toplevel,
                controlarea,
                texcommandarea,
                editcommandarea,
                form,
		format,
		language,
		run,
		resolution,
		previewer,
		shrink,
		display,
#ifdef USE_Xaw_TOOLKIT
		utilprog[XtNumber(utilprogs)-1],
		printzweiseitig[XtNumber(printzweiseitigs)-1],
#else
		utilprog,
		printzweiseitig,
#endif USE_Xaw_TOOLKIT
		printresolution,
		printlanguage,
		printdevice,
		document_Vorlage,
		popupLoad_form,
		popupProperties_form,
		popupPrint_form,
		popupEditor_form,
                scrollbar,
                stub,
                ca_caption,	/* caption for controlarea     */
                tex_caption,	/* caption for texcommandarea  */
                edit_caption,	/* caption for editcommandarea */
                about_caption,	/* caption for about...        */
                fm_caption,	/* caption for form            */
                sw_caption,	/* caption for scrolledwindow  */
		displayTool,
                nonexclusives,
                noticeshell,
                noticebox,
                popupshell2,
                loadpopup,
                proppopup,
                printpopup,
		edit_button4,
		TextEditorpopup,
		TEpopup, TEst1, TEst2,
		load, 
		scrolling_list,
	        file_button,
	        prop_button,
	        print_button,
	        editbutton1,
	        editbutton2,
	        editbutton3,
	        editbutton4,
                quit_button,
		texteditor,
                footer_text,
  	        MyViewport,
		box;

/* 
 * Form constraint resources used for most widgets in application.
 */
static Arg	genericARGS[] = {
	{ XtNxRefWidget, (XtArgVal)0 },
	{ XtNyRefWidget, (XtArgVal)0 },
	{ XtNxOffset,	 (XtArgVal)0 },
	{ XtNyOffset,	 (XtArgVal)0 },
	{ XtNxAddWidth,	 (XtArgVal)TRUE },
	{ XtNyAddHeight, (XtArgVal)TRUE },
};

  XtAppContext	app;

/*
 * THE WIDGET TREE: 
 *
 * 				Toplevel 
 *				   |
 * 				Footerpanel
 *				/     \
 * 			     Form     Statictext
 *			      /
 * 			Remaining OPEN LOOK widgets, gadgets, and flats
 */


/*
 * MAIN
 */
main(argc, argv)
	int             argc;
	char           *argv[];
{
  void		On_Exit();
  Arg		argue[10];
  int		ll;

#ifdef USE_Xaw_TOOLKIT
  void		editbutton1_callback();
  void		editbutton2_callback();
  void		editbutton3_callback();
  void		editbutton4_callback();

	static int	   actions_added=0;
	static String	button_translations1 =
		"<Btn1Down>,<Btn1Up>: set()edit_notified1()\n\
		 <Btn2Down>: reset()PopupMenu()\n\
		 <LeaveWindow>: reset()\n\
		 <EnterWindow>: highlight()\n";
	static XtActionsRec	button_actions1[] =
	{
   	 {"edit_notified1", (XtActionProc) editbutton1_callback},
	};
	static String	button_translations2 =
		"<Btn1Down>,<Btn1Up>: set()edit_notified2()\n\
		 <Btn2Down>: reset()PopupMenu()\n\
		 <LeaveWindow>: reset()\n\
		 <EnterWindow>: highlight()\n";
	static XtActionsRec	button_actions2[] =
	{
   	 {"edit_notified2", (XtActionProc) editbutton2_callback},
	};
	static String	button_translations3 =
		"<Btn1Down>,<Btn1Up>: set()edit_notified3()\n\
		 <Btn2Down>: reset()PopupMenu()\n\
		 <LeaveWindow>: reset()\n\
		 <EnterWindow>: highlight()\n";
	static XtActionsRec	button_actions3[] =
	{
   	 {"edit_notified3", (XtActionProc) editbutton3_callback},
	};
	static String	button_translations4 =
		"<Btn1Down>,<Btn1Up>: set()edit_notified4()\n\
		 <Btn2Down>: reset()PopupMenu()\n\
		 <LeaveWindow>: reset()\n\
		 <EnterWindow>: highlight()\n";
	static XtActionsRec	button_actions4[] =
	{
   	 {"edit_notified4", (XtActionProc) editbutton4_callback},
	};

	static String	text_translations =
		"<Key>Return: newline()new_text()\n";
	static XtActionsRec	text_actions[] =
	{
   	 {"new_text", (XtActionProc) send_to_prog},
	};
#endif USE_Xaw_TOOLKIT


  signal( SIGINT, On_Exit );

/*
 *  Voreinstellungen.
 */
	sprintf( PWD ,  "%s"	  ,  getenv("PWD" ) );
	sprintf( SOUNDS,  "%s"	  ,  getenv("SOUNDS" ) );

	parameters();

	if( actual.input_dir[0]== '\0' ) strcpy( actual.input_dir, PWD);
	if( actual.edi1_dir[0] == '\0' ) strcpy( actual.edi1_dir , PWD);
	if( actual.edi2_dir[0] == '\0' ) strcpy( actual.edi2_dir , PWD);
	if( actual.edi3_dir[0] == '\0' ) strcpy( actual.edi3_dir , PWD);
	if( actual.edi4_dir[0] == '\0' ) strcpy( actual.edi4_dir , PWD);

/*
 * Ueberpruefen, ob Datei und Pfad uebergeben wurden
 */
    if(argc!=1)
    {
	i=1;
	while(i<=argc-1){ 
	   if( argv[i][0] != '-' ) break;
	   if( argv[i][1] == 'd' ){
	  	if( argv[i][2] == 'i' ){
	  		if( argv[i][3] == 's' )i++ ;
	  	}
	   }
	   if( argv[i][1] == 'g' ){
	  	if( argv[i][2] == 'e' ){
	  		if( argv[i][3] == 'o' )i++ ;
	  	}
	   }
	   if( argv[i][1] == 'x' ){
	  	if( argv[i][2] == 'r' ){
	  		if( argv[i][3] == 'm' )i++ ;
	  	}
	   }
	   i++ ;
	}
	if(i<=argc-1){ /* Datei vorhanden*/
	    strcpy( actual.input_dir, PWD);
	    strcpy( actual.edi1_dir , PWD);
	    ll=strlen(argv[i])-1;
	    while(ll){ if( argv[i][ll] == '/' ) break; ll-- ; }
		if(ll){ /* Pfad vorhanden*/
			argv[i][ll]=0;
			if(argv[i][0]=='/')/* absoluter Pfad*/
				strcpy(actual.input_dir,argv[i]);
			 else{ /* relativer Pfad*/
				if(actual.input_dir[strlen(actual.input_dir)-1]!='/')
				strcat(actual.input_dir,"/");
				strcat(actual.input_dir,argv[i]);	}
	        	ll++;
		}
		strcpy(actual.input_file, &argv[i][ll] );
		strcpy(actual.edi1_file,  &argv[i][ll] );
		strncpy( inp_disp , actual.input_file , 15);
		strncpy( edi1_disp , actual.edi1_file , 12);
		build_pathname( actual.input_dir, actual.input_file, inp_path);
		build_pathname( PWD, actual.input_file, dvi_inp_path);
		build_whole_pathname( actual.edi1_dir, actual.edi1_file, edi1_path);
	}
    }

	pathname = actual.input_dir;
	chdir(actual.input_dir);

	swstring=malloc( 1 );
	swstring[0]=0;

	/*
	 * Initialize the environment.
	 */
	{

#ifdef USE_Xaw_TOOLKIT
#else
		OlToolkitInitialize((XtPointer)NULL);
#endif USE_Xaw_TOOLKIT
		toplevel = XtAppInitialize(&app,
			"XTexshell",
			(XrmOptionDescRec *)NULL,
			0, &argc, argv, (String *) NULL, (ArgList) NULL, 0);

		/*
		 * Get colors to use later.
		 */
		GetColors();

		/*
		 * Set FORM resources for the specific screen.
		 */
		genericARGS[2].value = (XtArgVal)H_PIXEL(10);
		genericARGS[3].value = (XtArgVal)V_PIXEL(10);

	}

	/*
	 * TeX icon
	 */

	i = 0;
	XtSetArg(argue[i], XtNiconName,
		(XtArgVal)inp_disp); i++;
	XtSetArg(argue[i], XtNiconPixmap,
		(XtArgVal) (XCreateBitmapFromData(
		XtDisplay(toplevel),
		RootWindowOfScreen(XtScreen(toplevel)),
		icon_bits, icon_width,
		icon_height)));i++;
	XtSetValues(toplevel, argue, i);

		
	/*
	 * Make all the widgets and then do placement on the form last.
	 */


	/*
	 * FOOTERPANEL: This will be the child of toplevel, with the FORM as
	 * the topchild and STATICTEXT as the footer child.
	 */
	{
		Widget          footerpanel;

		footerpanel = XtCreateManagedWidget("footerpanel",
			footerPanelWidgetClass, toplevel,
			NULL, 0);

		/*
		 * FORM: Form's caption is the top child of the footerpanel.
		 */
		fm_caption = XtVaCreateManagedWidget("",
			captionWidgetClass,
			footerpanel,
			XtNposition,	(XtArgVal)OL_LEFT,
			XtNalignment,	(XtArgVal)OL_CENTER,
#ifdef USE_Xaw_TOOLKIT
			XtNshowGrip,	(XtArgVal)FALSE,
#else
			XtNcaptionWidth,(XtArgVal)0,
#endif USE_Xaw_TOOLKIT
			0 );

		form = XtVaCreateManagedWidget("form",
			formWidgetClass, fm_caption,
			XtNborderWidth,	(XtArgVal)0,
			NULL, 0);

		/*
		 * Register help for the form, using the file "form.help"
		 */
#ifdef USE_Xaw_TOOLKIT
#else
		(void) OlRegisterHelp(OL_WIDGET_HELP, (XtPointer)form,
			"Form Widget", OL_DISK_SOURCE,
			"/usr/X/lib/tutorial/Xol/form.help");
#endif USE_Xaw_TOOLKIT

		/*
		 * Make STATICTEXT as the footer child of the footerpanel.
		 */
		footer_text = XtVaCreateManagedWidget("statictext",
			staticTextWidgetClass,
			footerpanel,
#ifdef USE_Xaw_TOOLKIT
			XtNlabel, (XtArgVal)"Choose a file to TeX ...",
			XtNresize,	(XtArgVal)FALSE,
#else
			XtNstring, (XtArgVal)"Choose a file to TeX ...",
#endif USE_Xaw_TOOLKIT
			XtNx, (XtArgVal)H_PIXEL(10),
			0 );
	}


	/*
	 * All the remaining widgets will be on the form.
	 */
	ca_caption = XtVaCreateManagedWidget("",
		captionWidgetClass,
		form,
		XtNxResizable,		(XtArgVal)TRUE,
		XtNxAttachRight,	(XtArgVal)TRUE,
		XtNlabel,		(XtArgVal)"",
#ifdef USE_Xaw_TOOLKIT
		XtNhSpace,		(XtArgVal)0,
		XtNvSpace,		(XtArgVal)0,
#endif USE_Xaw_TOOLKIT
		0 );


	/*
	 * CONTROLAREA: the control area contains a popup command window,
	 * a popup property window, and a menu 
	 */
	controlarea = XtVaCreateManagedWidget("controlarea",
			controlAreaWidgetClass, ca_caption,
#ifdef USE_Xaw_TOOLKIT
			XtNdefaultDistance,	(XtArgVal)0,
#endif USE_Xaw_TOOLKIT
			XtNborderWidth,		(XtArgVal)0,
			NULL, 0);


	/*
	 * POPUP: Used for Command Window.
	 */
	{
		Widget          CreateLoadPopup();
		file_button = XtVaCreateManagedWidget("inp_disp", 
				oblongButtonWidgetClass,
				controlarea,
				XtNlabel,		(XtArgVal)inp_disp,
				XtNheight,		(XtArgVal)V_PIXEL(16),
				XtNwidth,		(XtArgVal)H_PIXEL(95),
				XtNrecomputeSize,	(XtArgVal)FALSE,
                                0 );
 		  XtAddCallback(file_button, XtNselect,
			setfilenumber1_callback, (XtPointer)0);
 		  loadpopup = CreateLoadPopup(file_button); 
	}



	/*
	 * POPUP: Used for Property Sheet.
	 */
	{
		Widget  	CreatePropPopup();
		prop_button = XtVaCreateManagedWidget("TeX Properties...", 
			oblongButtonWidgetClass,
			controlarea,
			XtNxRefWidget,		file_button,
			XtNheight,		(XtArgVal)V_PIXEL(16),
			XtNwidth,		(XtArgVal)H_PIXEL(115),
			XtNrecomputeSize,	(XtArgVal)FALSE,
			0 );
 		  proppopup = CreatePropPopup(prop_button);
 		XtAddCallback(prop_button, XtNselect, OpenPopup,
			proppopup);
	}

	{
		static Widget   menubutton,
		                menupane,
		                widget;

		menubutton = XtVaCreateManagedWidget("Utilities",
			menuButtonWidgetClass,
			controlarea,
			XtNheight,		(XtArgVal)V_PIXEL(16),
			XtNwidth,		(XtArgVal)H_PIXEL(80),
			XtNpushpin,		(XtArgVal)OL_OUT,
			XtNlabelType,		(XtArgVal)OL_STRING,
			XtNlabelJustify,	(XtArgVal)OL_LEFT,
			XtNrecomputeSize,	(XtArgVal)FALSE,
			XtNxRefWidget,		prop_button,
			0 );

#ifdef USE_Xaw_TOOLKIT
    		menupane = XtCreatePopupShell("menu", 
			  simpleMenuWidgetClass, menubutton, NULL, 0);
#else
		/*
		 * Get the Widget id of the menupane of the menubutton.
		 */
		i = 0;
		XtSetArg(argue[i], XtNmenuPane, (XtArgVal)&menupane); i++;
		XtGetValues(menubutton, argue, i);

#endif USE_Xaw_TOOLKIT

		/*
		 * Make oblongbuttons on the menupane, with select
		 * callbacks.
		 */
		widget = XtCreateManagedWidget("Xfig",
			popupMenuButtonWidgetClass, menupane, NULL, 0);
		XtAddCallback(widget, XtNselect, menuSelect_cb, (XtPointer)1);

		widget = XtCreateManagedWidget("BIB TeX",
			popupMenuButtonWidgetClass, menupane, NULL, 0);
		XtAddCallback(widget, XtNselect, menuSelect_cb, (XtPointer)2);

		widget = XtCreateManagedWidget("MakeIndex",
			popupMenuButtonWidgetClass, menupane, NULL, 0);
		XtAddCallback(widget, XtNselect, menuSelect_cb, (XtPointer)3);

		widget = XtCreateManagedWidget("DVI --> PS  ",
			popupMenuButtonWidgetClass, menupane, NULL, 0);
		XtAddCallback(widget, XtNselect, menuSelect_cb, (XtPointer)4);

		widget = XtCreateManagedWidget("HPGL --> PS",
			popupMenuButtonWidgetClass, menupane, NULL, 0);
		XtAddCallback(widget, XtNselect, menuSelect_cb, (XtPointer)5);

		widget = XtCreateManagedWidget("HPGL --> MF",
			popupMenuButtonWidgetClass, menupane, NULL, 0);
		XtAddCallback(widget, XtNselect, menuSelect_cb, (XtPointer)6);

		widget = XtCreateManagedWidget("MF --> PK",
			popupMenuButtonWidgetClass, menupane, NULL, 0);
		XtAddCallback(widget, XtNselect, menuSelect_cb, (XtPointer)7);

		widget = XtCreateManagedWidget("METAFONT  ",
			popupMenuButtonWidgetClass, menupane, NULL, 0);
		XtAddCallback(widget, XtNselect, menuSelect_cb, (XtPointer)8);
	}


	/*
	 * CAPTION
	 */
	{
		about_caption = XtVaCreateManagedWidget("",
			captionWidgetClass,
			form,
			XtNposition,	(XtArgVal)OL_TOP,
			XtNalignment,	(XtArgVal)OL_CENTER,
			XtNlabel,	(XtArgVal)"INFO",
#ifdef USE_Xaw_TOOLKIT
			XtNhSpace,	(XtArgVal)0,
			XtNvSpace,	(XtArgVal)0,
#endif USE_Xaw_TOOLKIT
			0 );

		{
			static Widget   widget;

			widget = XtCreateManagedWidget("About...",
				oblongButtonWidgetClass, about_caption, NULL, 0);

			XtAddCallback(widget, XtNselect, rainbow_cb, NULL);
		}
	}


	/*
	 * Stub WIDGET: this will be used as a drawing canvas.
	 *	 
	 * First two arguments scale widget to resolution of screen.
	 *
	 * DrawAndPrint() will be called with an Expose event;
	 */
	stub = XtVaCreateManagedWidget("stub",
			stubWidgetClass,
			form,
			XtNheight,	(XtArgVal)V_PIXEL(100),
			XtNwidth,	(XtArgVal)H_PIXEL(100),
			XtNbackground,	skyblue_pixel,
#ifdef USE_Xaw_TOOLKIT
#else
			XtNexpose,	DrawAndPrint,
#endif USE_Xaw_TOOLKIT
			0 );
#ifdef USE_Xaw_TOOLKIT
	XtAddEventHandler(stub, ExposureMask,
		FALSE, DrawAndPrint, (XtPointer)NULL);
	i = 0;
	XtSetArg(argue[i], XtNbackground, skyblue_pixel); i++;
	XtSetArg(argue[i], XtNforeground, skyblue_pixel); i++;
	XtSetValues(stub, argue, i);
#else
	  	OlRegisterHelp(	OL_WIDGET_HELP, stub, "  ", 
              			OL_DISK_SOURCE,
				(XtPointer)HELPFILE);
#endif USE_Xaw_TOOLKIT

	/*
	 * Add an eventhandler to track when the pointer enters and leaves the
	 * stub widget window.
	 */
	XtAddEventHandler(stub, EnterWindowMask | LeaveWindowMask,
		FALSE, StubEventHandler, (XtPointer)NULL);

	/*
	 * Set the special cursor for stub widget window below once the widget
	 * tree realized.
	 */



	/*
	 * SCROLLED WINDOW
	 */
	{
		static Widget   scrolledwindow;

		sw_caption = XtVaCreateManagedWidget("sw_caption",
#ifdef USE_Xaw_TOOLKIT
			scrolledWindowWidgetClass,
#else
			captionWidgetClass,
#endif USE_Xaw_TOOLKIT
			form,
			XtNposition,	(XtArgVal)OL_TOP,
			XtNalignment,	(XtArgVal)OL_CENTER,
			XtNlabel,	(XtArgVal)"TeX messages:",
#ifdef USE_Xaw_TOOLKIT
			XtNhSpace,	(XtArgVal)0,
			XtNvSpace,	(XtArgVal)0,
#endif USE_Xaw_TOOLKIT
			0 );

		i = 0;
		XtSetArg(argue[i], XtNvStepSize, 20); i++;
		XtSetArg(argue[i], XtNhStepSize, 20); i++;
		XtSetArg(argue[i], XtNforceVerticalSB, (XtArgVal)TRUE); i++;
#ifdef USE_Xaw_TOOLKIT
		XtSetArg(argue[i], XtNhSpace, (XtArgVal)0); i++;
		XtSetArg(argue[i], XtNvSpace, (XtArgVal)0); i++;
#endif USE_Xaw_TOOLKIT
		scrolledwindow = XtCreateManagedWidget("scrolledwindow",
			scrolledWindowWidgetClass, sw_caption, argue, i);

#ifdef USE_Xaw_TOOLKIT
#else
		XtAddCallback(scrolledwindow, XtNvSliderMoved, scrollbar_cb,
			(XtPointer) 1);
		XtAddCallback(scrolledwindow, XtNhSliderMoved, scrollbar_cb,
			(XtPointer) 2);
#endif USE_Xaw_TOOLKIT

#ifdef USE_Xaw_TOOLKIT

	if (!actions_added) {
	    actions_added = 1;
	    /* add action to load file */
	    XtAppAddActions(app, button_actions1, XtNumber(button_actions1));
	    XtAppAddActions(app, button_actions2, XtNumber(button_actions2));
	    XtAppAddActions(app, button_actions3, XtNumber(button_actions3));
	    XtAppAddActions(app, button_actions4, XtNumber(button_actions4));
	    XtAppAddActions(app, text_actions, XtNumber(text_actions));
	}
#endif USE_Xaw_TOOLKIT


		i = 0;
		XtSetArg(argue[i], XtNheight, V_PIXEL(135)); i++;
		XtSetArg(argue[i], XtNwidth,  H_PIXEL(270)); i++;
		XtSetArg(argue[i], XtNbackground, background_pixel); i++;
#ifdef USE_Xaw_TOOLKIT
		XtSetArg(argue[i], XtNautoFill, (XtArgVal)TRUE); i++;
		XtSetArg(argue[i], XtNwrap, XawtextWrapLine); i++;
		XtSetArg(argue[i], XtNscrollVertical, XawtextScrollAlways); i++;
		XtSetArg(argue[i], XtNeditType, XawtextAppend); i++;
#endif USE_Xaw_TOOLKIT

		displayTool = XtCreateManagedWidget("display",
			textEditWidgetClass, scrolledwindow, argue, i);

#ifdef USE_Xaw_TOOLKIT

 	        XtOverrideTranslations(displayTool,
			   XtParseTranslationTable(text_translations));
#endif USE_Xaw_TOOLKIT

		insert_string(displayTool, "Let\'s go ...\n");
		XtAddCallback(displayTool, XtNmodifyVerification,
			send_to_prog, NULL);
	}


	/*
	 * 
	 *       the TeX-Command buttons
	 * 
	 */
	{
		tex_caption = XtVaCreateManagedWidget("",
			captionWidgetClass,
			form,
			XtNposition,		(XtArgVal)OL_TOP,
			XtNalignment,		(XtArgVal)OL_LEFT, 
			XtNxResizable,		(XtArgVal)TRUE,
			XtNxAttachRight,	(XtArgVal)TRUE,
			XtNlabel,		(XtArgVal)"Commands", 
#ifdef USE_Xaw_TOOLKIT
			XtNhSpace,		(XtArgVal)0,
			XtNvSpace,		(XtArgVal)0,
#endif USE_Xaw_TOOLKIT
			0 );

		texcommandarea = XtVaCreateManagedWidget("texcommandarea",
			controlAreaWidgetClass, tex_caption,
#ifdef USE_Xaw_TOOLKIT
			XtNdefaultDistance,	(XtArgVal)0,
#endif USE_Xaw_TOOLKIT
			XtNborderWidth,		(XtArgVal)0,
			NULL, 0);
		{
			Widget  	CreatePrintPopup();
			static Widget   widget;
			static Widget   noticetext;

			static Arg      noticeARGS[] = {
				{ XtNtextArea,		(XtArgVal)&noticetext },
				{ XtNcontrolArea,	(XtArgVal)&noticebox },
			};

			widget = XtVaCreateManagedWidget(" TeX ",
				oblongButtonWidgetClass,
				texcommandarea,
				XtNrecomputeSize,	(XtArgVal)FALSE,
				XtNheight,		(XtArgVal)V_PIXEL(16),
				XtNwidth,		(XtArgVal)H_PIXEL(45),
				0 );

			XtAddCallback(widget, XtNselect, TeX_callback, NULL);
 
			widget = XtVaCreateManagedWidget("Preview",
				oblongButtonWidgetClass,
				texcommandarea,
				XtNrecomputeSize,	(XtArgVal)FALSE,
				XtNheight,		(XtArgVal)V_PIXEL(16),
				XtNwidth,		(XtArgVal)H_PIXEL(55),
				XtNxRefWidget,		widget,
				0 );
			XtAddCallback(widget, XtNselect, Preview_callback, NULL);

			print_button = XtVaCreateManagedWidget("Print", 
				oblongButtonWidgetClass,
				texcommandarea,
				XtNrecomputeSize,	(XtArgVal)FALSE,
				XtNheight,		(XtArgVal)V_PIXEL(16),
				XtNwidth,		(XtArgVal)H_PIXEL(45),
				XtNxRefWidget,		widget,
				0 );
	 		  printpopup = CreatePrintPopup(print_button);
	 		XtAddCallback(print_button, XtNselect, OpenPopup,
			printpopup);

			quit_button = XtVaCreateManagedWidget("Quit ",
				oblongButtonWidgetClass,
				texcommandarea,
				XtNxRefWidget,		print_button,
				XtNrecomputeSize,	(XtArgVal)FALSE,
				XtNheight,		(XtArgVal)V_PIXEL(16),
				XtNwidth,		(XtArgVal)H_PIXEL(45),
				0 );
			XtAddCallback(quit_button, XtNselect, notice_cb1, NULL);


#ifdef USE_Xaw_TOOLKIT
#else
			/*
			 * Create notice popup shell.
			 */
			noticeshell = XtCreatePopupShell("notice",
				noticeShellWidgetClass, quit_button, NULL, 0);
			/*
			 * Get the widget ids of noticebox and textarea of noticebox.
			 */
			XtGetValues(noticeshell, noticeARGS, XtNumber(noticeARGS));

			/*
			 * Add text to text area of noticebox.
			 */
			i = 0;
			XtSetArg(argue[i], XtNstring,
				(XtArgVal)"Really want to quit ? \n "); i++;
			XtSetValues(noticetext, argue, i);

			widget = XtCreateManagedWidget("Yes",
				oblongButtonWidgetClass, noticebox, NULL, 0);
			XtAddCallback(widget, XtNselect, notice_cb2, noticebox);

			XtCreateManagedWidget("Cancel",
				oblongButtonWidgetClass, noticebox, NULL, 0);
#endif USE_Xaw_TOOLKIT

		}
	}

	/*
	 * 
	 *       the Edit buttons
	 * 
	 */
	{
		Widget          button,
		                menupane;
		edit_caption = XtVaCreateManagedWidget("",
			captionWidgetClass,
			form,
			XtNxResizable, (XtArgVal)TRUE,
			XtNxAttachRight, (XtArgVal)TRUE,
#ifdef USE_Xaw_TOOLKIT
			XtNhSpace, (XtArgVal)0,
			XtNvSpace, (XtArgVal)0,
#else
			XtNcaptionWidth,(XtArgVal)0,
			XtNlabel, (XtArgVal)"", 
#endif USE_Xaw_TOOLKIT
			0 );

		editcommandarea = XtVaCreateManagedWidget("editcommandarea",
			controlAreaWidgetClass, edit_caption,
#ifdef USE_Xaw_TOOLKIT
			XtNdefaultDistance,	(XtArgVal)0,
#endif USE_Xaw_TOOLKIT
			XtNborderWidth,		(XtArgVal)0,
			NULL, 0);
		{
		i=0;
		XtSetArg(argue[i], XtNlabel, (XtArgVal)edi1_disp); i++;
		XtSetArg(argue[i], XtNheight, (XtArgVal)V_PIXEL(16)); i++;
		XtSetArg(argue[i], XtNwidth, (XtArgVal)H_PIXEL(95)); i++;
		XtSetArg(argue[i], XtNrecomputeSize, (XtArgVal)FALSE); i++;
		editbutton1 = XtCreateManagedWidget("editbutton1",
			menuButtonGadgetClass, editcommandarea, argue, i);
#ifdef USE_Xaw_TOOLKIT
 	        XtOverrideTranslations(editbutton1,
			   XtParseTranslationTable(button_translations1));
	    
    		menupane = XtCreatePopupShell("menu", 
			  simpleMenuWidgetClass, editbutton1, NULL, 0);
#else
		i = 0;
		XtSetArg(argue[i], XtNmenuPane, (XtArgVal)&menupane); i++;
		XtGetValues(editbutton1, argue, i);
#endif USE_Xaw_TOOLKIT

		i = 0;
		button = XtCreateManagedWidget("Edit file",
			popupMenuButtonGadgetClass, menupane, argue, i);
 		XtAddCallback(button, XtNselect, setfilenumber2_callback,
			(XtPointer)1);

		i = 0;
		button = XtCreateManagedWidget("Load new",
			popupMenuButtonGadgetClass, menupane, argue, i);
 		XtAddCallback(button, XtNselect,
				setfilenumber1_callback, (XtPointer)1);

		}
		{
		i = 0;
		XtSetArg(argue[i], XtNlabel, (XtArgVal)edi2_disp); i++;
		XtSetArg(argue[i], XtNx, (XtArgVal) H_PIXEL(100));i++;
		XtSetArg(argue[i], XtNy, (XtArgVal) V_PIXEL(10)); i++;
		XtSetArg(argue[i], XtNheight, (XtArgVal)V_PIXEL(16)); i++;
		XtSetArg(argue[i], XtNwidth, (XtArgVal)H_PIXEL(95)); i++;
		XtSetArg(argue[i], XtNrecomputeSize, (XtArgVal)FALSE); i++;
		XtSetArg(argue[i], XtNxRefWidget, editbutton1); i++;
		editbutton2 = XtCreateManagedWidget("editbutton2",
			menuButtonGadgetClass, editcommandarea, argue, i);
#ifdef USE_Xaw_TOOLKIT
	        XtOverrideTranslations(editbutton2,
			   XtParseTranslationTable(button_translations2));
	    		menupane = XtCreatePopupShell("menu", 
			  simpleMenuWidgetClass, editbutton2, NULL, 0);
#else
		i = 0;
		XtSetArg(argue[i], XtNmenuPane, (XtArgVal)&menupane); i++;
		XtGetValues(editbutton2, argue, i);
#endif USE_Xaw_TOOLKIT

		i = 0;
		button = XtCreateManagedWidget("Edit file",
			popupMenuButtonGadgetClass, menupane, argue, i);
 		XtAddCallback(button, XtNselect, setfilenumber2_callback,
			(XtPointer)2);

		i = 0;
		button = XtCreateManagedWidget("Load new",
			popupMenuButtonGadgetClass, menupane, argue, i);
 		XtAddCallback(button, XtNselect,
				setfilenumber1_callback, (XtPointer)2);
		}
		{
		i = 0;
		XtSetArg(argue[i], XtNlabel, (XtArgVal)edi3_disp); i++;
		XtSetArg(argue[i], XtNx, (XtArgVal) H_PIXEL(100));i++;
		XtSetArg(argue[i], XtNy, (XtArgVal) V_PIXEL(10)); i++;
		XtSetArg(argue[i], XtNheight, (XtArgVal)V_PIXEL(16)); i++;
		XtSetArg(argue[i], XtNwidth, (XtArgVal)H_PIXEL(95)); i++;
		XtSetArg(argue[i], XtNrecomputeSize, (XtArgVal)FALSE); i++;
		XtSetArg(argue[i], XtNxRefWidget, editbutton2); i++;
		editbutton3 = XtCreateManagedWidget("editbutton3",
			menuButtonGadgetClass, editcommandarea, argue, i);
#ifdef USE_Xaw_TOOLKIT
	        XtOverrideTranslations(editbutton3,
			   XtParseTranslationTable(button_translations3));
	      		menupane = XtCreatePopupShell("menu", 
			  simpleMenuWidgetClass, editbutton3, NULL, 0);
#else
		i = 0;
		XtSetArg(argue[i], XtNmenuPane, (XtArgVal)&menupane); i++;
		XtGetValues(editbutton3, argue, i);

#endif USE_Xaw_TOOLKIT

		i = 0;
		button = XtCreateManagedWidget("Edit file",
			popupMenuButtonGadgetClass, menupane, argue, i);
 		XtAddCallback(button, XtNselect, setfilenumber2_callback,
			(XtPointer)3);

		i = 0;
		button = XtCreateManagedWidget("Load new",
			popupMenuButtonGadgetClass, menupane, argue, i);
 		XtAddCallback(button, XtNselect,
				setfilenumber1_callback, (XtPointer)3);
		}
		{
		i = 0;
		XtSetArg(argue[i], XtNlabel, (XtArgVal)edi4_disp); i++;
		XtSetArg(argue[i], XtNx, (XtArgVal) H_PIXEL(100));i++;
		XtSetArg(argue[i], XtNy, (XtArgVal) V_PIXEL(10)); i++;
		XtSetArg(argue[i], XtNheight, (XtArgVal)V_PIXEL(16)); i++;
		XtSetArg(argue[i], XtNwidth, (XtArgVal)H_PIXEL(95)); i++;
		XtSetArg(argue[i], XtNrecomputeSize, (XtArgVal)FALSE); i++;
		XtSetArg(argue[i], XtNxRefWidget, editbutton3); i++;
		editbutton4 = XtCreateManagedWidget("editbutton4",
			menuButtonGadgetClass, editcommandarea, argue, i);
#ifdef USE_Xaw_TOOLKIT
	        XtOverrideTranslations(editbutton4,
			   XtParseTranslationTable(button_translations4));
	    		menupane = XtCreatePopupShell("menu", 
			  simpleMenuWidgetClass, editbutton4, NULL, 0);
#else
		i = 0;
		XtSetArg(argue[i], XtNmenuPane, (XtArgVal)&menupane); i++;
		XtGetValues(editbutton4, argue, i);

#endif USE_Xaw_TOOLKIT

#ifndef MyEDITOR
		i = 0;
		button = XtCreateManagedWidget("Edit file",
			popupMenuButtonGadgetClass, menupane, argue, i); 
 		XtAddCallback(button, XtNselect, setfilenumber2_callback,
			(XtPointer)4);
#else
	/*
	 * POPUP the Text Editor:
	 */
		{
		Widget  	CreateEditorPopup();
		edit_button4 = XtVaCreateManagedWidget("Edit file", 
                                 popupMenuButtonWidgetClass, menupane,
                                 NULL);
 		TextEditorpopup = CreateEditorPopup(edit_button4);
 		XtAddCallback(edit_button4, XtNselect, setfilenumber2_callback,
			(XtPointer)4);
		XtAddCallback(edit_button4, XtNselect, Editor_callback, NULL);
 		XtAddCallback(edit_button4, XtNselect, OpenPopup,
			TextEditorpopup);
		}
#endif MyEDITOR

		i = 0;
		button = XtCreateManagedWidget("Load new",
			popupMenuButtonGadgetClass, menupane, argue, i);
 		XtAddCallback(button, XtNselect,
				setfilenumber1_callback, (XtPointer)4);
		}
	}


	/*
	 * Position all the widgets on the form.  Note that reference names are
	 * used. Note that 10 horizontal and vertical pixels are used in most
	 * cases; in a  few cases special values are used.
	 */
	{
		static Dimension
				width1,
		                width2;
		Arg             arg;

		genericARGS[2].value = (XtArgVal)0;
		genericARGS[3].value = (XtArgVal)0;
		SetPosition(ca_caption, NULL, NULL);
		
		genericARGS[2].value = (XtArgVal)H_PIXEL(10);
		genericARGS[3].value = (XtArgVal)V_PIXEL(5);
		SetPosition(about_caption, NULL, ca_caption);
		
		genericARGS[2].value = (XtArgVal)H_PIXEL(10);
		genericARGS[3].value = (XtArgVal)V_PIXEL(10);
		SetPosition(stub, NULL, about_caption);

		/*
		 * Position Scrolled Window to right of about_caption
		 *  or stub, whichever is wider.
		 */
		genericARGS[2].value = (XtArgVal)H_PIXEL(10);
		genericARGS[3].value = (XtArgVal)V_PIXEL(5);
		XtSetArg(arg, XtNwidth, &width1);
		XtGetValues(about_caption, &arg, 1);
		XtSetArg(arg, XtNwidth, &width2);
		XtGetValues(stub, &arg, 1);

		if (width1 > width2)
			SetPosition(sw_caption, about_caption, ca_caption);
		else
		        SetPosition(sw_caption, stub, ca_caption);

		genericARGS[2].value = (XtArgVal)0;
#ifdef USE_Xaw_TOOLKIT
		genericARGS[3].value = (XtArgVal)V_PIXEL(15);
#else
		genericARGS[3].value = (XtArgVal)V_PIXEL(10);
#endif USE_Xaw_TOOLKIT
		SetPosition(tex_caption, NULL, stub);

		genericARGS[2].value = (XtArgVal)0;
#ifdef USE_Xaw_TOOLKIT
		genericARGS[3].value = (XtArgVal)V_PIXEL(4);
#else
		genericARGS[3].value = (XtArgVal)0;
#endif USE_Xaw_TOOLKIT
		SetPosition(edit_caption, NULL, tex_caption);
	}

	play_sound(SOUND_SPACEMUSIC);

	/*
	 * Realize the widget tree.
	 */
	XtRealizeWidget(toplevel);

	/*
	 * The special cursor for the stub widget can be set now that it has
	 * been realized as part of the widget tree.
	 */
	SetStubCursor(stub);

	/*
	 * Turn control over to the Xt intrinsics and OPEN LOOK.
	 */
	XtAppMainLoop(app);
return(0);
} /* main */




/**************************************************************************
      Widget       " File ... "   LoadPopup
   ************************************************************************/
Widget
CreateLoadPopup(parent)
  Widget parent;
{
  Arg		argue[5];
  Position	x, y;
  Dimension	width, height;
  int		n;

 Widget popup, upper, lower, footer, caption1, caption2;
 Widget rt, findcurrent,button_area,cancel,
	ALL_checkbox,TEX_checkbox,DVI_checkbox;
  Widget  caption, create_fl_ex_nonex();
  void  load_callback(),ALL_callback(),TEX_callback(),DVI_callback(), 
	verify_callback(),document_Vorlage_callback(),
	next_tf_callback(), last_tf_callback();
  void       current_callback();
  void       findcurrent_callback();
#ifdef USE_Xaw_TOOLKIT
  void       FileSelected();
  void       do_load();
        int    actions_added=0;
	static String	file_list_translations =
		"<Btn1Down>,<Btn1Up>: Set()Notify()\n\
		<Btn1Up>(2): Set()Notify()load()\n\
		<Key>Return: load()\n";
	static XtActionsRec	file_name_actions[] =
	{
   	 {"load", (XtActionProc) do_load},
	};

#endif USE_Xaw_TOOLKIT
  static XtCallbackRec verify[] = {
      { (XtCallbackProc)verify_callback, (XtPointer)NULL },
      { NULL, NULL },
  };

  popup = XtVaCreatePopupShell("loadpopup", 
                popupWindowShellWidgetClass,
                parent,
                XtNverify, verify,
                XtNtitle, "Load File",
                NULL);

#ifndef USE_Xaw_TOOLKIT

  XtVaGetValues(popup,
                XtNupperControlArea, &upper,
                XtNlowerControlArea, &lower,
                XtNfooterPanel,      &footer,
                NULL);
#else
    popupLoad_form	= XtVaCreateManagedWidget(" ", boxWidgetClass, popup,
			XtNorientation,		XtorientVertical,
			XtNborderWidth,		(XtArgVal)0, 
    			NULL, 0);
    upper	= XtVaCreateManagedWidget(" ", boxWidgetClass, popupLoad_form,
			XtNorientation,		XtorientVertical, 
			XtNdefaultDistance,	(XtArgVal)0,
			XtNborderWidth,		(XtArgVal)0,
			XtNfromVert,		popupLoad_form,
    			NULL, 0);
    lower	= XtVaCreateManagedWidget(" ", boxWidgetClass, popupLoad_form,
			XtNorientation,		XtorientHorizontal, 
			XtNborderWidth,		(XtArgVal)0,
			XtNfromVert,		upper,
    			NULL, 0);
    footer	= XtVaCreateManagedWidget(" ", footerPanelWidgetClass, popupLoad_form,
			XtNorientation,		XtorientVertical, 
			XtNx,			(XtArgVal)0,
			XtNdefaultDistance,	(XtArgVal)0,
			XtNborderWidth,		(XtArgVal)0,
			XtNwidth,		(XtArgVal)250,
			XtNfromVert,		lower,
    			NULL, 0);
#endif USE_Xaw_TOOLKIT


  rt 	   = XtVaCreateManagedWidget("rt",
		rubberTileWidgetClass, upper, 
#ifdef USE_Xaw_TOOLKIT
		XtNinternalBorderWidth, (XtArgVal)0, 
#endif USE_Xaw_TOOLKIT 
		XtNborderWidth, (XtArgVal)0, 
		NULL);
  caption1 = XtVaCreateManagedWidget("Path:", 
#ifdef USE_Xaw_TOOLKIT
                dialogWidgetClass, upper, 
                XtNlabel, "Path:",
		XtNborderWidth, (XtArgVal)0, 
#else
                captionWidgetClass, upper, 
#endif USE_Xaw_TOOLKIT 
                NULL);
  pd.tf2 = XtVaCreateManagedWidget("popuptf2", 
                textFieldWidgetClass, caption1,
                XtNwidth, (XtArgVal)H_PIXEL(210),
                XtNstring, pathname,
#ifdef USE_Xaw_TOOLKIT
		XtNhorizDistance,	(XtArgVal)H_PIXEL(45),
		XtNeditType,		"edit",
#endif USE_Xaw_TOOLKIT 
                NULL);
  caption2 = XtVaCreateManagedWidget("File:",
#ifdef USE_Xaw_TOOLKIT
                dialogWidgetClass, upper, 
                XtNlabel, "File:",
		XtNborderWidth, (XtArgVal)0, 
#else
                captionWidgetClass, upper, 
#endif USE_Xaw_TOOLKIT 
                NULL);
  pd.tf = XtVaCreateManagedWidget("popuptf", 
                textFieldWidgetClass, caption2,
                XtNwidth, (XtArgVal)H_PIXEL(210),
                XtNstring, filename,
#ifdef USE_Xaw_TOOLKIT
		XtNhorizDistance,	(XtArgVal)H_PIXEL(45),
		XtNeditType,		"edit",
#endif USE_Xaw_TOOLKIT 
                NULL);
  /*
   * Create the ScrollingList widget
   */
  n = 0;
#ifdef USE_Xaw_TOOLKIT
     	box = XtCreateManagedWidget("box", formWidgetClass, rt,
					argue, n);
	n=0;
  XtSetArg(argue[n], XtNforceBars, True); n++;
  XtSetArg(argue[n], XtNallowVert, True); n++;
  XtSetArg(argue[n], XtNborderWidth, 1); n++;
  XtSetArg(argue[n], XtNwidth, 300); n++;
  XtSetArg(argue[n], XtNheight, 200); n++;
  
    MyViewport = XtCreateManagedWidget("vport", viewportWidgetClass, 
				      box, argue, n);
	if (!actions_added) {
	    actions_added = 1;
	    /* add action to load file */
	    XtAppAddActions(app, file_name_actions, XtNumber(file_name_actions));

	}

 	n = 0;   
   XtSetArg(argue[n], XtNdefaultColumns, 1); n++;
  XtSetArg(argue[n], XtNforceColumns, TRUE); n++;

	scrolling_list = XtCreateManagedWidget("list", listWidgetClass,
					    MyViewport, argue, n);
	XtAugmentTranslations(scrolling_list,
			   XtParseTranslationTable(file_list_translations));

#else
  XtSetArg(argue[n], XtNviewHeight, 11); n++;
  XtSetArg(argue[n], XtNselectable, FALSE); n++;
  scrolling_list = XtCreateManagedWidget("scrolling_list",
		                  scrollingListWidgetClass,
                                  rt, argue, n);
#endif USE_Xaw_TOOLKIT
  n = 0;
  XtSetArg(argue[n], XtNapplAddItem,    &AddItem); n++;
  XtSetArg(argue[n], XtNapplTouchItem,  &TouchItem); n++;
  XtSetArg(argue[n], XtNapplUpdateView, &UpdateView); n++;
  XtSetArg(argue[n], XtNapplDeleteItem, &DeleteItem); n++;
  XtSetArg(argue[n], XtNapplViewItem,   &ViewItem); n++;
  XtGetValues(scrolling_list, argue, n);

  button_area = XtVaCreateManagedWidget("",
		controlAreaWidgetClass, rt, 
#ifdef USE_Xaw_TOOLKIT
		XtNshowGrip, (XtArgVal)FALSE, 
#endif USE_Xaw_TOOLKIT
		NULL);
	n = 0;
	XtSetArg(argue[n], XtNset, all_select);n++;
	ALL_checkbox = XtCreateManagedWidget("*.*", 
                checkBoxWidgetClass,
                button_area,
                argue,n);
	n = 0;
	XtSetArg(argue[n], XtNset, tex_select);n++;
#ifdef USE_Xaw_TOOLKIT
	XtSetArg(argue[n], XtNfromHoriz, ALL_checkbox);n++;
	XtSetArg(argue[n], XtNwidth, (XtArgVal)H_PIXEL(50));n++;
	TEX_checkbox = XtCreateManagedWidget("*.tex", 
#else
	TEX_checkbox = XtCreateManagedWidget("       *.tex", 
#endif USE_Xaw_TOOLKIT
                checkBoxWidgetClass,
                button_area,
                argue,n);
	n = 0;
	XtSetArg(argue[n], XtNset, dvi_select);n++;
#ifdef USE_Xaw_TOOLKIT
	XtSetArg(argue[n], XtNfromHoriz, TEX_checkbox);n++;
	XtSetArg(argue[n], XtNwidth, (XtArgVal)H_PIXEL(50));n++;
	DVI_checkbox = XtCreateManagedWidget("*.dvi", 
#else
	DVI_checkbox = XtCreateManagedWidget("       *.dvi", 
#endif USE_Xaw_TOOLKIT
                checkBoxWidgetClass,
                button_area,
                argue,n);

  document_Vorlage = create_fl_ex_nonex(rt, document_VorlageItems,
		document_Vorlages,
                XtNumber(document_Vorlages), "Vorlage: ", 
                flatExclusivesWidgetClass,
                document_Vorlage_callback);
#ifdef USE_Xaw_TOOLKIT
#else
  caption = XtVaCreateManagedWidget("", 
                controlAreaWidgetClass, rt,
                NULL, 0);
  caption = XtVaCreateManagedWidget("", 
                controlAreaWidgetClass, rt,
                NULL, 0);
#endif USE_Xaw_TOOLKIT

  load = XtVaCreateManagedWidget("popupload", 
                oblongButtonWidgetClass,
                lower,
                XtNlabel, "Load",
                NULL);
  cancel = XtVaCreateManagedWidget("popupload", 
                oblongButtonWidgetClass,
                lower,
                XtNlabel, "Cancel",
                NULL);

  pd.st = XtVaCreateManagedWidget("popupst", 
                staticTextWidgetClass, footer,
#ifdef USE_Xaw_TOOLKIT
                XtNlabel,	"",
		XtNresize,	(XtArgVal)FALSE,
		XtNjustify,	XtJustifyLeft,
#else
                XtNstring,	"",
#endif USE_Xaw_TOOLKIT
                XtNgravity,	WestGravity,
                XtNwrap,	FALSE,
                NULL);


#ifdef USE_Xaw_TOOLKIT
  XtAddCallback(scrolling_list, XtNcallback, FileSelected, (XtPointer)&pd);
#else 
  XtAddCallback(scrolling_list, XtNuserMakeCurrent, current_callback, (XtPointer)&pd);
#endif USE_Xaw_TOOLKIT

  XtAddCallback(pd.tf2, XtNverification, next_tf_callback, pd.tf);
  XtAddCallback(pd.tf,  XtNverification, last_tf_callback, load);

  XtAddCallback(load, XtNselect, load_callback, (XtPointer)&pd);
#ifdef USE_Xaw_TOOLKIT
  XtAddCallback(cancel, XtNselect, DismissPopup, (XtPointer)popupLoad_form);
#endif USE_Xaw_TOOLKIT

  XtAddCallback(ALL_checkbox, XtNselect, ALL_callback, NULL);
  XtAddCallback(TEX_checkbox, XtNselect, TEX_callback, NULL);
  XtAddCallback(DVI_checkbox, XtNselect, DVI_callback, NULL);

#ifdef USE_Xaw_TOOLKIT
  XawToggleSetCurrent(document_Vorlage, (XtPointer)(1));
#else
  XtAddCallback(ALL_checkbox, XtNunselect, ALL_callback, NULL);
  XtAddCallback(TEX_checkbox, XtNunselect, TEX_callback, NULL);
  XtAddCallback(DVI_checkbox, XtNunselect, DVI_callback, NULL);
  OlActivateWidget(document_Vorlage,	OL_SELECTKEY, (XtPointer)(1));
#endif USE_Xaw_TOOLKIT
  return(popup);
}


static void
setfilenumber1_callback(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
    filenumber = (int)client_data;

     switch (filenumber) {
      case 0:
        strcpy(scrolldir, actual.input_dir);
        strcpy(scrollfile,actual.input_file);
        break;
      case 1:
        strcpy(scrolldir, actual.edi1_dir);
        strcpy(scrollfile,actual.edi1_file);
        break;
      case 2:
        strcpy(scrolldir, actual.edi2_dir);
        strcpy(scrollfile,actual.edi2_file);
        break;
      case 3:
        strcpy(scrolldir, actual.edi3_dir);
        strcpy(scrollfile,actual.edi3_file);
        break;
      case 4:
        strcpy(scrolldir, actual.edi4_dir);
        strcpy(scrollfile,actual.edi4_file);
        break;
      }
  filename = scrollfile;
  pathname = scrolldir;
  (void) initList(scrolling_list, scrolldir);
  XtVaSetValues(pd.tf,  XtNstring, scrollfile, NULL);
  XtVaSetValues(pd.tf,  XtNinsertPosition, (XtArgVal)strlen(scrollfile), NULL);
  XtVaSetValues(pd.tf2, XtNstring, scrolldir,  NULL);
  XtVaSetValues(pd.tf2, XtNinsertPosition, (XtArgVal)strlen(scrolldir),  NULL);
	OpenPopup(file_button, (XtPointer)loadpopup, (XtPointer)NULL);
}


static void
setfilenumber2_callback(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
    filenumber = (int)client_data;

     switch (filenumber) {
      case 0:
        pathname = inp_path;
        break;
      case 1:
        pathname = edi1_path;
        break;
      case 2:
        pathname = edi2_path;
        break;
      case 3:
        pathname = edi3_path;
        break;
      case 4:
        pathname = edi4_path;
        break;
      }
	Edit_callback(widget, (XtPointer)NULL, (XtPointer)NULL);
}


void
next_tf_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
#else
  OlTextFieldVerify *tfv = (OlTextFieldVerify *)call_data;
  Widget nextwid = (Widget)client_data;

  /*
   * If the user hits return, move focus to specified field
   */
  if(tfv->reason == OlTextFieldReturn)
    if(!OlCallAcceptFocus(nextwid, CurrentTime))
      insert_string( displayTool, "cannot set input focus\n" );
#endif USE_Xaw_TOOLKIT
}



void
last_tf_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
#else
  OlTextFieldVerify *tfv = (OlTextFieldVerify *)call_data;
  Widget nextwid = (Widget)client_data;

  /*
   * If the user hits return, move focus to specified field
   */
  if(tfv->reason == OlTextFieldReturn)
    OlActivateWidget(nextwid, OL_SELECTKEY, (XtPointer)NULL);
#endif USE_Xaw_TOOLKIT
}


void
ALL_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
  Arg       warg[2];
  int       n;
  Boolean   set;
	n=0;
	XtSetArg(warg[n], XtNset, &set); n++;
	XtGetValues(w, warg, n);
	
	if(set == TRUE)
	{ all_select = TRUE;
	 }else
	{ all_select = FALSE;
	 }
	(void) initList(scrolling_list,scrolldir);
}


void
TEX_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
  Arg       warg[2];
  int       n;
  Boolean   set;
	n=0;
	XtSetArg(warg[n], XtNset, &set); n++;
	XtGetValues(w, warg, n);
	
	if(set == TRUE)
	{ tex_select = TRUE;
	 }else
	{ tex_select = FALSE;
	 }
	(void) initList(scrolling_list,scrolldir);
}


void
DVI_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
  Arg       warg[2];
  int       n;
  Boolean   set;
	n=0;
	XtSetArg(warg[n], XtNset, &set); n++;
	XtGetValues(w, warg, n);
	
	if(set == TRUE)
	{ dvi_select = TRUE;
	 }else
	{ dvi_select = FALSE;
	 }
	(void) initList(scrolling_list,scrolldir);
}


void
document_Vorlage_callback(widget, client_data, call_data)
  Widget    widget;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  actual.document_Vorlage = ( (int) client_data ) -1;
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  actual.document_Vorlage = olfcd->item_index;
#endif USE_Xaw_TOOLKIT
}



void
load_callback(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
  popupdata *popd = (popupdata *)client_data;
  struct    stat info;
  char	    path_buf[150],path_buf2[150],myname[300];
  char	    *wargs[12];
  int       size, retval, retval2;
  int	    *statusp = 0,
	    options  = 0,
	    copy_id   = 0;
  int	    l = strlen(path_buf) - 1, l_suf = 0;
  Arg       arg[1];

  /*
   * read the pathname / filename
   */
  bzero( path_buf, 150 );
#ifdef USE_Xaw_TOOLKIT
  XtVaGetValues(popd->tf , XtNstring, &filename, NULL);
  XtVaGetValues(popd->tf2, XtNstring, &pathname, NULL);
#else
  filename = OlTextFieldGetString(popd->tf,  &size);
  pathname = OlTextFieldGetString(popd->tf2, &size);
#endif USE_Xaw_TOOLKIT
  strcpy(myname,pathname);
  if(*filename == '\0') 
    {
      if( strcmp(scrolldir,myname) )
      {	strcpy(scrolldir,myname);
	scrollfile[0]=0;

/*Reset errorMessage */
	XtVaSetValues(popd->st, XtNstring, "\0", NULL);

/*Abfrage auf Unterschied zwischen Text und "angeklicktem lasttoken",
  evtl. neue Scrollliste*/
	(void) initList(scrolling_list,scrolldir);
     	popdown = FALSE;    } 
     else
     {	sprintf(errormsg, " Hey, you didn\'t specify any file ?!");
	XtVaSetValues(popd->st, XtNstring, errormsg, NULL);
	popdown = FALSE;	}
    } 
  else
    {
  
      if( pathname[0] != '\0' )
        { strcat( path_buf, pathname );
	  if( path_buf[strlen(path_buf)-1] != '/' ) strcat(path_buf, "/");
        }

      strcat( path_buf, filename );

  retval = stat( path_buf, &info);
  if(retval != 0) {
     switch (filenumber) {
      case 0:
   /*
    * Testen, ob Suffix ".tex" vorhanden
    */
       while( l > 0 && path_buf[l] != '/' & !l_suf )
        	{  if( path_buf[l] == '.' ) l_suf = l;   else l--;  }

   /*
    * Eventuelle Suffix ".tex" anhaengen:
    */
     if( !l_suf ) {
        strcat( path_buf, ".tex" );
	retval = stat( path_buf, &info);}
        if(retval == 0) { strcat( filename, ".tex" );}
      break;
     default:
      break;}
  }
  if(retval != 0) {
     if(actual.document_Vorlage == 0) {
	/*
	 * Put an error message in the footer
	 */
  	   sprintf(errormsg, "%s :  %s", filename, sys_errlist[errno]);
	   FooterMessage(footer_text, errormsg);
      }else{
	i=0;
    	bzero( path_buf2, 150 );
	wargs[i]=COPY;		i++;
	      switch (actual.document_Vorlage) {
	      case 1:
		if( actual.TeXformat!=1 && actual.TeXformat!=3 ){
		   sprintf( myname, "%s/VORLAGE1_TEX_USER", getenv("HOME") );
        	   strcpy( path_buf2  , myname);
		   retval2 = stat( path_buf2, &info);
		   if(retval2 == 0){ 
		    wargs[i]=path_buf2;}
		   else{
		    wargs[i]=VORLAGE1_TEX_DEFAULT;}
		  } 
		else{
		   sprintf( myname, "%s/VORLAGE1_LATEX_USER", getenv("HOME") );
        	   strcpy( path_buf2  , myname);
		   retval2 = stat( path_buf2, &info);
		   if(retval2 == 0){ 
		    wargs[i]=path_buf2;}
		   else{
		   wargs[i]=VORLAGE1_LATEX_DEFAULT;}
		  } 
	        break;
	      case 2:
		if( actual.TeXformat!=1 && actual.TeXformat!=3 ){
		   sprintf( myname, "%s/VORLAGE2_TEX_USER", getenv("HOME") );
        	   strcpy( path_buf2  , myname);
		   retval2 = stat( path_buf2, &info);
		   if(retval2 == 0){ 
		    wargs[i]=path_buf2;}
		   else{
		    wargs[i]=VORLAGE2_TEX_DEFAULT;}
		  } 
		else{
		   sprintf( myname, "%s/VORLAGE2_LATEX_USER", getenv("HOME") );
        	   strcpy( path_buf2  , myname);
		   retval2 = stat( path_buf2, &info);
		   if(retval2 == 0){ 
		    wargs[i]=path_buf2;}
		   else{
		   wargs[i]=VORLAGE2_LATEX_DEFAULT;}
		  } 
	        break;
	      case 3:
	        break;
              }
	i++; 
    	bzero( path_buf, 150 );
        strcpy( path_buf  , pathname);
  	if( path_buf[strlen(path_buf)-1] != '/' ) strcat(path_buf, "/");
      	strcat( path_buf, filename );
	wargs[i]=path_buf;	i++;
	wargs[i]=0;		i++;

	if( !(copy_id=fork()) ){
		execv( COPYPATH, wargs );
		perror("texshell: cp failed");
	        exit(1);
	}
	waitpid(copy_id, statusp, options);
     }
  }
    XtVaSetValues(popd->st, XtNstring, "\0", NULL);
    popdown = TRUE;
#ifdef USE_Xaw_TOOLKIT
  XawToggleSetCurrent(document_Vorlage, (XtPointer)(1));
  DismissPopup(widget, (XtPointer)popupLoad_form, (XtPointer)NULL); 
#else
  OlActivateWidget(document_Vorlage,	OL_SELECTKEY, (XtPointer)(1));
#endif USE_Xaw_TOOLKIT
    	bzero( path_buf, 150 );
        strcpy( path_buf  , filename);
     switch (filenumber) {
      case 0:
        strcpy( actual.input_file  , filename);
        strcpy( actual.input_dir , pathname);
	strncpy( inp_disp , path_buf , 15);

/*
 * Wecheln der Directory, ermoeglicht Finden der Pfade
 */
	chdir(actual.input_dir);
	strcpy(PWD,actual.input_dir);

	XtSetArg(arg[0], XtNiconName, (XtArgVal)inp_disp);
	XtSetValues(toplevel, arg, 1);

	XtSetArg(arg[0], XtNlabel, inp_disp);
	XtSetValues(file_button, arg, 1);

	build_pathname( actual.input_dir, actual.input_file, inp_path);
	build_pathname( PWD, actual.input_file, dvi_inp_path);

      case 1:
        strcpy( actual.edi1_file , filename);
        strcpy( actual.edi1_dir , pathname);
	strncpy( edi1_disp , path_buf , 12);

	XtSetArg(arg[0], XtNlabel, edi1_disp);
	XtSetValues(editbutton1, arg, 1);

	build_whole_pathname( actual.edi1_dir, actual.edi1_file, edi1_path);
      break;

      case 2:
        strcpy( actual.edi2_file , filename);
        strcpy( actual.edi2_dir , pathname);
	strncpy( edi2_disp , path_buf , 12);

	XtSetArg(arg[0], XtNlabel, edi2_disp);
	XtSetValues(editbutton2, arg, 1);

	build_whole_pathname( actual.edi2_dir, actual.edi2_file, edi2_path);
      break;

      case 3:
        strcpy( actual.edi3_file , filename);
        strcpy( actual.edi3_dir , pathname);
	strncpy( edi3_disp , path_buf , 12);

	XtSetArg(arg[0], XtNlabel, edi3_disp);
	XtSetValues(editbutton3, arg, 1);

	build_whole_pathname( actual.edi3_dir, actual.edi3_file, edi3_path);
      break;

      case 4:
        strcpy( actual.edi4_file , filename);
        strcpy( actual.edi4_dir , pathname);
	strncpy( edi4_disp , path_buf , 12);

	XtSetArg(arg[0], XtNlabel, edi4_disp);
	XtSetValues(editbutton4, arg, 1);

	build_whole_pathname( actual.edi4_dir, actual.edi4_file, edi4_path);
      break;
     }
  }
}


/*****************************************************************/
/*  Properties                                                   */
/*****************************************************************/
Widget
CreatePropPopup(parent)
  Widget parent;
{
  Widget  popup, upper, lower, footer, caption;
  void    verify_callback(), apply_callback(),
	  setDefaults_callback(), 
          reset_callback(), resetFactory_callback(), 
          set_button_defaults();
  Widget  create_fl_ex_nonex(), 
          apply_button, setDefaults_button, reset_button, resetFactory_button;
  void    format_callback(), language_callback(), utilprog_callback(),
          run_callback(), resolution_callback(), 
	  previewer_callback(), shrink_callback(), display_callback();
#ifdef USE_Xaw_TOOLKIT
  Widget  labelwidget;
  int     i;
#endif USE_Xaw_TOOLKIT

  static XtCallbackRec verify[] = {
      { (XtCallbackProc)verify_callback, (XtPointer)NULL },
      { NULL, NULL },
  };
  static XtCallbackRec apply[] = {
      { (XtCallbackProc)apply_callback, (XtPointer)NULL },
      { NULL, NULL },
  };
  static XtCallbackRec setDefaults[] = {
      { (XtCallbackProc)setDefaults_callback, (XtPointer)NULL },
      { NULL, NULL },
  };
  static XtCallbackRec reset[] = {
      { (XtCallbackProc)reset_callback, (XtPointer)NULL },
      { NULL, NULL },
  };
  static XtCallbackRec resetFactory[] = {
      { (XtCallbackProc)resetFactory_callback, (XtPointer)NULL },
      { NULL, NULL },
  };

  popup = XtVaCreatePopupShell("proppopup", 
                popupWindowShellWidgetClass,
                parent,
                XtNapply, apply,
		XtNsetDefaults, setDefaults,
                XtNreset, reset,
                XtNresetFactory, resetFactory,
                XtNverify, verify,
                XtNtitle, "Properties",
                NULL);

#ifndef USE_Xaw_TOOLKIT

  XtVaGetValues(popup,
                XtNupperControlArea, &upper,
                XtNlowerControlArea, &lower,
                XtNfooterPanel,      &footer,
                NULL);
#else
    popupProperties_form	= XtVaCreateManagedWidget(" ", boxWidgetClass, popup,
			XtNorientation,		XtorientVertical,
			XtNborderWidth,		(XtArgVal)0, 
    			NULL, 0);
    upper	= XtVaCreateManagedWidget(" ", boxWidgetClass, popupProperties_form,
			XtNorientation,		XtorientVertical, 
			XtNdefaultDistance,	(XtArgVal)0,
			XtNborderWidth,		(XtArgVal)0,
			XtNvSpace,		(XtArgVal)2,
			XtNfromVert,		popupProperties_form,
    			NULL, 0);
    lower	= XtVaCreateManagedWidget(" ", boxWidgetClass, popupProperties_form,
			XtNorientation,		XtorientHorizontal, 
			XtNborderWidth,		(XtArgVal)0,
			XtNfromVert,		upper,
    			NULL, 0);
/*
    footer	= XtVaCreateManagedWidget(" ", footerPanelWidgetClass, popupProperties_form,
			XtNorientation,		XtorientVertical, 
			XtNx,			(XtArgVal)0,
			XtNdefaultDistance,	(XtArgVal)0,
			XtNborderWidth,		(XtArgVal)0,
			XtNwidth,		(XtArgVal)250,
			XtNfromVert,		lower,
    			NULL, 0);
 */
#endif USE_Xaw_TOOLKIT

  /*
   * Create FlatExclusives and FlatNonexclusives widgets
   */
  format      = create_fl_ex_nonex(upper, formatItems, formats,
                XtNumber(formats), "Format:", 
                flatExclusivesWidgetClass,
                format_callback);
  language    = create_fl_ex_nonex(upper, languageItems, languages,
                XtNumber(languages), "Language:", 
                flatExclusivesWidgetClass,
                language_callback);
#ifdef USE_Xaw_TOOLKIT
  caption = XtVaCreateManagedWidget("", captionWidgetClass,
                     upper,
                     XtNlabel, "run:",
		     XtNorientation,	XtorientHorizontal, 
		     XtNborderWidth,	(XtArgVal)0,
		     XtNhSpace,		(XtArgVal)0,
                     NULL);
    labelwidget = XtVaCreateManagedWidget("", labelWidgetClass,
                     caption,
                     XtNlabel, "run:",
		     XtNborderWidth, (XtArgVal)0, 
                     NULL);
  for(i=0;i<XtNumber(utilprogs);i++) {
    utilprog[i] = XtVaCreateManagedWidget("", 
		     flatNonexclusivesWidgetClass, caption,
                     XtNlabel, (XtArgVal)utilprogs[i],
                     NULL);
   }
  run         = create_fl_ex_nonex(upper, runItems, runs,
                XtNumber(runs), "No. of TeX run's:", 
                flatExclusivesWidgetClass,
                run_callback);
#else
  caption = XtVaCreateManagedWidget("", 
                controlAreaWidgetClass, upper, 
		XtNborderWidth,		(XtArgVal)0,
                NULL);
  utilprog    = create_fl_ex_nonex(caption, utilprogItems, utilprogs,
                XtNumber(utilprogs), "run:", 
                flatNonexclusivesWidgetClass,
                utilprog_callback);
  run         = create_fl_ex_nonex(caption, runItems, runs,
                XtNumber(runs), "No. of TeX run's:", 
                flatExclusivesWidgetClass,
                run_callback);
#endif USE_Xaw_TOOLKIT
  resolution  = create_fl_ex_nonex(upper, resolutionItems, resolutions,
                XtNumber(resolutions), "Resolution:", 
                flatExclusivesWidgetClass,
                resolution_callback);
  previewer   = create_fl_ex_nonex(upper, previewerItems, previewers,
                XtNumber(previewers), "Preview:", 
                flatExclusivesWidgetClass,
                previewer_callback);
  shrink      = create_fl_ex_nonex(upper, shrinkItems, shrinks,
                XtNumber(shrinks), "Shrink:", 
                flatExclusivesWidgetClass,
                shrink_callback);
  display     = create_fl_ex_nonex(upper, displayItems, displays,
                XtNumber(displays), "Display:", 
                flatExclusivesWidgetClass,
                display_callback);

#ifdef USE_Xaw_TOOLKIT
  apply_button = XtVaCreateManagedWidget("", 
                oblongButtonWidgetClass,
                lower,
                XtNlabel, "Apply",
                NULL);
  setDefaults_button = XtVaCreateManagedWidget("", 
                oblongButtonWidgetClass,
                lower,
                XtNlabel, "Set Defaults",
                NULL);
  reset_button = XtVaCreateManagedWidget("", 
                oblongButtonWidgetClass,
                lower,
                XtNlabel, "Reset",
                NULL);
  resetFactory_button = XtVaCreateManagedWidget("", 
                oblongButtonWidgetClass,
                lower,
                XtNlabel, "Reset to Factory",
                NULL);
  XtAddCallback(utilprog[0],  XtNselect, utilprog_callback, (XtPointer)0);
  XtAddCallback(utilprog[1],  XtNselect, utilprog_callback, (XtPointer)1);

  XtAddCallback(apply_button,  XtNselect, apply_callback, (XtPointer)popupProperties_form);
  XtAddCallback(setDefaults_button, XtNselect, setDefaults_callback, (XtPointer)popupProperties_form);
  XtAddCallback(reset_button, XtNselect, reset_callback, (XtPointer)popupProperties_form);
  XtAddCallback(resetFactory_button, XtNselect, resetFactory_callback, (XtPointer)popupProperties_form);
#endif USE_Xaw_TOOLKIT

  /*
   * Set up the defaults
   */
  set_button_defaults(actual);

  return(popup);
}


void
apply_callback(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
  popdown = TRUE;
#ifdef USE_Xaw_TOOLKIT
  DismissPopup(widget, (XtPointer)client_data, (XtPointer)NULL);
#endif USE_Xaw_TOOLKIT
}


void
setDefaults_callback(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
  void  save_rc();

  save_rc(&actual,&defaults);
  popdown = TRUE;
#ifdef USE_Xaw_TOOLKIT
  DismissPopup(widget, (XtPointer)client_data, (XtPointer)NULL);
#endif USE_Xaw_TOOLKIT
}


void
reset_callback(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
  void set_button_defaults();

  set_button_defaults(actual);
}


void
resetFactory_callback(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
  void set_button_defaults(),save_rc();

  memcpy( &actual, &defaults, sizeof(TeXshell_DATA) );
  save_rc(0,0);
  set_button_defaults(actual);
  popdown = FALSE;
}


void
set_button_defaults(settings)
TeXshell_DATA	settings;
{
  Boolean    value;
  int n;
  Arg wargs[2];

#ifdef USE_Xaw_TOOLKIT
  XawToggleSetCurrent(format,	  	(XtPointer)(settings.TeXformat+1)	);
  XawToggleSetCurrent(language,		(XtPointer)(settings.TeXlanguage+1)	);

  if( settings.BiBTeX != actual.BiBTeX ){
	n = 0;
	XtSetArg(wargs[n], XtNset, settings.BiBTeX);n++;
	XtSetValues(utilprog[0], wargs, n);}
  if( settings.MakeIndex != actual.MakeIndex ){
	n = 0;
	XtSetArg(wargs[n], XtNset, settings.MakeIndex);n++;
	XtSetValues(utilprog[1], wargs, n);}
 
  XawToggleSetCurrent(run,			(XtPointer)(settings.TeXrun+1)		);
  XawToggleSetCurrent(resolution,		(XtPointer)settings.i_resolution	);
  XawToggleSetCurrent(previewer,		(XtPointer)settings.i_previewer		);
  XawToggleSetCurrent(shrink,		(XtPointer)settings.i_shrink_factor	);
  XawToggleSetCurrent(display,		(XtPointer)settings.i_leaves		);
#else
  OlActivateWidget(format,	OL_SELECTKEY,  	(XtPointer)(settings.TeXformat+1)	);
  OlActivateWidget(language,	OL_SELECTKEY,	(XtPointer)(settings.TeXlanguage+1)	);

  OlVaFlatGetValues(utilprog, BIBTEXINDEX,	XtNset, &value, NULL);
  if( settings.BiBTeX != value )
	OlActivateWidget(utilprog, OL_SELECTKEY,(XtPointer)(BIBTEXINDEX+1)		);

  OlVaFlatGetValues(utilprog, MAKEINDEXINDEX,	XtNset, &value, NULL);
  if( settings.MakeIndex != value )
	OlActivateWidget(utilprog, OL_SELECTKEY,(XtPointer)(MAKEINDEXINDEX+1)		);

  OlActivateWidget(run,		OL_SELECTKEY,	(XtPointer)(settings.TeXrun+1)		);
  OlActivateWidget(resolution,	OL_SELECTKEY,	(XtPointer)settings.i_resolution	);
  OlActivateWidget(previewer,	OL_SELECTKEY,	(XtPointer)settings.i_previewer		);
  OlActivateWidget(shrink,	OL_SELECTKEY,	(XtPointer)settings.i_shrink_factor	);
  OlActivateWidget(display,	OL_SELECTKEY,	(XtPointer)settings.i_leaves		);
#endif USE_Xaw_TOOLKIT
}


void
format_callback(w, client_data, call_data)
  Widget    w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  actual.TeXformat = ( (int) client_data ) -1;
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  actual.TeXformat = olfcd->item_index;
#endif USE_Xaw_TOOLKIT
}


void
language_callback(w, client_data, call_data)
  Widget    w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  actual.TeXlanguage = ( (int) client_data ) -1;
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  actual.TeXlanguage = olfcd->item_index;
#endif USE_Xaw_TOOLKIT
}


void
utilprog_callback(w, client_data, call_data)
  Widget    w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  Arg       warg[2];
  int       n;
  Boolean   set;
	n=0;
	XtSetArg(warg[n], XtNset, &set); n++;
	XtGetValues(w, warg, n);
	
     switch ((int)client_data) {
      case 0:
	if(set == TRUE)
	{ actual.BiBTeX = TRUE;
	 }else
	{ actual.BiBTeX = FALSE;
	 }
        break;
      case 1:
	if(set == TRUE)
	{ actual.MakeIndex = TRUE;
	 }else
	{ actual.MakeIndex = FALSE;
	 }
        break;
      }
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  /*
   * Get the current state of the buttons
   */
  if(olfcd->item_index == BIBTEXINDEX)
    OlVaFlatGetValues(w, BIBTEXINDEX, XtNset, &actual.BiBTeX, NULL);
  if(olfcd->item_index == MAKEINDEXINDEX)
    OlVaFlatGetValues(w, MAKEINDEXINDEX, XtNset, &actual.MakeIndex, NULL);
#endif USE_Xaw_TOOLKIT
}


void
run_callback(w, client_data, call_data)
  Widget    w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  actual.TeXrun = ( (int) client_data ) -1;
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  actual.TeXrun = olfcd->item_index;
#endif USE_Xaw_TOOLKIT
}


void
resolution_callback(w, client_data, call_data)
  Widget    w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  actual.i_resolution = ( (int) client_data ) ;
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  actual.i_resolution = olfcd->item_index+1;
#endif USE_Xaw_TOOLKIT
  par_translate();
}


void
previewer_callback(w, client_data, call_data)
  Widget    w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  actual.i_previewer = ( (int) client_data ) ;
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  actual.i_previewer = olfcd->item_index+1;
#endif USE_Xaw_TOOLKIT
  par_translate();
}


void
shrink_callback(w, client_data, call_data)
  Widget    w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  actual.i_shrink_factor = ( (int) client_data ) ;
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  actual.i_shrink_factor = olfcd->item_index+1;
#endif USE_Xaw_TOOLKIT
  par_translate();
}


void
display_callback(w, client_data, call_data)
  Widget    w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  actual.i_leaves = ( (int) client_data ) ;
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  actual.i_leaves = olfcd->item_index+1;
#endif USE_Xaw_TOOLKIT
  par_translate();
}


Widget
create_fl_ex_nonex(parent, flitems, names, number,
                           label, class, callback)
  Widget      parent;
  FlatItems   *flitems;
  char       *names[];
  int         number;
  String      label;
  WidgetClass class;
  void        (*callback)();
{
#ifdef USE_Xaw_TOOLKIT
  Widget flat_ex_buttons[10], labelwidget;
#else
  Widget fl_ex_nonex;
#endif USE_Xaw_TOOLKIT
  Widget caption;
  int    i;

  /* Create Exclusives or Nonexclusives widgets */
  caption = XtVaCreateManagedWidget("", captionWidgetClass,
                     parent,
                     XtNlabel, label,
#ifdef USE_Xaw_TOOLKIT
		     XtNorientation,	XtorientHorizontal, 
		     XtNborderWidth,	(XtArgVal)0,
		     XtNhSpace,		(XtArgVal)0,
#endif USE_Xaw_TOOLKIT
                     NULL);
#ifdef USE_Xaw_TOOLKIT
    labelwidget = XtVaCreateManagedWidget("", labelWidgetClass,
                     caption,
                     XtNlabel, label,
		     XtNborderWidth, (XtArgVal)0, 
                     NULL);
    flat_ex_buttons[0] = XtVaCreateManagedWidget("", class, caption,
                     XtNlabel, (XtArgVal)names[0],
                     XtNstate, (XtArgVal)TRUE,
                     XtNradioData, (XtPointer)(1),
                     NULL);
		  XtOverrideTranslations(flat_ex_buttons[0],
			XtParseTranslationTable(
				"<EnterWindow>:highlight(Always)\n\
				 <LeaveWindow>:unhighlight()\n\
				 <Btn1Down>,<Btn1Up>:set()notify()\n"));
 		  XtAddCallback(flat_ex_buttons[0], XtNselect,
			callback, (XtPointer)1);
  for(i=1;i<number;i++) {
    flat_ex_buttons[i] = XtVaCreateManagedWidget("", class, caption,
                     XtNlabel, (XtArgVal)names[i],
                     XtNradioGroup, flat_ex_buttons[0],
                     XtNradioData, (XtPointer)(i+1),
                     NULL);
		  XtOverrideTranslations(flat_ex_buttons[i],
			XtParseTranslationTable(
				"<EnterWindow>:highlight(Always)\n\
				 <LeaveWindow>:unhighlight()\n\
				 <Btn1Down>,<Btn1Up>:set()notify()\n"));
 		  XtAddCallback(flat_ex_buttons[i], XtNselect,
			callback, (XtPointer)(i+1));
   }
 return(flat_ex_buttons[0]);
#else
  for(i=0;i<number;i++) {
    (flitems[i]).label = (XtArgVal)names[i];
    (flitems[i]).selectProc = (XtArgVal)callback;
    if(class == flatNonexclusivesWidgetClass)
      (flitems[i]).unselectProc = (XtArgVal)callback;
    else
      (flitems[i]).unselectProc = (XtArgVal)NULL;
    (flitems[i]).clientData = (XtArgVal)names[i];
  }
  fl_ex_nonex = XtVaCreateManagedWidget("", class, caption,
                     XtNitems, flitems,
                     XtNnumItems, number,
                     XtNitemFields, FlatFields,
                     XtNnumItemFields, XtNumber(FlatFields),
                     NULL);
  return(fl_ex_nonex);
#endif USE_Xaw_TOOLKIT
}



Widget
CreatePrintPopup(parent)
  Widget parent;
{
  Arg		argue[5];
  Position	x, y;
  Dimension	width, height;
  int		n;

 Widget popup, upper, lower, footer;
 Widget control, caption, caption2;
 Widget print, cancel, landscape_checkbox;
#ifdef USE_Xaw_TOOLKIT
  Widget  labelwidget;
  int     i;
#endif USE_Xaw_TOOLKIT
  Widget  create_fl_ex_nonex();
  void  verify_callback(),
	landscape_callback(),
	printresolution_callback(), printzweiseitig_callback(),
	printlanguage_callback(), printdevice_callback(),
	set_print_button_defaults();
  static XtCallbackRec verify[] = {
      { (XtCallbackProc)verify_callback, (XtPointer)NULL },
      { NULL, NULL },
  };

  popup = XtVaCreatePopupShell("printpopup", 
                popupWindowShellWidgetClass,
                parent,
                XtNverify, verify,
                XtNtitle, "Print",
                NULL);
#ifndef USE_Xaw_TOOLKIT

  XtVaGetValues(popup,
                XtNupperControlArea, &upper,
                XtNlowerControlArea, &lower,
                XtNfooterPanel,      &footer,
                NULL);
#else
    popupPrint_form	= XtVaCreateManagedWidget(" ", boxWidgetClass, popup,
			XtNorientation,		XtorientVertical,
			XtNborderWidth,		(XtArgVal)0, 
    			NULL, 0);
    upper	= XtVaCreateManagedWidget(" ", boxWidgetClass, popupPrint_form,
			XtNorientation,		XtorientVertical, 
			XtNdefaultDistance,	(XtArgVal)0,
			XtNborderWidth,		(XtArgVal)0,
			XtNvSpace,		(XtArgVal)2,
			XtNfromVert,		popupPrint_form,
    			NULL, 0);
    lower	= XtVaCreateManagedWidget(" ", boxWidgetClass, popupPrint_form,
			XtNorientation,		XtorientHorizontal, 
			XtNborderWidth,		(XtArgVal)0,
			XtNfromVert,		upper,
    			NULL, 0);
    footer	= XtVaCreateManagedWidget(" ", footerPanelWidgetClass, popupPrint_form,
			XtNorientation,		XtorientVertical, 
			XtNx,			(XtArgVal)0,
			XtNdefaultDistance,	(XtArgVal)0,
			XtNborderWidth,		(XtArgVal)0,
			XtNwidth,		(XtArgVal)250,
			XtNfromVert,		lower,
    			NULL, 0);
#endif USE_Xaw_TOOLKIT

  control = XtVaCreateManagedWidget("control", 
		controlAreaWidgetClass, upper, 
#ifdef USE_Xaw_TOOLKIT
		XtNborderWidth, (XtArgVal)0, 
#endif USE_Xaw_TOOLKIT 
		NULL);
  caption = XtVaCreateManagedWidget("Page:", 
#ifdef USE_Xaw_TOOLKIT
                dialogWidgetClass, control, 
                XtNlabel, "Page:",
		XtNborderWidth, (XtArgVal)0, 
#else
                captionWidgetClass, control, 
#endif USE_Xaw_TOOLKIT 
                NULL);
  print_pd.tf11 = XtVaCreateManagedWidget("popuptf11", 
#ifdef USE_Xaw_TOOLKIT
                textFieldWidgetClass, caption,
#else
                textFieldWidgetClass, control,
#endif USE_Xaw_TOOLKIT 
                XtNwidth,	(XtArgVal)H_PIXEL(50),
                XtNstring,	begin_pageno,
#ifdef USE_Xaw_TOOLKIT
		XtNhorizDistance,	(XtArgVal)H_PIXEL(45),
		XtNeditType,		"edit",
#endif USE_Xaw_TOOLKIT 
                NULL);
  caption2 = XtVaCreateManagedWidget(" - ", 
#ifdef USE_Xaw_TOOLKIT
                dialogWidgetClass, control, 
                XtNlabel, " - ",
		XtNborderWidth, (XtArgVal)0, 
		XtNhorizDistance,	(XtArgVal)H_PIXEL(100),
#else
                captionWidgetClass, control, 
#endif USE_Xaw_TOOLKIT 
                NULL);
  print_pd.tf12 = XtVaCreateManagedWidget("popuptf12", 
#ifdef USE_Xaw_TOOLKIT
                textFieldWidgetClass, caption2,
#else
                textFieldWidgetClass, control,
#endif USE_Xaw_TOOLKIT 
                XtNwidth, (XtArgVal)H_PIXEL(50),
                XtNstring, end_pageno,
#ifdef USE_Xaw_TOOLKIT
		XtNhorizDistance,	(XtArgVal)H_PIXEL(32),
		XtNeditType,		"edit",
#endif USE_Xaw_TOOLKIT 
                NULL);
  control = XtVaCreateManagedWidget("control", 
		controlAreaWidgetClass, upper, 
#ifdef USE_Xaw_TOOLKIT
		XtNborderWidth, (XtArgVal)0, 
#endif USE_Xaw_TOOLKIT 
		NULL);
  caption = XtVaCreateManagedWidget("Number of copies:", 
#ifdef USE_Xaw_TOOLKIT
                dialogWidgetClass, control, 
                XtNlabel, "Number of copies:",
		XtNborderWidth, (XtArgVal)0, 
#else
                captionWidgetClass, control, 
#endif USE_Xaw_TOOLKIT 
                NULL);
  print_pd.tf21 = XtVaCreateManagedWidget("popuptf21", 
#ifdef USE_Xaw_TOOLKIT
                textFieldWidgetClass, caption,
#else
                textFieldWidgetClass, control,
#endif USE_Xaw_TOOLKIT 
                XtNwidth, (XtArgVal)H_PIXEL(50),
                XtNstring, number_of_copies,
#ifdef USE_Xaw_TOOLKIT
		XtNhorizDistance,	(XtArgVal)H_PIXEL(125),
		XtNeditType,		"edit",
#endif USE_Xaw_TOOLKIT 
                NULL);
#ifdef USE_Xaw_TOOLKIT
  caption = XtVaCreateManagedWidget("caption", 
    		labelWidgetClass, control,
                XtNlabel, "Landscape:",
		XtNborderWidth, (XtArgVal)0, 
		XtNhorizDistance,	(XtArgVal)H_PIXEL(200),
		XtNvertDistance,	(XtArgVal)H_PIXEL(8),
                NULL);
landscape_checkbox = XtVaCreateManagedWidget("  ", 
                checkBoxWidgetClass, control,
		XtNhorizDistance,	(XtArgVal)H_PIXEL(275),
                NULL);
#else
landscape_checkbox = XtVaCreateManagedWidget("    Landscape:", 
                checkBoxWidgetClass, control,
                NULL);
#endif USE_Xaw_TOOLKIT 
  control = XtVaCreateManagedWidget("control", 
		controlAreaWidgetClass, upper, 
#ifdef USE_Xaw_TOOLKIT
		XtNborderWidth, (XtArgVal)0, 
#endif USE_Xaw_TOOLKIT 
		NULL);
  caption = XtVaCreateManagedWidget("h_offset:", 
#ifdef USE_Xaw_TOOLKIT
                dialogWidgetClass, control, 
                XtNlabel, "h_offset:",
		XtNborderWidth, (XtArgVal)0, 
#else
                captionWidgetClass, control, 
#endif USE_Xaw_TOOLKIT 
                NULL);
  print_pd.tf31 = XtVaCreateManagedWidget("popuptf31", 
#ifdef USE_Xaw_TOOLKIT
                textFieldWidgetClass, caption,
#else
                textFieldWidgetClass, control,
#endif USE_Xaw_TOOLKIT 
                XtNwidth, (XtArgVal)H_PIXEL(50),
                XtNstring, h_offset,
#ifdef USE_Xaw_TOOLKIT
		XtNhorizDistance,	(XtArgVal)H_PIXEL(70),
		XtNeditType,		"edit",
#endif USE_Xaw_TOOLKIT 
                NULL);
  caption = XtVaCreateManagedWidget("caption", 
#ifdef USE_Xaw_TOOLKIT
    		labelWidgetClass, control,
                XtNlabel, "mm   ",
		XtNborderWidth, (XtArgVal)0, 
		XtNhorizDistance,	(XtArgVal)H_PIXEL(125),
		XtNvertDistance,	(XtArgVal)H_PIXEL(8),
#else
                staticTextWidgetClass, control, 
                XtNstring, "mm   ",
#endif USE_Xaw_TOOLKIT
                NULL);
  caption2 = XtVaCreateManagedWidget("v_offset:", 
#ifdef USE_Xaw_TOOLKIT
                dialogWidgetClass, control, 
                XtNlabel, "v_offset:",
		XtNborderWidth, (XtArgVal)0, 
		XtNhorizDistance,	(XtArgVal)H_PIXEL(170),
#else
                captionWidgetClass, control, 
#endif USE_Xaw_TOOLKIT 
                NULL);
  print_pd.tf32 = XtVaCreateManagedWidget("popuptf32", 
#ifdef USE_Xaw_TOOLKIT
                textFieldWidgetClass, caption2,
#else
                textFieldWidgetClass, control,
#endif USE_Xaw_TOOLKIT 
                XtNwidth, (XtArgVal)H_PIXEL(50),
                XtNstring, v_offset,
#ifdef USE_Xaw_TOOLKIT
		XtNhorizDistance,	(XtArgVal)H_PIXEL(70),
		XtNeditType,		"edit",
#endif USE_Xaw_TOOLKIT 
                NULL);
  caption = XtVaCreateManagedWidget("caption", 
#ifdef USE_Xaw_TOOLKIT
    		labelWidgetClass, control,
                XtNlabel, "mm   ",
		XtNborderWidth, (XtArgVal)0, 
		XtNhorizDistance,	(XtArgVal)H_PIXEL(290),
		XtNvertDistance,	(XtArgVal)H_PIXEL(8),
#else
                staticTextWidgetClass, control, 
                XtNstring, "mm   ",
#endif USE_Xaw_TOOLKIT
                NULL);
  control = XtVaCreateManagedWidget("", 
                controlAreaWidgetClass, upper, 
		XtNborderWidth,		(XtArgVal)0,
                NULL);
#ifdef USE_Xaw_TOOLKIT
#else
  caption = XtVaCreateManagedWidget("Print ", 
                captionWidgetClass, control, 
                NULL);
#endif USE_Xaw_TOOLKIT
#ifdef USE_Xaw_TOOLKIT
  caption = XtVaCreateManagedWidget("", captionWidgetClass,
                     control,
                     XtNlabel, "Print:",
		     XtNorientation,	XtorientHorizontal, 
		     XtNborderWidth,	(XtArgVal)0,
		     XtNhSpace,		(XtArgVal)0,
                     NULL);
    labelwidget = XtVaCreateManagedWidget("", labelWidgetClass,
                     caption,
                     XtNlabel, "Print:",
		     XtNborderWidth, (XtArgVal)0, 
                     NULL);
  for(i=0;i<XtNumber(printzweiseitigs);i++) {
    printzweiseitig[i] = XtVaCreateManagedWidget("", 
		     flatNonexclusivesWidgetClass, caption,
                     XtNlabel, (XtArgVal)printzweiseitigs[i],
                     XtNstate, (XtArgVal)TRUE,
                     NULL);
   }
#else
  printzweiseitig    = create_fl_ex_nonex(control, printzweiseitigItems,
		printzweiseitigs,
                XtNumber(printzweiseitigs), "", 
                flatNonexclusivesWidgetClass,
                printzweiseitig_callback);
#endif USE_Xaw_TOOLKIT
  caption = XtVaCreateManagedWidget(" pages ", 
#ifdef USE_Xaw_TOOLKIT
    		labelWidgetClass, control,
                XtNlabel, " pages ",
		XtNborderWidth, (XtArgVal)0, 
		XtNhorizDistance,	(XtArgVal)H_PIXEL(120),
		XtNvertDistance,	(XtArgVal)H_PIXEL(8),
#else
                captionWidgetClass, control, 
#endif USE_Xaw_TOOLKIT
                NULL);
  printresolution    = create_fl_ex_nonex(upper, printresolutionItems,
		printresolutions,
                XtNumber(printresolutions), "Resolution:", 
                flatExclusivesWidgetClass,
                printresolution_callback);
  printlanguage    = create_fl_ex_nonex(upper, printlanguageItems,
		printlanguages,
                XtNumber(printlanguages), "Print as:", 
                flatExclusivesWidgetClass,
                printlanguage_callback);
  printdevice      = create_fl_ex_nonex(upper, printdeviceItems,
		printdevices,
                XtNumber(printdevices), "Print on:", 
                flatExclusivesWidgetClass,
                printdevice_callback);
  print = XtVaCreateManagedWidget("popupprint", 
                oblongButtonWidgetClass,
                lower,
                XtNlabel, "Print",
                NULL);
  cancel = XtVaCreateManagedWidget("", 
                oblongButtonWidgetClass,
                lower,
                XtNlabel, "Cancel",
                NULL);
  print_pd.st = XtVaCreateManagedWidget("", 
                staticTextWidgetClass, footer,
#ifdef USE_Xaw_TOOLKIT
                XtNlabel,	"",
		XtNresize,	(XtArgVal)FALSE,
		XtNjustify,	XtJustifyLeft,
#else
                XtNstring,	"",
#endif USE_Xaw_TOOLKIT
                XtNgravity, WestGravity,
                XtNwrap, FALSE,
                NULL);

  XtAddCallback(print, XtNselect, Print_callback, (XtPointer)&print_pd);
  XtAddCallback(landscape_checkbox, XtNselect, landscape_callback, NULL);
#ifdef USE_Xaw_TOOLKIT
  XtAddCallback(cancel, XtNselect, DismissPopup, (XtPointer)popupPrint_form);
  XtAddCallback(printzweiseitig[0],  XtNselect, printzweiseitig_callback, (XtPointer)0);
  XtAddCallback(printzweiseitig[1],  XtNselect, printzweiseitig_callback, (XtPointer)1);
#else
  XtAddCallback(landscape_checkbox, XtNunselect, landscape_callback, NULL);
#endif USE_Xaw_TOOLKIT

  /*
   * Set up the defaults
   */
  set_print_button_defaults(actual);

  return(popup);
}


void
set_print_button_defaults(settings)
TeXshell_DATA	settings;
{
  Boolean	value;
  int n;
  Arg wargs[2];

#ifdef USE_Xaw_TOOLKIT

  if( settings.OddPages != actual.OddPages ){
	n = 0;
	XtSetArg(wargs[n], XtNset, settings.OddPages);n++;
	XtSetValues(printzweiseitig[0], wargs, n);}
  if( settings.EvenPages != actual.EvenPages ){
	n = 0;
	XtSetArg(wargs[n], XtNset, settings.EvenPages);n++;
	XtSetValues(printzweiseitig[1], wargs, n);}
  
  XawToggleSetCurrent(printresolution,	 (XtPointer)(1+settings.printresolution));
  XawToggleSetCurrent(printlanguage,	 (XtPointer)(1+settings.printlanguage));
  XawToggleSetCurrent(printdevice,		 (XtPointer)(1+settings.printdevice));
#else
  OlVaFlatGetValues(printzweiseitig, ODDPAGESINDEX, XtNset, &value, NULL);
  if( value != settings.OddPages )
    OlActivateWidget(printzweiseitig, OL_SELECTKEY, (XtPointer)(ODDPAGESINDEX+1));

  OlVaFlatGetValues(printzweiseitig, EVENPAGESINDEX, XtNset, &value, NULL);
  if( value != settings.EvenPages )
    OlActivateWidget(printzweiseitig,	OL_SELECTKEY, (XtPointer)(EVENPAGESINDEX+1));

  OlActivateWidget(printresolution,	OL_SELECTKEY, (XtPointer)(1+settings.printresolution));
  OlActivateWidget(printlanguage,	OL_SELECTKEY, (XtPointer)(1+settings.printlanguage));
  OlActivateWidget(printdevice,		OL_SELECTKEY, (XtPointer)(1+settings.printdevice));
#endif USE_Xaw_TOOLKIT
}


void
printzweiseitig_callback(w, client_data, call_data)
  Widget    w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  Arg       warg[2];
  int       n;
  Boolean   set;
	n=0;
	XtSetArg(warg[n], XtNset, &set); n++;
	XtGetValues(w, warg, n);
	
     switch ((int)client_data) {
      case 0:
	if(set == TRUE)
	{ actual.OddPages = TRUE;
	 }else
	{ actual.OddPages = FALSE;
        break;
      case 1:
	 }
	if(set == TRUE)
	{ actual.EvenPages = TRUE;
	 }else
	{ actual.EvenPages = FALSE;
	 }
        break;
      }
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  /*
   * Get the current state of the buttons
   */
  if(olfcd->item_index == ODDPAGESINDEX)
    OlVaFlatGetValues(w, ODDPAGESINDEX, XtNset, &actual.OddPages, NULL);
  if(olfcd->item_index == EVENPAGESINDEX)
    OlVaFlatGetValues(w, EVENPAGESINDEX, XtNset, &actual.EvenPages, NULL);
#endif USE_Xaw_TOOLKIT
}


void
printresolution_callback(widget, client_data, call_data)
  Widget    widget;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  actual.printresolution = ( (int) client_data ) -1;
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  actual.printresolution = olfcd->item_index;
#endif USE_Xaw_TOOLKIT
}


void
landscape_callback(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
  Arg       warg[2];
  int       n;
  Boolean   set;
	n=0;
	XtSetArg(warg[n], XtNset, &set); n++;
	XtGetValues(widget, warg, n);
	
	if(set == TRUE)
	{ landscape = TRUE;
	 }else
	{ landscape = FALSE;
	 }
}


void
printlanguage_callback(widget, client_data, call_data)
  Widget    widget;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  actual.printlanguage = ( (int) client_data ) -1;
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  actual.printlanguage = olfcd->item_index;
#endif USE_Xaw_TOOLKIT
}


void
printdevice_callback(widget, client_data, call_data)
  Widget    widget;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
  actual.printdevice = ( (int) client_data ) -1;
#else
  OlFlatCallData *olfcd = (OlFlatCallData *)call_data;

  actual.printdevice = olfcd->item_index;
#endif USE_Xaw_TOOLKIT
}




Widget
CreateEditorPopup(parent)
  Widget parent;
{
    Arg         wargs[10];
    int		n;
 Widget upper, lower, footer;
 Widget control, caption1, caption2, caption3, rt, sw, dt;
 Widget File_button, View_button, Edit_button, Find_button;
  void  verify_callback();
  static XtCallbackRec verify[] = {
      { (XtCallbackProc)verify_callback, (XtPointer)NULL },
      { NULL, NULL },
  };

  TEpopup = XtVaCreatePopupShell("TextEditorpopup", 
                popupWindowShellWidgetClass,
                parent,
#ifndef USE_Xaw_TOOLKIT
		XtNpushpin, (XtArgVal)OL_IN,
		XtNresizeCorners, (XtArgVal)TRUE,
#endif USE_Xaw_TOOLKIT
		XtNx, (XtArgVal)600,
		XtNy, (XtArgVal)320,
                XtNverify, verify,
                XtNtitle, "TeX - Edit",
                NULL);

#ifndef USE_Xaw_TOOLKIT

  XtVaGetValues(TEpopup,
                XtNupperControlArea, &upper,
                XtNlowerControlArea, &lower,
                XtNfooterPanel,      &footer,
                NULL);
#else
    popupEditor_form	= XtVaCreateManagedWidget(" ", boxWidgetClass, TEpopup,
			XtNorientation,		XtorientVertical,
			XtNborderWidth,		(XtArgVal)0, 
    			NULL, 0);
    upper	= XtVaCreateManagedWidget(" ", boxWidgetClass, popupEditor_form,
			XtNorientation,		XtorientVertical, 
			XtNdefaultDistance,	(XtArgVal)0,
			XtNborderWidth,		(XtArgVal)0,
			XtNvSpace,		(XtArgVal)2,
			XtNfromVert,		popupProperties_form,
    			NULL, 0);
    lower	= XtVaCreateManagedWidget(" ", boxWidgetClass, popupEditor_form,
			XtNorientation,		XtorientHorizontal, 
			XtNborderWidth,		(XtArgVal)0,
			XtNfromVert,		upper,
    			NULL, 0);
#endif USE_Xaw_TOOLKIT


#ifndef USE_Xaw_TOOLKIT
  control = XtCreateManagedWidget("control", controlAreaWidgetClass,
                             upper, NULL, 0);
  File_button = XtVaCreateManagedWidget("popupfile", 
                menuButtonWidgetClass,
                control,
                XtNlabel, "File",
                NULL);
  View_button = XtVaCreateManagedWidget("popupview", 
                menuButtonWidgetClass,
                control,
                XtNlabel, "View",
                NULL);
  Edit_button = XtVaCreateManagedWidget("popupedit", 
                menuButtonWidgetClass,
                control,
                XtNlabel, "Edit",
                NULL);
  Find_button = XtVaCreateManagedWidget("popupfind", 
                menuButtonWidgetClass,
                control,
                XtNlabel, "Find",
                NULL);
  caption1 = XtVaCreateManagedWidget("        Zeile:", 
                captionWidgetClass, control, 
                NULL);
  TEst1 = XtVaCreateManagedWidget("popupst1", 
                textFieldWidgetClass, control,
                XtNcharsVisible, 6,
                XtNstring, "1",
                NULL);
  caption2 = XtVaCreateManagedWidget("   Spalte:", 
                captionWidgetClass, control, 
                NULL);
  TEst2 = XtVaCreateManagedWidget("popupst2", 
                textFieldWidgetClass, control,
                XtNcharsVisible, 4,
                XtNstring, "1",
                NULL);
  caption3 = XtVaCreateManagedWidget("   ", 
                captionWidgetClass, control, 
                NULL);

   n = 0;
   XtSetArg(wargs[n], XtNdndPreviewHints,
		OlDnDSitePreviewDefaultSite); n++;
   dt = XtCreateManagedWidget("dt", dropTargetWidgetClass,
		control, wargs, n);
   rt = XtCreateManagedWidget("rt", rubberTileWidgetClass,
		lower, NULL, 0);
/*
   n = 0;
   XtSetArg(wargs[n], XtNforceVerticalSB, (XtArgVal)TRUE);n++;
   sw = XtVaCreateManagedWidget("sw", scrolledWindowWidgetClass,
		lower, wargs, n);
*/
   sw = XtVaCreateManagedWidget("sw", scrolledWindowWidgetClass,
		rt,
		XtNforceVerticalSB, (XtArgVal)TRUE,
		NULL, 0);

   texteditor = XtVaCreateManagedWidget("popupte", 
                textEditWidgetClass, sw,
		XtNcharsVisible, 72,
		XtNlinesVisible, 30,
		XtNwrapMode, (XtArgVal)OL_WRAP_OFF,
		XtNgrowMode, (XtArgVal)OL_GROW_HORIZONTAL,
		XtNsourceType, (XtArgVal)OL_DISK_SOURCE,
		NULL, 0);
   XtAddCallback(texteditor, XtNmodifyVerification, modify_callback, NULL);
   XtAddCallback(texteditor, XtNmotionVerification, motion_callback, NULL);
#endif USE_Xaw_TOOLKIT
  return(TEpopup);
}


static void
modify_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
#else
 static char	zeile[6], spalte[3];
 OlTextModifyCallData *modified = (OlTextModifyCallData*)call_data;
#endif USE_Xaw_TOOLKIT
}


static void
motion_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
  Arg		wargs[10];
  int		n;
  char		zeile[6], spalte[3];
  int		izeile, ispalte;

#ifdef USE_Xaw_TOOLKIT
#else
 OlTextMotionCallData *moved = (OlTextMotionCallData*)call_data;
 izeile = LineOfPosition(OlTextEditTextBuffer(texteditor),
				moved->new_cursor) +1;
 ispalte = RowOfPosition(OlTextEditTextBuffer(texteditor),
				moved->new_cursor,izeile) +1;
	sprintf( spalte, "%d", ispalte);
	sprintf( zeile,  "%d", izeile);


	n = 0;
	XtSetArg(wargs[n], XtNstring, zeile);n++;
	XtSetValues(TEst1, wargs, n);
	n = 0;
	XtSetArg(wargs[n], XtNstring, spalte);n++;
	XtSetValues(TEst2, wargs, n);
#endif USE_Xaw_TOOLKIT
}


static void
TeX_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
    int		*statusp = 0,
		options  = 0;

      if(Tex_id)
	{

/* KILLProcessGroup fuer TeXruns und Tochterprogramme (s. TeXruns) */
		(void)kill((pid_t)-Tex_id, SIGKILL);
		waitpid(-Tex_id, statusp, options);
	}
      
 { int	to_tex[2], /* pipe descriptors from parent->child */
	to_shell[2],/* pipe descriptors from child->parent */
	to_shell_Err[2];/* pipe descriptors from child->parent */

      reset_displayTool();

      pipe(to_tex);
      pipe(to_shell);

	pipe(to_shell_Err);
	redirect_input( &Err_in, to_shell_Err[0] );

      if(!(Tex_id=fork()) ) TeXruns(to_tex,to_shell,to_shell_Err);
      else
      if( Tex_id>0 )
      {
	redirect_input( &from_TeX, to_shell[0] );

	if( to_Child )
		dup2(to_tex[1], to_Child );
	else
		to_Child=dup(to_tex[1]);

	close(to_tex[0]);         /* close pipes */
	close(to_tex[1]);
	close(to_shell[0]);
	close(to_shell[1]);
	close(to_shell_Err[0]);	/* close pipes     */
	close(to_shell_Err[1]);

      }
 }

}



static void
Preview_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
    struct      stat info;
    int         retval,
		to_shell_Err[2],/* pipe descriptors from child->parent */
		to_shell_Out[2];/* pipe descriptors from child->parent */
 
    char 	buf[200];
    int		*statusp = 0,
		options  = 0;
    if(Dvi_id){
	(void)kill((pid_t)-Dvi_id, SIGTERM);
	waitpid(-Dvi_id, statusp, options);	}

    if( dvi_inp_path[0] == '\0' )
	insert_string( displayTool,"\nZuerst Input-Text einladen!\n");
    else
    {

	pipe(to_shell_Err);
	pipe(to_shell_Out);

	if( !(Dvi_id=fork()) )
	  {
/* Previewer und Tochterprogramme bilden eigene Prozessgruppe! */
		setpgrp();

		dup2(to_shell_Out[1], 1);	/* redirect stdout*/
		dup2(to_shell_Err[1], 2);	/* redirect stderr*/

		close(to_shell_Err[0]);		/* close pipes    */
		close(to_shell_Err[1]);
		close(to_shell_Out[0]);
		close(to_shell_Out[1]);

		bzero( buf, 200 );
		strcpy( buf, dvi_inp_path );
		strcat( buf, ".dvi" );
		retval = stat( buf, &info);
		if(retval != 0) {
			bzero( buf, 200 );
			strcpy( buf, inp_path );
			strcat( buf, ".dvi" );
			retval = stat( buf, &info);
			if(retval != 0) {
			   fprintf(stderr, "\nDVI-File nicht gefunden!\n" );
			   exit(0);
			 }
			strcpy( dvi_inp_path, inp_path );
			strcpy( buf, dvi_inp_path );
			strcat( buf, ".dvi" );
		  }

    	switch (actual.i_previewer) {
      	  case 0:
	    break;
      	  case 1:
      	  	    i = 0;
      	  	    if(landscape) i = 1;
		    execl( XDVIPATH,   XDVI,
        /* Starting page  	*/		           p_begin_pageno,
        /* ignore specials	*/		"-hushspecials",
        /* initial shrink (1-4) */		"-s",       shrink_factor,
#ifdef linux
        /* Geometrie	  	*/		"-geometry",    "630x738",
        /* IconGeometrie	*/		"-icongeometry","-472+0",
#else
        /* Geometrie	  	*/		"-geometry",    "630x850",
        /* IconGeometrie	*/		"-icongeometry","-600+0",
#endif linux
	/* Resolution in dpi	*/     	 	"-p",           dpi,
	/* Paper size (DIN A4)	*/     	 	"-paper", papersize[i],
	/* Home X-Position	*/             	"-sidemargin",  home_x,
	/* Home Y-Position	*/             	"-topmargin",   home_y,
	/* backgroundColor	*/             	"-bg", 		"White",
	/* borderColor		*/             	"-bd", 		"Blue",
	/* cursorColor		*/             	"-cr", 		"Blue",
	/* Paper borderColor	*/             	"-hl", 		"Blue",
	/* darkness		*/		"-gamma",	"2.0",
					   	buf,
					   	(char*)0);
	    break;
      	  case 2:
		    execl( TEXXPATH,   TEXX,
        /* Starting page  (funktioniert nicht)  "-pg",  begin_pageno, */
        /* normal shrink (1-4)			"-ns",  shrink_factor,*/
        /* Geometrie (...i_shrink_factor)       "=",    "300x400",    */
	/* Resolution in dpi	     	*/ 	"-dpi", dpi,
	/* Home X-Position	         */   	"-sm",  home_x,	      
	/* Home Y-Position	          */   	"-tm",  home_y,	     
        /* Number of leaves (1 or 2)    */      "-l",   leaves,
					   	buf,
					 	0);
	    break;
      	  case 3:
		bzero( buf, 200 );
		strcpy( buf, dvi_inp_path );
		strcat( buf, ".ps" );
		retval = stat( buf, &info);
		if(retval != 0) {
			bzero( buf, 200 );
			strcpy( buf, inp_path );
			strcat( buf, ".ps" );
			retval = stat( buf, &info);
			if(retval != 0) {
			   fprintf(stderr, "\nPS-File nicht gefunden!\n" );
			   exit(0);
			 }
			strcpy( dvi_inp_path, inp_path );
			strcpy( buf, dvi_inp_path );
			strcat( buf, ".ps" );
		  }
		    execl( GHOSTVIEWPATH,   GHOSTVIEW,
	/* Window-Position			"-Wp", "0",	"0",        */
	/* Window-Size in Pixel 		"-Ws", b_Dvi,	"900",	    */
#ifdef linux
        /* Geometrie	  	*/		"-geometry",    "630x738+0+0",
#else
        /* Geometrie	  	*/		"-geometry",    "630x850+0+0",
#endif linux
	/* Resolution in dpi	*/     	 	"-dpi",   "55",
	/* Paper size (DIN A4)	*/     	 	"-a4",
	/* Datum in Ghostview	*/     	 	"-nodate",
						buf,
						0);
	    break;
      	  case 4:
		bzero( buf, 200 );
		strcpy( buf, dvi_inp_path );
		strcat( buf, ".ps" );
		retval = stat( buf, &info);
		if(retval != 0) {
			bzero( buf, 200 );
			strcpy( buf, inp_path );
			strcat( buf, ".ps" );
			retval = stat( buf, &info);
			if(retval != 0) {
			   fprintf(stderr, "\nPS-File nicht gefunden!\n" );
			   exit(0);
			 }
			strcpy( dvi_inp_path, inp_path );
			strcpy( buf, dvi_inp_path );
			strcat( buf, ".ps" );
		  }
		    execl( GSPREVIEWPATH,   GSPREVIEW,
#ifdef linux
        /* Geometrie	  	*/		"-geometry",    "628x738+0+0",
#else
        /* Geometrie	  	*/		"-geometry",    "628x850+0+0",
#endif linux
	/* Resolution in dpi	     	 	"-res",   "300",  */
	/* Paper size (DIN A4)     	 	"-paper A4",   	  */
						buf,
						0);
	    break;
	}
	    perror("texshell, Ausgabe");
	    exit(1);
	  }
	else
	  {
	        redirect_input( &Out_in, to_shell_Out[0] );
	        redirect_input( &Err_in, to_shell_Err[0] );

		close(to_shell_Err[0]);	/* close pipes    */
		close(to_shell_Err[1]);
		close(to_shell_Out[0]);
		close(to_shell_Out[1]);
	  }
    }
}




static void
Print_callback(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
  int		*statusp = 0,
		options  = 0,
		to_shell_Err[2];/* pipe descriptors from child->parent */
 print_popupdata *print_pd = (print_popupdata *)client_data;

 if(Print_id){
/* KILLProcessGroup fuer Printruns und Tochterprogramme (s. Printruns) */
		(void)kill((pid_t)-Print_id, SIGKILL);
		waitpid(-Print_id, statusp, options);
 }
      
 reset_displayTool();
  DismissPopup(widget, (XtPointer)popupPrint_form, (XtPointer)NULL); 

 pipe(to_shell_Err);
 redirect_input( &Err_in, to_shell_Err[0]);

 if(!(Print_id=fork()) )
	Printruns(to_shell_Err,print_pd);

/* close pipes     */

 close(to_shell_Err[0]);
 close(to_shell_Err[1]);
}


static void
Printruns(to_shell_Err,print_pd)
	int		to_shell_Err[2];/* pipe descriptors from child->parent */
	print_popupdata	*print_pd;
{
 int	*statusp = 0,
	options  = 0,
	run_id   = 0,
	to_printer[2],	/* pipe descriptors from dvilj2p->lpr	*/
	to_filter[2],	/* pipe descriptors from dvips->gs	*/
	size, retval;


 struct      stat info;

 char 	buf[200];
#ifdef USE_Xaw_TOOLKIT
 char 	*buf1;
#endif USE_Xaw_TOOLKIT
 char	*wargs[20];



/* Printruns und Tochterprogramme bilden eigene Prozessgruppe! */
  setpgrp();


/* Kanal umlenken */
  dup2(to_shell_Err[1], 2);	/* redirect stderr	*/

/* close pipes */
  close(to_shell_Err[0]);
  close(to_shell_Err[1]);


  if( dvi_inp_path[0] == '\0' ){
	fprintf( stderr, "\nZuerst Input-Text einladen!\n");
	exit(1);
  }

  strcpy( buf, dvi_inp_path );
  strcat( buf, ".dvi" );
  retval = stat( buf, &info);
  if(retval != 0){
	strcpy( buf, inp_path );
	strcat( buf, ".dvi" );
	retval = stat( buf, &info);
	if(retval != 0){
		fprintf( stderr, "\nDvi-File: %s nicht gefunden!\n",dvi_inp_path);
		exit(1);
	}
	strcpy( dvi_inp_path, inp_path );
  }


/* Beginn evtl. Drucker ansprechen */
if(actual.printdevice<MAXDEVICES){

/* pipe  -> lpr	*/
	pipe(to_printer);
/* fork -> lpr */
	if( !fork() ){
		dup2(to_printer[0],   0);	/* redirect stdin */

		close(to_printer[0]);
		close(to_printer[1]);

		printer_args[position_of_Printer_name]=printername[actual.printdevice];

		execv( PRINTERPATH, printer_args );
		perror("xtexshell, Printruns, lp:");
	}
}

if(actual.printlanguage==1 || actual.printdevice==DESKJET){

/* PostScript Output */
#ifdef USE_Xaw_TOOLKIT
   strcpy( begin_pageno, "-p");
	XtVaGetValues(print_pd->tf11 , XtNstring, &buf1, NULL);
   strcat( begin_pageno, buf1);
   strcpy( end_pageno, "-l" );
	XtVaGetValues(print_pd->tf12 , XtNstring, &buf1, NULL);
   strcat( end_pageno,   buf1);
   strcpy( number_of_copies, "-c" );
	XtVaGetValues(print_pd->tf21 , XtNstring, &buf1, NULL);
   strcat( number_of_copies, buf1);
   strcpy( h_offset, "-O" );
	XtVaGetValues(print_pd->tf31 , XtNstring, &buf1, NULL);
   strcat( h_offset, buf1);
   strcat( h_offset, "mm,");
	XtVaGetValues(print_pd->tf32 , XtNstring, &buf1, NULL);
   strcat( h_offset, buf1);
   strcat( h_offset, "mm" );
/*
   XawToggleGetCurrent(printzweiseitig, 0, XtNset, &actual.OddPages, NULL);
   XawToggleGetCurrent(printzweiseitig, 1, XtNset, &actual.EvenPages, NULL);
 */
#else
   strcpy( begin_pageno, "-p");
   strcat( begin_pageno, OlTextFieldGetString(print_pd->tf11, &size));
   strcpy( end_pageno, "-l" );
   strcat( end_pageno,   OlTextFieldGetString(print_pd->tf12, &size));
   strcpy( number_of_copies, "-c" );
   strcat( number_of_copies, OlTextFieldGetString(print_pd->tf21, &size));
   strcpy( h_offset, "-O" );
   strcat( h_offset, OlTextFieldGetString(print_pd->tf31, &size));
   strcat( h_offset, "mm,");
   strcat( h_offset, OlTextFieldGetString(print_pd->tf32, &size));
   strcat( h_offset, "mm" );
   OlVaFlatGetValues(printzweiseitig, 0, XtNset, &actual.OddPages, NULL);
   OlVaFlatGetValues(printzweiseitig, 1, XtNset, &actual.EvenPages, NULL);
#endif USE_Xaw_TOOLKIT

   i=0;
   wargs[i]=dvipsargs[0];				i++;
   if( !actual.printresolution){
/* 300DPI */
	   wargs[i]=dvipsargs[1];		i++;
   }else{
/* 600DPI */
	   wargs[i]=dvipsargs[2];		i++;
	   wargs[i]=dvipsargs[3];		i++;
   }
#ifdef linux
   wargs[i]=dvipsargs[9];			i++;
#endif
   if(actual.OddPages  && !actual.EvenPages)
		{wargs[i]=dvipsargs[4];	i++; } /*odd  pages only*/
   if(actual.EvenPages && !actual.OddPages )
		{wargs[i]=dvipsargs[5];	i++; } /*even pages only*/
   wargs[i]=number_of_copies;			i++;
   wargs[i]=begin_pageno;			i++;
   wargs[i]=end_pageno;				i++;
   wargs[i]=h_offset;				i++;
   if(landscape)
		{ wargs[i]=dvipsargs[6];	i++; }
   wargs[i]=dvi_inp_path;			i++;
   wargs[i]=dvipsargs[7];			i++;

   if(actual.printdevice<MAXDEVICES){

/* Output on Printer via GhostScript! */

/* pipe  -> gs	*/
	pipe(to_filter);

/* fork -> gs */
	if( !fork() ){
		dup2(to_printer[1],	1);	/* redirect stdout */
		dup2(to_filter[0],	0);	/* redirect stdin */
		close(to_printer[0]);
		close(to_printer[1]);
		close(to_filter[0]);
		close(to_filter[1]);

		GS_args[2]=GS_devices[actual.printdevice];
		execv( GSPATH, GS_args );
		perror("xtexshell, Printruns, gs:");
	} else
/* fork -> Output */
	if( !(run_id=fork()) ){
		wargs[i]=dvipsargs[8];		i++;
		wargs[i]=0;
		dup2(to_filter[1],   1);	/* redirect stdout */
		close(to_printer[0]);
		close(to_printer[1]);
		close(to_filter[0]);
		close(to_filter[1]);
/* send contents of dvi-File ( PS-Code ) */
	{
		int	jj;
		fprintf(stderr,"%s",wargs[0]);
		for (jj=1;jj<i;jj++)	fprintf(stderr," %s",wargs[jj]);
		fprintf(stderr,"\n");
		fflush(stderr);
	}
		execv( DVIPSPATH, wargs );
		perror("texshell, Printruns: dvips");
	}
   }else{
/* Output on File! */
	sprintf( buf, "-o%s.ps",dvi_inp_path);
	wargs[i]=buf;			i++;
	wargs[i]=0;
	if( !(run_id=fork()) ){
/* send contents of dvi-File ( PS-Code ) */
	{
		int	jj;
		fprintf(stderr,"%s",wargs[0]);
		for (jj=1;jj<i;jj++)	fprintf(stderr," %s",wargs[jj]);
		fprintf(stderr,"\n");
		fflush(stderr);
	}

		execv( DVIPSPATH, wargs );
		perror("texshell, Printruns: dvips");
	}
   }
} else {
/* PCL Output */
#ifdef USE_Xaw_TOOLKIT
   strcpy( begin_pageno, "-f");
	XtVaGetValues(print_pd->tf11 , XtNstring, &buf1, NULL);
   strcat( begin_pageno,	buf1);
   strcpy( end_pageno, "-t" );
	XtVaGetValues(print_pd->tf12 , XtNstring, &buf1, NULL);
   strcat( end_pageno,		buf1);
   strcpy( number_of_copies, "-c" );
	XtVaGetValues(print_pd->tf21 , XtNstring, &buf1, NULL);
   strcat( number_of_copies,	buf1);
   strcpy( h_offset, "-x" );
	XtVaGetValues(print_pd->tf31 , XtNstring, &buf1, NULL);
   strcat( h_offset,		buf1);
   strcpy( v_offset, "-y" );
	XtVaGetValues(print_pd->tf32 , XtNstring, &buf1, NULL);
   strcat( v_offset,		buf1);
/*
   XawToggleGetCurrent(printzweiseitig, 0, XtNset, &actual.OddPages, NULL);
   XawToggleGetCurrent(printzweiseitig, 1, XtNset, &actual.EvenPages, NULL);
 */
#else
   strcpy( begin_pageno, "-f");
   strcat( begin_pageno,	OlTextFieldGetString(print_pd->tf11, &size));
   strcpy( end_pageno, "-t" );
   strcat( end_pageno,		OlTextFieldGetString(print_pd->tf12, &size));
   strcpy( number_of_copies, "-c" );
   strcat( number_of_copies,	OlTextFieldGetString(print_pd->tf21, &size));
   strcpy( h_offset, "-x" );
   strcat( h_offset,		OlTextFieldGetString(print_pd->tf31, &size));
   strcpy( v_offset, "-y" );
   strcat( v_offset,		OlTextFieldGetString(print_pd->tf32, &size));
   OlVaFlatGetValues(printzweiseitig, 0, XtNset, &actual.OddPages, NULL);
   OlVaFlatGetValues(printzweiseitig, 1, XtNset, &actual.EvenPages, NULL);
#endif USE_Xaw_TOOLKIT

   i=0;
   if( !actual.printresolution){
/* 300DPI */
	strcpy(print_PCL_tool_path,DVILJ2PPATH);
	wargs[i]=pclargs[0];   			i++;
   } else {
/* 600DPI */
	strcpy(print_PCL_tool_path,DVILJ4PATH);
	wargs[i]=pclargs[1];   			i++;
   }
   if(actual.OddPages && !actual.EvenPages){wargs[i]=pclargs[2];	i++; } /*odd pages  only*/
   if(actual.EvenPages && !actual.OddPages){wargs[i]=pclargs[3];	i++; } /*even pages only*/
   wargs[i]=number_of_copies;   		i++;
   wargs[i]=begin_pageno;   			i++;
   wargs[i]=end_pageno;   			i++;
   wargs[i]=h_offset;   			i++;
   wargs[i]=v_offset;   			i++;
   if(actual.i_leaves == 2){ wargs[i]=pclargs[4];	i++; }
   if(landscape)    { wargs[i]=pclargs[5];	i++; }
   wargs[i]=dvi_inp_path;   			i++;



   if(actual.printdevice<MAXDEVICES-1){
	if( !(run_id=fork()) ){
		wargs[i]=pclargs[6];      	i++;
		wargs[i]=0;

/* send contents of dvi-File ( PCL-Code ) */
	{
		int	jj;
		fprintf(stderr,"%s",wargs[0]);
		for (jj=1;jj<i;jj++)	fprintf(stderr," %s",wargs[jj]);
		fprintf(stderr,"\n");
		fflush(stderr);
	}

		dup2(to_printer[1],   1);	/* redirect stdout */
		close(to_printer[0]);
		close(to_printer[1]);

		execv( print_PCL_tool_path, wargs );
		perror("texshell, Printruns: dvilj");
	}
   } else {
	if( !(run_id=fork()) ){
		sprintf( buf, "-e%s.lj",dvi_inp_path);
		wargs[i]=buf;      		i++;
		wargs[i]=0;

/* send contents of dvi-File ( PCL-Code ) */
	{
		int	jj;
		fprintf(stderr,"%s",wargs[0]);
		for (jj=1;jj<i;jj++)	fprintf(stderr," %s",wargs[jj]);
		fprintf(stderr,"\n");
		fflush(stderr);
	}

		execv( print_PCL_tool_path, wargs );
		perror("texshell, Printruns: dvilj");
	}
   }
}
/*
 * Wait on Child-Processes for Return
 */
waitpid(run_id, statusp, options);

/*
 * Ueberpruefung der Spoolerwarteschlange 
 */ 
if( actual.printdevice<MAXDEVICES ){
   if( !(run_id=fork()) ){

	if(actual.printlanguage==1 || actual.printdevice==DESKJET)
		sleep(15);
	else
		sleep(2);

	dup2(2, 1);	/* redirect stdout */
	fprintf(stderr,"\n\nDie Druckerwarteschlange enthaelt:\n" );fflush(stderr);
        execl( QUEUEPATH,	QUEUE,
#ifdef linux
        			"-P",
#else
        			"-o",
#endif
        			printername[actual.printdevice],
        			0 );
        perror("texshell: lpq");
   }
}

/*
 * Wait on Process PID=run_id for Return
 */
wait(statusp);

fprintf(stderr,"\n\n!!!! Print: FERTIG !!!!!!!!!!!!!!!!!!!!!!!!!\n");fflush(stderr);

exit(0);

}



static void
Edit_callback(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
    char 	buf[200],
    	 	buf2[200];
    int		status=0,
		options  = WNOHANG,
		to_shell_Err[2],/* pipe descriptors from child->parent */
		to_shell_Out[2];/* pipe descriptors from child->parent */

	bzero( buf, 200 );
	bzero( buf2, 200 );
	strcpy( buf2, pathname );
	if( pathname[0] == '\0' )
	   { 	pathname = actual.input_dir;
 (void) initList(scrolling_list, actual.input_dir);
  XtVaSetValues(pd.tf,  XtNstring, actual.input_file, NULL);
  XtVaSetValues(pd.tf,  XtNinsertPosition, (XtArgVal)strlen(actual.input_file), NULL);
  XtVaSetValues(pd.tf2, XtNstring, actual.input_dir,  NULL);
  XtVaSetValues(pd.tf2, XtNinsertPosition, (XtArgVal)strlen(actual.input_dir),  NULL);
	OpenPopup(file_button, (XtPointer)loadpopup, (XtPointer)NULL);
/*	       if( inp_path[0] != '\0' )
				sprintf( buf, "%s.tex", inp_path); */

	   }
	  else
	   {    sprintf( buf, "%s", pathname);

		if(Edit_id)
		  {
		    kill(Edit_id, SIGINT);
		    sleep(1);
		    if( Edit_id!=waitpid(Edit_id, &status, options)){
			insert_string( displayTool, 
				"\nAbbruch Text einladen!\n" );
			return;
	   	    }
		  }

		pipe(to_shell_Err);
		pipe(to_shell_Out);

		if( !(Edit_id=fork()) )
		  {
			dup2(to_shell_Out[1], 1);	/* redirect stdout*/
			dup2(to_shell_Err[1], 2);	/* redirect stderr*/

			close(to_shell_Err[0]);		/* close pipes    */
			close(to_shell_Err[1]);
			close(to_shell_Out[0]);
			close(to_shell_Out[1]);

/*
	fprintf(stderr,"\n X-pos: %s",x_Edi);
	fprintf(stderr,"\n Y-pos: %s",y_Edi);
	fprintf(stderr,"\n Aktuelle Breite: %d",actual.breite);
 */
		    	execl( EDITORPATH,	EDITOR,
						"-Wp", x_Edi, y_Edi,
			        		"-Ws", b_Edi, h_Edi,
		/*		     		"-Wt", actual.Edit_font,  */
			        		"-Ei", "on",
						buf,
						0);
			perror("texshell, Edit ");
		 	exit(1);
		  }

	        redirect_input( &Out_in, to_shell_Out[0] );
	        redirect_input( &Err_in, to_shell_Err[0] );

		close(to_shell_Err[0]);	/* close pipes    */
		close(to_shell_Err[1]);
		close(to_shell_Out[0]);
		close(to_shell_Out[1]);
	   }
}


static void
Editor_callback(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
    Arg         wargs[10];
    int		n;

   bzero(TextEditorTitel , 200 );
   strcpy(TextEditorTitel, "TeX Edit");

   if(pathname){
	strcat(TextEditorTitel, " -  ");
	strcat(TextEditorTitel, pathname);
	n = 0;
	XtSetArg(wargs[n], XtNsource, pathname);n++;
	XtSetValues(texteditor, wargs, n);
	n = 0;
	XtSetArg(wargs[n], XtNtitle, TextEditorTitel);n++;
	XtSetArg(wargs[n], XtNx, (XtArgVal)600);n++;
	XtSetArg(wargs[n], XtNy, (XtArgVal)320);n++;
	XtSetValues(TEpopup, wargs, n);}
}


/*
 * Build the whole pathname (without suffix).
 */
static int
build_pathname( directory, file_buf, path_buf )
	char	*file_buf,
		*directory,
		*path_buf;
{
   int			l = strlen(file_buf) - 1, i = l, l_suf = 0;

/*
 *	Loeschen des alten Pfadnamens
 */
   path_buf[0]=0;

/*
 *	Ist der Dateiname gueltig, d.h. vorhanden?
 */
  if(l < 0 )	return( FALSE );

/*
 * Build the whole pathname.
 */


  if( directory[0] != '\0' )
     {	strcat( path_buf, directory );
	if( path_buf[strlen(path_buf)-1] != '/' ) strcat(path_buf, "/"); }

/*
 * Testen, ob Suffix in "file_buf" vorhanden
 */
    while( l > 0 && file_buf[l] != '/' & !l_suf )
	{  if( file_buf[l] == '.' ) l_suf = l;   else l--;  }

/*
 * Eventuelle Suffix von "file_buf" entfernen
 */
   if( l_suf ) { while( l_suf <= i ){file_buf[l_suf] = '\0';  l_suf++;} }

/*
 * File-Name an Directory-Name anhaengen
 */
   strcat( path_buf, file_buf );

   return( TRUE );
}




/*
 * Build the whole pathname (with suffix).
 */
static int
build_whole_pathname( directory, file_buf, path_buf )
	char	*file_buf,
		*directory,
		*path_buf;
{
   int			l = strlen(file_buf) - 1;

/*
 *	Loeschen des alten Pfadnamens
 */
   path_buf[0]=0;

/*
 *	Ist der Dateiname gueltig, d.h. vorhanden?
 */
  if(l < 0 )	return( FALSE );

/*
 * Build the whole pathname.
 */
  if( directory[0] != '\0' )
     {	strcat( path_buf, directory );
	if( path_buf[strlen(path_buf)-1] != '/' ) strcat(path_buf, "/"); }
/*
 * File-Name an Directory-Name anhaengen
 */
   strcat( path_buf, file_buf );

   return( TRUE );
}




/*
 * Default-Einstellungen einlesen.
 */
static void
parameters()
{
	void get_rc();

/*
 *	Default-setting, falls .xtexshellrc nicht vorhanden
 */
	  
	memcpy( &actual, &defaults, sizeof(TeXshell_DATA) );
/*
 *	Uebergabe und Weiterbehandlung der eingelesenen Werte.
 */
	get_rc( &actual );
	par_translate();

	if( actual.input_file[0] != '\0' ){
	    	bzero( inp_disp, 16 );
	        strncpy( inp_disp , actual.input_file , 15);
		build_pathname( actual.input_dir, actual.input_file, inp_path);
		build_pathname( PWD, actual.input_file, dvi_inp_path);
	}
	if( actual.edi1_file[0] != '\0' ){
	    	bzero( edi1_disp, 16 );
	        strncpy( edi1_disp , actual.edi1_file , 15);
		build_whole_pathname( actual.edi1_dir, actual.edi1_file, edi1_path);
	}
	if( actual.edi2_file[0] != '\0' ){
	    	bzero( edi2_disp, 16 );
	        strncpy( edi2_disp , actual.edi2_file , 15);
		build_whole_pathname( actual.edi2_dir, actual.edi2_file, edi2_path);
	}
	if( actual.edi3_file[0] != '\0' ){
	    	bzero( edi3_disp, 16 );
	        strncpy( edi3_disp , actual.edi3_file , 15);
		build_whole_pathname( actual.edi3_dir, actual.edi3_file, edi3_path);
	}
	if( actual.edi4_file[0] != '\0' ){
	    	bzero( edi4_disp, 16 );
	        strncpy( edi4_disp , actual.edi4_file , 15);
		build_whole_pathname( actual.edi4_dir, actual.edi4_file, edi4_path);
	}
	if( actual.eig_dpi>0 ){
		sprintf( eig_resolution, "%d", actual.eig_dpi );
		resolutions[5]=eig_resolution;
	} else {
		strcpy( eig_resolution, "eigene" );
		resolutions[5]=eig_resolution;
	}

	strncpy( eig_tex, actual.eig_TeX, 6 );
	strcat( eig_tex, "\0" );
	texprogs[0][4]=texprogs[1][4]=actual.eig_TeX;
	formats[4]=eig_tex;
}


/*
 *	Positionierung der einzelnen Fenster.
 */
static void
par_translate()
{	
/*   double  atof();  in stdlib.h bereitsdeklariert! 20.02.95 M.M.   */

	sprintf( b_Dvi,   "%d", actual.breite );	/*b_Dvi: Breite Dvipage*/

	sprintf( b_Edi, "%d", 1152-actual.breite-13 );	/*b_Edi: BreiteTextedit*/
	sprintf( h_Edi, "%d", 700-actual.hoehe-8 );	/*h_Edi: Hoehe Textedit*/
#ifdef linux
	sprintf( x_Edi, "%d", actual.breite+1-126 );	/*x_Edi: x-Pos Textedit*/
	sprintf( y_Edi, "%d", 139+actual.hoehe-92 );	/*y_Edi: y-Pos Textedit*/
#else
	sprintf( x_Edi, "%d", actual.breite+1 );	/*x_Edi: x-Pos Textedit*/
	sprintf( y_Edi, "%d", 139+actual.hoehe );	/*y_Edi: y-Pos Textedit*/
#endif linux

    	switch (actual.i_resolution) {
      	  case 1:
		actual.i_dpi = 101;
	    break;
      	  case 2:
		actual.i_dpi = 118;
	    break;
      	  case 3:
		actual.i_dpi = 300;
	    break;
      	  case 4:
		actual.i_dpi = 360;
	    break;
      	  case 5:
		actual.i_dpi = 600;
	    break;
      	  case 6:
	    if(actual.eig_dpi>0)
		actual.i_dpi = actual.eig_dpi;
	    else
		actual.i_dpi = defaults.i_dpi;
	    break;
      	  default:
	    break;
	}

	sprintf( dpi, "%d", actual.i_dpi);
	sprintf( shrink_factor, "%d", actual.i_shrink_factor);
	sprintf( begin_pageno, "%d", actual.i_begin_pageno);
	sprintf( p_begin_pageno, "+%d", actual.i_begin_pageno);
	sprintf( end_pageno, "%d", actual.i_end_pageno);
	sprintf( leaves, "%d", actual.i_leaves);
/*
 *		Home-Position ( Umrechung:  mm -> inch )
 */
	sprintf( home_x, "%5.3f", actual.x_home*3.937008e-02*0.250*actual.i_shrink_factor);
	sprintf( home_y, "%5.3f", actual.y_home*3.937008e-02*0.125*actual.i_shrink_factor);
	X_offset = atof(h_offset);
	Y_offset = atof(v_offset);
	sprintf( x_offset, "%5.3f", X_offset*3.937008e-02);
	sprintf( y_offset, "%5.3f", atof(v_offset)*3.937008e-02);

}



/*
 *     Ein bisschen Musik  . . .
 */
static void
play_sound(sounds)
	char    sounds[];
{
    int		*statusp = 0,
		options  = 0;
    char        volume[6];

		if( strcmp(SOUNDS, "off") == 0 ) return;
                strcpy( volume , "-v 25" );
		if(Play_id)
		  {
		    kill(Play_id, SIGTERM);
		    waitpid(Play_id, statusp, options);
		  }

		Play_id = fork();
		if( !Play_id )
		  {
		    execl( PLAYPATH, PLAY,
			   volume, sounds,
			   0);
		    perror("texshell, play not found ");
		    exit(1);
		  }
}


void
initList(sl, directory)
  Widget sl;
  String directory;
{
#ifdef USE_Xaw_TOOLKIT
  DIR           *dirp;
  struct dirent *dp;
  file          *filep, *prevp;

  short         Fcount = 0,counter;
  struct stat	stbuf;
  unsigned	long Fl=0,Dl=0;
  char		*Liste,*FListe,mypath[300];
  char **filelist;
  char **cur_file;
  char **last_file;
  int entry_cnt = 20;
  int		lpath,ip;
  int		j; 
  void		sort(),aussortieren();

#else
  OlListItem     item;
  DIR           *dirp;
  struct dirent *dp;
  file          *filep, *prevp;

  short         Fcount = 0,counter;
  struct stat	stbuf;
  unsigned	long Fl=0,Dl=0;
  char		*Liste,*FListe,mypath[300];
  int		lpath,ip;
  void		sort(),aussortieren();

#endif USE_Xaw_TOOLKIT   

  while( item_count ){clearList(sl);item_count--;}

  Liste=malloc( 1 );
  Liste[0]=0;
  FListe=malloc( 1 );
  FListe[0]=0;

  if(directory[0] == NULL)
    strcpy(directory,PWD);
  dirp = opendir(directory);
  if(dirp == NULL) {
	strcpy(directory,PWD);
	dirp = opendir(directory);

	sprintf(errormsg, " No such directory !!!!");
	XtVaSetValues(pd.st, XtNstring, errormsg, NULL);
  }
  strcpy(mypath,directory);
  if( mypath[strlen(mypath)-1]!='/' ) strcat(mypath,"/");
  lpath=strlen(mypath);

/* Directory: Filenamen einlesen */

  for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {

/*HIER NAMEN KOPIEREN: dp->d_name; */
    strcpy(&mypath[lpath],dp->d_name);
    stat(mypath, &stbuf);

    if( !S_ISDIR(stbuf.st_mode) && dp->d_name[0]!='.' )
    {	Fl+=strlen(dp->d_name)+1;
	FListe=realloc( FListe , Fl );
	strcpy(&FListe[Fl-strlen(dp->d_name)-1],dp->d_name);
	FListe[Fl-1]=0;
	Fcount++;
    }
    else if( !strcmp(dp->d_name,"..") || dp->d_name[0]!='.')
    {	Dl+=strlen(dp->d_name)+2;
	Liste=realloc( Liste , Dl );
	strcpy(&Liste[Dl-strlen(dp->d_name)-2],dp->d_name);
	Liste[Dl-2]='/';
	Liste[Dl-1]=0;
	item_count++;
    }
  }
  closedir(dirp);


/* Directory: Filenamen sortieren */

  sort(Liste,item_count);
  sort(FListe,Fcount);
  aussortieren(FListe,Fcount);
      ip=finde_Element(FListe,newFcount-1);
      Fl=ip+strlen(&FListe[ip])+1;
      FListe[Fl-1]=0;
  Liste=realloc(Liste, Fl+Dl );
  bcopy(FListe, &Liste[Dl], Fl);
  item_count+=newFcount;
  

/* Directory: Filenamen sortiert in Liste einfuegen */

  head=NULL;
#ifdef USE_Xaw_TOOLKIT

 	filelist = (char **) calloc(entry_cnt, sizeof (char *));
	cur_file = filelist;
       	last_file = filelist + entry_cnt - 1;
        for (j=0 ;j<item_count; j++)
	{
	 iptest = finde_Element(Liste,j);
	 *cur_file++ = SaveString(&Liste[iptest]);
		if (cur_file == last_file) {
			filelist = (char **) realloc(filelist,
					    2 * entry_cnt * sizeof (char *));
			cur_file = filelist + entry_cnt - 1;
			entry_cnt = 2 * entry_cnt;
			last_file = filelist + entry_cnt - 1;
		}
	}
       *cur_file = NULL;
       
          XawListChange(sl,filelist,item_count,0,TRUE);

#else  
  (*UpdateView)(sl, FALSE);
  for (counter=0; counter<item_count; counter++) {
    filep = (file *)XtCalloc(1, sizeof(file));
    if(head == NULL)
      head = prevp = filep;
    else {
      prevp->next = filep;
      prevp = filep;
    }
    filep->next = NULL;
    item.label_type = OL_STRING;
    item.attr = counter;
    item.label = filep->filename =
	 XtNewString( &Liste[finde_Element(Liste,counter)] );
    item.mnemonic = NULL;
    filep->token = (*AddItem)(sl, 0, 0, item);
  }
  (*UpdateView)(sl, TRUE);
#endif USE_Xaw_TOOLKIT

  free(FListe);
  free(Liste);
}


void
current_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
#else
  popupdata	*popd = (popupdata *)client_data;
  String	get_file_name();
  file		*current, *findset();
  char		myname[500];
  int		i;

  OlListToken token = (OlListToken)call_data;
  OlListItem *newItem = OlListItemPointer(token);
  OlListItem *lastItem;

/* Reset errorMessage*/  
  XtVaSetValues(popd->st, XtNstring, "\0", NULL);

  if(lasttoken == token) {      /* unset current choice */
    newItem->attr &= ~OL_LIST_ATTR_CURRENT;
    (*TouchItem)(w, token);
    lasttoken = NULL;
    return;
  }

  if(lasttoken) {
    lastItem = OlListItemPointer(lasttoken);
    if(lastItem->attr & OL_LIST_ATTR_CURRENT)
      lastItem->attr &= ~OL_LIST_ATTR_CURRENT;
    (*TouchItem)(w, lasttoken);
  }
  newItem->attr |= OL_LIST_ATTR_CURRENT;
  (*TouchItem)(w, token);
  lasttoken = token;

  current = findset();
/*  filename= get_file_name(current->filename);

  XtVaSetValues(popd->tf, XtNstring, filename, NULL);*/

  
  if( current->filename[strlen(current->filename)-1]=='/' )
  {	strcpy(myname,pathname);
	if( myname[strlen(myname)-1] !='/'  )  strcat(myname,"/");
	if(!strcmp("../",current->filename))
	{	if( (i=strlen(myname)-1)>0 )
		{	if(myname[i]=='/')i--;
			while( myname[i]!='/' && i>=0) i--;}
		myname[i+1]=0;		}
	else
		strcat(myname,current->filename);
	XtVaSetValues(popd->tf,  XtNstring, "\0",     NULL);
	XtVaSetValues(popd->tf2, XtNstring, myname,   NULL);
	(void) initList(scrolling_list,myname);
	strcpy(scrolldir,myname);
	scrollfile[0]=0;
	pathname=scrolldir;	}
  else
  {	strcpy(myname,current->filename);
	XtVaSetValues(popd->tf,  XtNstring, myname,   NULL);
	XtVaSetValues(popd->tf2, XtNstring, pathname, NULL);	}
#endif USE_Xaw_TOOLKIT
}


void
clearList(sl)
  Widget    sl;
{
#ifdef USE_Xaw_TOOLKIT
#else
  file       *filep, *prevp;
/*mm  OlListItem *fileItem;*/ /* Wird nicht benoetigt */

  (*UpdateView)(sl, FALSE);
  filep = prevp = head;
  while(filep) {
    (*DeleteItem)(sl, filep->token);
      if(filep == head) {
        head = filep->next;
        XtFree(filep);
        filep = prevp = head;
      } else {
        prevp->next = filep->next;
        XtFree(filep);
        filep = prevp->next;
      }

  }
  lasttoken = NULL;
#endif USE_Xaw_TOOLKIT
}


void
findcurrent_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
#ifdef USE_Xaw_TOOLKIT
#else
  Widget sl = (Widget)client_data;

  if(lasttoken)
    (*ViewItem)(sl, lasttoken);
#endif USE_Xaw_TOOLKIT
}


#ifdef USE_Xaw_TOOLKIT
#else
file *
findset()
{
  file       *filep;
  OlListItem *fileItem;

  filep = head;
  while(filep) {
    fileItem = OlListItemPointer(filep->token);
    if(fileItem->attr & OL_LIST_ATTR_CURRENT)
      return(filep);
    else
      filep = filep->next;
  }
  return((file *)NULL);
}
#endif USE_Xaw_TOOLKIT


String 
get_file_name(FileName)
   String FileName;
{
	static char the_filename[256];

        sprintf(the_filename, "%s", FileName);
	return(the_filename);
}


static void
TeXruns(to_tex,to_shell,to_shell_Err)
int	to_tex[2], /* pipe descriptors from parent->child */
	to_shell[2],/* pipe descriptors from child->parent */
	to_shell_Err[2];/* pipe descriptors from child->parent */
{
 int	*statusp = 0,
	options  = 0,
	runs,
	run_id=0;
  char	buf[200];

  char	*wargs[12];
  Boolean    plainTeX=TRUE;

/* TeXruns und Tochterprogramme bilden eigene Prozessgruppe! */
  setpgrp();

/* Kanaele umlenken */
  dup2(to_tex[0],   0);		/* redirect stdin	*/
  dup2(to_shell[1], 1);		/* redirect stdout	*/
  dup2(to_shell_Err[1], 2);	/* redirect stderr	*/

  close(to_tex[0]);		/* close pipes		*/
  close(to_tex[1]);
  close(to_shell[0]);
  close(to_shell[1]);
  close(to_shell_Err[0]);	/* close pipes		*/
  close(to_shell_Err[1]);


/* Kein File gefunden */
  if( inp_path[0] == '\0' )
  {	fprintf(stderr, "\nZuerst Input-Text einladen!\n" );
  	fflush(stderr);
	exit(1);					}


/* plain oder nicht? */

  plainTeX=( actual.TeXformat!=1 && actual.TeXformat!=3 );

#ifdef USE_Xaw_TOOLKIT
#else
	OlVaFlatGetValues(utilprog, 0, XtNset, &actual.BiBTeX, NULL);
	OlVaFlatGetValues(utilprog, 1, XtNset, &actual.MakeIndex, NULL);
#endif USE_Xaw_TOOLKIT


/*
 * dvi-File erzeugen 
 */
		    
  if( !(run_id=fork()) ){
	execl( TEXPATH, texprogs[actual.TeXlanguage][actual.TeXformat],
			inp_path,
			0);
        perror("texshell, virtex");
        exit(1);
  }

  runs=1;


Laeufe:

/* Warten aufs Ende des vorherigen Jobs*/
  waitpid(run_id, statusp, options);run_id=0;

     if(actual.BiBTeX){
	if( !(run_id=fork()) ){
	    	fprintf(stderr,"\nStarting BiBTeX\n");fflush(stderr);
	    	execl( BIBTEXPATH, BIBTEX,
				inp_path,
				0);
	        perror("texshell, BiBTeX");
	        exit(1);
	}
     }

     if(actual.MakeIndex){
	if(run_id)
		waitpid(run_id, statusp, options);

	if( !(run_id=fork()) ){

	    	fprintf(stderr,"\nStarting MakeIndex\n");fflush(stderr);
		i=0;
		wargs[i]=MAKEINDEX;			i++;
		if(plainTeX){
			wargs[i]="-s";			i++; 
			wargs[i]="makeidx.ist";		i++;
		} 
		wargs[i]=inp_path;			i++;
		wargs[i]=0;				i++;

		execv( MAKEINDEXPATH, wargs );
	        perror("texshell, MakeIndex");
	        exit(1);
	}
     }

     if(run_id)	waitpid(run_id, statusp, options);

     if(runs<=actual.TeXrun){     

	if(runs == actual.TeXrun)
          fprintf(stderr,"\n\n ----> noch 1. TeX-Lauf\n\n");
	else
          fprintf(stderr,"\n\n ----> noch %d. TeX-Laeufe\n\n", actual.TeXrun+1-runs);
        fflush(stderr);

	if(!(run_id=fork()))
	    {
		execl( TEXPATH, texprogs[actual.TeXlanguage][actual.TeXformat],
				inp_path,
				0);
	        perror("texshell, virtex");
	        exit(1);
	    }
     runs++;
     if( runs<=actual.TeXrun )goto Laeufe;

     }


/* Postscript, muss noch erzeugt werden */
 
  if(actual.i_previewer==3 || actual.i_previewer==4){
	if(run_id)
		waitpid(run_id, statusp, options);

	fprintf(stderr,"\n\n ----> nun noch DVI->PS\n\n");fflush(stderr);

	sprintf( buf, "-o%s.ps",dvi_inp_path);

	i=0;
	wargs[i]=DVIPS;				i++;
	wargs[i]=dvi_inp_path;			i++;
	wargs[i]=buf;				i++;
	wargs[i]="-ta4";			i++;
	wargs[i]=0;

	if( !(run_id=fork()) ){
		execv( DVIPSPATH, wargs );
		perror("texshell: dvips");
	        exit(1);
	}
  }
	waitpid(run_id, statusp, options);

	fprintf(stderr,"\n\n!!!!!! TeX: FERTIG !!!!!!!!!!!!!!!!!!!!!!!!!\n");fflush(stderr);
	exit(0);
}


void 
sort(liste,anz)
  char *liste;
  int anz;
{
  int	gap,i,j,jp,ip;


  for( gap=anz/2; gap > 0; gap/=2 )
	for( i=gap; i<anz; i++ )
		for( j=i-gap;j>=0;j-=gap )
		{ 
		  ip=finde_Element(liste,j);
		  jp=finde_Element(liste,j+gap);
		  if(strcmp(&liste[ip],&liste[jp])<=0)
			break;
		  vertausche_Elemente(liste,ip,jp);
		}
}


void 
aussortieren(liste,anz)
  char *liste;
  int anz;
{
 int	i,j,jp,ip;

  if(!all_select)
  {
    for( i=0; i<anz; i++ )
	{ 
	ip=finde_Element(liste,i);
                 
	if(tex_select && suffix_ident(&liste[ip],".tex") ) continue;
	if(dvi_select && suffix_ident(&liste[ip],".dvi") ) continue;
			
	    for( j=i+1; j<anz; j++ )
		{ 
		ip=finde_Element(liste,j-1);
		jp=finde_Element(liste,j);
		vertausche_Elemente(liste,ip,jp);
		}
	    anz=anz-1;
	    i=i-1;
	}
  }
  newFcount=anz;
}


int
suffix_ident(s,t)
	char	s[],t[];
{

	int  len=strlen(s)-strlen(t);

	if( len>= 0 && !bcmp(&s[len], t, strlen(t)) ) return(TRUE);

	return(FALSE);
}


int
finde_Element(str,ele)
	char	*str;
	int	ele;
{
	int i=0,j=0;

	while(j<ele)
	{	if(str[i]==0)j++;i++;}
	return(i);
}


void
vertausche_Elemente(str,el1,el2)
	char	*str;
	int	el1,el2;
{
	char	temp[255+1];
	int	l1=strlen(&str[el1]),
		l2=strlen(&str[el2]),
		j;

	if(l1<l2)
	{	strcpy(temp,&str[el2]);
		for(j=el2-1;j>=el1+l1; j--) str[j-l1+l2]=str[j];
		strcpy(&str[el2-l1+l2], &str[el1]);
		strcpy(&str[el1], temp);
	}
	else if(l1>l2)
	{	strcpy(temp,&str[el1]);
		for(j=el1+l1; j<el2; j++) str[j-l1+l2]=str[j];
		strcpy(&str[el1], &str[el2]);
		strcpy(&str[el2-l1+l2], temp);
	}
	else if(l1==l2)
	{	strcpy(temp,&str[el1]);
		strcpy(&str[el1], &str[el2]);
		strcpy(&str[el2], temp);
	}
}


#ifdef USE_Xaw_TOOLKIT
#else
int
RowOfPosition(Buffa,ele,line)
	TextBuffer	*Buffa;
	int	ele,line;
{
	int	j=ele,lline=line-2;

	while( lline>=0 ){ j-=LengthOfTextBufferLine(Buffa,lline);lline--; }

	return(j);
}
#endif USE_Xaw_TOOLKIT




/* 
 * Get all pending input and append it to the display 
 * widget. Discard lines that begin with a newline.
 */
void
get_from_prog(client_data, fid, id)
  XtPointer    client_data;
  int         *fid;
  XtInputId   *id;
{
  char   buf[BUFSIZ];
  int    nbytes;

  nbytes = read(*fid, buf, BUFSIZ);
  if (nbytes) {

  /* Null terminate at the end of the bytes read.  */

     buf[nbytes] = '\0';
     insert_string(displayTool, buf);
  }
  else if( *fid==from_TeX )		/* EOF has reached */
  {	close(from_TeX);	from_TeX=0; 	XtRemoveInput( *id);	}
  else if( *fid==Err_in )		/* EOF has reached */
  {	close(Err_in);		Err_in=0;	XtRemoveInput( *id);	}
  else if( *fid==Out_in )		/* EOF has reached */
  {	close(Out_in);		Out_in=0;	XtRemoveInput( *id);	}

}


/* 
 * Get all pending input and append it to the display 
 * widget. Discard lines that begin with a newline.
 */
void
get_from_others(client_data, fid, id)
  XtPointer    client_data;
  int         *fid;
  XtInputId   *id;
{
  char   buf[BUFSIZ];
  int    nbytes;

  nbytes = read(*fid, buf, BUFSIZ);
  if (nbytes) {

  /* Null terminate at the end of the bytes read.  */

     buf[nbytes] = '\0';
     insert_string(displayTool, "\n");
     insert_string(displayTool, buf);
     insert_string(displayTool, "\n");
  }
}


void
send_to_prog(w, client_data, call_data)
  Widget    w;
  XtPointer client_data, call_data;
{
  static char		send_buf[300];
  static int		start_new = TRUE;

#ifdef USE_Xaw_TOOLKIT
  char  *messagestring;
  int   message_len = 0, i,ihelp,j;
  
	XtVaGetValues(displayTool, XtNstring, &messagestring, NULL);
        message_len = strlen(messagestring);
	ihelp = message_len - displayTool_buf_len ;
	
	
	if( start_new )	
  	 { 
  	   strcpy(send_buf,&messagestring[message_len-ihelp]);
         }
	else
	{		
	       strcat(send_buf,&messagestring[message_len-ihelp]);
         }
              start_new=FALSE;
	i=j=0;
	if(from_TeX){
		while( i< strlen(send_buf) ){
		   if(send_buf[i]=='\n'){
		    	write(to_Child, &send_buf[j], i-j+1 );
		    	j=i+1;
		   }
		   i++;
		}
	}

	else
		send_buf[0]=0;

	if( j==strlen(send_buf) )
		start_new=TRUE;
	else
		strcpy(send_buf, &send_buf[j]);

	insert_string(displayTool, send_buf);
#else
  char			*buffer;
  int			i, j,
			retval=OlTextEditCopyBuffer(displayTool, &buffer);
  OlTextModifyCallData	*mcd=(OlTextModifyCallData*)call_data;
  
  if( displayTool_buf_len == strlen(buffer) && mcd->text_length )
  {
	if( start_new )	strcpy(send_buf, mcd->text);
	else		strcat(send_buf, mcd->text);
	start_new=FALSE;

	i=j=0;
	if(from_TeX){
		while( i< strlen(send_buf) ){
		   if(send_buf[i]=='\n'){
		    	write(to_Child, &send_buf[j], i-j+1 );
		    	j=i+1;
		   }
		   i++;
		}
	}
	else
		send_buf[0]=0;

	if( j==strlen(send_buf) )
		start_new=TRUE;
	else
		strcpy(send_buf, &send_buf[j]);

	displayTool_buf_len = strlen(buffer)+mcd->text_length;
  } else
  if( mcd->new_cursor==mcd->current_cursor-1 && strlen(send_buf)>0 ){
  	send_buf[strlen(send_buf)-1]=0;
  	displayTool_buf_len--;
  }

  XtVaSetValues(displayTool,
  		XtNcursorPosition, (OlTextPosition)strlen(buffer),
  		0);
  XtFree(buffer);
#endif USE_Xaw_TOOLKIT
}


/*
 * Clear the text buffer and go to position 1.
 */
void
reset_displayTool()
{
  Arg	argue[10];
  int	i;
#ifdef USE_Xaw_TOOLKIT
   i=0;
   XtSetArg( argue[i], XtNstring, "" );i++;
   XtSetValues( displayTool, argue, i );
#else
  if(OlTextEditClearBuffer((TextEditWidget)displayTool) == FALSE) {
    fprintf(stderr,"OlTextEditClearBuffer() failed\n");
  }
#endif USE_Xaw_TOOLKIT
  displayTool_buf_len=0;
  free(swstring);
  Dlswstring=1;
  swstring=malloc( 1 );
  swstring[0]=0;
}




void
insert_string(text_widget, buf)
  Widget   text_widget;
  char    *buf;
{
  Arg	argue[10];
  int	i,i5,n5;
  long int	n;

  displayTool_buf_len+=strlen(buf);
#ifdef USE_Xaw_TOOLKIT

	Dlswstring+=strlen(buf);
	swstring=realloc( swstring , Dlswstring );
	strcpy(&swstring[Dlswstring-strlen(buf)-1],buf);
	swstring[Dlswstring-1]=0;

	i5=0;
	n5=0;
	n=displayTool_buf_len-2;
	while( n>=0 && n5<=5){ if(swstring[n]=='\n'){n5++;i5=n+1;}n--;}

	i=0;
	XtSetArg( argue[i], XtNstring, swstring );i++;
	XtSetValues( text_widget, argue, i );
	i=0;
	XtSetArg( argue[i], XtNdisplayPosition, (XawTextPosition)i5 );i++;
	XtSetArg( argue[i], XtNinsertPosition, Dlswstring-1 );i++;
	XtSetValues( text_widget, argue, i );
#else
	i = OlTextEditInsert(text_widget, buf, strlen(buf));
#endif USE_Xaw_TOOLKIT
}


/*
 * Set File-Descriptors from daughter to display
 */
void
redirect_input( fd_in, fd_from )
	int	*fd_in,fd_from;
{
   if( *fd_in>0 )
	dup2( fd_from, *fd_in ); /* New Input-descriptor */
   else{
   	if( (*fd_in=dup( fd_from ))<0 )   /* Initialization */
				perror("redirect_input");

	XtAppAddInput( app, *fd_in , (XtPointer) XtInputReadMask, get_from_prog,
			displayTool);
	}
}



/*
 * Stand: 12.01.1995
 *
 * UTILITIES fuer xtexshell.c
 *
 */

static void
DrawAndPrint(widget, xevent, region)
	Widget          widget;
	XEvent*		xevent;		/* not used */
	Region          region;		/* not used */
{
	Display        *display;
	static Window   window;
	static Boolean  done1 = FALSE, done2 = FALSE;
	static GC       gc[6];
	XGCValues       values;
	int             i, ix5, ix10, coord, axis, finish = 180 * 64;
	static int      hpixel, vpixel;
	Font            fid = (Font)0;
	char           *fontname = 
                        "*-adobe-helvetica-bold-r-normal-*-240-*-iso8859-1";
	char           *fontnamesmall = 
                        "*-adobe-helvetica-bold-r-normal-*-100-*-iso8859-1";
	XtGCMask        mask;

	display = XtDisplay(widget);
	window = XtWindow(widget);

	if (!done1) {
		hpixel = (int)H_PIXEL(1);
		vpixel = (int)V_PIXEL(1);
		if (hpixel == 0)
			hpixel = 1;
		if (vpixel == 0)
			vpixel = 1;
		done1 = TRUE;
	}
	if (rainbow) {

		XClearWindow(display, window);
		values.line_width = 5 * hpixel;

		if (!done2) {
			mask = (XtGCMask)(GCForeground | GCLineWidth);

			values.foreground = red_pixel;
			gc[0] = XtGetGC(widget, mask, &values);
			values.foreground = orange_pixel;
			gc[1] = XtGetGC(widget, mask, &values);
			values.foreground = yellow_pixel;
			gc[2] = XtGetGC(widget, mask, &values);
			values.foreground = green_pixel;
			gc[3] = XtGetGC(widget, mask, &values);
			values.foreground = blue_pixel;
			gc[4] = XtGetGC(widget, mask, &values);
			values.foreground = purple_pixel;
			gc[5] = XtGetGC(widget, mask, &values);
		}
		for (i = 0; i < 6; i++) {

			ix5 = i * 5;
			ix10 = i * 10;

			axis = 95 - ix10;
			coord = ix5 + 5;

			XDrawArc(display,
				window,
				gc[i],
				coord * hpixel,
				coord * vpixel,
				(unsigned int)(axis * hpixel),
				(unsigned int)(axis * vpixel),
				0,
				finish);
		}
	} else
		{
		XClearWindow(display, window);
		fid = XLoadFont(display, fontnamesmall);

		/*
		 * If successful, label the widget.
		 */
		if (fid != (Font)0) {
			values.font = fid;
			gc[0] = XtGetGC(widget, (XtGCMask)GCFont, &values);
			XDrawString(display, window, gc[0], 15 * hpixel,
				20 * vpixel, VERSION, strlen(VERSION));
			XDrawString(display, window, gc[0], 15 * hpixel,
				40 * vpixel, MMCOPYRIGHT, strlen(MMCOPYRIGHT));
			XtReleaseGC(stub, gc[0]);
			XUnloadFont(display, fid);
		}

	}
	/*
	 * Get font for this screen resolution.
	 */
	fid = XLoadFont(display, fontname);

	/*
	 * If successful, label the widget.
	 */
	if (fid != (Font)0) {
		values.font = fid;
		gc[0] = XtGetGC(widget, (XtGCMask)GCFont, &values);
		XDrawString(display, window, gc[0], 1 * hpixel,
			90 * vpixel, "T", 1);
		XDrawString(display, window, gc[0], 12 * hpixel,
			100 * vpixel, "E", 1);
		XDrawString(display, window, gc[0], 26 * hpixel,
			90 * vpixel, "X-shell", 7);
		XtReleaseGC(stub, gc[0]);
		XUnloadFont(display, fid);
	}

}


/* 
 * Function for changing the footer message.
 */
static void
FooterMessage(footer_text, buf)
	Widget          footer_text;
	char            buf[];
{
	Arg             arg;

#ifdef USE_Xaw_TOOLKIT
	XtSetArg(arg, XtNlabel, buf);
#else
	XtSetArg(arg, XtNstring, buf);
#endif USE_Xaw_TOOLKIT
	XtSetValues(footer_text, &arg, 1);
}


/* 
 * Function for getting color values for the display.
 */
static void
GetColors()
{
	static char    *colors[] = {
		"purple", "blue", "green", "yellow", "orange", "red",
		"skyblue", "lightgrey"};
	XrmValue        fromValue,
	                toValue;

	for (i = 0; i < 8; i++) {
		fromValue.size = sizeof (colors[i]);
		fromValue.addr = colors[i];
		XtConvert(toplevel, XtRString, &fromValue, XtRPixel, &toValue);

		switch (i) {
		case 0:
			purple_pixel = *((Pixel *)toValue.addr);
			break;
		case 1:
			blue_pixel = *((Pixel *)toValue.addr);
			break;
		case 2:
			green_pixel = *((Pixel *)toValue.addr);
			break;
		case 3:
			yellow_pixel = *((Pixel *)toValue.addr);
			break;
		case 4:
			orange_pixel = *((Pixel *)toValue.addr);
			break;
		case 5:
			red_pixel = *((Pixel *)toValue.addr);
			break;
		case 6:
			skyblue_pixel = *((Pixel *)toValue.addr);
			break;
		case 7:
			background_pixel = *((Pixel *)toValue.addr);
			break;
		}
	}
}


static void
SetPosition(widget, xwidget, ywidget)
	Widget          widget,xwidget,ywidget;
{
	static int      nargs;

	if (nargs == 0)nargs = XtNumber(genericARGS);

	XtSetArg(genericARGS[0], XtNxRefWidget, xwidget);
	XtSetArg(genericARGS[1], XtNyRefWidget, ywidget);

	XtSetValues(widget, genericARGS, nargs); 
}


/*
 * Function for creating a special cursor for the stub widget.
 */
static void
SetStubCursor(widget)
	Widget          widget;
{
	static Cursor   cursor;

#ifdef USE_Xaw_TOOLKIT
	cursor = XCreateFontCursor(XtDisplay(widget), XC_question_arrow);
#else
	cursor = GetOlQuestionCursor(XtScreen(widget));
#endif USE_Xaw_TOOLKIT
	XDefineCursor(XtDisplay(widget), XtWindow(widget), cursor);
}


/* 
 *  Event handler example to give functionality to the stub widget.
 */
/*ARGSUSED*/
static void
StubEventHandler(widget, closure, event, continue_to_dispatch)
	Widget          widget;			/* not used */
	XtPointer       closure;		/* not used */
	XEvent*		event;
	Boolean*	continue_to_dispatch;	/* not used */
{

	if (event->type == EnterNotify)
		FooterMessage(footer_text,
			"Press HELP-Key for HELP about XTeXshell");
	else if (event->type == LeaveNotify)
		FooterMessage(footer_text,
			"\0");
}




/* 
 * The MenuSelect_cb callback is used by the pulldown menu
 */
static void
menuSelect_cb(widget, client_data, call_date)
	Widget          widget;
	XtPointer       client_data,
	                call_date;
{
	int             n = (int)client_data;
	char            buf[MAXBUF];
    int		*statusp = 0,
		options  = 0;

    if(n==1)
	{
		(void) sprintf(buf, "Starting  XFig ...");
		FooterMessage(footer_text, buf);
		if(XFig_id)
		  {
		    kill(XFig_id, SIGTERM);
		    waitpid(XFig_id, statusp, options);
		  }

		XFig_id = fork();
		if( !XFig_id )
		  {
		    execv( XFIGPATH, xfigargs );
		    perror("texshell, xfig not found ");
		    exit(1);
		  }
	}
	else{
		(void) sprintf(buf, "Not yet implemented!");
		FooterMessage(footer_text, buf);
	}
}


static void
notice_cb1(widget, call_date, client_data)
	Widget          widget;		
	XtPointer       call_date,
	                client_data;
{
  Widget	dialog;
  Arg		argue[5];
  Position	x, y;
  Dimension	width, height;
  int		n;

#ifdef USE_Xaw_TOOLKIT
	    n = 0;
	    XtSetArg(argue[n], XtNwidth, &width); n++;
	    XtSetArg(argue[n], XtNheight, &height); n++;
	    XtGetValues(widget, argue, n);
	    XtTranslateCoords(widget, (Position) (width / 2), 
	    		(Position) (height / 2), &x, &y);

	    n = 0;
	    XtSetArg(argue[n], XtNx, x);n++;
	    XtSetArg(argue[n], XtNy, y);n++;

	noticeshell = XtCreatePopupShell("notice",
				noticeShellWidgetClass, widget, argue, n);

	dialog = XtVaCreateManagedWidget("widget", dialogWidgetClass,
			noticeshell,
    			XtNlabel,	(XtArgVal)"Really want to quit ? \n ",
    			NULL, 0);

    XawDialogAddButton(dialog, "yes", notice_cb2, (XtPointer)dialog);
    XawDialogAddButton(dialog, "cancel", DismissPopup,(XtPointer)dialog);
#else
	XtSetArg(argue[0], XtNemanateWidget, (XtArgVal)widget);
	XtSetValues(noticebox, argue, 1);
#endif USE_Xaw_TOOLKIT
	XtPopup(noticeshell, XtGrabExclusive);
}


static void
notice_cb2(widget, client_data, call_date)
	Widget          widget;
	XtPointer       client_data, call_date;
{
    int		*statusp = 0,
		options  = 0;

	play_sound(SOUND_TSCHUESSI);
	FooterMessage(footer_text, "Bye bye ...");

	if(Tex_id){
		(void)kill((pid_t)-Tex_id, SIGKILL);
		waitpid(-Tex_id, statusp, options);
	}
	if(Dvi_id){
		(void)kill((pid_t)-Dvi_id, SIGKILL);
		waitpid(-Dvi_id, statusp, options);
	}
	if(Edit_id)   kill(Edit_id,  SIGINT);
	if(XFig_id)   kill(XFig_id,  SIGKILL);
	if(Print_id){
		(void)kill((pid_t)-Print_id, SIGKILL);
		waitpid(-Print_id, statusp, options);
	}
	wait(statusp);
        exit(0);
}


static void
OpenPopup(widget, client_data, call_data)
  Widget widget;
  XtPointer client_data, call_data;
{
  Widget popup = (Widget)client_data;
  XtPopup(popup, XtGrabNone);
}


static void 
DismissPopup(widget, client_data, call_data)
	Widget		widget;		
	XtPointer	client_data, call_data;	
{
    Widget popup = XtParent( (Widget) client_data);
    XtPopdown(popup);
}


void
verify_callback(w, client_data, call_data)
  Widget w;
  XtPointer client_data, call_data;
{
  Boolean *popdownmenu = (Boolean *)call_data;
  if(popdown == FALSE)
    *popdownmenu = FALSE;
}


static void
rainbow_cb(widget, client_data, call_date)
	Widget          widget;
	XtPointer       client_data, call_date;
{
	if (rainbow){
		rainbow = FALSE;
		play_sound(SOUND_GONG);}
	else
		rainbow = TRUE;

	DrawAndPrint(stub, (XEvent *)NULL, (Region)NULL);
}


static void
scrollbar_cb(widget, client_data, call_date)
	Widget          widget;
	XtPointer       client_data, call_date;
{
#ifdef USE_Xaw_TOOLKIT
#else
	OlScrollbarVerify
			*sbv = (OlScrollbarVerify *)call_date;
	char            buf[MAXBUF];

	sbv->ok = TRUE;

	/*
	 * Update the form's scrollbar page indicator.
	 */
	if (widget == scrollbar)
		sbv->new_page = (int)(sbv->new_location / 10) + 1;
#endif USE_Xaw_TOOLKIT
}



void
On_Exit()
{
    int		*statusp = 0,
		options  = 0;

	if(Tex_id){
		(void)kill((pid_t)-Tex_id, SIGKILL);
		waitpid(-Tex_id, statusp, options);
	}
	if(Dvi_id){
		(void)kill((pid_t)-Dvi_id, SIGKILL);
		waitpid(-Dvi_id, statusp, options);
	}
	if(Edit_id)   kill(Edit_id,  SIGINT);
	if(Play_id)   kill(Play_id,  SIGKILL);
	if(XFig_id)   kill(XFig_id,  SIGKILL);
	if(Print_id){
		(void)kill((pid_t)-Print_id, SIGKILL);
		waitpid(-Print_id, statusp, options);
	}
	wait(statusp);
	exit(0);

}
char *
SaveString(string)
char *string;
{
	char *new;

	new = malloc(strlen(string) + 1);
	strcpy(new, string);
	return(new);
}


void
FileSelected(w, client_data, ret_val)
    Widget	    w;
    XtPointer	    client_data;
    XtPointer	    ret_val;
{
    char		myname[500];
    int i;
    
    XawListReturnStruct *ret_struct = (XawListReturnStruct *) ret_val;


  if( ret_struct->string[strlen(ret_struct->string)-1]=='/' )
  {	strcpy(myname,pathname);
	if( myname[strlen(myname)-1] !='/'  )  strcat(myname,"/");
	if(!strcmp("../",ret_struct->string))
	{	if( (i=strlen(myname)-1)>0 )
		{	if(myname[i]=='/')i--;
			while( myname[i]!='/' && i>=0) i--;}
		myname[i+1]=0;		}
	else
		strcat(myname,ret_struct->string);
	XtVaSetValues(pd.tf,  XtNstring, "\0",     NULL);
	XtVaSetValues(pd.tf2, XtNstring, myname,   NULL);
	(void) initList(scrolling_list,myname);
	strcpy(scrolldir,myname);
	scrollfile[0]=0;
	pathname=scrolldir;	}
  else
  {	strcpy(myname,ret_struct->string);
	XtVaSetValues(pd.tf,  XtNstring, myname,   NULL);
	XtVaSetValues(pd.tf2, XtNstring, pathname, NULL);	}
}

void do_load(widget, client_data, call_date)
	Widget          widget;
	XtPointer       client_data, call_date;
  {
   void load_callback();
     load_callback(widget, (XtPointer)&pd ,call_date);
  }

void editbutton1_callback(widget, client_data, call_date)
	Widget          widget;
	XtPointer       client_data, call_date;
  {
     setfilenumber2_callback(widget, (XtPointer)1 ,call_date);
  }
void editbutton2_callback(widget, client_data, call_date)
	Widget          widget;
	XtPointer       client_data, call_date;
  {
     setfilenumber2_callback(widget, (XtPointer)2 ,call_date);
  }
void editbutton3_callback(widget, client_data, call_date)
	Widget          widget;
	XtPointer       client_data, call_date;
  {
     setfilenumber2_callback(widget, (XtPointer)3 ,call_date);
  }
void editbutton4_callback(widget, client_data, call_date)
	Widget          widget;
	XtPointer       client_data, call_date;
  {
     setfilenumber2_callback(widget, (XtPointer)4 ,call_date);
  }

/* end of texshell.c */
