#ifdef VMS
#include "decw$include:xlib.h"
#include "decw$include:xutil.h"
#include "decw$include:xos.h"
#include "decw$include:keysym.h"
#include "decw$include:cursorfont.h"
#include "decw$include:xatom.h"
#include <descrip.h>
#include <processes.h>
#define fork vfork
#else
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/keysym.h>
#include <X11/cursorfont.h>
#include <X11/Xatom.h>
#ifdef DOGL
#include <GL/glx.h>
#include <GL/gl.h>
#include <GL/glu.h>
#endif
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

#ifdef CRAY
#include <fortran.h>
#endif


#ifdef CRAY
typedef char BMap;
#else
typedef unsigned char BMap;
#endif

#define ABS(a) (((a) > 0) ? (a) : (-(a)))
#define SIGN(a) (((a) > 0) ? 1 : -1)
#define MAXI(a,b)      ((a)>=(b)?(a):(b))
#define MINI(a,b)      ((a)<=(b)?(a):(b))

#define FONT "-*-fixed-medium-r-semicondensed-*-13-*-*-*-*-*-*-*"
#define DenWindow 0
#define OpenWindow 1
#define MovePen 2
#define DrawLine 3
#define DrawString 4
#define ClearScreen 6
#define SolidLine 8
#define DashedLine 9
#define LineWidth 10
#define MolWindow 15
#define ParseNorbs 16
#define ChangeColor 99

static char *selstr = 
	"To Select: Hold mouse button down while dragging the cursor";
static char *dselstr = 
	"To DeSelect: Hold mouse button down while dragging the cursor";
static int SelRes = -3;
static int SelDel = 0;
static int xison = 0;
static int *ichx;
static int DoFreq = 0;
static int *nfreq;     
static float *freq;
static double *frint;
static double *ramint;
static int *ihasi = NULL;
static int DoEig = 0;
static int *iuhf;
static int ibeta;
static double *esp;
static double *plevel;
typedef struct { double r; double g; double b; } RGB;
static RGB *mapcol;
static unsigned long mappedcols[5];
static double *valcol;
static double *espvdw;
static int *cubetyp;     
static float *frmul;
typedef struct { double cellc[6];
		 int nspg;
               } CELLSTRU;
static CELLSTRU *cellconstants;

static int *ipcol;     
static int nplev;
static char *alphbet[] = {"alpha","beta"};
static char *rwopt[] = {"Read","Write"};
static char *cubeopt[] = {"Gaussian","Vasp","Jaguar","GRID"};
static char *labels[] = {"atom","atom+number","ForceF.Type","atom+charge","PDBsymbol","Residue"};
#ifdef MPFIT
static char *pots[] = {"True Electrost. Pot.","Multipole Derived","Charges Derived","Write Surface","Read Surface","Surface OFF","ESP charges","DMA El.Pot.Charges","Mull.Charges","Read ESP Charges","EEM charges","Gasteiger","Dipole On/Off","Solv. Acc. Surf","Elec. Dens. Map","Fit MultiPoles"};
#else
static char *pots[] = {"True Electrost. Pot.","Multipole Derived","Charges Derived","Write Surface","Read Surface","Surface OFF","ESP charges","DMA El.Pot.Charges","Mull.Charges","Read ESP Charges","EEM charges","Gasteiger","Dipole On/Off","Solv. Acc. Surf","Elec. Dens. Map"};
#endif
static char *eems[] = {"EEM NPA","EEM Mull","EEM PESP","EEM ESFF"};
static char *pots2[] = {"True Electrost. Pot.","Multipole Derived","Charges Derived"};
static char *readgrd[] = {"Replace Grid","Subtract"};
static char *surftyp[] = {"Van der Waals","IsoDensity (Slow)"};
static char *hyds[] = {"Excl. All Hydrogens","Excl. H except H-bond","(Re)calculate H-bond","H-bond parameters"};
static char *postopt[] = {"Mono","Color"};
static char *dumopt[] = {"Include Dummies","Exclude Dummies"};
static char *vrmlopt[] = {"VRML1.0","VRML2.0","Povray","OpenGL"};
static char *vrml2dopt[] = {"VRML2.0","OpenGL"};
static char *denopt[] = {"Normal","Color Mapped"};
static char *xyzopt[] = {"XYZ","Mol2","MSF","Tinker","Tinker QM/MM"};
static char *mapopt[] = {"XYZ file","Mol2 file","MSF","Tinker .xyz","Optimise with Sybyl","Optimise with Quanta","Optimise with Tinker"};
static char *wropt[] = {"Z-Mat Gamess","Z-Mat Gaussian","Z-Mat MOPAC","XYZ","Mol2","MSF","Tinker","Tinker QM/MM","PDB","CSSR","MSI","Molden Format","mol","CML","AMBFOR"};
static char *pdbwh[]={ "Write with Hydrogens", "Write without H","Write Displayed Res. Only"};
static char *palopt[] = {"Background Mode","BackGround Color","Def. BackGround","Atom Colors","Color Editor","Reset Colors","Shade Depth"};
static char *bgopt[] = {"Solid Color","Gradient Color"};
static char *spdopt[] = {"Normal Density","Spin Density"};
static int *ivdwpl;
static char *vdwstr[]={ "Ball & Stick", "Space Filling"};
static char *alnopt[]={ "Align 2 molecules", "Interactive Docking"};
static char *dckopt[]={ "Read from PDB file", "Pick Molcule on Screen"};
static int *iqon;
static int *ihasq;
static int *icolps;
static int *idelx;
static int *ivtwo;
static int *ixyz;
static int *iixyz;
static int *ipnt;     
static int *iwropt;
static int *itotc;
static int *imult;
static int *ito;
static int *imo;
static int *ibo;
static int *ihs;
static int *itm;
static int *ibatch;
static int denmode = 0;
static int *ispd;
static int *ibgcol;
static int *ibgclo;
static int *ibgmod;
static int *natc;

static int  CheckForConfig();
static Bool IsConfig();

static int idum1;
static int startx;
static int starty;
static int moving = 0;
static int gmoving = 0;
static int *ball;
static int btype = 0;

void  Key(unsigned char key);
static Bool gijsup = 0;
static Bool cnvup = 0;
static Bool geoup = 0;
static Bool distup = 0;
static Bool FRup = 0;
static Bool specup = 0;
static Bool scoup = 0;
static Bool pmfup = 0;
static double scomax, scomin;
static int qboxup = 0;
static int qbopt = 0;
static int qbinct = 0;
static int qbcomm = 0;
static int qbrfile = 0;
static int qbres = 0;
static int pdb = 0;
static int *icalc;
static int *ipdbon;
static int frfor = 0;
static int coarse = 1;
static Bool do3dx = 0;
static int *dospa;
static int *do3d;
static int *ambchg;
static Bool isdash = 0;
static Bool backb = 0;
static Bool hbon = 0;
static Bool denm = 1;
static int setcmap = 0;
static int ZERO = 0;
static int ONE = 1;
static int TWO = 2;
static Colormap cmap;
static int StarNet = 0;
#define ball_width 7
#define ball_height 7
static BMap ball_bits[] = {
   0x1c, 0x3e, 0x7f, 0x7f, 0x7f, 0x3e, 0x1c};
#define bigsmall_width 17
#define bigsmall_height 17
static BMap bigsmall_bits[] = {
   0x80, 0xff, 0x01, 0x80, 0x00, 0x01, 0xfe, 0x0f, 0x01, 0x82, 0x08, 0x01,
   0x82, 0x08, 0x01, 0x82, 0x08, 0x01, 0x82, 0x08, 0x01, 0x82, 0xff, 0x01,
   0x02, 0x08, 0x00, 0x02, 0x08, 0x00, 0x02, 0x08, 0x00, 0x02, 0x08, 0x00,
   0x02, 0x08, 0x00, 0x02, 0x08, 0x00, 0x02, 0x08, 0x00, 0xfe, 0x0f, 0x00,
   0x00, 0x00, 0x00};
#define skull_width 17
#define skull_height 17
static BMap skull_bits[] = {
   0xe0, 0x0f, 0x00, 0xf0, 0x1f, 0x00, 0xf8, 0x3f, 0x00, 0xfc, 0x7f, 0x00,
   0x9e, 0xf3, 0x00, 0x8e, 0xe3, 0x00, 0x8e, 0xe3, 0x00, 0xfe, 0xfe, 0x00,
   0x7c, 0x7c, 0x00, 0x78, 0x3c, 0x00, 0xf1, 0x1f, 0x01, 0xf1, 0x1f, 0x01,
   0x52, 0x95, 0x00, 0x44, 0x45, 0x00, 0xf8, 0x3f, 0x00, 0xfc, 0x7f, 0x00,
   0x07, 0xc0, 0x01};
#define ff_width 17
#define ff_height 17
static BMap ff_bits[] = {
   0x00, 0x00, 0x00, 0xf8, 0x03, 0x00, 0xf8, 0x03, 0x00, 0x18, 0xfc, 0x00,
   0x0c, 0xfc, 0x00, 0x0c, 0x0c, 0x00, 0x0c, 0x06, 0x00, 0x7c, 0x06, 0x00,
   0x7e, 0x06, 0x00, 0x06, 0x3e, 0x00, 0x06, 0x3f, 0x00, 0x06, 0x03, 0x00,
   0x03, 0x03, 0x00, 0x03, 0x03, 0x00, 0x83, 0x01, 0x00, 0x80, 0x01, 0x00,
   0x80, 0x01, 0x00};
#define mlf_width 17
#define mlf_height 17
static BMap mlf_bits[] = {
   0x00, 0x00, 0x00, 0x0e, 0xe0, 0x00, 0x1c, 0x70, 0x00, 0x3c, 0x78, 0x00,
   0x7c, 0x7c, 0x00, 0xec, 0x6e, 0x00, 0xcc, 0x67, 0x00, 0x8c, 0x63, 0x00,
   0x0c, 0x61, 0x00, 0x0c, 0x60, 0x00, 0x0c, 0x60, 0x00, 0x0c, 0x60, 0x00,
   0x0c, 0x60, 0x00, 0x0c, 0x60, 0x00, 0x0c, 0x60, 0x00, 0x1e, 0xf0, 0x00,
   0x00, 0x00, 0x00};
#define hbit_width 17
#define hbit_height 17
static BMap hbit_bits[] = {
   0x00, 0x00, 0x00, 0x70, 0xe0, 0x00, 0x70, 0xe0, 0x00, 0x70, 0xe0, 0x00,
   0x38, 0x70, 0x00, 0x38, 0x70, 0x00, 0x38, 0x70, 0x00, 0x38, 0x70, 0x00,
   0xfc, 0x3f, 0x00, 0xfc, 0x3f, 0x00, 0x1c, 0x38, 0x00, 0x1c, 0x38, 0x00,
   0x0e, 0x1c, 0x00, 0x0e, 0x1c, 0x00, 0x0e, 0x1c, 0x00, 0x0e, 0x1c, 0x00,
   0x07, 0x0e, 0x00};
#define orig_width 17
#define orig_height 17
static BMap orig_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00,
   0x10, 0x01, 0x00, 0x20, 0x01, 0x00, 0x40, 0x01, 0x00, 0x80, 0x01, 0x00,
   0xfe, 0xff, 0x00, 0x00, 0x03, 0x00, 0x00, 0x05, 0x00, 0x00, 0x09, 0x00,
   0x00, 0x11, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00,
   0x00, 0x00, 0x00};
#define cell_width 17
#define cell_height 17
static BMap cell_bits[] = {
   0x00, 0x00, 0x00, 0xe0, 0xff, 0x00, 0x30, 0xc0, 0x00, 0x08, 0xa0, 0x00,
   0x24, 0x90, 0x00, 0xfe, 0x8f, 0x00, 0x02, 0x88, 0x00, 0x22, 0x88, 0x00,
   0x02, 0x88, 0x00, 0x22, 0x88, 0x00, 0x02, 0x88, 0x00, 0xe2, 0xeb, 0x00,
   0x12, 0x48, 0x00, 0x0a, 0x28, 0x00, 0x06, 0x18, 0x00, 0xfe, 0x0f, 0x00,
   0x00, 0x00, 0x00};
#define surf_width 17
#define surf_height 17
static BMap surf_bits[] = {
   0x92, 0x92, 0x00, 0x12, 0x91, 0x00, 0x24, 0x48, 0x00, 0x44, 0x44, 0x00,
   0x98, 0x23, 0x00, 0x74, 0x30, 0x00, 0xf2, 0x0c, 0x00, 0x2a, 0x1f, 0x00,
   0x45, 0x63, 0x00, 0xaa, 0x88, 0x00, 0x92, 0xb6, 0x00, 0x6c, 0x22, 0x01,
   0x50, 0x49, 0x01, 0x40, 0x22, 0x01, 0x80, 0xb6, 0x00, 0x80, 0x88, 0x00,
   0x00, 0x63, 0x00};
#define ogl_width 17
#define ogl_height 17
static BMap ogl_bits[] = {
   0x00, 0xa0, 0x01, 0x40, 0xe0, 0x01, 0xe0, 0xc0, 0x01, 0xd0, 0x81, 0x01,
   0xc8, 0x03, 0x00, 0xc4, 0x07, 0x00, 0xc2, 0xff, 0x00, 0x41, 0xc0, 0x00,
   0xe2, 0xbf, 0x00, 0x24, 0xa0, 0x00, 0xa8, 0xa0, 0x00, 0x30, 0xa0, 0x00,
   0xa0, 0xa0, 0x00, 0x20, 0xa0, 0x00, 0xa0, 0xaa, 0x00, 0x20, 0x60, 0x00,
   0xe0, 0x3f, 0x00};
#define foto_width 17
#define foto_height 17
static BMap foto_bits[] = {
   0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x1c, 0x00, 0x00, 0xfe, 0xff, 0x00,
   0xfe, 0xff, 0x00, 0x7e, 0xfc, 0x00, 0xbe, 0xfb, 0x00, 0x5e, 0xf4, 0x00,
   0x5e, 0xf4, 0x00, 0x5e, 0xf4, 0x00, 0xbe, 0xfb, 0x00, 0x7e, 0xfc, 0x00,
   0xfe, 0xff, 0x00, 0xfe, 0xff, 0x00, 0xfc, 0x7f, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00};
#define palette_width 17
#define palette_height 17
static BMap palette_bits[] = {
   0x00, 0x80, 0x01, 0x00, 0xb0, 0x01, 0xf8, 0x78, 0x00, 0xfc, 0xfd, 0x00,
   0xfc, 0xfd, 0x00, 0xc6, 0xff, 0x00, 0x82, 0xff, 0x00, 0x86, 0xff, 0x00,
   0xc6, 0xff, 0x00, 0xfe, 0xff, 0x00, 0xfe, 0xff, 0x00, 0xfe, 0x7f, 0x00,
   0xfc, 0x7f, 0x00, 0xfc, 0x7f, 0x00, 0xfc, 0x3f, 0x00, 0xf2, 0x1f, 0x00,
   0xe1, 0x07, 0x00};
#define g_width 17
#define g_height 17
static BMap g_bits[] = {
   0xc0, 0x07, 0x00, 0x30, 0x18, 0x00, 0x0c, 0x60, 0x00, 0x04, 0x40, 0x00,
   0x02, 0x80, 0x00, 0x22, 0x88, 0x00, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01,
   0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x11, 0x10, 0x01, 0x22, 0x88, 0x00,
   0xc2, 0x87, 0x00, 0x04, 0x40, 0x00, 0x0c, 0x60, 0x00, 0x30, 0x18, 0x00,
   0xc0, 0x07, 0x00};
#define vrml_width 17
#define vrml_height 17
static BMap vrml_bits[] = {
   0x00, 0x00, 0x00, 0xe6, 0xc3, 0x00, 0x66, 0xc6, 0x00, 0x66, 0xc4, 0x00,
   0x66, 0xc6, 0x00, 0xec, 0x63, 0x00, 0x6c, 0x63, 0x00, 0x78, 0x36, 0x00,
   0x78, 0x36, 0x00, 0x30, 0x18, 0x00, 0x30, 0x18, 0x00, 0x60, 0x0c, 0x00,
   0x60, 0x0c, 0x00, 0xc0, 0x06, 0x00, 0xc0, 0x06, 0x00, 0x80, 0x03, 0x00,
   0x80, 0x03, 0x00};
#define align_width 17
#define align_height 17
static BMap align_bits[] = {
   0x20, 0x00, 0x00, 0x70, 0x04, 0x00, 0x98, 0x04, 0x00, 0x0d, 0x0f, 0x00,
   0x06, 0x13, 0x00, 0x86, 0xa3, 0x00, 0xc6, 0x42, 0x00, 0xc6, 0x42, 0x00,
   0xc6, 0x42, 0x00, 0xc6, 0x42, 0x00, 0xc6, 0x42, 0x00, 0xcd, 0x41, 0x00,
   0xd8, 0x40, 0x00, 0xf0, 0xa1, 0x00, 0x20, 0x13, 0x00, 0x20, 0x0e, 0x00,
   0x00, 0x04, 0x00};
#define mol_width 169
#define mol_height 52
static BMap mol_bits[] = {
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfe,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0xfe,0x00,0xfc,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x01,0xfe,0x00,0x03,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x06,0xfe,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0xfe,0x40,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x10,0xfe,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0xfe,0x20,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x20,0xfe,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0xfe,0x20,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x20,0xfe,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0xfe,0x20,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,
 0xfe,0x20,0x00,0xc0,0x3f,0xc0,0x1f,0x00,0xff,0x00,0xf8,0x00,0x80,0xff,0x1f,
 0x80,0xff,0xff,0xf1,0x03,0xf8,0x20,0xfe,0x20,0x00,0xc0,0x3f,0xe0,0x1f,0xe0,
 0xff,0x07,0xf8,0x00,0x80,0xff,0x7f,0x80,0xff,0xff,0xf1,0x03,0xf8,0x20,0xfe,
 0x20,0x00,0xc0,0x3f,0xe0,0x1f,0xf0,0xff,0x0f,0xf8,0x00,0x80,0xff,0xff,0x80,
 0xff,0xff,0xf0,0x03,0xf8,0x20,0xfe,0x20,0x00,0xe0,0x3f,0xe0,0x1f,0xf8,0xff,
 0x0f,0xfc,0x00,0xc0,0xff,0xff,0xc0,0xff,0xff,0xf8,0x07,0xfc,0x20,0xfe,0x20,
 0x00,0xe0,0x3f,0xf0,0x0f,0xfc,0xe1,0x1f,0x7c,0x00,0xc0,0x07,0xfe,0xc1,0x07,
 0x00,0xf8,0x07,0x7c,0x20,0xfe,0x20,0x00,0xe0,0x3f,0xf0,0x0f,0x7e,0x80,0x1f,
 0x7c,0x00,0xc0,0x07,0xf8,0xc1,0x07,0x00,0xf8,0x07,0x7c,0x20,0xfe,0x20,0x00,
 0xe0,0x3f,0xf8,0x0f,0x3f,0x00,0x3f,0x7c,0x00,0xc0,0x07,0xf0,0xc1,0x07,0x00,
 0xf8,0x0f,0x7c,0x20,0xfe,0x20,0x00,0xe0,0x3f,0xb8,0x0f,0x1f,0x00,0x3f,0x7c,
 0x00,0xc0,0x07,0xf0,0xc1,0x07,0x00,0xf8,0x0f,0x7c,0x20,0xfe,0x20,0x00,0xf0,
 0x3d,0xbc,0x8f,0x0f,0x00,0x3e,0x7e,0x00,0xe0,0x07,0xf0,0xe1,0x03,0x00,0xfc,
 0x1f,0x7e,0x20,0xfe,0x20,0x00,0xf0,0x3d,0xdc,0x87,0x0f,0x00,0x3e,0x3e,0x00,
 0xe0,0x03,0xf0,0xe1,0x03,0x00,0x7c,0x1f,0x3e,0x20,0xfe,0x20,0x00,0xf0,0x3d,
 0xde,0xc7,0x07,0x00,0x3e,0x3e,0x00,0xe0,0x03,0xf0,0xe1,0xff,0x3f,0x7c,0x1e,
 0x3e,0x20,0xfe,0x20,0x00,0xf0,0x3d,0xde,0xc7,0x07,0x00,0x3e,0x3e,0x00,0xe0,
 0x03,0xf0,0xe1,0xff,0x3f,0x7c,0x3e,0x3e,0x20,0xfe,0x20,0x00,0xf0,0x3d,0xce,
 0xc7,0x03,0x00,0x3e,0x3e,0x00,0xe0,0x03,0xf0,0xe1,0xff,0x1f,0x7c,0x3e,0x3e,
 0x20,0xfe,0x20,0x00,0xf8,0x3c,0xef,0xe7,0x03,0x00,0x1f,0x3f,0x00,0xf0,0x03,
 0xf8,0xf1,0xff,0x1f,0x7e,0x3c,0x3f,0x20,0xfe,0x20,0x00,0xf8,0x3c,0xe7,0xe3,
 0x03,0x00,0x1f,0x1f,0x00,0xf0,0x01,0xf8,0xf0,0x01,0x00,0x3e,0x7c,0x1f,0x20,
 0xfe,0x20,0x00,0xf8,0xbc,0xe7,0xe3,0x03,0x80,0x1f,0x1f,0x00,0xf0,0x01,0xf8,
 0xf0,0x01,0x00,0x3e,0x7c,0x1f,0x20,0xfe,0x20,0x00,0xf8,0xbc,0xe7,0xe3,0x03,
 0x80,0x0f,0x1f,0x00,0xf0,0x01,0x7c,0xf0,0x01,0x00,0x3e,0x78,0x1f,0x20,0xfe,
 0x20,0x00,0xf8,0xfc,0xe3,0xe3,0x07,0xc0,0x0f,0x1f,0x00,0xf0,0x01,0x7c,0xf0,
 0x01,0x00,0x3e,0xf8,0x1f,0x20,0xfe,0x20,0x00,0x7c,0xfc,0xf3,0xe1,0x07,0xe0,
 0x87,0x0f,0x00,0xf8,0x00,0x3e,0xf8,0x00,0x00,0x3f,0xf0,0x0f,0x20,0xfe,0x20,
 0x00,0x7c,0xfc,0xf1,0xc1,0x0f,0xf0,0x83,0x0f,0x00,0xf8,0x00,0x3f,0xf8,0x00,
 0x00,0x1f,0xf0,0x0f,0x20,0xfe,0x20,0x00,0x7c,0xfc,0xf1,0xc1,0x3f,0xfc,0x83,
 0x0f,0x00,0xf8,0xc0,0x1f,0xf8,0x00,0x00,0x1f,0xf0,0x0f,0x20,0xfe,0x20,0x00,
 0x7c,0xfc,0xf0,0x81,0xff,0xff,0x81,0xff,0x7f,0xf8,0xff,0x0f,0xf8,0xff,0x1f,
 0x1f,0xe0,0x0f,0x20,0xfe,0x20,0x00,0x7e,0xfc,0xf0,0x01,0xff,0xff,0xc0,0xff,
 0x7f,0xfc,0xff,0x07,0xfc,0xff,0x9f,0x1f,0xe0,0x0f,0x20,0xfe,0x20,0x00,0x3e,
 0xfc,0xf8,0x00,0xfe,0x3f,0xc0,0xff,0x3f,0xfc,0xff,0x03,0xfc,0xff,0x8f,0x0f,
 0xe0,0x07,0x20,0xfe,0x20,0x00,0x3e,0x7c,0xf8,0x00,0xf8,0x0f,0xc0,0xff,0x3f,
 0xfc,0xff,0x00,0xfc,0xff,0x8f,0x0f,0xc0,0x07,0x20,0xfe,0x20,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x20,0xfe,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0xfe,0x20,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x20,0xfe,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0xfe,0x20,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,
 0xfe,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x20,0xfe,0x40,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0xfe,
 0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x10,0xfe,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0xfe,0x00,
 0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x06,0xfe,0x00,0xfc,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x01,0xfe,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0xfe};
#define icon_bitmap_width 100
#define icon_bitmap_height 70
static BMap icon_bitmap_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x80, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xe0, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x70, 0xa2, 0xec, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x0e, 0x14, 0xe1, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0xa7, 0xd2, 0x0b, 0x19, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0xc0, 0x12, 0x04, 0x50, 0x76, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0xa9, 0x2a, 0x25, 0xd0, 0x01, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x05, 0x40, 0x88, 0x92, 0x06,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0xa8, 0x8a, 0x22, 0x24,
   0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x02, 0x10, 0x88,
   0xa8, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x54, 0x4b,
   0x25, 0x25, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x81,
   0x48, 0x10, 0xb0, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5e,
   0x35, 0x12, 0x45, 0x25, 0xd2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x02, 0x88, 0x54, 0x88, 0x88, 0xc8, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xb2, 0x22, 0x80, 0x12, 0x52, 0x12, 0x03, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x42, 0x8a, 0x2a, 0xa4, 0x08, 0xc5, 0x04, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x5e, 0x10, 0x41, 0x01, 0x51, 0x91, 0x06, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x9b, 0x4a, 0x16, 0xd4, 0x84, 0x54, 0x0c, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0xf2, 0x22, 0xa1, 0x32, 0x52, 0x09, 0x0d,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x44, 0x14, 0x88, 0x08, 0x52,
   0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0xa8, 0xa2, 0x22, 0xaa,
   0x80, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x83, 0x06, 0x89,
   0x02, 0x15, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x15, 0x58,
   0x70, 0x54, 0x51, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x61,
   0x21, 0x05, 0x21, 0x94, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x26,
   0x9e, 0x45, 0x48, 0x94, 0x02, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x4a, 0x26, 0x18, 0x91, 0x21, 0xa8, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x80, 0xa3, 0x94, 0x42, 0x22, 0x4a, 0x8d, 0x70, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xf8, 0x3f, 0x11, 0x29, 0x84, 0x90, 0x64, 0x6a, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xfe, 0x7e, 0xac, 0x8c, 0x52, 0x25, 0x81, 0x55, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xbf, 0x7f, 0x1d, 0xa1, 0x0f, 0x48, 0x2a, 0x60, 0x00,
   0x00, 0x00, 0x00, 0x80, 0xf7, 0xed, 0x39, 0x04, 0xa0, 0x52, 0x84, 0x4a,
   0x00, 0x00, 0x00, 0x00, 0xc0, 0xfd, 0xff, 0x53, 0xa9, 0x04, 0x93, 0x29,
   0x59, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xdf, 0x6e, 0x25, 0x12, 0xa9, 0x04,
   0x4a, 0x4a, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xf7, 0xf3, 0xc3, 0x46, 0x40,
   0x58, 0x10, 0x51, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xbe, 0x7f, 0xb4, 0x68,
   0xf5, 0x82, 0xc5, 0x64, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xf6, 0xdd, 0x21,
   0x02, 0x08, 0x68, 0x54, 0x38, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x3f, 0x7e,
   0xb5, 0xb4, 0x42, 0x13, 0x05, 0x29, 0x00, 0x00, 0x00, 0x00, 0x80, 0xee,
   0xdf, 0x90, 0x01, 0x17, 0x42, 0x69, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x80,
   0x0e, 0x3c, 0x26, 0xaa, 0xa0, 0x56, 0x89, 0x32, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xfb, 0x77, 0x89, 0xc1, 0x3d, 0x48, 0x4a, 0x1c, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xfe, 0x23, 0x21, 0x2c, 0x80, 0x8a, 0x92, 0x0a, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0xe0, 0x8c, 0xe1, 0xea, 0x51, 0x68, 0x0e, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xf1, 0x0c, 0x00, 0x8c, 0x96, 0x04,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x26, 0xd1, 0xcb, 0xa1, 0x20,
   0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x59, 0x0a, 0x10, 0x2e,
   0xad, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x91, 0xd0, 0x75,
   0xe1, 0xc5, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0x25,
   0x81, 0xaa, 0xf7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
   0x12, 0x3e, 0x20, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x5a, 0xa5, 0xa0, 0x95, 0xfa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x46, 0x48, 0x0a, 0xc9, 0xfc, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xdc, 0x16, 0x7f, 0x12, 0x0e, 0x3f, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x18, 0x51, 0x80, 0xb3, 0x07, 0xfc, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x70, 0x1a, 0x29, 0xa5, 0x01, 0xe0, 0x07, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x49, 0x07, 0xe2, 0x00, 0x00, 0x1f,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x2a, 0x50, 0x3f, 0x00, 0x00,
   0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0x0f, 0x00,
   0x00, 0xe0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0x00,
   0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
#define gijsface_width 160
#define gijsface_height 144
static BMap gijsface_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x1c, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x0a, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x03, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,
   0x07, 0x24, 0xf0, 0x07, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0x3e, 0xfe, 0xff,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0x60, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff,
   0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0,
   0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xfe, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x60, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa0,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb0, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0,
   0xff, 0xff, 0x0f, 0xf8, 0xf4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0x0f, 0x00,
   0x90, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0x03, 0x00, 0x00, 0xfe, 0xff, 0xff,
   0xff, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8,
   0xff, 0xff, 0x03, 0x00, 0x00, 0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0x00, 0x00,
   0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xfc, 0xff, 0x7f, 0x00, 0x10, 0x00, 0xf0, 0xff, 0xff,
   0xff, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc,
   0xff, 0x3f, 0x00, 0x80, 0x00, 0x04, 0xfb, 0xff, 0xff, 0xff, 0xff, 0x0f,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0x3f, 0x00, 0x00,
   0x00, 0x80, 0xfd, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xfc, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x08, 0xfe, 0xff,
   0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc,
   0xff, 0x1f, 0x00, 0x00, 0x00, 0x8e, 0xfd, 0xff, 0xff, 0xff, 0xff, 0x3f,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0x0f, 0x00, 0x00,
   0x00, 0x00, 0xfd, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xfe, 0xff, 0x07, 0x00, 0x00, 0x00, 0x20, 0xfc, 0xff,
   0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe,
   0xff, 0x03, 0x00, 0x00, 0x00, 0x4c, 0xfe, 0xff, 0xff, 0xff, 0xff, 0x7f,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x03, 0x00, 0x00,
   0x00, 0x38, 0xf8, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x0c, 0xfc, 0xff,
   0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,
   0xff, 0x01, 0x00, 0x00, 0x00, 0x78, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0x00, 0x00, 0x00,
   0x00, 0x0a, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x80, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x01, 0xf8, 0xff,
   0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff,
   0x7f, 0x00, 0x00, 0x00, 0x80, 0x0c, 0x6c, 0xff, 0xff, 0xff, 0xff, 0xff,
   0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0x7f, 0x00, 0x00, 0x00,
   0x00, 0x02, 0xb2, 0xbb, 0xff, 0xff, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xc0, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb0, 0x9b,
   0xfe, 0xff, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff,
   0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x00, 0xfd, 0xff, 0xff, 0xff,
   0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x3f, 0x00, 0x00, 0x00,
   0x00, 0x04, 0x00, 0x10, 0x6e, 0xfe, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xc0, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28,
   0xee, 0xf9, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff,
   0x1f, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0xdb, 0x7f, 0xf9, 0xff, 0xff,
   0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x1f, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x10, 0x60, 0xf7, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xc0, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x09,
   0x14, 0xfe, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff,
   0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0xc1, 0x1d, 0xf8, 0xff, 0xff,
   0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0x1f, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xe0, 0xff, 0xa7, 0xf7, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xe0, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff,
   0xff, 0xf7, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff,
   0x0f, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0x0f, 0x00, 0x00, 0x00,
   0x01, 0xe8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xf0, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff,
   0x0f, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0x0f, 0xf8, 0x3f, 0x1e,
   0xe2, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00,
   0x00, 0x00, 0xf0, 0xff, 0x0f, 0xfe, 0xff, 0xff, 0xa3, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff,
   0x87, 0xff, 0xff, 0xff, 0xf3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xe7, 0xff, 0xff, 0xff,
   0xc1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00,
   0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff,
   0xff, 0xff, 0xff, 0xff, 0x00, 0xfe, 0xff, 0xff, 0xff, 0x2f, 0xff, 0xff,
   0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff,
   0x00, 0xfc, 0xff, 0xff, 0xff, 0x2f, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00,
   0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xfe, 0xff, 0xff,
   0xff, 0xbf, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff,
   0xc7, 0xff, 0xff, 0x7f, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xbf, 0xff, 0xff,
   0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0x83, 0x7f, 0xfe, 0x1f,
   0x00, 0xf7, 0xff, 0xff, 0xff, 0x13, 0xfd, 0xff, 0xff, 0x0f, 0x00, 0x00,
   0x00, 0x00, 0xfe, 0xff, 0x83, 0x7f, 0xfc, 0x1f, 0x00, 0xff, 0xff, 0xff,
   0xcd, 0x1f, 0xfd, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff,
   0x03, 0x12, 0xfc, 0x07, 0x00, 0xf3, 0xbf, 0xff, 0x01, 0x80, 0xfd, 0xff,
   0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x03, 0x00, 0xe0, 0x07,
   0x00, 0xe7, 0xff, 0xff, 0x11, 0x00, 0xfd, 0xff, 0xff, 0x0f, 0x00, 0x00,
   0x00, 0x80, 0xff, 0xff, 0x03, 0x00, 0x20, 0x03, 0x80, 0xff, 0xbf, 0x9f,
   0x60, 0x00, 0xff, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff,
   0x03, 0x00, 0x00, 0x00, 0x00, 0xca, 0xbf, 0x1d, 0x20, 0x00, 0xfc, 0xff,
   0xff, 0x03, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00,
   0x80, 0x0b, 0xa4, 0x02, 0x10, 0x80, 0xf8, 0xff, 0xff, 0x03, 0x00, 0x00,
   0x00, 0x00, 0xfe, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0xff, 0x84, 0x02,
   0x80, 0x42, 0xf8, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff,
   0x03, 0x00, 0x00, 0x00, 0x00, 0xfd, 0x8f, 0x05, 0x00, 0x82, 0xf8, 0xff,
   0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0x03, 0x00, 0x00, 0x00,
   0x40, 0xff, 0x0b, 0x00, 0x10, 0x80, 0xf8, 0xff, 0xff, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xfc, 0xff, 0x03, 0x00, 0x00, 0x00, 0x80, 0x49, 0x18, 0x00,
   0x1e, 0xe0, 0xfc, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff,
   0x03, 0x00, 0x00, 0x00, 0x80, 0x23, 0xfc, 0x03, 0x80, 0xc2, 0xe0, 0xff,
   0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0x03, 0x00, 0x00, 0x00,
   0x80, 0x4b, 0x1e, 0xc0, 0x08, 0x21, 0xfc, 0xff, 0x7f, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xf8, 0xff, 0x07, 0x00, 0x00, 0x00, 0x40, 0xeb, 0x1f, 0x80,
   0x00, 0xc1, 0xf9, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff,
   0x07, 0x00, 0x00, 0x00, 0x80, 0xff, 0x07, 0x00, 0x40, 0x0c, 0xec, 0xff,
   0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0x07, 0x00, 0x00, 0x00,
   0x80, 0xff, 0x3f, 0x80, 0x00, 0xff, 0xfa, 0xf8, 0xff, 0x07, 0x00, 0x00,
   0x00, 0x00, 0xe0, 0xff, 0x07, 0x00, 0x00, 0x00, 0x80, 0xff, 0x3f, 0x80,
   0x00, 0xef, 0xfc, 0xf8, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,
   0x07, 0x00, 0x00, 0x00, 0x00, 0x0c, 0xff, 0x03, 0x60, 0xe5, 0xf8, 0xf9,
   0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xbe, 0x0f, 0x00, 0x00, 0x00,
   0x00, 0x48, 0xff, 0xeb, 0xe8, 0x03, 0xea, 0xe9, 0xff, 0x3f, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x3c, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x2f,
   0x40, 0x02, 0xf8, 0xed, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78,
   0x0e, 0x00, 0x00, 0x00, 0xf0, 0x6f, 0xff, 0x05, 0x90, 0x3d, 0xee, 0xe5,
   0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,
   0xfc, 0xff, 0xff, 0xdd, 0x88, 0xfd, 0xfc, 0xf5, 0xff, 0x7f, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xe1, 0xff, 0xff, 0xff, 0x7f,
   0x00, 0x26, 0xea, 0xf8, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x80, 0xe0, 0xff, 0xff, 0x7f, 0xf8, 0xfd, 0x87, 0xf8, 0xf8,
   0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
   0xff, 0xff, 0x7f, 0x19, 0x0d, 0x81, 0xf8, 0xfd, 0xff, 0xff, 0x03, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0x3f, 0xac,
   0x0f, 0x1c, 0xf4, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xe4, 0xc2, 0x7f, 0xfc, 0xff,
   0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00,
   0xf8, 0xff, 0xff, 0xf7, 0x80, 0x7f, 0xfe, 0xff, 0xff, 0xff, 0x07, 0x00,
   0x00, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xb1,
   0x4f, 0xc0, 0xfc, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xc0,
   0x01, 0x00, 0x00, 0x00, 0xfc, 0xfe, 0xff, 0xbf, 0x4f, 0x1f, 0xff, 0xff,
   0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x03, 0x00, 0x00, 0x00,
   0x00, 0xf8, 0xff, 0x3f, 0xcb, 0xf7, 0xfc, 0xff, 0xff, 0xff, 0x03, 0x00,
   0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0x7c,
   0x68, 0xcf, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0xf0,
   0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0x3f, 0x44, 0x9b, 0xfc, 0xff,
   0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x20, 0x7f, 0x00, 0x00, 0x00,
   0x00, 0xfc, 0xcf, 0xbf, 0x4c, 0x9f, 0xfc, 0xff, 0xff, 0xff, 0x03, 0x00,
   0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff,
   0xcc, 0xed, 0xfe, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
   0xff, 0x00, 0x00, 0x80, 0xfa, 0xff, 0xff, 0xff, 0x9c, 0x9f, 0xff, 0xff,
   0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0xf3,
   0xff, 0xff, 0xff, 0xff, 0xc0, 0xd9, 0xfe, 0xff, 0xff, 0xff, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x80, 0xff, 0xff, 0xff, 0xdf, 0xff,
   0xe1, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0xf0, 0x00, 0x80, 0x0f, 0x00, 0xc0, 0x8d, 0xff, 0xa0, 0xfe, 0xff, 0xff,
   0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x01, 0x00, 0x01,
   0x00, 0xc0, 0x00, 0xf8, 0x40, 0xfd, 0xff, 0xff, 0xff, 0xbf, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0x00, 0xf8, 0xe0, 0xf8,
   0xfc, 0xf7, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0xc0, 0x01, 0x00, 0x00, 0xf0, 0xff, 0x5f, 0xfa, 0xff, 0xfd, 0xff, 0xff,
   0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x03, 0x00, 0x00,
   0xf0, 0xff, 0xff, 0xdb, 0xbf, 0xff, 0xfd, 0xff, 0xff, 0x7f, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0xff, 0xff, 0x9f, 0x73,
   0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x07, 0x00, 0x00, 0xff, 0xff, 0xbf, 0xf1, 0xf5, 0xff, 0xfc, 0xff,
   0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00,
   0xfc, 0xff, 0x2f, 0x38, 0xf7, 0xff, 0xf9, 0xff, 0xff, 0x07, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0xc0, 0xbf, 0x60, 0xfe,
   0xfd, 0xff, 0xfb, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x1f, 0x00, 0x00, 0xc0, 0x12, 0xe0, 0xbf, 0xf7, 0xff, 0xfd, 0xff,
   0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00,
   0x00, 0x00, 0xf6, 0xff, 0xfc, 0xff, 0xf9, 0xff, 0xff, 0xff, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0xdc, 0xf8,
   0xff, 0xff, 0xf9, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x80, 0x7f, 0x00, 0x00, 0x00, 0xc0, 0xf9, 0xff, 0xff, 0xff, 0xf9, 0xff,
   0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xfb, 0x00, 0x00,
   0x00, 0xc0, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x80, 0xf3, 0x03, 0x00, 0x00, 0xdc, 0xff, 0xff,
   0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xf3, 0x07, 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x1f, 0x00,
   0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x3f, 0x00, 0xc0, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xf7, 0xff, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xe1,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};

#define hourglass_width 13
#define hourglass_height 19
static BMap hourglass_bits[] = {
   0xfe, 0x0f, 0xfe, 0x0f, 0x5c, 0x05, 0xac, 0x04, 0x5c, 0x04, 0x2c, 0x02,
   0x58, 0x01, 0xb0, 0x00, 0x60, 0x00, 0xe0, 0x00, 0x60, 0x00, 0xb0, 0x00,
   0x58, 0x01, 0x2c, 0x02, 0x5c, 0x04, 0xac, 0x04, 0x5c, 0x05, 0xfe, 0x0f,
   0xfe, 0x0f};
/*
   0xfe, 0x0f, 0xfe, 0x0f, 0x54, 0x05, 0xac, 0x04, 0x54, 0x04, 0x2c, 0x02,
   0x58, 0x01, 0xb0, 0x00, 0x60, 0x00, 0xa0, 0x00, 0x60, 0x00, 0xb0, 0x00,
   0x58, 0x01, 0x2c, 0x02, 0x54, 0x04, 0xac, 0x04, 0x54, 0x05, 0xfe, 0x0f,
   0xfe, 0x0f};
*/

#define stipple_width 16 
#define stipple_height 16 

static BMap stipple_bits[] = {
   0xaa, 0xaa, 0x55, 0x55, 0xaa, 0xaa, 0x55, 0x55, 0xaa, 0xaa, 0x55, 0x55,
   0xaa, 0xaa, 0x55, 0x55, 0xaa, 0xaa, 0x55, 0x55, 0xaa, 0xaa, 0x55, 0x55,
   0xaa, 0xaa, 0x55, 0x55, 0xaa, 0xaa, 0x55, 0x55};

static Pixmap hlfgrey = (Pixmap) NULL;

#define hlfgrey_width 8
#define hlfgrey_height 8
static BMap hlfgrey_bits[] = {
   0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa};

static Pixmap qwgrey = (Pixmap) NULL;
#define qwgrey_width 8
#define qwgrey_height 8
static BMap qwgrey_bits[] = {
   0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44};

static Pixmap tqwgrey = (Pixmap) NULL;
#define tqwgrey_width 8
#define tqwgrey_height 8
static BMap tqwgrey_bits[] = {
   0xee, 0xbb, 0xee, 0xbb, 0xee, 0xbb, 0xee, 0xbb};

static Pixmap upPix,  downPix,  lPix, rPix, molPix, gPix,fastPix,slowPix,blastPix,SkullPix,OrigPix,FotoPix,ColPix,CellPix,SurfPix,VRMLPix,HPix,AlignPix,FFPix,BigPix, ballPix, HourPix, MLFPix, OGLPix;

#define down_width 16
#define down_height 16
static BMap down_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x07, 0x10, 0x04, 0x10, 0x04,
   0x10, 0x04, 0x1e, 0x3c, 0x04, 0x10, 0x08, 0x08, 0x10, 0x04, 0x20, 0x02,
   0x40, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00};

#define up_width 16
#define up_height 16
static BMap up_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x40, 0x01, 0x20, 0x02, 0x10, 0x04,
   0x08, 0x08, 0x04, 0x10, 0x1e, 0x3c, 0x10, 0x04, 0x10, 0x04, 0x10, 0x04,
   0xf0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
#define l_width 16
#define l_height 16
static BMap l_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x01, 0x40, 0x01, 0x20, 0x1f,
   0x10, 0x10, 0x08, 0x10, 0x04, 0x10, 0x08, 0x10, 0x10, 0x10, 0x20, 0x1f,
   0x40, 0x01, 0x80, 0x01, 0x00, 0x01, 0x00, 0x00};
#define r_width 16
#define r_height 16
static BMap r_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x01, 0x80, 0x02, 0xf8, 0x04,
   0x08, 0x08, 0x08, 0x10, 0x08, 0x20, 0x08, 0x10, 0x08, 0x08, 0xf8, 0x04,
   0x80, 0x02, 0x80, 0x01, 0x80, 0x00, 0x00, 0x00};
#define pace_width 16
#define pace_height 16
static BMap slow_bits[] = {
   0xe0, 0x03, 0x18, 0x0c, 0x04, 0x10, 0x02, 0x20, 0x02, 0x20, 0x01, 0x40,
   0x01, 0x40, 0x81, 0x40, 0x81, 0x40, 0x81, 0x41, 0x82, 0x21, 0x82, 0x21,
   0x84, 0x13, 0x98, 0x0f, 0xe0, 0x03, 0x00, 0x00};
static BMap fast_bits[] = {
   0xe0, 0x03, 0x18, 0x0c, 0x04, 0x10, 0x02, 0x20, 0x02, 0x20, 0x01, 0x40,
   0x01, 0x40, 0x81, 0x40, 0x81, 0x41, 0x81, 0x43, 0x82, 0x27, 0x82, 0x2f,
   0x84, 0x1f, 0x98, 0x0f, 0xe0, 0x03, 0x00, 0x00};
static BMap blast_bits[] = {
   0xe0, 0x03, 0x18, 0x0c, 0x04, 0x10, 0x02, 0x20, 0x02, 0x20, 0x01, 0x40,
   0x01, 0x40, 0x81, 0x7f, 0x81, 0x7f, 0x81, 0x7f, 0x82, 0x3f, 0x82, 0x3f,
   0x84, 0x1f, 0x98, 0x0f, 0xe0, 0x03, 0x00, 0x00};

#define MAX_COLORS  256
#ifndef COLOR_OFFSET
#define COLOR_OFFSET 0.25
#endif
static float coloff = COLOR_OFFSET;

static Display *display;
static int screen;
static unsigned long colors[MAX_COLORS];
static unsigned short colorr[MAX_COLORS];
static unsigned short colorg[MAX_COLORS];
static unsigned short colorb[MAX_COLORS];
static int colcells = 16;
static int IBGcolor = 0;
static int OBGcolor = 0;
static int BGmode = 0;
#define SHCOLNUM 7
static int shcolors[SHCOLNUM] = {190,193,196,199,202,205,208};
static int rimcols[7] = {0,0,3,1,6,10,5};
#define LIGHT  1
#define MEDIUM 0
#define DARK   2

#define MAXSAVE 100000
#define MXSAVESTR 1000
static struct{float xxval;
              float yyval;
              int evtype;} savecom[MAXSAVE];
              
static int count = 0;
static int scount = 0;
static int cnt = 0;
static int ihlp ;
static int hold = 0;
static int holdt = 0;
static int holdp = 0;
static char savestr[MXSAVESTR][255];
static int nsavestr[MXSAVESTR];
	 
static Bool monoscr = 0;
static int linwid = 1;
static int linmax = 10;

static float xoff = 0.0;
static float yoff = 0.0;
static float scale = 1.0;
static int MotionCount = 0;
static int ZoomX1, ZoomY1;
static int ZoomX2, ZoomY2;
static int ZoomW, ZoomH;
static Bool ZoomEnable = True, ZoomSelection = False;
static Bool Select = True;
static Cursor ZoomCursor;
static Cursor AtomCursor;
static Cursor WaitCursor;
static int *ixp;
static int *iyp;
static int *iaton;
static int *iatoms;
static int *natoms;
static int *jring;
static int *isimpl;
static int *fancy;
static int *atcol;
static int *shade;
static int *persp;
static int aflag = 0,anum,acnt;
static int bflag = 0;
static int cflag = 0;
static int dflag = 0;
static int doalign = 0;
static int bretval = 320;
#define MINDIFF 15
static int asel[6];
static int aselkeep[2];
static float aret;
static float toangs = 0.52917706e0;

static Window win,winC,subC,winMC,subMC,winau,wincnv,wingeo,winspec,subSPEC,winsco,winpmf; 			
static Window Fwin,RESwin,COMMwin,DISTwin,subDIST,SUBwin,CPwin,CTwin;
static Window rootW;
static GC gc;				
static Pixmap stipple;
static Pixmap gijs;
static Pixmap molback;
static Pixmap distpix;
static Pixmap bckwin;
static Pixmap colmap;
static unsigned int BckW = 100;	
static unsigned int BckH = 20;	
static Drawable molcur;
XSizeHints size_hints;		
XTextProperty windowProp;
XIconSize *size_list;	
XEvent report;
XEvent event;
XGCValues values;
XWindowAttributes xwa;
static XFontStruct *mfinfo;
Pixmap icon_pixmap;
Region region;
void fwincall(char *str);
static int addfile = 0;
static int poszset = 0;

static int xlx, yly ;			/* more statics for     */
static int start_xlx, start_yly;	/* line drawing		*/
static unsigned int width, height;		/* window size		*/
static unsigned int Vsize = 800;
static int Mwidth, Mheight;		/* window size		*/

static int wx = 10, wy = 30;	/* window location	*/
static unsigned int border_width = 0;	/* no border 		*/

unsigned int icon_width, icon_height;       
unsigned long foreground_pixel;
static XSetWindowAttributes xswa;
static XVisualInfo *vi;
#ifdef DOGL
static GLXContext cx;
static int attributeList[] = {GLX_RGBA, GLX_DEPTH_SIZE,16, GLX_DOUBLEBUFFER, None };
#endif
#define FFOGD 2.0
#define FFOGDS 4.0
static int has_opengl = 0;

static char *window_name  = "MOLDEN";
static char *icon_name    = "Molden";
static char *display_name = NULL;

#define MAXSTRLEN 80 
#define MAXSTRLMW 40 
#define DEFSTRNAME ""
#define DEFAUTHGEOM  "-100+100"
#define DEFCNVGEOM  "-10+10"
#define DEFPMFGEOM  "-10+440"
#define DEFCNV2GEOM  "-410+10"
#define DEFQBOXGEOM  "-400-400"
#define DEFPOPGEOM  "-200+200"
#define DEFQX	3
#define DEFQY	3
#define QBOXWIDE  450
#define QBOXHIGH   40
#define QBOXTX    340
#define QBOXZM    290
#define QBOXRF    290
#define QBOXRFD   331
#define QBOXFR      4
#define QBOXBORD    4
#define CNVOFFX    30
#define CNVOFFY    30
#define CNVBORD    10
#define DBHIGH     46
#define DBWIDE    236


static int CNVWIDE = 300;
static int CNVHIGH = 300;
static int gwi = 300;
static int ghi = 300;
static int nwframes = 0;
static int nhframes = 0;


#define SBOXWIDE  600
#define SBOXHIGH  400
#define SBOXOFFX  52
#define SBOXBLEN  200
#define SBOXOFFL  SBOXOFFX+SBOXBLEN+10
static int SUBup = 0;
static int *iwxyz;
static int *ipdbwh;

#ifdef DOQUEUE
static int nques = 4;
static int qopt = 0;
static char *ques[] = {"short","medium","long","power"};
static int quetims[] = {9,105,325,650};
#endif

static char *subwname[]  = {"Submit Gamess-UK Job","Submit Gaussian Job","Submit Mopac Job"};

static char *topt1[] = {"Single Point","Geometry Optimisation",
"Cart. Geom. Optimisation","Transition State","Frequency (Numerical)",
"Frequency (Analytical)","SDCI","Polarisability","HyperPolarisability",
"Magnetisability","Raman Intensities","IR Intensities","Localised Orbitals"};
static char *topt2[] = {"Single Point","Geometry Optimisation","Transition State","Frequency"};
static char *topt3[] = {"Single Point","Geometry Optimisation","Transition State","Frequency","Geometry Opt. & Frequency"};
static char **toph[3] = {topt1,topt2,topt3};
static int topn[3] = {13,4,5};
static char **topt;
static int toptn;
static char *tkey1[] = {" "," "," "," "," "," "," "," "," "," "," "," "," "};
static char *tkey2[] = {" ","Opt","Opt=TS","Freq"};
static char *tkey2b[] = {" ","Opt=Z-matrix","Opt=(TS,Z-matrix)","Freq"};
static char *tkey3[] = {"1SCF","EF","TS","FORCE LET","FORCE"};
static char **tkeyh[3] = {tkey1,tkey2,tkey3};
static char **tkey;
static int itopt[3] = {1,1,1};

static char *mopt1[] = {"RHF","Direct RHF","UHF","GVB n","MP2","Direct MP2","MP3","CASSCF"};
static char *mopt2[] = {"HF","RHF","UHF","ROHF","MP2","MP4","QCISD","CASSCF","LSDA","BHandH","BHandHLYP","Becke 3 LYP","AM1","dreiding","Amber"};
static char *mopt3[] = {"PM3","AM1","MNDO","MINDO3","PM6","RM1"};
static char **moph[3] = {mopt1,mopt2,mopt3};
static int mopn[3] = {8,15,6};
static char **mopt;
static int moptn;
static char *mkey1[] = {" "," "," "," "," "," "," "," "};
static char *mkey2[] = {"HF","RHF","UHF","ROHF","MP2","MP4","QCISD","CASSCF(4,6)","SVWN","BHandH","BHandHLYP","Becke3LYP","AM1","dreiding","Amber"};
static char *mkey3[] = {"PM3","AM1","MNDO","MINDO3","PM6","RM1"};
static char **mkeyh[3] = {mkey1,mkey2,mkey3};
static char **mkey;
static int imopt[3] = {0,0,1};

static char *bopt1[] = {"STO-3G","3-21G","4-31G","6-31G","6-31G*","6-31G**","MINI1","MINI4","MIDI1","MIDI4","DZ","TZV","TZVP","ECPMIN","ECPDZ","ECPTZV","ECPTZVP"};
static char *bopt2[] = {"STO-3G","3-21G","4-31G","6-31g","6-31G*","6-31G**","6-31+G*","LANL2DZ"};
static char *bopt3[] = {" "};
static char **boph[3] = {bopt1,bopt2,bopt3};
static int bopn[3] = {17,8,1};
static char **bopt;
static int boptn;
static char *bkey1[] = {"STO-3G","3-21G","4-31G","6-31G","6-31G*","6-31G**","6-31+G*","LANL2DZ"};
static char *bkey2[] = {"STO-3G","3-21G","4-31G","6-31G","6-31G*","6-31G**","6-31+G*","LANL2DZ"};
static char *bkey3[] = {" "};
static char **bkeyh[3] = {bkey1,bkey2,bkey3};
static char **bkey;
static int ibopt[3] = {0,0,0};


static char *spopt[] = {"Singlet","Doublet","Triplet","Quartet","Quintet","Sextet","Septet","Octet"};
static int ispopt = 0;

static char *molopt1[] = {"No extra keys","Molden G94/98","Molden G92"};
static char *molopt2[] = {"No extra keys","extra keys"};
static char **molopt;
static int imolopt[3] = {1,1,1};

static char *copt[] = {"-3","-2","-1","0","1","2","3"};
static int icopt = 3;

static char *resopt[] = {"Dont Save EDs","ed3","ed2","ed2 + ed3","Restart HF","Restart CASSCF","Restart MCSCF","Restart CI","Restart MRDCI","Restart FULLCI"};
static char *reskey[] = {" ","-t ed3","-t ed2","-t ed2 -t ed3","-r hf","-r casscf","-r mcscf","-r ci","-r mrdci","-r fullci"};
static int iresopt = 0;

static int iscfd = 1;
static int ihess = 1;
static char scfdir[] = "SCF=Direct";
static char nullstr[] = " ";
static int jmode;
static int izmat = 1;
static int ioniom = 0;
static int ionon = 0;

#define SUBLEN1 80
#define SUBLEN2 15
static char rungam[SUBLEN1];
#ifdef VMS
static struct dsc$descriptor_s *glin1;
static struct dsc$descriptor_s *glin2;
static struct dsc$descriptor_s *gtitl;
static struct dsc$descriptor_s *jname;
static struct dsc$descriptor_s *qname;
static struct dsc$descriptor_s *ename;
static struct dsc$descriptor_s *vfile;
static struct dsc$descriptor_s *mfile;
static struct dsc$descriptor_s *oglfile;
static struct dsc$descriptor_s *povfile;
#else
#ifdef CRAY
static _fcd glin1;
static _fcd glin2;
static _fcd gtitl;
static _fcd jname;
static _fcd qname;
static _fcd ename;
static _fcd vfile;
static _fcd mfile;
static _fcd oglfile;
static _fcd povfile;
#else
static char *glin1;
static char *glin2;
static char *gtitl;
static char *jname;
static char *qname;
static char *ename;
static char *vfile;
static char *mfile;
static char *oglfile;
static char *povfile;
#endif
#endif

#define MAXCMD 80
static char cmdstr[MAXCMD];
static int cycle = 0;
static int delcyclefile = 0;
static int fndfile = 0;
static int tnkpid = 0;
static int tnkupd = 0;
static int tnkloop = 0;
static int handle = 0;
static int tnk_single = 0;
static double newen;

static unsigned long infofg, infobg;
static unsigned long Black, White;
static Window QBox, PopUp, FrBox,EBox, PopOk;
static char   strname[MAXSTRLEN];
static char   molwstr[MAXSTRLMW] = " ";
static char   densstr[MAXSTRLMW] = " ";
static char   *qboxprmt;
static char   stemp[MAXSTRLEN];
static char   atemp[MAXSTRLEN];
static char   chgtmp[MAXSTRLEN];
static char   pchgtmp[MAXSTRLEN];
static int norbs;

#define gray50_width 8
#define gray50_height 8
static BMap gray50_bits[] = {
   0x33, 0xcc, 0x33, 0xcc, 0x33, 0xcc, 0x33, 0xcc};

typedef struct { Window win;            /* parent window */
                 int x,y,w,h;           /* size of button rectangle */
                 int lit;               /* if true, invert colors */
                 int active;            /* if false, stipple gray */
                 int toggle;            /* if true, clicking toggles state */
                 int boggle;            /* if true, clicking toggles state */
                 int lastused;          /* lastused */
		 int fg;		/* foreground color index */
                 int bg;		/* colors */
                 char *str;             /* string in button */
                 char *explstr;         /* string with explanation */
                 Pixmap pix;            /* use pixmap instead of string */
                 int pw,ph;             /* size of pixmap */
                 int style;             /* ... */
                 int fwidth;            /* width of frame */
               } BSTRU;

typedef struct { Window win;            /* parent window */
		 int x,y;		/* pos. of scroll rectangle */
                 unsigned int w,h;      /* size of scroll rectangle */
		 int *wn;		/* number of elements in list */
		 int *wpos;		/* position of window in list */
		 int wh;		/* hight of the rectangle in elements */
               } SCRSTRU;

static SCRSTRU zscroll;

#define SCRMIN 10

typedef struct {char   **list;		/* pointer to list of strings */
		float  *rlst;		/* pointer to float array */
		double  *flst;		/* pointer to double array */
		int *ilst;		/* pointer into list */
		int *nents;		/* number of entries in list */
		} LSTRU;

typedef struct {char   **list;		/* pointer to list of strings */
		int nents;		/* number of entries in list */
		} LSSTRU;

typedef struct { Window win;            /* parent window */
                 int x,y;		/* size of list rectangle */
                 unsigned int w,h;      /* size of list rectangle */
		 unsigned int wwin;	/* size of parent window */
		 int mxents;		/* max entries in visible window on list*/
		 LSTRU list;
		 char *label;		/* tabel header */
		 int lpnt;		/* position of window in list */
		 int select;		/* selected entry */
		 BSTRU arrbut[2];	/* pointer to arrbuttons */
		 SCRSTRU scrbar;	/* scrollbar */
               } LISTSTRU;

typedef void (*ptr_void_proc)();
static int nbytes_select;
static char *select_pointer;
typedef struct { Window win;            /* parent window */
		 int pop;		/* is it a popup */
		 int active;		/* is it active  */
		 int changed;		/* is it changed  */
		 int fake;		/* is it a fake empty box  */
                 int x,y;		/* size of list rectangle */
                 unsigned int w,h;      /* size of list rectangle */
		 int col;		/* color of rectangle */
		 int bgcol;		/* background color of fake rectangle */
                 char *prompt;          /* prompt string */
		 int qbopt;		/* what is the answer, any of 3 below */
                 char str[MAXSTRLEN+1]; /* query string */
		 int strmax;		/* maximum length of string */
		 int	*iflt;		/* int answer */
		 short int	*i2flt;	/* short int answer */
		 float	*qflt;		/* float answer */
		 double	*dflt;		/* double answer */
		 int qbinct;		/* option to be given to fortan */
                 char *explstr;         /* string with explanation */
		 ptr_void_proc callback;/* callback routine */
               } QBOXSTRU;

#define mxvalc 10
typedef struct { double edge;
		 double ctval[mxvalc];
		 double pxyz[3];
                 int nvalc,nspts,istyp; 
               } SRFSTRU;

static SRFSTRU *surface;

static double *scle;
static int *nps1;
static int *nps2;
static double *adjuss;
static double *rng1;
static double *rng2;
static double *vlcnt;

typedef struct { double hdmin;
		 double hdmax;
		 float hamin;
		 float hamax;
               } HBSTRU;

static HBSTRU *hbpars;

typedef struct { int button;
		 Window win;
		 BSTRU *barr;
		 QBOXSTRU *qarr;
		 int borq;
		 int active;
		 int *winup;
               } EXPLSTRU;

static EXPLSTRU expldat = {-1,-1,NULL,NULL,0,0,NULL};

static char *cellopts[] = {"Molecule","Mol+Cell","Packed-Cell 1",
"Packed-Cell 2","Packed-1+Surf","Packed-2+Surf","Multiple-Cells",
"Multiple-CellsA","Multiple-CellsB","Multiple-CellsC","Multiple-CellsAB",
"Multiple-CellsAC","Multiple-CellsBC","Cell Rot On/Off",
"Edit Cell Parameters","Delete Sel. Atoms","Move Sel. Atoms","SuperCell", "Optimise xtinker","Write"};
static int ncell = 20;
static char *cellwopts[] = {"Write DMAREL","Write CRYSTAL95","Write SHELX","Write VASP","write PLUTON","write MOPAC Tv","write CPMD","write CIF"};
static int nwcell = 8;
static double CellTran[] = {0.0,0.0,0.0};
static char *xtinkopts[] = {"Charges","Multipoles"};

static char *cellpars[] = {"A    ","B    ","C    ","ALPHA","BETA ","GAMMA","SpaceGroupNumber","SpaceGroupName"};
static char *cellvec[] = {"A","B","C"};
static int CPact[5][6] = {
  {1,1,1,1,1,1},
  {1,1,1,0,1,0},
  {1,1,1,0,0,0},
  {1,0,1,0,0,0},
  {1,0,0,0,0,0}
};
static int CPup = 0;
static int CPopt = 0;
#define CPBOXWIDE  250
#define CPBOXHIGH  310
#define CPBOXOFFX  20
#define CPBOXOFFY  20

static int CTdel = 0;
static int CTup = 0;
static int CTsdone = 0;
static int CTdsdone = 0;
static int CTconn = 1;
#define CTBOXWIDE  260
#define CTBOXHIGH  140
#define CTBOXOFFX  15
#define CTBOXOFFY  20

#define GLTOL 5

#define MAXPNT 2000
typedef struct { double fmaxt,frmst,dmaxt,drmst,fgmin,fgmax,dgmin,dgmax,enmax,enmin;
                 int ngeoms;
                 int nepnts;
                 int gcvav;
		 int ifmxav,ifrmav,idmxav,idrmav,ieav,ifrav,mxpnt;
               } GEO1STRU;

static GEO1STRU *geo1ptr;

typedef struct { double formax[MAXPNT];
                 double forrms[MAXPNT];
                 double dismax[MAXPNT];
                 double disrms[MAXPNT];
                 double epoints[MAXPNT];
                 int isav[MAXPNT];
               } GEO2STRU;

static GEO2STRU *geo2ptr;

typedef struct { double *formax;
                 double *forrms;
                 double *dismax;
                 double *disrms;
                 double *epoints;
                 double *fmaxt;
		 double *frmst;
		 double *dmaxt;
		 double *drmst;
		 double *fgmin;
		 double *fgmax;
		 double *dgmin;
		 double *dgmax;
		 double *enmax;
		 double *enmin;
                 int *isav;
                 int *ngeoms;
                 int *nepnts;
                 int *gcvav;
		 int *ifmxav;
		 int *ifrmav;
		 int *idmxav;
		 int *idrmav;
		 int *ieav;
		 int *mxpnt;
		 int mxorg;
               } GEOPSTRU;

static GEOPSTRU geopntr;
static GEOPSTRU TMPgeopntr;

#define MAXITER 1000
typedef struct { double convg1[MAXITER];
                 double convg2[MAXITER];
                 double cnvmax,cnvmin;
                 int jstrt1,jend1;
                 int jstrt2,jend2;
                 int icvav1,icvav2;
               } CNVSTRU;

static CNVSTRU *cnvptr;

#define MAXAT 1000

typedef struct {
	int swap;
	int prec;
	int box;
	int vir;
	int pres;
	int x;
	int v;
	int f;
	int natoms;
	int nframes;
	long *fpos;
	FILE *fptr;
       } sttrr;

static sttrr strx = {0,0,0,0,0,0,0,0,0,0,NULL,NULL};

typedef struct {
	int etot;
	FILE *fptr;
       } stedr;

static stedr stre;

void cltrr();

static Bool Selecting = 0;

typedef struct { double *variable;
		 double varinit;
		 double varincr[3];
		 int isel;
		 int vartype;
		 int vdirection;
		 int frame;
		 int nframe;
		 int on;
		 int part;
               } ANIMSTRU;

static ANIMSTRU animptr = {NULL,0.0,{0.01,5.0,5.0},0,0,1,0,60,0,0};

typedef struct { double bl[MAXAT];
		 double alph[MAXAT];
		 double bet[MAXAT];
		 int ibl[MAXAT];
		 int ialph[MAXAT];
		 int ibet[MAXAT];
		 int ianz[MAXAT];
		 int iz[MAXAT][4];
		 int imap[MAXAT];
               } ZMATSTRU;

static ZMATSTRU *zmatptr;

typedef struct { double *bl;
		 double *alph;
		 double *bet;
		 int *ibl;
		 int *ialph;
		 int *ibet;
		 int *nz;
		 int *ianz;
		 int *iz;
		 int *imap;
		 int *ihaszm;
		 int *mxzat;
		} ZMSTRU;

static ZMSTRU zmptr;
static ZMSTRU TMPzmptr;

typedef struct { int ianz;
		 int iz[4];
		 double bl;
		 double alph;
		 double bet;
		} ZLINESTRU;

typedef struct { double cstoc[MAXAT][3];
		 double czstoc[MAXAT][3];
		 double astoc[MAXAT];
		 double bstoc[MAXAT];
		 int ianstc[MAXAT];
               } TSTOCSTRU;

static TSTOCSTRU *tstoc;

typedef struct { double *cstoc;
		 double *czstoc;
		 double *astoc;
		 double *bstoc;
		 int *ianstc;
               } STOCSTRU;

static STOCSTRU stoc;
static STOCSTRU TMPstoc;

#define MAXORB 256

typedef struct { double qd[MAXORB][MAXORB];
                 double pd[MAXORB];
                 double gd[MAXORB][3];
                 double hd[MAXORB][6];
               } TORBSTRU;

static TORBSTRU *torb;

typedef struct { double *qd;
		 double *pd;
		 double *gd;
		 double *hd;
               } ORBSTRU;

static ORBSTRU orb;
static ORBSTRU TMPorb;

typedef struct { double *focc;
		 double *focb;
		 double *vectrs;
		 double *vectrb;
		 double *p;
		 double *paa;
		 double *averag;
		 float *eiga;
		 float *eigb;
		 float *stoalfa;
		 float *stobnorm;
		 int *ncols;
		 int *ncolb;
		 int *nocc;
		 int *nocb;
		 int *naorbs;
		 int *mxorb;
		 int *istos;
               } DORBSTRU;

static DORBSTRU dorb;
static DORBSTRU TMPdorb;

typedef struct { double *denn;
		 double *pmnn;
		 double *dens;
		 double *denst;
		 double *edx;
		 double *edy;
		 double *rz;
		 double *bucket;
		 int *iedlog;
		 int *ix;
		 int *iy;
		 int *mx3d;
		 int *mx3d2;
		 int mxorg;
               } GRDSTRU;

static GRDSTRU sgrd;
static GRDSTRU TMPsgrd;

typedef struct { double *fmap;
		 int *mx3d;
		 int mxorg;
               } MGRDSTRU;

static MGRDSTRU mgrd;
static MGRDSTRU TMPmgrd;
static int *mapit;
static int *ipsi;

typedef struct { double *coo;
		 double *rzp;
		 double *qat;
		 int *isurf;
		 int *lwrit;
		 int *lring;
		 int *ianz;
		 int *iaton;
		 int *iatclr;
		 int *iresid;
		 int *ixp;
		 int *iyp;
		 int *iconn;
		 int *inat;
		 short int *ityp;
		 short int *ipdbt;
		 int *mxnat;
		 int *iatoms;
		 int mxorg;
               } COOSTRU;

static COOSTRU xyz;
static COOSTRU TMPxyz;

#define NHETRES -4
static char *fragments[] = {"Read","-CH3","-CH=CH2","-HC=O","-COOH","-NH2","-OH","-CHCH","-CycloHexane","-Phenyl","-Cl","-Br","-I","-OCH3","-SH","-NO2","CH4","Period. Chain","Amino Acid","Sequence"};
static int nfrag = 20;
static char *fragmnts[] = {"-CH3","-CH=CH2","-HC=O","-COOH","-NH2","-OH","-CHCH","-CycloHexane","-Phenyl","-Cl","-Br","-I","-OCH3","-SH","-NO2","CH4","ACE","FOR","NME","NH2"};
static int nfrags = 16;
static char *Periodic[] = {"Translation","Screw Axis"};
static char *ChainLength[] = {"1","2","3","4","5","6","7","8","9","10"};
static char *AminoAcids[] = {"GLY","ALA","SER","CYS","THR","ILE","VAL","MET",
"ASP","ASN","LEU","LYS","GLU","GLN","PRO","ARG","HIS","PHE","TYR","TRP",
"ASX","GLX","HYP","A","C","G","T","U","1MA","5MC","OMC","1MG","2MG","M2G",
"7MG","OMG","YG","I","+U","H2U","5MU","PSU"};
static char *AAlet[] = {"G","A","S","C","T","I","V","M","D","N","L","K","E",
"Q","P","R","H","F","Y","W","?","?","?","A","C","G","T","U","?","?","?","?","?","?","?","?","?","I","?","?","?","?"};
static int NAminos = 20;
static char *AminoCaps[] = {"GLY","ALA","SER","CYS","THR","ILE","VAL","MET",
"ASP","ASN","LEU","LYS","GLU","GLN","PRO","ARG","HIS","PHE","TYR","TRP",
"ACE","FOR","NME","NH2"};
static char *AmiOpt[] = {"Add","Delete","Insert","Replace"};
static char *HetOpt[] = {"Center","Contacts","Calculate Charges","Delete Molecule","Add to Surface"};
#ifdef DOGL
static char *AmiBOpt[] = {"Switch On","Switch Off","Center","Contacts","Add to Surface","Delete","Insert","Replace","Cap Residue","Rotamer","Fit Rotamer","Best Rotamer","Change Rot. Libr.","Add to Flex. Resid.","Add"};
#else
static char *AmiBOpt[] = {"Switch On","Switch Off","Center","Contacts","Delete","Insert","Replace","Cap Residue","Rotamer","Fit Rotamer","Best Rotamer","Change Rot. Libr.","Add to Flex. Resid.","Add"};
#endif
static char *Rotamers[] = {
"Rotamer1","Rotamer2","Rotamer3","Rotamer4","Rotamer5","Rotamer6","Rotamer7",
"Rotamer8","Rotamer9","Rotamer10", "Rotamer11","Rotamer12","Rotamer13","Rotamer14",
"Rotamer15","Rotamer16","Rotamer17","Rotamer18","Rotamer19","Rotamer20","Rotamer21",
"Rotamer22","Rotamer23","Rotamer24","Rotamer25","Rotamer26","Rotamer27","Rotamer28",
"Rotamer29","Rotamer30","Rotamer31","Rotamer32","Rotamer33","Rotamer34","Rotamer35",
"Rotamer36","Rotamer37","Rotamer38","Rotamer39","Rotamer40","Rotamer41","Rotamer42",
"Rotamer43","Rotamer44","Rotamer45","Rotamer46","Rotamer47","Rotamer48","Rotamer49",
"Rotamer50","Rotamer51","Rotamer52","Rotamer53","Rotamer54","Rotamer55","Rotamer56",
"Rotamer57","Rotamer58","Rotamer59","Rotamer60","Rotamer61","Rotamer62","Rotamer63",
"Rotamer64","Rotamer65","Rotamer66","Rotamer67","Rotamer68","Rotamer69","Rotamer70",
"Rotamer71","Rotamer72","Rotamer73","Rotamer74","Rotamer75","Rotamer76","Rotamer77",
"Rotamer78","Rotamer79","Rotamer80","Rotamer81"
};
static char *RotLib[] = {"Richardson","Dunbrack"};
#define MAXSEQ 1000
static int Sequence[MAXSEQ];
static int NSeq = 0;
static char SeqStat[64] = " ";
static int LastAmino = -1;
static int InsertAmino = -1;
static int ReplaceAmino = 0;
static int CurAmino = -1;
#define MXEXP 20
static int oque[MXEXP] = {MXEXP*0};
static int oqlen = 0;
static int oqpos = 0;

#define BENZLEN 11
#define CCBENZ 1.40
#define CHBENZ 1.089

static ZLINESTRU benzyl[BENZLEN] = { {6,{0,0,0,0},0.0,0.0,0.0},
				{6,{1,0,0,0},CCBENZ,0.0,0.0},
				{6,{2,1,0,0},CCBENZ,120.0,0.0},
				{6,{3,2,1,0},CCBENZ,120.0,0.0},
				{6,{4,3,2,0},CCBENZ,120.0,0.0},
				{6,{5,4,3,0},CCBENZ,120.0,0.0},
				{1,{2,1,3,0},CHBENZ,120.0,180.0},
				{1,{3,2,4,0},CHBENZ,120.0,180.0},
				{1,{4,3,5,0},CHBENZ,120.0,180.0},
				{1,{5,4,3,0},CHBENZ,120.0,180.0},
				{1,{6,5,4,0},CHBENZ,120.0,180.0}
				};

static ZLINESTRU CHCH2[5] =   { {6,{0,0,0,0},0.0,0.0,0.0},
				{6,{1,0,0,0},1.335,0.0,0.0},
				{1,{1,2,0,0},1.089,120.0,0.0},
				{1,{2,1,3,0},1.089,120.0,0.0},
				{1,{2,1,3,0},1.089,120.0,180.0}
				};

static ZLINESTRU COOH[4] =   {  {6,{0,0,0,0},0.0,0.0,0.0},
				{8,{1,0,0,0},1.400,0.0,0.0},
				{8,{1,2,0,0},1.220,120.0,0.0},
				{1,{2,1,3,0},0.950,109.471,0.0}
				};

static ZLINESTRU CHO[3] =   {   {6,{0,0,0,0},0.0,0.0,0.0},
				{8,{1,0,0,0},1.220,0.0,0.0},
				{1,{1,2,0,0},1.089,120.0,0.0}
				};

static ZLINESTRU OH[2] =    {   {8,{0,0,0,0},0.0,0.0,0.0},
				{1,{1,0,0,0},0.947,0.0,0.0}
				};

static ZLINESTRU CHCH[5] =   {  {6,{0,0,0,0},0.0,0.0,0.0},
				{99,{1,0,0,0},1.0,0.0,0.0},
				{6,{1,2,0,0},1.189,90.0,0.0},
				{99,{3,1,2,0},1.0,90.0,0.0},
				{1,{3,4,1,0},1.051,90.0,180.0}
				};

static ZLINESTRU CL[1] =    {   {17,{0,0,0,0},0.0,0.0,0.0}
				};

static ZLINESTRU BR[1] =    {   {35,{0,0,0,0},0.0,0.0,0.0}
				};

static ZLINESTRU I[1] =    {   {53,{0,0,0,0},0.0,0.0,0.0}
				};

static ZLINESTRU OCH3[5] =   {  {8,{0,0,0,0},0.0,0.0,0.0},
				{6,{1,0,0,0},1.400,0.0,0.0},
				{1,{2,1,0,0},1.089,109.471,0.0},
				{1,{2,1,3,0},1.089,109.471,120.0},
				{1,{2,1,3,0},1.089,109.471,-120.0}
				};

static ZLINESTRU SH[2] =    {   {16,{0,0,0,0},0.0,0.0,0.0},
				{1,{1,0,0,0},0.947,0.0,0.0}
				};

static ZLINESTRU NO2[3] =   {   {7,{0,0,0,0},0.0,0.0,0.0},
				{8,{1,0,0,0},1.210,0.0,0.0},
				{8,{1,2,0,0},1.210,125.25,0.0}
				};

static ZLINESTRU NH2[3] =   {   {7,{0,0,0,0},0.0,0.0,0.0},
				{1,{1,0,0,0},1.010,0.0,0.0},
				{1,{1,2,0,0},1.010,120.0,0.0}
				};

static ZLINESTRU CH4[5] =   {   {6,{0,0,0,0},0.0,0.0,0.0},
				{1,{1,0,0,0},1.089,0.0,0.0},
				{1,{1,2,0,0},1.089,109.471,0.0},
				{1,{1,2,3,0},1.089,109.471,120.0},
				{1,{1,2,3,0},1.089,109.471,-120.0}
				};

static ZLINESTRU SCREW[2] = {	{99,{0,0,0,0},0.0,0.0,0.0},
				{99,{1,0,0,0},10.0,0.0,0.0}
				};

static ZLINESTRU BACK[6] = {	{7,{0,0,0,0},0.0,0.0,0.0},
				{6,{1,0,0,0},1.460,0.0,0.0},
				{6,{2,1,0,0},1.510,111.6,0.0},
				{8,{3,2,1,0},1.220,121.0,113.0},
				{8,{3,2,4,0},1.220,122.5,180.0},
				{1,{1,2,3,0},1.020,121.0,61.0}
			    };

static short int BACK_TYP[5] = { 2,3,38,4,1};

static ZLINESTRU BACKHS[2] = {  {1,{1,2,6,0},1.020,107.9,120.0},
				{1,{1,2,6,0},1.020,107.9,-120.0}
			     };

static short int BACKHS_TYP[2] = {2,3};

typedef struct { double rots[4]; double ener[1];} ROTSSTRU;

static ZLINESTRU GLY[2] = {     {1,{2,3,1,0},1.100,109.3,121.6},
				{1,{2,3,1,0},1.100,109.3,-121.6}
			   };
static short int GLY_TYP[2] = { 4,5};
static int GLY_CHI[4] = {-1,-1,-1,-1};
static ROTSSTRU GLY_ROT[1] = {
				{ 0.0, 0.0, 0.0, 0.0, 0.0}
				};


static ZLINESTRU ALA[5] = {     {6,{2,3,1,0},1.536,110.1,122.910},
				{1,{2,3,1,0},1.100,108.234,-118.193},
				{1,{7,2,3,0},1.100,110.3,179.999},
				{1,{7,2,3,0},1.100,110.3,60.0},
				{1,{7,2,3,0},1.100,110.3,-60.326}
			   };
static short int ALA_TYP[5] = { 5,4,7,8,9};
static int ALA_CHI[4] = {-1,-1,-1,-1};
static ROTSSTRU ALA_ROT[1] = {
				{ 0.0, 0.0, 0.0, 0.0, 0.0}
				};


static ZLINESTRU SER[6] = {     {6,{2,3,1,0},1.530,110.1,122.8},
				{8,{7,2,1,0},1.417,111.1,62.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,108.8,-121.8},
				{1,{7,2,8,0},1.100,108.8,121.8},
				{1,{8,7,2,0},1.000,109.5,180.0}
			   };
static short int SER_TYP[6] = { 5,31,4,7,8,10 };
static int SER_CHI[4] = {2,6,-1,-1};
static ROTSSTRU SER_ROT[3] = {
				{  62.0, 180.0, 0.0, 0.0, 0.00},
				{-177.0, 180.0, 0.0, 0.0, 0.47},
				{ -65.0, 180.0, 0.0, 0.0, 0.77}
				};

static ROTSSTRU SER_ROTD[3] = {
				{  65.3, 180.0, 0.0, 0.0, 0.00},
				{ 179.0, 180.0, 0.0, 0.0, 0.41},
				{ -63.9, 180.0, 0.0, 0.0, 0.28}
				};


static ZLINESTRU CYS[6] = {     {6,{2,3,1,0},1.530,110.1,122.8},
				{16,{7,2,1,0},1.822,114.4,-65.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,108.8,-121.8},
				{1,{7,2,8,0},1.100,108.8,121.8},
				{1,{8,7,2,0},1.300,109.5,0.0}
			   };
static short int CYS_TYP[6] = { 5,37,4,7,8,10 };
static int CYS_CHI[4] = {2,6,-1,-1};
static ROTSSTRU CYS_ROT[3] = {
				{  62.0,  0.0, 0.0, 0.0, 0.47},
				{-177.0,  0.0, 0.0, 0.0, 0.39},
				{ -65.0,  0.0, 0.0, 0.0, 0.00}
				};

static ROTSSTRU CYS_ROTD[3] = {
				{  63.7,  0.0, 0.0, 0.0, 0.75},
				{-177.3,  0.0, 0.0, 0.0, 0.43},
				{ -64.3,  0.0, 0.0, 0.0, 0.00}
				};


static ZLINESTRU THR[9] = {     {6,{2,3,1,0},1.540,109.1,123.4},
				{8,{7,2,1,0},1.433,109.6,62.0},
				{6,{7,2,8,0},1.521,110.5,-120.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,108.5,120.2},
				{1,{8,7,2,0},1.000,109.5,60.0},
				{1,{9,7,2,0},1.100,109.5,180.0},
				{1,{9,7,13,0},1.100,109.5,120.0},
				{1,{9,7,13,0},1.100,109.5,-120.0}
			   };
static short int THR_TYP[9] = { 5,32,8,4,7,13,16,17,18};
static int THR_CHI[4] = {2,6,-1,-1};
static ROTSSTRU THR_ROT[3] = {
				{  62.0,  60.0, 0.0, 0.0, 0.00},
				{-175.0,  60.0, 0.0, 0.0, 1.16},
				{ -65.0,  60.0, 0.0, 0.0, 0.07}
				};

static ROTSSTRU THR_ROTD[3] = {
				{  61.1,  60.0, 0.0, 0.0, 0.00},
				{-173.3,  60.0, 0.0, 0.0, 1.11},
				{ -60.4,  60.0, 0.0, 0.0, 0.07}
				};


static ZLINESTRU ILE[14] = {    {6,{2,3,1,0},1.540,109.1,123.4},
				{6,{7,2,1,0},1.530,110.4,-65.0},
				{6,{7,2,8,0},1.521,110.5,-120.0},
				{6,{8,7,2,0},1.512,113.8,170.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,107.8,120.0},
				{1,{8,7,10,0},1.100,109.0,121.8},
				{1,{8,7,10,0},1.100,109.0,-121.8},
				{1,{9,7,2,0}, 1.100,109.5,180.0},
				{1,{9,7,15,0},1.100,109.5,120.0},
				{1,{9,7,15,0},1.100,109.5,-120.0},
				{1,{10,8,7,0},1.100,109.5,180.0},
				{1,{10,8,18,0},1.100,109.5,120.0},
				{1,{10,8,18,0},1.100,109.5,-120.0}
			   };
static short int ILE_TYP[14] = { 5,7,8,10,4,7,13,14,16,17,18,22,23,24 };
static int ILE_CHI[4] = {2,4,-1,-1};
static ROTSSTRU ILE_ROT[7] = {
				{  62.0, 100.0, 0.0, 0.0, 2.72},
				{  62.0, 170.0, 0.0, 0.0, 0.90},
				{-177.0,  66.0, 0.0, 0.0, 1.97},
				{-177.0, 165.0, 0.0, 0.0, 1.22},
				{ -65.0, 100.0, 0.0, 0.0, 2.34},
				{ -65.0, 170.0, 0.0, 0.0, 0.00},
				{ -57.0, -60.0, 0.0, 0.0, 0.84}
				};

static ROTSSTRU ILE_ROTD[9] = {
				{  60.6,  85.4, 0.0, 0.0, 2.78},
				{  61.1, 171.0, 0.0, 0.0, 0.97},
				{  61.7, -80.0, 0.0, 0.0, 4.11},
				{-167.9,  66.8, 0.0, 0.0, 1.86},
				{-171.4, 167.4, 0.0, 0.0, 1.36},
				{-165.5, -78.0, 0.0, 0.0, 3.76},
				{ -67.1,  83.0, 0.0, 0.0, 2.30},
				{ -63.8, 170.1, 0.0, 0.0, 0.00},
				{ -59.2, -61.0, 0.0, 0.0, 0.81}
				};


static ZLINESTRU VAL[11] = {    {6,{2,3,1,0},1.540,109.1,123.4},
				{6,{7,2,1,0},1.521,110.5,-65.0},
				{6,{7,2,8,0},1.521,110.5,-120.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,107.7,120.0},
				{1,{8,7,2,0},1.100,109.5,180.0},
				{1,{8,7,12,0},1.100,109.5,120.0},
				{1,{8,7,12,0},1.100,109.5,-120.0},
				{1,{9,7,8,0}, 1.100,109.5,180.0},
				{1,{9,7,15,0},1.100,109.5,120.0},
				{1,{9,7,15,0},1.100,109.5,-120.0}
			   };
static short int VAL_TYP[11] = { 5,7,8,4,7,13,14,15,16,17,18};
static int VAL_CHI[4] = {2,-1,-1,-1};
static ROTSSTRU VAL_ROT[3] = {
				{  63.0, 0.0, 0.0, 0.0, 1.44},
				{ 175.0, 0.0, 0.0, 0.0, 0.00},
				{ -60.0, 0.0, 0.0, 0.0, 0.77}
				};

static ROTSSTRU VAL_ROTD[3] = {
				{  65.5, 0.0, 0.0, 0.0, 1.36},
				{ 175.9, 0.0, 0.0, 0.0, 0.00},
				{ -61.7, 0.0, 0.0, 0.0, 0.81}
				};


static ZLINESTRU MET[12] = {    {6,{2,3,1,0},1.530,110.1,122.8},
				{6,{7,2,1,0},1.520,114.1,-65.0},
				{16,{8,7,2,0},1.801,112.8,-65.0},
				{6,{9,8,7,0},1.791,100.9,-70.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,109.4,108.9},
				{1,{7,2,8,0},1.100,109.4,-108.9},
				{1,{8,7,9,0},1.100,109.2,121.6},
				{1,{8,7,9,0},1.100,109.2,-121.6},
				{1,{10,9,8,0}, 1.100,109.5,180.0},
				{1,{10,9,16,0},1.100,109.5,120.0},
				{1,{10,9,16,0},1.100,109.5,-120.0}
			   };
static short int MET_TYP[12] = { 5,6,36,12,4,7,8,10,11,28,29,30};
static int MET_CHI[4] = {2,3,4,-1};
static ROTSSTRU MET_ROT[13] = {
				{  62.0, 180.0,  75.0, 0.0, 1.28},
				{  62.0, 180.0, -75.0, 0.0, 1.08},
				{-177.0,  65.0,  75.0, 0.0, 0.74},
				{-177.0,  65.0, 180.0, 0.0, 1.46},
				{-177.0, 180.0,  75.0, 0.0, 0.78},
				{-177.0, 180.0, 180.0, 0.0, 1.08},
				{-177.0, 180.0, -75.0, 0.0, 0.63},
				{ -67.0, 180.0,  75.0, 0.0, 0.07},
				{ -67.0, 180.0, 180.0, 0.0, 0.53},
				{ -67.0, 180.0, -75.0, 0.0, 0.35},
				{ -65.0, -65.0, 103.0, 0.0, 1.15},
				{ -65.0, -65.0, 180.0, 0.0, 1.39},
				{ -65.0, -65.0, -70.0, 0.0, 0.00}
				};

static ROTSSTRU MET_ROTD[27] = {
				{  60.8,   78.3,   73.3, 0.0, 2.33},
				{  57.6,   78.1,  177.7, 0.0, 2.60},
				{  59.4,   77.8,  -97.4, 0.0, 9.99},
				{  64.4, -178.3,   76.1, 0.0, 1.20},
				{  64.9, -176.0, -175.0, 0.0, 1.53},
				{  63.4,  179.1,  -71.8, 0.0, 1.17},
				{  72.5,  -70.1,   99.6, 0.0, 9.99},
				{  72.2,  -70.4,  174.3, 0.0, 3.75},
				{  72.6,  -72.0,  -71.4, 0.0, 2.69},
				{-176.0,   64.0,   72.5, 0.0, 0.58},
				{-174.5,   69.3, -166.1, 0.0, 1.42},
				{-172.4,   76.6,  -96.9, 0.0, 1.76},
				{-177.8,  179.2,   72.1, 0.0, 0.59},
				{-177.4,  174.6,  177.3, 0.0, 0.99},
				{-174.6,  179.7,  -71.6, 0.0, 0.52},
				{-178.7,  -73.7,   99.6, 0.0, 9.99},
				{-178.2,  -78.4,  173.0, 0.0, 2.39},
				{-178.8,  -82.3,  -73.4, 0.0, 1.41},
				{ -78.6,   67.3,   73.0, 0.0, 2.08},
				{ -78.9,   69.3, -175.6, 0.0, 2.69},
				{ -77.7,   70.6,  -98.9, 0.0, 3.34},
				{ -67.4,  178.0,   70.4, 0.0, 0.06},
				{ -67.3,  179.2, -177.6, 0.0, 0.39},
				{ -67.7, -176.3,  -73.7, 0.0, 0.30},
				{ -65.8,  -64.9,   99.6, 0.0, 1.04},
				{ -62.7,  -64.0,  171.9, 0.0, 1.02},
				{ -65.8,  -61.8,  -69.4, 0.0, 0.00}
				};


static ZLINESTRU ASP[7] = {     {6,{2,3,1,0},1.530,110.1,122.8},
				{6,{7,2,1,0},1.516,112.6,-70.0},
				{8,{8,7,2,0},1.250,118.4,-15.0},
				{8,{8,7,9,0},1.250,118.4,180.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,109.3,121.6},
				{1,{7,2,8,0},1.100,109.3,-121.6}
			   };
static short int ASP_TYP[7] = { 5,6,29,30,4,7,8};
static int ASP_CHI[4] = {2,3,-1,-1};

static ROTSSTRU ASP_ROT[5] = {
				{  62.0, -10.0, 0.0, 0.0, 0.95},
				{  62.0,  30.0, 0.0, 0.0, 0.98},
				{-177.0,   0.0, 0.0, 0.0, 0.49},
				{-177.0,  65.0, 0.0, 0.0, 1.27},
				{ -70.0, -15.0, 0.0, 0.0, 0.00}
				};

static ROTSSTRU ASP_ROTD[9] = {
				{  57.1,   54.3, 0.0, 0.0, 1.60},
				{  62.5,    1.3, 0.0, 0.0, 0.61},
				{  62.4,  -55.8, 0.0, 0.0, 1.30},
				{-173.6,   58.5, 0.0, 0.0, 0.75},
				{-172.3,   -0.8, 0.0, 0.0, 0.33},
				{-167.9,  -55.7, 0.0, 0.0, 1.09},
				{ -69.1,   65.0, 0.0, 0.0, 1.65},
				{ -72.1,  -12.7, 0.0, 0.0, 0.00},
				{ -65.4,  -49.8, 0.0, 0.0, 0.27}
				};


static ZLINESTRU ASN[9] = {     {6,{2,3,1,0},1.530,110.1,122.8},
				{6,{7,2,1,0},1.516,112.6,-65.0},
				{8,{8,7,2,0},1.230,120.8,-21.0},
				{7,{8,7,9,0},1.327,116.4,180.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,109.3,121.6},
				{1,{7,2,8,0},1.100,109.3,-121.6},
				{1,{10,8,7,0}, 1.000,120.0,0.0},
				{1,{10,8,14,0},1.000,120.0,180.0}
			   };
static short int ASN_TYP[9] = { 5,6,29,21,4,7,8,25,26};
static int ASN_CHI[4] = {2,3,-1,-1};

static ROTSSTRU ASN_ROT[7] = {
				{  62.0, -10.0, 0.0, 0.0, 1.02},
				{  62.0,  30.0, 0.0, 0.0, 0.88},
				{-174.0, -20.0, 0.0, 0.0, 0.70},
				{-177.0,  30.0, 0.0, 0.0, 0.55},
				{ -65.0, -20.0, 0.0, 0.0, 0.00},
				{ -65.0, -75.0, 0.0, 0.0, 0.94},
				{ -65.0, 120.0, 0.0, 0.0, 1.36}
				};

static ROTSSTRU ASN_ROTD[18] = {
				{  50.3, -115.0, 0.0, 0.0, 2.98},
				{  64.5,  -53.9, 0.0, 0.0, 1.41},
				{  64.6,    1.5, 0.0, 0.0, 0.82},
				{  60.0,   57.0, 0.0, 0.0, 1.22},
				{  68.9,  101.9, 0.0, 0.0, 2.57},
				{  69.3,  175.1, 0.0, 0.0, 3.76},
				{-176.0, -114.6, 0.0, 0.0, 1.31},
				{-173.5,  -66.3, 0.0, 0.0, 1.11},
				{-170.8,  -20.2, 0.0, 0.0, 0.81},
				{-169.3,   24.3, 0.0, 0.0, 0.62},
				{-171.9,   60.6, 0.0, 0.0, 0.97},
				{-160.3,  121.5, 0.0, 0.0, 2.49},
				{ -77.3, -137.6, 0.0, 0.0, 2.27},
				{ -65.7,  -63.9, 0.0, 0.0, 0.25},
				{ -70.4,  -23.2, 0.0, 0.0, 0.00},
				{ -79.5,   34.3, 0.0, 0.0, 1.85},
				{ -77.3,   96.5, 0.0, 0.0, 1.13},
				{ -64.7,  139.8, 0.0, 0.0, 1.32}
				};


static ZLINESTRU LEU[14] = {    {6,{2,3,1,0},1.530,110.1,122.8},
				{6,{7,2,1,0},1.530,116.3,-65.0},
				{6,{8,7,2,0},1.521,110.7,174.0},
				{6,{8,7,9,0},1.521,110.7,119.9},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,108.3,122.2},
				{1,{7,2,8,0},1.100,108.3,-122.2},
				{1,{8,7,9,0},1.100,107.5,-120.1},
				{1,{9,8,7,0}, 1.100,109.5,180.0},
				{1,{9,8,15,0},1.100,109.5,120.0},
				{1,{9,8,15,0},1.100,109.5,-120.0},
				{1,{10,8,7,0}, 1.100,109.5,180.0},
				{1,{10,8,18,0},1.100,109.5,120.0},
				{1,{10,8,18,0},1.100,109.5,-120.0}
			   };
static short int LEU_TYP[14] = { 5,6,10,11,4,7,8,10,22,23,24,25,26,27};
static int LEU_CHI[4] = {2,3,-1,-1};
static ROTSSTRU LEU_ROT[5] = {
				{  62.0,  80.0, 0.0, 0.0, 2.55},
				{-177.0,  65.0, 0.0, 0.0, 0.43},
				{-172.0, 145.0, 0.0, 0.0, 2.05},
				{ -85.0,  65.0, 0.0, 0.0, 1.90},
				{ -65.0, 175.0, 0.0, 0.0, 0.00}
				};

static ROTSSTRU LEU_ROTD[9] = {
				{  58.7,  80.7, 0.0, 0.0, 2.63},
				{  71.8, 164.6, 0.0, 0.0, 3.05},
				{  58.2, -73.6, 0.0, 0.0, 4.69},
				{-179.2,  63.0, 0.0, 0.0, 0.46},
				{-164.9, 170.7, 0.0, 0.0, 1.89},
				{-169.8, -73.1, 0.0, 0.0, 2.99},
				{ -86.1,  54.6, 0.0, 0.0, 1.68},
				{ -64.7, 174.5, 0.0, 0.0, 0.00},
				{ -81.5, -55.0, 0.0, 0.0, 2.55}
				};


static ZLINESTRU LYS[17] = {    {6,{2,3,1,0},1.530,110.1,122.8},
				{6,{7,2,1,0},1.520,114.1,-67.0},
				{6,{8,7,2,0},1.520,111.3,180.0},
				{6,{9,8,7,0},1.520,111.3,180.0},
				{7,{10,9,8,0},1.490,111.9,180.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,108.9,121.9},
				{1,{7,2,8,0},1.100,108.9,-121.9},
				{1,{8,7,9,0},1.100,109.6,121.4},
				{1,{8,7,9,0},1.100,109.6,-121.4},
				{1,{9,8,10,0},1.100,109.6,121.4},
				{1,{9,8,10,0},1.100,109.6,-121.4},
				{1,{10,9,11,0},1.100,109.5,121.5},
				{1,{10,9,11,0},1.100,109.5,-121.5},
				{1,{11,10,9,0}, 1.000,109.5,180.0},
				{1,{11,10,21,0},1.000,109.5,120.0},
				{1,{11,10,21,0},1.000,109.5,-120.0}
			   };
static short int LYS_TYP[17] = { 5,6,9,12,27,4,7,8,10,11,19,20,28,29,40,41,42};
static int LYS_CHI[4] = {2,3,4,5};
static ROTSSTRU LYS_ROT[27] = {
				{  62.0, 180.0,  68.0, 180.0, 2.10},
				{  62.0, 180.0, 180.0,  65.0, 1.74},
				{  62.0, 180.0, 180.0, 180.0, 1.21},
				{  62.0, 180.0, 180.0, -65.0, 1.97},
				{  62.0, 180.0, -68.0, 180.0, 2.25},
				{-177.0,  68.0, 180.0,  65.0, 1.79},
				{-177.0,  68.0, 180.0, 180.0, 1.15},
				{-177.0,  68.0, 180.0, -65.0, 2.10},
				{-177.0, 180.0,  68.0,  65.0, 1.73},
				{-177.0, 180.0,  68.0, 180.0, 1.30},
				{-177.0, 180.0, 180.0,  65.0, 0.90},
				{-177.0, 180.0, 180.0, 180.0, 0.19},
				{-177.0, 180.0, 180.0, -65.0, 1.07},
				{-177.0, 180.0, -68.0, 180.0, 1.43},
				{-177.0, 180.0, -68.0, -65.0, 2.25},
				{ -90.0,  68.0, 180.0, 180.0, 2.38},
				{ -67.0, 180.0,  68.0,  65.0, 1.73},
				{ -67.0, 180.0,  68.0, 180.0, 1.05},
				{ -67.0, 180.0, 180.0,  65.0, 0.99},
				{ -67.0, 180.0, 180.0, 180.0, 0.00},
				{ -67.0, 180.0, 180.0, -65.0, 0.82},
				{ -67.0, 180.0, -68.0, 180.0, 1.02},
				{ -67.0, 180.0, -68.0, -65.0, 1.73},
				{ -62.0, -68.0, 180.0,  65.0, 1.90},
				{ -62.0, -68.0, 180.0, 180.0, 0.63},
				{ -62.0, -68.0, 180.0, -65.0, 1.49},
				{ -62.0, -68.0, -68.0, 180.0, 1.84} 
				};

static ROTSSTRU LYS_ROTD[81] = {
				{  66.8,  76.3,  66.4,  71.1, 9.99},
				{  66.9,  76.7,  66.8, 175.9, 3.85},
				{  57.5,  74.0,  85.8, -83.1, 4.09},
				{  65.7,  78.2, 174.6,  62.6, 3.85},
				{  68.9,  76.7, 177.2, 175.3, 4.09},
				{  68.9,  77.8,-177.5, -68.4, 3.55},
				{  66.8,  82.3, -86.0,  74.7, 9.99},
				{  69.5,  85.2, -93.8,-177.2, 4.50},
				{  66.8,  82.3, -83.6, -67.0, 9.99},
				{  65.8, 175.6,  68.3,  68.9, 2.67},
				{  64.7, 175.2,  70.9, 174.9, 2.23},
				{  68.4,-179.3,  87.4, -84.8, 3.44},
				{  65.9,-178.1, 173.2,  66.9, 2.00},
				{  66.0,-179.4,-179.5, 179.9, 1.19},
				{  65.6,-178.1,-175.9, -68.7, 2.03},
				{  67.2,-175.2, -71.5,  74.3, 3.55},
				{  64.3,-172.4, -68.2,-176.8, 2.10},
				{  67.2,-173.7, -70.3, -68.0, 2.57},
				{  67.2, -83.2,  80.8,  69.9, 4.50},
				{  64.1, -83.7,  88.2, 177.6, 4.50},
				{  66.9, -81.3,  88.3, -80.2, 9.99},
				{  71.8, -79.7,-178.6,  65.4, 4.09},
				{  69.4, -80.1,-178.3, 177.0, 3.27},
				{  64.2, -81.9, 174.4, -65.5, 3.68},
				{  66.9, -76.7, -78.3,  74.7, 9.99},
				{  63.7, -77.8, -67.7, 179.7, 3.68},
				{  67.5, -77.5, -75.5, -67.1, 4.50},
				{-178.7,  68.1,  65.3,  66.2, 3.08},
				{-172.9,  65.9,  71.0, 179.7, 2.33},
				{-179.1,  68.7,  81.0, -81.3, 3.35},
				{-178.4,  67.8, 170.7,  67.0, 1.98},
				{-177.7,  70.3, 175.8, 179.3, 1.21},
				{-174.2,  66.7,-178.3, -65.6, 2.05},
				{-170.3,  87.2, -90.8,  76.8, 3.68},
				{-172.6,  88.2, -91.5,-177.5, 2.94},
				{-173.8,  86.5, -86.4, -69.3, 3.68},
				{-174.3, 174.4,  72.8,  70.5, 1.98},
				{-177.5, 173.7,  71.5, 177.8, 1.35},
				{-172.2, 168.9,  87.1, -78.4, 2.51},
				{-176.7, 176.0, 175.4,  65.1, 1.10},
				{-177.2, 177.1, 179.5, 179.9, 0.32},
				{-177.1, 177.0,-176.6, -67.4, 1.13},
				{ 179.6,-178.0, -75.8,  70.6, 2.67},
				{-175.0,-177.3, -70.2,-176.8, 1.35},
				{-175.4,-178.7, -71.0, -65.1, 2.04},
				{-162.4, -81.9,  82.2,  74.2, 4.50},
				{-163.0, -83.1,  95.7,-178.9, 3.68},
				{-164.5, -82.8,  88.3, -80.2, 9.99},
				{-161.2, -77.8,-177.5,  66.4, 3.08},
				{-165.2, -87.2,-177.2,-178.9, 2.32},
				{-166.1, -83.0,-177.8, -67.3, 3.08},
				{-160.1, -90.5, -80.9,  68.3, 4.09},
				{-166.8, -96.6, -69.4, 178.4, 3.14},
				{-168.0, -93.8, -76.0, -65.7, 3.44},
				{ -88.0,  81.2,  68.0,  69.3, 3.55},
				{ -80.9,  81.3,  66.9,-179.6, 2.94},
				{ -86.8,  86.0,  84.3, -83.2, 3.85},
				{ -80.7,  75.7, 176.2,  62.3, 2.43},
				{ -81.0,  74.0,-178.3, 177.9, 2.12},
				{ -87.6,  74.5, 178.0, -61.8, 2.51},
				{ -86.6,  83.2, -85.6,  68.2, 4.09},
				{ -82.6,  71.2, -96.3,-172.0, 3.55},
				{ -85.8,  78.0, -86.1, -66.3, 4.50},
				{ -70.1, 178.9,  73.0,  72.3, 1.70},
				{ -68.5, 176.2,  69.4, 177.3, 1.13},
				{ -70.3, 174.9,  84.2, -76.5, 2.49},
				{ -67.1,-178.4, 177.7,  66.5, 0.89},
				{ -67.1,-179.4,-179.4, 179.5, 0.00},
				{ -66.8,-178.0,-177.5, -65.9, 0.87},
				{ -66.8,-174.8, -76.5,  78.2, 2.29},
				{ -67.6,-175.0, -72.6,-176.5, 1.07},
				{ -65.1,-174.8, -72.3, -65.7, 1.66},
				{ -64.8, -75.8,  85.4,  76.5, 3.55},
				{ -62.3, -76.6,  91.0,-179.6, 2.53},
				{ -62.3, -83.2,  88.3, -84.3, 3.68},
				{ -63.5, -67.5,-177.9,  64.3, 1.52},
				{ -62.2, -66.1,-177.3,-177.9, 0.72},
				{ -60.1, -67.0,-174.3, -69.4, 1.38},
				{ -65.2, -68.9, -76.9,  78.3, 2.98},
				{ -63.4, -66.5, -70.5,-179.8, 1.73},
				{ -60.5, -68.5, -73.1, -72.7, 2.39}
				};



static ZLINESTRU GLU[10] = {    {6,{2,3,1,0},1.530,110.1,122.8},
				{6,{7,2,1,0},1.521,114.1,-67.0},
				{6,{8,7,2,0},1.516,112.5,180.0},
				{8,{9,8,7,0}, 1.250,118.4,-10.0},
				{8,{9,8,10,0},1.250,118.4,180.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,108.9,121.8},
				{1,{7,2,8,0},1.100,108.9,-121.8},
				{1,{8,7,9,0},1.100,109.3,121.6},
				{1,{8,7,9,0},1.100,109.3,-121.6}
			   };
static short int GLU_TYP[10] = { 5,6,9,34,35,4,7,8,10,11};
static int GLU_CHI[4] = {2,3,4,-1};

static ROTSSTRU GLU_ROT[8] = {
				{  62.0, 180.0, -20.0, 0.0, 1.07},
				{  70.0, -80.0,   0.0, 0.0, 1.61},
				{-177.0,  65.0,  10.0, 0.0, 0.99},
				{-177.0, 180.0,   0.0, 0.0, 0.19},
				{-177.0, -80.0, -25.0, 0.0, 1.98},
				{ -65.0,  85.0,   0.0, 0.0, 1.01},
				{ -67.0, 180.0, -10.0, 0.0, 0.00},
				{ -65.0, -65.0, -40.0, 0.0, 0.53}
				};

static ROTSSTRU GLU_ROTD[27] = {
				{  54.3,  83.1,  49.0, 0.0, 2.95},
				{  54.5,  88.3,   6.4, 0.0, 2.66},
				{  50.8,  78.6, -61.4, 0.0, 3.82},
				{  64.2,-178.4,  58.7, 0.0, 1.47},
				{  64.6,-177.4,   1.7, 0.0, 1.23},
				{  65.3,-176.6, -58.5, 0.0, 1.47},
				{  58.6, -93.4,  51.0, 0.0, 2.06},
				{  68.3, -81.5,   2.6, 0.0, 1.52},
				{  65.1, -74.4, -51.1, 0.0, 2.69},
				{-172.8,  62.1,  52.1, 0.0, 1.07},
				{-178.4,  67.8,   9.7, 0.0, 0.93},
				{-174.2,  72.2, -65.1, 0.0, 2.02},
				{-177.6, 175.8,  57.3, 0.0, 0.66},
				{-177.3, 177.9,  -0.2, 0.0, 0.28},
				{-175.2, 179.2, -57.4, 0.0, 0.73},
				{-155.8, -76.6,  63.4, 0.0, 3.05},
				{-169.0, -86.3, -14.5, 0.0, 1.99},
				{-166.0, -80.1, -49.5, 0.0, 1.83},
				{ -66.3,  71.1,  52.3, 0.0, 1.35},
				{ -66.2,  82.2,   1.9, 0.0, 0.92},
				{ -66.8,  91.0, -54.1, 0.0, 1.90},
				{ -68.3, 179.3,  56.0, 0.0, 0.58},
				{ -67.7, 177.8,  -2.2, 0.0, 0.00},
				{ -65.3,-178.2, -54.7, 0.0, 0.44},
				{ -64.1, -79.0,  64.0, 0.0, 1.60},
				{ -64.2, -71.2,  -9.8, 0.0, 0.62},
				{ -67.7, -60.7, -52.4, 0.0, 0.48}
				};

static ZLINESTRU GLN[12] = {    {6,{2,3,1,0},1.530,110.1,122.8},
				{6,{7,2,1,0},1.521,114.1,-67.0},
				{6,{8,7,2,0},1.516,112.5,180.0},
				{8,{9,8,7,0},1.231,120.9,-25.0},
				{7,{9,8,10,0},1.329,116.3,180.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,108.9,121.8},
				{1,{7,2,8,0},1.100,108.9,-121.8},
				{1,{8,7,9,0},1.100,109.3,121.6},
				{1,{8,7,9,0},1.100,109.3,-121.6},
				{1,{11,9,8,0}, 1.000,120.0,0.0},
				{1,{11,9,17,0},1.000,120.0,180.0}
			   };
static short int GLN_TYP[12] = { 5,6,9,34,24,4,7,8,10,11,34,35};
static int GLN_CHI[4] = {2,3,4,-1};

static ROTSSTRU GLN_ROT[9] = {
				{  62.0, 180.0,  20.0, 0.0, 1.25},
				{  70.0, -75.0,   0.0, 0.0, 1.78},
				{-177.0,  65.0,-100.0, 0.0, 1.82},
				{-177.0,  65.0,  60.0, 0.0, 0.81},
				{-177.0, 180.0,   0.0, 0.0, 0.46},
				{ -65.0,  85.0,   0.0, 0.0, 1.50},
				{ -67.0, 180.0, -25.0, 0.0, 0.00},
				{ -65.0, -65.0, -40.0, 0.0, 0.52},
				{ -65.0, -65.0, 100.0, 0.0, 1.56}
				};

static ROTSSTRU GLN_ROTD[36] = {
				{  64.1,  74.9,-124.0, 0.0, 9.99},
				{  64.9,  86.9, -33.0, 0.0, 3.22},
				{  62.5,  84.6,  38.5, 0.0, 2.24},
				{  67.7,  84.8, 117.2, 0.0, 3.76},
				{  61.5,-174.9,-179.8, 0.0, 2.37},
				{  64.0,-177.6, -79.1, 0.0, 1.53},
				{  65.1,-177.5,  -4.1, 0.0, 1.23},
				{  65.4,-177.1,  79.5, 0.0, 1.39},
				{  64.1, -82.4,-111.9, 0.0, 9.99},
				{  66.3, -76.0, -34.4, 0.0, 2.16},
				{  64.8, -89.6,  38.2, 0.0, 1.72},
				{  57.6, -79.7, 123.9, 0.0, 2.75},
				{-174.0,  60.6,-124.1, 0.0, 1.60},
				{-175.4,  74.1, -37.5, 0.0, 1.61},
				{-176.1,  65.7,  44.6, 0.0, 0.51},
				{-178.1,  70.4, 109.0, 0.0, 2.70},
				{-175.5, 178.6,-179.1, 0.0, 1.89},
				{-178.0, 176.1, -77.6, 0.0, 0.95},
				{-177.0, 177.3,   1.0, 0.0, 0.39},
				{-176.6,-179.4,  74.8, 0.0, 0.83},
				{-165.2, -77.7,-112.0, 0.0, 3.52},
				{-169.4, -81.4, -34.9, 0.0, 1.61},
				{-165.7, -83.7,  46.1, 0.0, 2.94},
				{-170.6, -75.8, 125.3, 0.0, 2.65},
				{ -70.8,  73.4,-123.8, 0.0, 2.40},
				{ -64.6,  86.7, -35.4, 0.0, 1.69},
				{ -68.4,  74.8,  37.4, 0.0, 1.30},
				{ -72.0,  83.7, 110.1, 0.0, 3.02},
				{ -66.9, 179.0,-177.9, 0.0, 1.28},
				{ -66.8,-179.7, -76.8, 0.0, 0.41},
				{ -67.5, 177.6,  -1.1, 0.0, 0.00},
				{ -65.8,-178.9,  75.3, 0.0, 0.53},
				{ -66.1, -82.1,-111.8, 0.0, 2.43},
				{ -63.4, -63.2, -46.3, 0.0, 0.13},
				{ -67.0, -76.5,  44.4, 0.0, 1.26},
				{ -68.5, -61.2, 119.9, 0.0, 1.19}
				};

static ZLINESTRU PRO[10] = {    {6,{2,3,1,0},1.530,112.2,115.146},
				{6,{6,2,1,0},1.512,104.1,-27.9},
				{6,{7,6,2,0},1.518,103.0,39.0},
				{1,{2,3,1,0},1.100,104.1,-122.6},
				{1,{6,2,7,0},1.100,111.4,120.3},
				{1,{6,2,7,0},1.100,111.4,-120.3},
				{1,{7,6,8,0},1.100,111.7,120.1},
				{1,{7,6,8,0},1.100,111.7,-120.1},
				{1,{8,7,1,0},1.100,111.8,120.0},
				{1,{8,7,1,0},1.100,111.8,-120.0}
			   };
static short int PRO_TYP[10] = { 5,6,9,4,7,8,10,11,19,20};
static int PRO_CHI[4] = {2,3,-1,-1};

/* definitie */
static ROTSSTRU PRO_ROT[2] = {
				{ -27.943,  39.047, 0.0, 0.0, 0.00},
				{  27.570, -35.774, 0.0, 0.0, 0.01}
				};

static ROTSSTRU PRO_ROTD[2] = {
				{ 27.0, -34.6, 0.0, 0.0, 0.00},
				{-25.1,  36.3, 0.0, 0.0, 0.02}
				};

static ZLINESTRU ARG[19] = {    {6,{2,3,1,0},1.530,110.1,122.8},
				{6,{7,2,1,0},1.520,114.1,-67.0},
				{6,{8,7,2,0},1.520,111.3,180.0},
				{7,{9,8,7,0},1.459,112.0,180.0},
				{6,{10,9,8,0},1.330,124.2,180.0},
				{7,{11,10,9,0},1.326,120.0,0.0},
				{7,{11,10,12,0},1.326,120.0,180.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,108.9,121.9},
				{1,{7,2,8,0},1.100,108.9,-121.9},
				{1,{8,7,9,0},1.100,109.6,121.4},
				{1,{8,7,9,0},1.100,109.6,-121.4},
				{1,{9,8,10,0},1.100,109.4,121.5},
				{1,{9,8,10,0},1.100,109.4,-121.5},
				{1,{10,9,11,0}, 1.000,118.0,180.0},
				{1,{12,11,10,0},1.000,120.0,0.0},
				{1,{12,11,22,0},1.000,120.0,180.0},
				{1,{13,11,10,0},1.000,120.0,0.0},
				{1,{13,11,24,0},1.000,120.0,180.0}
			   };
static short int ARG_TYP[19] = { 5,6,9,22,17,25,26,4,7,8,10,11,19,20,28,55,56,58,59};
static int ARG_CHI[4] = {2,3,4,5};
static ROTSSTRU ARG_ROT[34] = {
				{  62.0, 180.0,  65.0,  85.0, 2.01},
				{  62.0, 180.0,  65.0,-175.0, 1.24},
				{  62.0, 180.0, 180.0,  85.0, 1.02},
				{  62.0, 180.0, 180.0, 180.0, 1.02},
				{  62.0, 180.0, 180.0, -85.0, 1.06},
				{  62.0, 180.0, -65.0, 175.0, 1.60},
				{  62.0, 180.0, -65.0, -85.0, 1.71},
				{-177.0,  65.0,  65.0,  85.0, 1.24},
				{-177.0,  65.0,  65.0,-175.0, 1.43},
				{-177.0,  65.0, 180.0,  85.0, 0.89},
				{-177.0,  65.0, 180.0, 180.0, 1.06},
				{-177.0, 180.0,  65.0,  85.0, 0.59},
				{-177.0, 180.0,  65.0,-175.0, 0.76},
				{-177.0, 180.0,  65.0,-105.0, 1.36},
				{-177.0, 180.0, 180.0,  85.0, 0.92},
				{-177.0, 180.0, 180.0, 180.0, 0.59},
				{-177.0, 180.0, 180.0, -85.0, 0.73},
				{-177.0, 180.0, -65.0, 105.0, 1.30},
				{-177.0, 180.0, -65.0, 175.0, 1.14},
				{-177.0, 180.0, -65.0, -85.0, 0.69},
				{ -67.0, 180.0,  65.0,  85.0, 0.83},
				{ -67.0, 180.0,  65.0,-175.0, 0.41},
				{ -67.0, 180.0,  65.0,-105.0, 1.51},
				{ -67.0, 180.0, 180.0,  85.0, 0.57},
				{ -67.0, 180.0, 180.0, 180.0, 0.00},
				{ -67.0, 180.0, 180.0, -85.0, 0.31},
				{ -67.0, 180.0, -65.0, 105.0, 1.06},
				{ -67.0, 180.0, -65.0, 175.0, 0.37},
				{ -67.0,-167.0, -65.0, -85.0, 0.30},
				{ -62.0, -68.0, 180.0,  85.0, 1.51},
				{ -62.0, -68.0, 180.0, 180.0, 0.95},
				{ -62.0, -68.0, 180.0, -85.0, 0.83},
				{ -62.0, -68.0, -65.0, 175.0, 1.24},
				{ -62.0, -68.0, -65.0, -85.0, 0.95}
				};

static ROTSSTRU ARG_ROTD[81] = {
				{  55.4,  79.7,  62.4,  82.3, 3.50},
				{  59.2,  85.4,  68.2,-166.2, 2.95},
				{  54.5,  79.4,  64.6,-103.2, 9.99},
				{  54.5,  86.6, 178.2,  85.5, 3.26},
				{  53.9,  87.8,-178.5, 178.1, 2.60},
				{  53.5,  87.8,-176.0, -81.1, 3.09},
				{  54.5,  83.5, -78.4, 102.9, 9.99},
				{  50.0,  82.4, -92.5, 169.0, 3.50},
				{  54.5,  83.5, -77.1, -84.1, 9.99},
				{  62.0, 177.8,  64.9,  84.4, 1.80},
				{  64.1,-175.8,  68.0,-172.6, 1.39},
				{  65.1,-178.6,  61.1,-104.5, 2.43},
				{  65.3, 180.0, 178.0,  85.7, 1.16},
				{  66.5,-177.6,-178.9,-177.2, 1.12},
				{  66.4,-175.2,-177.5, -82.5, 1.22},
				{  63.8,-171.9, -64.5, 102.9, 2.67},
				{  63.4,-176.5, -66.7, 173.2, 1.44},
				{  62.9, 179.9, -69.2, -82.5, 1.95},
				{  65.2, -85.1,  84.2,  84.5, 3.91},
				{  63.2, -85.5,  80.7,-172.0, 3.91},
				{  63.6, -82.1,  71.6,-103.2, 9.99},
				{  63.6, -78.2,-179.8,  85.7, 9.99},
				{  57.6, -83.1,-176.1,-178.4, 2.95},
				{  68.7, -75.7,-177.8, -85.7, 3.09},
				{  63.6, -77.9, -77.1, 102.9, 9.99},
				{  63.7, -78.1, -64.2, 169.9, 2.84},
				{  63.8, -78.2, -59.5, -83.3, 3.50},
				{-176.5,  65.8,  60.2,  80.8, 1.69},
				{ 179.4,  65.8,  65.3,-170.9, 1.47},
				{-173.6,  68.1,  67.3,-103.0, 2.95},
				{ 179.3,  66.2,-178.6,  85.1, 1.45},
				{-177.0,  67.4, 177.0, 171.0, 1.21},
				{ 178.1,  66.9,-178.7, -85.3, 1.71},
				{-176.1,  81.2, -80.9, 103.3, 3.91},
				{-175.6,  79.6, -90.4, 172.4, 2.10},
				{-178.7,  78.6, -78.3, -84.6, 2.84},
				{-177.3, 178.6,  64.9,  80.8, 0.72},
				{-174.1, 176.8,  67.8,-167.7, 0.66},
				{-176.7, 178.8,  63.4,-103.7, 1.36},
				{-176.8, 177.6, 178.8,  85.2, 0.92},
				{-176.9, 176.3, 178.8,-179.4, 0.46},
				{-177.5, 176.5,-177.8, -85.2, 0.78},
				{-174.4, 178.1, -63.4, 105.1, 1.23},
				{-175.4, 179.7, -64.8, 165.2, 0.78},
				{-175.6, 179.6, -65.0, -82.6, 0.80},
				{-169.7, -83.6,  80.9,  82.5, 9.99},
				{-166.0, -82.2,  78.0,-172.4, 3.91},
				{-169.7, -83.6,  71.6,-103.2, 9.99},
				{-171.4, -85.4,-174.0,  84.2, 3.26},
				{-171.3, -87.2,-179.0,-176.1, 2.26},
				{-171.0, -84.3,-176.8, -81.1, 2.67},
				{-170.0, -92.9, -72.5, 104.0, 3.26},
				{-170.2, -91.1, -67.4, 170.0, 2.10},
				{-165.9, -84.4, -59.4, -82.3, 2.75},
				{ -79.0,  87.7,  66.3,  84.2, 2.60},
				{ -83.1,  81.9,  69.8,-178.0, 2.23},
				{ -80.8,  86.2,  67.4,-101.7, 3.91},
				{ -78.6,  73.8,-179.4,  85.1, 2.75},
				{ -85.8,  70.4, 174.6, 179.0, 1.69},
				{ -80.8,  79.3, 177.3, -81.8, 2.23},
				{ -82.6,  77.9, -78.4, 102.9, 9.99},
				{ -85.1,  77.1, -91.5, 168.7, 3.50},
				{ -81.6,  78.0, -79.6, -84.1, 3.91},
				{ -66.2, 179.5,  66.1,  84.3, 0.66},
				{ -66.7, 178.5,  65.6,-170.1, 0.37},
				{ -67.2,-178.5,  63.1,-101.8, 1.59},
				{ -66.9, 179.7, 178.7,  86.7, 0.51},
				{ -67.7, 179.1,-179.0, 176.3, 0.00},
				{ -68.1,-179.7,-176.3, -82.7, 0.38},
				{ -68.9,-175.6, -68.5, 102.2, 1.36},
				{ -67.0, 179.5, -67.9, 173.2, 0.30},
				{ -68.4,-170.6, -64.5, -85.4, 0.44},
				{ -63.9, -76.1,  80.0,  79.6, 1.95},
				{ -64.3, -80.3,  78.7,-165.9, 1.95},
				{ -62.5, -80.5,  71.6,-105.6, 3.26},
				{ -62.6, -68.9, 179.4,  83.8, 1.30},
				{ -62.7, -72.4,-177.9,-177.8, 0.85},
				{ -63.2, -69.8,-175.2, -87.0, 0.87},
				{ -64.9, -74.5, -79.7,  95.0, 2.39},
				{ -63.6, -67.9, -65.0, 169.4, 1.13},
				{ -62.8, -68.8, -60.8, -83.5, 1.00}
				};

static ZLINESTRU HIS[13] = {    {6,{2,3,1,0},1.530,110.1,122.8},
				{6,{7,2,1,0},1.497,113.8,-65.0},
				{7,{8,7,2,0},1.378,122.7,-69.0},
				{6,{9,8,7,0},1.321,109.3,180.0},
				{7,{10,9,8,0},1.318,108.5,0.0},
				{6,{11,10,9,0},1.373,108.9,0.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,108.9,121.8},
				{1,{7,2,8,0},1.100,108.9,-121.8},
				{1,{9,8,10,0},  1.000,125.3,180.0},
				{1,{10,9,8,0}, 1.100,125.7,180.0},
				{1,{11,10,9,0},1.000,125.6,180.0},
				{1,{12,11,10,0},1.100,126.4,180.0}
			   };
static short int HIS_TYP[13] = { 5,6,20,13,24,11,4,7,8,22,31,34,25};
static int HIS_CHI[4] = {2,3,-1,-1};
static ROTSSTRU HIS_ROT[8] = {
				{  62.0, -75.0, 0.0, 0.0, 0.73},
				{  62.0,  80.0, 0.0, 0.0, 1.13},
				{-177.0,-165.0, 0.0, 0.0, 1.02},
				{-177.0, -80.0, 0.0, 0.0, 0.59},
				{-177.0,  60.0, 0.0, 0.0, 0.36},
				{ -65.0, -70.0, 0.0, 0.0, 0.00},
				{ -65.0, 165.0, 0.0, 0.0, 0.81},
				{ -65.0,  80.0, 0.0, 0.0, 0.48}
				};

static ROTSSTRU HIS_ROTD[9] = {
				{  63.0,  85.6,  0.0,   0.0, 1.09},
				{  64.8, 166.2,  0.0,   0.0, 2.37},
				{  65.4, -79.5,  0.0,   0.0, 0.85},
				{-178.4,  71.5,  0.0,   0.0, 0.39},
				{-172.8,-170.3,  0.0,   0.0, 1.02},
				{-172.6, -83.8,  0.0,   0.0, 0.53},
				{ -66.0,  85.6,  0.0,   0.0, 0.42},
				{ -68.1, 168.7,  0.0,   0.0, 0.60},
				{ -63.7, -72.9,  0.0,   0.0, 0.00}
				};

static ZLINESTRU PHE[15] = {    {6,{2,3,1,0},1.530,110.4,122.8},
				{6,{7,2,1,0},1.501,113.8,-65.0},
				{6,{8,7,2,0},1.384,120.7,-85.0},
				{6,{9,8,7,0},1.382,120.7,180.0},
				{6,{10,9,8,0},1.378,120.1,0.0},
				{6,{11,10,9,0},1.378,119.7,0.0},
				{6,{12,11,10,0},1.381,120.0,0.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,108.9,121.8},
				{1,{7,2,8,0},1.100,108.9,-121.8},
				{1,{9,8,7,0},1.100,119.6,0.0},
				{1,{10,9,8,0},1.100,119.9,180.0},
				{1,{11,10,9,0},1.100,120.1,180.0},
				{1,{12,11,10,0},1.100,120.0,180.0},
				{1,{13,12,11,0},1.100,119.5,180.0}
			   };
static short int PHE_TYP[15] = { 5,6,10,13,17,14,11,4,7,8,22,31,40,34,25};
static int PHE_CHI[4] = {2,3,-1,-1};
static ROTSSTRU PHE_ROT[4] = {
				{  62.0,  90.0, 0.0, 0.0, 0.73},
				{-177.0,  80.0, 0.0, 0.0, 0.14},
				{ -65.0, -85.0, 0.0, 0.0, 0.00},
				{ -65.0, -30.0, 0.0, 0.0, 0.95}
				};

static ROTSSTRU PHE_ROTD[6] = {
				{  63.0,  90.4, 0.0, 0.0, 0.86},
				{  62.0,  -6.5, 0.0, 0.0, 3.71},
				{-178.8,  78.1, 0.0, 0.0, 0.23},
				{-174.2,  21.2, 0.0, 0.0, 1.90},
				{ -66.9,  97.7, 0.0, 0.0, 0.00},
				{ -68.8, -15.3, 0.0, 0.0, 1.04}
				};


static ZLINESTRU TYR[16] = {    {6,{2,3,1,0},1.530,110.4,122.8},
				{6,{7,2,1,0},1.501,113.8,-65.0},
				{6,{8,7,2,0},1.389,120.8,-85.0},
				{6,{9,8,7,0},1.381,121.2,180.0},
				{6,{10,9,8,0},1.390,119.4,0.0},
				{6,{11,10,9,0},1.382,120.4,0.0},
				{6,{12,11,10,0},1.382,119.4,0.0},
				{8,{11,10,9,0},1.376,119.7,180.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,108.9,121.8},
				{1,{7,2,8,0},1.100,108.9,-121.8},
				{1,{9,8,7,0},1.100,119.4,0.0},
				{1,{10,9,8,0},1.100,120.3,180.0},
				{1,{12,11,10,0},1.100,120.3,180.0},
				{1,{13,12,11,0},1.100,119.4,180.0},
				{1,{14,11,10,0},1.000,109.5,0.0}
			   };
static short int TYR_TYP[16] = { 5,6,10,13,17,14,11,33,4,7,8,22,31,34,25,52};
static int TYR_CHI[4] = {2,3,-1,-1};
/* 1 te veel ?  alex ?*/
static ROTSSTRU TYR_ROT[5] = {
				{  62.0,  90.0, 0.0, 0.0, 0.72},
				{-177.0,  80.0, 0.0, 0.0, 0.14},
				{ -65.0, -85.0, 0.0, 0.0, 0.00},
				{ -65.0, -30.0, 0.0, 0.0, 0.95},
				{ -65.0,  30.0, 0.0, 0.0, 0.00}
				};
static ROTSSTRU TYR_ROTD[6] = {
				{  63.6,  90.2, 0.0, 0.0, 0.83},
				{  69.7,  -9.5, 0.0, 0.0, 3.55},
				{-179.6,  77.5, 0.0, 0.0, 0.22},
				{-174.2,  21.0, 0.0, 0.0, 1.90},
				{ -65.8,  97.8, 0.0, 0.0, 0.00},
				{ -67.2, -16.7, 0.0, 0.0, 1.17}
				};


static ZLINESTRU TRP[19] = {    {6,{2,3,1,0},1.530,110.1,122.8},
				{6,{7,2,1,0},1.498,113.6,-65.0},
				{6,{8,7,2,0},1.365,126.9,95.0},
				{7,{9,8,7,0},1.374,110.2,180.0},
				{6,{10,9,8,0},1.375,108.7,0.0},
				{6,{11,10,9,0},1.409,107.6,0.0},
				{6,{12,11,10,0},1.397,118.9,180.0},
				{6,{13,12,11,0},1.382,118.6,0.0},
				{6,{14,13,12,0},1.406,121.3,0.0},
				{6,{15,14,13,0},1.370,121.2,0.0},
				{1,{2,3,1,0},1.100,108.2,-118.2},
				{1,{7,2,8,0},1.100,109.0,121.8},
				{1,{7,2,8,0},1.100,109.0,-121.8},
				{1,{9,8,7,0},1.100,124.9,0.0},
				{1,{10,9,8,0},1.000,125.7,180.0},
				{1,{13,12,10,0},1.100,120.7,180.0},
				{1,{14,13,12,0},1.100,119.4,180.0},
				{1,{15,14,13,0},1.100,119.4,180.0},
				{1,{16,15,14,0},1.100,121.2,180.0}
			   };
static short int TRP_TYP[19] = { 5,6,10,23,14,11,15,19,16,18,4,7,8,22,31,37,49,58,46};
static int TRP_CHI[4] = {2,3,-1,-1};
static ROTSSTRU TRP_ROT[7] = {
				{  62.0, -90.0, 0.0, 0.0, 0.63},
				{  62.0,  90.0, 0.0, 0.0, 1.03},
				{-177.0,-105.0, 0.0, 0.0, 0.40},
				{-177.0,  90.0, 0.0, 0.0, 0.34},
				{ -65.0, -90.0, 0.0, 0.0, 1.09},
				{ -65.0,  -5.0, 0.0, 0.0, 0.83},
				{ -65.0,  95.0, 0.0, 0.0, 0.00}
				};
static ROTSSTRU TRP_ROTD[9] = {
				{  61.2, -89.9,   0.0,   0.0, 0.67},
				{  66.0,  -6.3,   0.0,   0.0, 2.37},
				{  61.5,  89.2,   0.0,   0.0, 1.04},
				{-177.3,-104.9,   0.0,   0.0, 0.38},
				{-175.1,  17.3,   0.0,   0.0, 0.99},
				{-179.8,  84.7,   0.0,   0.0, 0.51},
				{ -70.1, -92.2,   0.0,   0.0, 1.04},
				{ -68.6,  -4.2,   0.0,   0.0, 0.51},
				{ -67.4, 100.3,   0.0,   0.0, 0.00}
				};


static ZLINESTRU ACE[6] =   {   {6,{0,0,0,0},0.0,0.0,0.0},
				{8,{1,0,0,0},1.220,0.0,0.0},
				{6,{1,2,0,0},1.335,120.0,0.0},
				{1,{3,1,2,0},1.089,109.471,180.0},
				{1,{3,1,2,0},1.089,109.471,60.0},
				{1,{3,1,2,0},1.089,109.471,-60.0}
				};

static ZLINESTRU FOR[3] =   {   {6,{0,0,0,0},0.0,0.0,0.0},
				{8,{1,0,0,0},1.220,0.0,0.0},
				{1,{1,2,0,0},1.089,120.0,0.0}
				};

static ZLINESTRU NME[6] =   {  {7,{0,0,0,0},0.0,0.0,0.0},
				{6,{1,0,0,0},1.300,0.0,0.0},
				{1,{1,2,0,0},1.020,120.0,0.0},
				{1,{2,1,3,0},1.089,109.471,180.0},
				{1,{2,1,4,0},1.089,109.471,120.0},
				{1,{2,1,4,0},1.089,109.471,-120.0}
				};

static ZLINESTRU AMINO[28];

typedef struct { ZLINESTRU *zmat;
		 short int *ipdbt;
		 int *chis;
		 ROTSSTRU *rots;
		 int zlines;
		 int nrots;
		} AMINOSTRU;

static AMINOSTRU aminozmtr[20] = { 
	{GLY,GLY_TYP,GLY_CHI,GLY_ROT,2,0}, {ALA,ALA_TYP,ALA_CHI,ALA_ROT,5,0}, 
	{SER,SER_TYP,SER_CHI,SER_ROT,6,3}, {CYS,CYS_TYP,CYS_CHI,CYS_ROT,6,3}, 
	{THR,THR_TYP,THR_CHI,THR_ROT,9,3}, {ILE,ILE_TYP,ILE_CHI,ILE_ROT,14,5}, 
	{VAL,VAL_TYP,VAL_CHI,VAL_ROT,11,3},{MET,MET_TYP,MET_CHI,MET_ROT,12,13}, 
	{ASP,ASP_TYP,ASP_CHI,ASP_ROT,7,5}, {ASN,ASN_TYP,ASN_CHI,ASN_ROT,9,7}, 
	{LEU,LEU_TYP,LEU_CHI,LEU_ROT,14,5},{LYS,LYS_TYP,LYS_CHI,LYS_ROT,17,27}, 
	{GLU,GLU_TYP,GLU_CHI,GLU_ROT,10,8},{GLN,GLN_TYP,GLN_CHI,GLN_ROT,12,9},
	{PRO,PRO_TYP,PRO_CHI,PRO_ROT,10,2},{ARG,ARG_TYP,ARG_CHI,ARG_ROT,19,34}, 
	{HIS,HIS_TYP,HIS_CHI,HIS_ROT,13,8},{PHE,PHE_TYP,PHE_CHI,PHE_ROT,15,4}, 
	{TYR,TYR_TYP,TYR_CHI,TYR_ROT,16,5},{TRP,TRP_TYP,TRP_CHI,TRP_ROT,19,7}
	};

static AMINOSTRU aminozmtd[20] = { 
	{GLY,GLY_TYP,GLY_CHI,GLY_ROT,2,0}, {ALA,ALA_TYP,ALA_CHI,ALA_ROT,5,0}, 
	{SER,SER_TYP,SER_CHI,SER_ROTD,6,3}, {CYS,CYS_TYP,CYS_CHI,CYS_ROTD,6,3}, 
	{THR,THR_TYP,THR_CHI,THR_ROTD,9,3}, {ILE,ILE_TYP,ILE_CHI,ILE_ROTD,14,9}, 
	{VAL,VAL_TYP,VAL_CHI,VAL_ROTD,11,3},{MET,MET_TYP,MET_CHI,MET_ROTD,12,27}, 
	{ASP,ASP_TYP,ASP_CHI,ASP_ROTD,7,9}, {ASN,ASN_TYP,ASN_CHI,ASN_ROTD,9,18}, 
	{LEU,LEU_TYP,LEU_CHI,LEU_ROTD,14,9},{LYS,LYS_TYP,LYS_CHI,LYS_ROTD,17,81}, 
	{GLU,GLU_TYP,GLU_CHI,GLU_ROTD,10,27},{GLN,GLN_TYP,GLN_CHI,GLN_ROTD,12,36},
	{PRO,PRO_TYP,PRO_CHI,PRO_ROTD,10,2},{ARG,ARG_TYP,ARG_CHI,ARG_ROTD,19,81}, 
	{HIS,HIS_TYP,HIS_CHI,HIS_ROTD,13,9},{PHE,PHE_TYP,PHE_CHI,PHE_ROTD,15,6}, 
	{TYR,TYR_TYP,TYR_CHI,TYR_ROTD,16,6},{TRP,TRP_TYP,TRP_CHI,TRP_ROTD,19,9}
	};

static AMINOSTRU *aminozmt = aminozmtd;

#define NUMAT 20000
#define MXCON 10
#define NUMADD 50000
static int addat = NUMADD;

typedef struct { double coo[NUMAT][3];
		 double rzp[NUMAT];
		 int ianz[NUMAT];
		 int iaton[NUMAT];
		 int iatclr[NUMAT];
		 int iresid[NUMAT];
		 int ixp[NUMAT];
		 int iyp[NUMAT];
		 int iconn[NUMAT][MXCON+1];
               } ATOMSTRU;

static ATOMSTRU *atomptr;

typedef struct { double xyz[NUMAT][3]; } XYZSTRU;

static XYZSTRU *XYZ;

#define MXDRES 40
#define MXROT 81
#define MXROTRES 10

typedef struct { double estat[MXROT][MXDRES];
		 int ndrs;
		 int idrs[MXDRES];
		 int lrots[MXDRES];
		 } PMFROTSTRU;

static PMFROTSTRU *pmfrot;

typedef struct { double etot;
		 int ndrs;
		 int mx;
		 int mn;
		 int idrs[MXDRES];
		 int rot[MXDRES];
		 } RESROTSTRU;

static RESROTSTRU resrot[MXROTRES];
static int nresrot = 0;
static double flxen[MXROTRES];

static int *iresflx = NULL;
typedef struct { double vo[3];
		 double r[3];
		 double v1[3];
		 double v2[3];
		 double v3[3];
               } COMSRFSTRU;

static COMSRFSTRU *comsrfptr;
static int *NAT;

typedef struct { float fc[NUMAT][3];
               } FCSTRU;

static FCSTRU *fcptr;

static int *isurf;

#define MAXDM 20
typedef struct { double rdm[MAXDM];
		 int idmon[MAXDM][2];
		 int ndm;
               } MONSTRU;

static MONSTRU *monptr;

typedef struct { double dipo[3];
		 int ihasq;
		 int ihsdp;
		 int iqon;
		 int idipon;
               } CHGDIP;

static CHGDIP *qdpptr;

#define MXEL 100
typedef struct { double theta1;
		 double phi1;
		 double rroot;
		 double rincr;
		 double vdwr[MXEL];
		 double vrad[MXEL];
		 double scal;
		 double fscal;
		 double scali;
		 double smag;
		 int ipoints;
		 int ipnt;
		 int icol[MXEL];
               } SCALSTRU;

static SCALSTRU *scalptr;

#define NUMCAL 5000
#define MXCHAI 50
#define MXRES 42
#define MXHETA 50

typedef struct { int icalf[NUMCAL][6];
		 int ncalf;
		 int ianf[MXCHAI];
		 int islu[MXCHAI];
		 int nchain;
		 int iamino[NUMCAL];
		 int iamicl[MXRES];
		 int ihet[MXHETA];
		 int iclhet[MXHETA];
		 int reson[NUMCAL];
		 int issdon;
		} CALFSTRU;

static CALFSTRU *calfptr;
typedef struct { int icxp[NUMCAL];
		 int icyp[NUMCAL];
		} CALFPSTRU;
static CALFPSTRU *calfpptr;

static int *isal;
static int *irsnr;
static int *ishoh;

typedef struct  { int *iamino;
		  int phi;
		  int psi;
		  int omega;
		  int chi1;
		  int chi2;
		  int chi3;
		  int chi4;
		} AASTRU;
		 
static AASTRU aaptr[NUMCAL];

#define MXSYM 103
#define MXHSYM 64

static int *ResChanged = NULL;
static int CurrRes = 0;
static int ipdb[MXSYM];
static int ihpdb[MXHSYM*3];
static double xyzpdb[MXSYM][3];
static double xyzhpdb[MXHSYM*3][3];

#define MXHETATM 50
static char  *HetAtm[MXHETATM];
static int NHetAtm = 0;

#define MXCOLNAM 20
static char  *ColNam[MXCOLNAM];
static int NColNam = 0;

typedef struct { double rx[3];
		 double ry[3];
		 double rz[3];
		 double t[3];
		 double td[3];
		} ROTSTRU;

static ROTSTRU *rotptr;

typedef struct { double xv;
		 double yv;
		 double zv;
		 double c0;
		 double pincr;
		 double ssincr;
		} POSSTRU;

static POSSTRU *posptr;

#define MAXSURF 500
static void DoExpl();
static void ogunsel();
static void handle_explalarm();
void dispsf(void);
void ogmoll(int iopt);
void ogbck(int isec);
void ogres(int ires, int iopt,int iupd);
void ogdipole();
void zmt2cor(int ires, int iopt);
void moused(int button, unsigned int state, int x, int y);
void mouseu(int button, int state, int x, int y);
void motion(int x, int y, int iopt);
void Reshape();
void empty_model();
void initOpengl();
void setobg();
void DelHet(int het);
void znorm(double rpts, double cnst, double *dens, double *vn,
	   int npts1, int npts2, int i, int j);
/*static int SSon[MAXSURF] = {};*/
void printString(int x, int y, int init, char *s);
void makeRasterFont(Display *dpy);
static int SSon[MAXSURF];
static int SSont[MAXSURF];
static int SSdone = 0;
static int NSurf = 0;
static int NSurft = 0;
static float diffuseColor[MAXSURF][4] =
{ 
  {0.15,0.15,1.0,0.8}, 
  {1.0 ,0.1 ,0.1,0.8}, 
  {1.0,1.0,0.0,0.8},
  {1.0,0.5,0.5,0.8},
  {1.0,0.5,0.5,0.8},
  {1.0,0.5,0.5,0.8},
  {1.0,0.5,0.5,0.8},
  {1.0,0.5,0.5,0.8},
  {1.0,0.5,0.5,0.8},
  {1.0,0.5,0.5,0.8},
  {1.0,1.0,1.0,0.8},
  {1.0,0.5,0.5,0.8},
  {1.0,0.5,0.5,0.8},
  {1.0,0.5,0.5,0.8},
  {1.0,0.5,0.5,0.8}
};

#ifdef DOGL
static GLfloat fogColor[4] = {0.5, 0.5, 0.5, 1.0};
static GLfloat gradcol[2][4] = { {0.0, 0.0, 0.9, 1.0}, {1.0, 1.0, 1.0, 1.0}};
static float AxesXYZ[4][3] =
{ 
  {0.0,0.0,0.0}, 
  {1.0,0.0,0.0}, 
  {0.0,1.0,0.0}, 
  {0.0,0.0,1.0} 
};

static int AxesProj[4][2];

static GLfloat AxesCol[4][4] =
{ 
  {0.0,0.0,0.0,1.0}, 
  {1.0,0.0,0.0,1.0}, 
  {0.0,1.0,0.0,1.0}, 
  {0.0,0.0,1.0,1.0} 
};

static char *AxesStr[] = {"O","X","Y","Z"};

#endif
#define RESUND -20000
static int rsold = RESUND;
static int bckx,bcky;

void ogind();

static int update_model = 1;
static int update_res = -1;
static int update_sel = 1;

static char *VRMLFname;

static char *GEOMstr;
static int GEOMset = 0;
#define MXTITL 41
static char *mlftit[MXTITL];
static int ntits = 0;

static BSTRU qboxclose[2];

static int ISOup = 0;
static Window ISOwin;
#define ISOWINW 250
#define ISOWINH 290
#define ISOOffx 10
#define NBUTISO 2
static BSTRU isobut[NBUTISO];
static int ISOt = 0;

static char  *nofor[1] = {"       "};
static int Nnofor = 1;

#define MXMM3 164
static char  *mm3[MXMM3];
static int Nmm3 = 0;

static int mm3ptr[] = {
4,20,22,23,27,35,43,47,72,123,50,162,25,26,0,
1,2,3,21,28,29,37,49,55,56,57,66,67,70,105,
112,113,159,160,161,7,8,9,36,38,39,42,44,45,71,
106,107,108,109,110,142,143,145,149,150,154,163,5,6,40,
46,48,68,69,74,75,76,77,78,79,80,81,82,83,84,
85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,
100,101,102,114,115,116,117,118,119,120,144,147,148,158,10,
51,58,18,24,59,152,14,15,16,17,41,73,103,104,153,
11,52,124,60,61,64,65,62,63,30,33,12,53,125,31,
34,13,54,126,127,128,129,130,131,132,133,134,135,136,137,
138,139,140,141,32,19,111,121,122,146,151,155,156,157
};

static int mm3atnr[] = {
1,1,1,1,1,1,1,1,1,1,2,3,5,5,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,
10,12,14,15,15,15,16,16,16,16,16,16,16,16,16,
17,18,20,26,26,27,27,28,28,32,34,35,36,38,50,
52,53,54,56,57,58,59,60,61,62,63,64,65,66,67,
68,69,70,71,82,0,0,0,0,0,0,0,0,0
};

/* static int mm3ptr[] = {
 4,20,22,23,27,43,47,72,123,35,50,25,26,0,1,
 2,3,21,28,29,37,49,55,56,57,66,67,70,105,112,
 113,155,156,157,7,8,9,36,38,39,42,44,45,71,106,
 107,108,109,110,142,143,145,149,150,154,5,6,40,46,48,
 68,69,74,75,76,77,78,79,80,81,82,83,84,85,86,
 87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,
 102,114,115,116,117,118,119,120,144,147,148,158,10,51,58,
 18,24,59,152,14,15,16,17,41,73,103,104,153,11,52,
 124,60,61,64,65,62,63,30,12,33,53,125,31,13,34,
 54,126,127,128,129,130,131,132,133,134,135,136,137,138,139,
 140,141,32,19,111,121,122,146,151
};

static int mm3atnr[] = {
 1,1,1,1,1,1,1,1,1,1,2,5,5,6,6,6,6,6,6,6,6,6,6,6,6,
 6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
 7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
 8,7,9,10,12,14,15,15,15,16,16,16,16,16,16,16,16,16,17,18,
 20,26,26,27,27,28,28,32,35,34,36,38,50,53,52,54,56,57,58,
 59,60,61,62,63,64,65,66,67,68,69,70,71,82,0,0,0,0,0,0
}; */

static int gffatnr[] = {
 0,6,6,6,6,6,6,6,6,6,
 6,6,6,6,6,6,6,6,1,1,
 1,1,1,1,1,1,1,1,1,1,
 1,9,17,35,53,7,7,7,7,7,
 7,7,7,7,7,7,7,7,8,8,
 8,8,15,15,15,15,15,15,15,15,
 15,15,15,16,16,16,16,16,16,16,16
};

#define MXCHTP 136

static char  *chmtnk[MXCHTP];
static int Nchmtnk = 0;

static int chmptr[] = {
/* Hydrogen */
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,82,
83,84,85,86,87,88,115,116,117,118,119,
/* Carbon */
19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,
37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,
55,56,57,58,59,60,61,89,90,91,92,93,94,95,96,97,98,120,
121,122,123,124,125,126,127,128,129,
/* Nitrogen */
62,63,64,65,66,67,68,69,70,71,72,99,130,
/* Oxygen */
73,74,75,76,77,78,100,101,102,103,104,131,132,133,134,
/* Other atoms */
79,80,81,105,106,107,108,109,110,111,112,113,114,135
/* 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,82,
19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,
37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,
55,56,57,58,59,60,61,83,84,85,86,87,88,62,63,64,65,66,
67,68,69,70,71,72,89,73,74,75,76,77,78,90,91,92,93,79,
80,81,94,95,96,97,98,9980,81,94,95,96,97,98,99 */
};

static int chmatnr[] = {
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
16,16,16,16,26,2,10,11,12,17,19,20,30,15
};

#define MXAMB 701
static char  *ambstr[MXAMB];
static int Nambstr = 0;

static int ambatnr[] = {
7,6,6,1,8,1,7,6,6,1,8,1,6,1,7,6,6,1,8,1,
6,1,6,1,6,1,7,6,6,1,8,1,6,1,6,1,6,1,6,1,
7,6,6,1,8,1,6,1,6,1,6,1,6,1,7,6,6,1,8,1,
6,1,8,1,7,6,6,1,8,1,6,1,8,1,6,1,7,6,6,1,
8,1,6,1,16,1,7,6,6,1,8,1,6,1,16,7,6,6,8,1,
6,1,6,1,6,1,7,6,6,1,8,1,6,1,6,6,1,6,1,6,
1,7,6,6,1,8,1,6,1,6,6,1,6,1,6,8,1,7,6,6,
1,8,1,6,1,6,6,1,6,7,1,6,6,1,6,1,6,1,6,1,
7,6,6,1,8,1,6,1,6,7,1,6,1,6,1,7,1,7,6,6,
1,8,1,6,1,6,7,1,6,1,6,1,7,7,6,6,1,8,1,6,
1,6,7,6,1,6,1,7,1,7,6,6,1,8,1,6,1,6,8,7,
6,6,1,8,1,6,1,6,8,7,1,7,6,6,1,8,1,6,1,6,
1,6,8,7,6,6,1,8,1,6,1,6,1,6,8,7,1,7,6,6,
1,8,1,6,1,6,1,16,6,1,7,6,6,1,8,1,6,1,6,1,
6,1,6,1,7,1,7,6,6,1,8,1,6,1,6,1,6,1,7,1,
6,7,1,7,6,6,1,8,1,6,1,6,1,6,1,7,1,7,6,6,
1,8,6,1,7,6,6,1,8,1,6,1,6,1,6,8,6,1,8,6,
1,6,8,7,1,7,1,6,1,7,6,6,1,8,1,7,6,6,1,8,
1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,
6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,
1,8,1,7,6,6,1,8,1,6,1,7,6,6,1,8,1,7,6,6,
1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,
1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,
6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,
1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,
7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,
6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,
8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,8,1,7,
6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,
1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,
1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,
6,6,1,8,1,7,6,6,1,8,1,7,6,6,1,8,1,7,6,6,
1,8,1,7,6,6,1,8,8,1,3,11,19,37,55,12,20,30,17
};


#define MXMOL2 41
static char  *mol2[MXMOL2];
static int Nmol2 = 0;

#define MXGMX 53
static char  *gmx[MXGMX];
static int Ngmx = 0;

#define MXGMX2 57
static char  *gmx2[MXGMX2];
static int Ngmx2 = 0;

#define MXG43 49
static char  *g43[MXG43];
static int Ng43 = 0;

#define MXAMO 201
static char  *amostr[MXAMO];
static int Namostr = 0;

#define MXMSF 235
static char  *chmsf[MXMSF];
static int Nchmsf = 0;

#define MXTRR 512
static char  *grostr[MXTRR];
static int Ngrostr = 0;

#define MXGFF 71
static char  *gffext[MXGFF];
static int Ngffext = 0;

static char  *exepath[1];
static int Nexepath = 0;

static int isnul = 0;
static char **typs[12] = { nofor,mm3,chmtnk,ambstr,amostr,mol2,chmsf,ambstr,NULL,gmx,gmx2,g43};
static char **typsn[12] = { nofor,mm3,chmtnk,ambstr,amostr,mol2,chmsf,gffext,NULL,gmx,gmx2,g43};
static int *Ntyps[12] = { &Nnofor,&Nmm3,&Nchmtnk,&Nambstr,&Namostr,&Nmol2,&Nchmsf,&Nambstr,&isnul,&Ngmx,&Ngmx2,&Ng43};
static int *Ntypsn[12] = { &Nnofor,&Nmm3,&Nchmtnk,&Nambstr,&Namostr,&Nmol2,&Nchmsf,&Ngffext,&isnul,&Ngmx,&Ngmx2,&Ng43};
static int ffsgn[12] = { 1,1,1,1,1,1,1,-1,1,1,1,1};
static int *ffptr[12] = { NULL,mm3ptr,chmptr,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL};
static int *ffatnr[12] = { NULL,mm3atnr,chmatnr,ambatnr,NULL,NULL,NULL,gffatnr,NULL,NULL,NULL,NULL};

#define MXSG 238
static char  *spacegr[MXSG];
static int Nspgr = 0;

static char  *achain[NUMCAL];
static int ncal = 0;

static int ATMup = 0;
static Window ATMwin;
static Window subATM;
#define ATMWINW 250
#define ATMWINH 350
#define ATMOffx 10
#define NBUTATM 6
static BSTRU butATM[NBUTATM];
static int ATMt = 0;
static int itcopt = 3;
static char *ForceFields[] = {"No Force Field","Tinker MM3","Tinker Charmm","Tinker Amber","Tink AmoebaPRO","Sybyl","Quanta Charmm","Amber/GAFF","PMF","Gromacs","Gromacs2","Gromos96"};
static int *fftyp;
static int ATMsel = 0;
static short int *ityp;
static double *qat;

static int SEQup = 0;
static Window SEQwin;
#define SEQWINW 430
#define SEQWINH 220
#define SEQOffx 15
#define SEQRESY  40
#define SEQSTATY 105
#define SEQCONFY 150
#define SEQBROWY 180
#define NBUTSEQ 25
static BSTRU butSEQ[NBUTSEQ];
static char *Conformations[] = {"Alpha-Helix","Beta","Turn"};
static double phis[3] = {-58.0, -139.0, -60.0};
static double psis[3] = {-47.0, 135.0, -30.0};
static double phi_angle = -58.0;
static double psi_angle = -47.0;
static int iconform = 0;
static short int *ipdbt;

static int TNKup = 0;
static Window TNKwin, subTNK;
#define TNKWINW 430
#define TNKWINH 175
#define TNKOffx 15
#define TNKRESY  17
#define TNKBWIDE 30
#define TNKBROWY 135
#define NBUTTNK 6
static BSTRU butTNK[NBUTTNK];
static char *TnkProgs[] = {"minimize","optimize","newton","dynamic","Xtinker"};
static char *AmbProgs[] = {"ambfor"};
static char **Progs = TnkProgs;
static int nprogs = 5;
static int *tnkprg;
static double mxgrads[] = {0.01,0.01,0.01,0.0,0.01};
static double *currgrd;
static double *uscl;
static double scl = 1.0;
static int *archfrq;
static int *arch;
static int *tnkbg;
static int AddChrg = 1;
static int *tnkit;
static int *iqopt;
static int *ibell;
static int *natorg;
static int *irtcel;
#ifdef VMS
static struct dsc$descriptor_s *tnkjn;
#else
#ifdef CRAY
static _fcd tnkjn;
#else
static char *tnkjn;
#endif
#endif

static SCRSTRU dptscr[2];
static int dptwn[3];
static int dptwpos[3];
static BSTRU butdpt[2];
static int DPTup = 0;
static Window DPTwin;

static SCRSTRU ecolscr[3];
static int ecolwn[3];
static int ecolwpos[3];
static int activecolor = 1;
static BSTRU butecol[1];
static int ECOLup = 0;
static Window ECOLwin;
#define ECOLWINW 250
#define ECOLWINH 180
void colcall(char* str);

static int COLup = 0;
static Window COLwin;
#define NBUTSC 2
static BSTRU colbut[NBUTSC];
#define COLWINW 513
#define COLWINH 400
#define COLWINIW 464
#define COLWINIH 361
#define COLFRBord 20
#define COLBord 10
#define COLOffx 10
#define COLOffy 50
#define COLWINHT COLOffy-COLFRBord+COLWINH
static int ipropopt = 0;
static int propat = 0;
static char *propopts[] = {"Atom Color","VDW radius","Display radius","ESP VDW radius"};
#define PATMCOL 0
#define PVDWRAD 1
#define PDISRAD 2
#define PESPRAD 3

static int MAPup = 0;
static Window MAPwin;
#define NBUTSM 4
static BSTRU mapbut[NBUTSM];
#define MAPWINW 513
#define MAPWINH 400
#define MAPOFFX  200
#define MAPOFFY  170
static char *mapstr[] = {"Red        < ","Yellow       ","Green        ","Light Blue   ","Blue       > "};
static double *mapval;
static int *imapopt;
static char *mapopts[] = {"Molden Gridfile","Gaussian Cube"};
static int iviropt = 0;
static char *viropts[] = {"VRML2.0","OpenGL"};

static int VIRup = 0;
static Window VIRwin;
static BSTRU virbut[2];
#define VIRWINW 513
#define VIRWINH 170

static int DELup = 0;
static Window DELAYwin;
static BSTRU delbut[3];
#define DELWINW 300
#define DELWINH 120
static int DelayRemember = 0;
static int *ideltm;

static int SRFup = 0;
static Window SRFwin;
static BSTRU srfbut[5];
#define SRFWINW 310
#define SRFWINH 250
static float cursrfcol[2][4] = {{0.0,0.0,1.0,0.8},{1.0,0.0,0.0,0.8}};
static int cursrfcoli = 0;
static int idorad = 0;

static int FLXup = 0;
static Window FLXwin;
static BSTRU flxbut[8];
#define FLXWINW 320
#define FLXWINH 250
static short int *itypBackup = NULL;
static int *idoh;
static int *itot;

static int PARup = 0;
static Window PARwin;
static BSTRU parbut[3];
#define PARWINW 320
#define PARWINH 250

static int CHGup = 0;
static int CHGret = 0;
static Window CHGwin;
static BSTRU chgbut[2];
#define CHGWINW 350
#define CHGWINH 150

static int *imol;

static int ONIup = 0;
static Window ONIwin, subONI;
#define NBUTSO 24
#define OMETHH  0
#define OBASSH  1
#define OALLH   2
#define OSELH   3
#define OMETHL  4
#define OBASSL  5
#define OALLL   6
#define OSELL   7
#define OMETHM  8
#define OBASSM  9
#define OALLM  10
#define OSELM  11
#define OSEL   12
#define OUSEL  13
#define OCOLO  14
#define OSELR  15
#define OCLOS  16
#define OCHARH 17
#define OMULTH 18
#define OCHARM 19
#define OMULTM 20
#define OCHARL 21
#define OMULTL 22
#define OAMBCH 23
static BSTRU onbut[NBUTSO];
#define OBOXWIDE 350
#define OBOXHIGH 350
#define OBOXOFFX 10
#define OBOXBLEN 100
#define ONIHCOL 12
#define ONIMCOL 9
#define ONILCOL 1
static char olev[3][MAXSTRLEN];
static int imopth = 0;
static int imoptl = 0;
static int imoptm = 0;
static int ibopth = 0;
static int iboptl = 0;
static int iboptm = 0;
static int *ispopth;
static int *ispoptl;
static int *ispoptm;
static int *icopth;
static int *icoptl;
static int *icoptm;
static int my_linkat = 0;

static QBOXSTRU IANZboxes[MAXAT];
static QBOXSTRU IZboxes[MAXAT][4];
static QBOXSTRU BLboxes[MAXAT];
static QBOXSTRU ALPHboxes[MAXAT];
static QBOXSTRU BETboxes[MAXAT];
static QBOXSTRU EXPbox[1];
static QBOXSTRU TMPbox;

static QBOXSTRU *IANZbox = IANZboxes;
static QBOXSTRU *BLbox = BLboxes;
static QBOXSTRU *ALPHbox = ALPHboxes;
static QBOXSTRU *BETbox = BETboxes;
static QBOXSTRU *IZbox = (QBOXSTRU *) IZboxes;
static char *IANZstr = 
	"Element string. To change element\ntype new element and hit Enter/Return";
static char *IZstr = 
	"Previously defined atoms used to define\nbondlength, bondangle and dihedral of current atom\nTo edit: Click with 1st mouse button to activate,\ntype previously defined atom number and hit Enter/Return\n4th field can be ignored";
static char *BLstr = 
	"Bondlength between current atom and\natom specified in first connectivity field.\nTo edit: Click with 1st mouse button to activate,\n         type new bondlength and hit Enter/Return\nClick with 2nd mouse button for actions with this variable";
static char *ALPHstr = 
	"Bondangle between current atom and\natoms specified in first two connectivity fields.\nTo edit: Click with 1st mouse button to activate,\n         type new bondangle and hit Enter/Return\nClick with 2nd mouse button for actions with this variable";
static char *BETstr = 
	"Dihedral angle between current atom and\natoms specified in first three connectivity fields.\nTo edit: Click with 1st mouse button to activate,\n         type new angle and hit Enter/Return\nClick with 2nd mouse button for actions with this variable";

static Window ZMEwin, subZM;
static int ZMEbig = 1;
#define ZMEWINW 513
#define ZMEQHIGH 40
#define ZMESHIGH 40
#define ZMEFRBord 20
#define ZMEBord 10
#define ZMETab1 35
#define ZMETab2 5
#define ZMETab3 5
#define ZME_window_high 8
static int ZMEiz, ZMEizs, ZMEanW, ZMEconW, ZMEbutW, ZMEvarW, ZMEvarWs, ZMEiz4W;
static int ZMEZWIDE;
#define ZMEZHIGH ZME_window_high*ZMEQHIGH+2*ZMEFRBord+ZMEBord
#define ZMEZOffx 10
#define ZMEZOffy 50
#define ZMESCR 5
#define ZMEBOFFY 10
#define ZMEBHIGH 160
#define ZMEBWIDE 30
#define ZMEButOffy ZMEZOffy-ZMEFRBord+ZMEZHIGH+ZMEBOFFY
#define ZMEWOffy ZMEZOffy-ZMEFRBord+ZMEZHIGH+ZMEBHIGH+ZMESHIGH
#define ZMEWHIGH 120
#define ZMEWBOFF 80
#define ZMEWINH ZMEZOffy-ZMEFRBord+ZMEZHIGH+ZMEBHIGH+ZMESHIGH+ZMEWHIGH-3
#define ZMEBW2  ZMEWINW/2-2*ZMEZOffx
#define ZMEBW4  (ZMEBW2-ZMEZOffx)/2
#define ZMBCOL -15

static int ZMEup = 0;
static int ZME_window_pos;
static int ZMEmode = 0;
static int ZMEAA = 0;
static int ZMEsel = 0;
static int ZMEatom = 0;
#define MAXZMEERR 70
static char ZMEerr[MAXZMEERR];
static char *zmevaropt[] = {"constant","variable","mark","unmark","animate","link","-link"};
static char *zmevarclr[] = {"constant","variable"};
static char *zmeblform[] = {"%f","%#9.3f"};
static char *zmeform[] = {"%f","%#8.3f"};
static char ZMEups[5];

#define ZMEBUTTS 22

static BSTRU ZMEbut[ZMEBUTTS];

#define ZMEARR1 0
#define ZMEARR2 1
#define ZMEAPPL 2
#define ZMECAN1 3
#define ZMEFRG  4
#define ZMEDEL  5
#define ZMEADD  6
#define ZMEGAM  7
#define ZMEGAU  8
#define ZMEMOP  9
#define ZMECAR  10
#define ZMEWRT  11
#define ZMESEL  12
#define ZMEUSEL 13
#define ZMESELA 14
#define ZMENEW  15
#define ZMECANC 16
#define ZMECVAR 17
#define ZMEMAP  18
#define ZMESUB  19
#define ZMEORD  20
#define ZMEUS   21

static BSTRU ZMEBbut[3];
#define ZMESIN  0
#define ZMEDBL  1
#define ZMETRI  2

static int ZMEopt = ZMEGAM;
static int ZMEmul = ZMESIN;
static int *igztyp;
static int *igtfil;

static BSTRU ZMEAAbut[ZME_window_high];
static BSTRU ZMEAASbut[ZME_window_high];
static BSTRU ZMEswitch[2];

#define TABBUTN 99
static int TabPos[TABBUTN][2] = {
	{0,0},{0,17},
	{1,0},{1,1},{1,12},{1,13},{1,14},{1,15},{1,16},{1,17},
	{2,0},{2,1},{2,12},{2,13},{2,14},{2,15},{2,16},{2,17},
	{3,0},{3,1},{3,2},{3,3},{3,4},{3,5},{3,6},{3,7},{3,8},{3,9},{3,10},{3,11},{3,12},{3,13},{3,14},{3,15},{3,16},{3,17},
	{4,0},{4,1},{4,2},{4,3},{4,4},{4,5},{4,6},{4,7},{4,8},{4,9},{4,10},{4,11},{4,12},{4,13},{4,14},{4,15},{4,16},{4,17},
	{5,0},{5,1},{5,2},
	{8,0},{8,1},{8,2},{8,3},{8,4},{8,5},{8,6},{8,7},{8,8},{8,9},{8,10},{8,11},{8,12},{8,13},
	{5,3},{5,4},{5,5},{5,6},{5,7},{5,8},{5,9},{5,10},{5,11},{5,12},{5,13},{5,14},{5,15},{5,16},{5,17},
	{6,0},{6,1},{6,2},
	{9,0},{9,1},{9,2},{9,3},{9,4},{9,5},{9,6},{9,7},{9,8},
	{11,9}
		};
static BSTRU TabBut[TABBUTN];
static BSTRU AtmBut[TABBUTN];
#define ZMETABH 24
#define ZMETABA 22

#define NUMDIS 11
static int DisAtoms[NUMDIS] = {1,6,7,8,9,14,15,16,17,35,53};
static float SingleDis[NUMDIS][NUMDIS] = {
	{1.008,1.089,1.008,0.950,1.008,1.008,1.008,1.008,1.008,1.008,1.008},
	{1.089,1.450,1.440,1.400,1.330,1.850,1.850,1.710,1.750,1.900,2.092},
	{1.008,1.440,1.418,1.400,1.360,1.000,1.491,1.625,1.790,2.140,1.800},
	{0.950,1.400,1.400,1.480,1.390,1.620,1.600,1.500,1.700,2.000,1.890},
	{1.008,1.330,1.360,1.390,1.417,1.561,1.500,1.570,1.628,1.756,2.000},
	{1.008,1.850,1.000,1.620,1.561,2.300,2.000,2.000,2.030,2.270,2.300},
	{1.008,1.850,1.490,1.600,1.500,2.000,1.894,1.860,2.020,2.140,2.420},
	{1.008,1.710,1.625,1.500,1.570,2.000,1.860,2.030,2.000,2.270,2.300},
	{1.008,1.750,1.790,1.700,1.628,2.030,2.020,2.000,1.988,2.138,2.303},
	{1.008,1.900,2.140,1.700,1.756,2.270,2.140,2.270,1.988,2.290,2.500},
	{1.008,2.092,1.800,1.890,2.000,2.270,2.420,2.300,2.303,2.500,2.662}
	};

static float DoubleDis[NUMDIS][NUMDIS] = {
	{1.008,1.089,1.008,0.950,1.008,1.008,1.008,1.008,1.008,1.008,1.008},
	{1.089,1.335,1.300,1.220,1.330,1.850,1.850,1.800,1.750,1.900,2.092},
	{1.008,1.300,1.346,1.220,1.360,1.000,1.491,1.625,1.790,2.140,1.800},
	{0.950,1.220,1.220,1.210,1.390,1.620,1.490,1.450,1.700,2.000,1.890},
	{1.008,1.330,1.360,1.390,1.417,1.561,1.500,1.570,1.628,1.756,2.000},
	{1.008,1.850,1.000,1.620,1.561,2.300,2.000,2.000,2.030,2.270,2.300},
	{1.008,1.850,1.490,1.490,1.500,2.000,1.894,1.860,2.020,2.140,2.420},
	{1.008,1.800,1.625,1.450,1.570,2.000,1.860,2.030,2.000,2.270,2.300},
	{1.008,1.750,1.790,1.700,1.628,2.030,2.020,2.000,1.988,2.138,2.303},
	{1.008,1.900,2.140,1.700,1.756,2.270,2.140,2.270,1.988,2.290,2.500},
	{1.008,2.092,1.800,1.890,2.000,2.270,2.420,2.300,2.303,2.500,2.662}
	};

static float TripleDis[NUMDIS][NUMDIS] = {
	{1.008,1.089,1.008,0.950,1.008,1.008,1.008,1.008,1.008,1.008,1.008},
	{1.089,1.204,1.158,1.400,1.330,1.850,1.850,1.710,1.750,1.900,2.092},
	{1.008,1.158,1.100,1.400,1.360,1.000,1.491,1.625,1.790,2.140,1.800},
	{0.950,1.400,1.400,1.480,1.390,1.620,1.600,1.500,1.700,2.000,1.890},
	{1.008,1.330,1.360,1.390,1.417,1.561,1.500,1.570,1.628,1.756,2.000},
	{1.008,1.850,1.000,1.620,1.561,2.300,2.000,2.000,2.030,2.270,2.300},
	{1.008,1.850,1.490,1.600,1.500,2.000,1.894,1.860,2.020,2.140,2.420},
	{1.008,1.710,1.625,1.500,1.570,2.000,1.860,2.030,2.000,2.270,2.300},
	{1.008,1.750,1.790,1.700,1.628,2.030,2.020,2.000,1.988,2.138,2.303},
	{1.008,1.900,2.140,1.700,1.756,2.270,2.140,2.270,1.988,2.290,2.500},
	{1.008,2.092,1.800,1.890,2.000,2.270,2.420,2.300,2.303,2.500,2.662}
	};

static char *elements[] = {
	"Bq","H","He","Li","Be","B","C","N","O","F","Ne",
	"Na","Mg","Al","Si","P","S","Cl","Ar",
	"K","Ca","Sc","Ti","V","Cr","Mn","Fe","Co","Ni","Cu",
	"Zn","Ga","Ge","As","Se","Br","Kr",
	"Rb","Sr","Y","Zr","Nb","Mo","Tc","Ru","Rh","Pd","Ag",
	"Cd","In","Sn","Sb","Te","I","Xe",
	"Cs","Ba","La","Ce","Pr","Nd","Pm","Sm","Eu","Gd","Tb","Dy",
	"Ho","Er","Tm","Yb","Lu","Hf","Ta","W","Re","Os","Ir","Pt",
	"Au","Hg","Tl","Pb","Bi","Po","At","Rn",
	"Fr","Ra","Ac","Th","Pa","U","Np","Pu","Am","Cm","Bk","Cf","X"};

#define ZC_DEF 1
#define ZC_CONN 0
#define ZC_AT1 3
#define ZC_AT2 4
#define ZC_MARK -7
#define ZC_VAR  ZC_DEF
#define ZC_CONST -4
#define ZC_LINK -13

#define MAXFRPNT 3000
typedef struct { Window win;
		 double *fpts;
                 int x[MAXFRPNT];
                 int y[MAXFRPNT];
                 int index[MAXFRPNT];
                 int npts;
		 int current;
		 int yelev;
		 int color;
		 int wide;
		 int high;
                } FRSTRU;

static char *frsym[MAXFRPNT];
static int nfr = 0;

static FRSTRU scfEfirst;
static FRSTRU scfElast;

static FRSTRU geoFmax;
static FRSTRU geoFrms;
static FRSTRU geoSmax;
static FRSTRU geoSrms;
static FRSTRU geoE;

static FRSTRU spect;
static FRSTRU docksco;

static int *npmfs;
static double *ewin = NULL;

/* Spectrum variables */
#define SPBHIGH  90
static int SPECWIDE = 600;
static int SPECHIGH = 300;
#define NSBUTTS 5
static BSTRU spbut[NSBUTTS];
static char *pktyp[] = {"Gaussian", "Lorentzian"};
static char *sptyp[] = {"Infra Red", "Raman"};
static double *spint;
static double *out_spec = NULL;
static int specsize = 0;
static int lorentzian = 1;
static int spmode = 0;
static double hwhm = 20.0;
static double spec_mx;
static double spec_mn;
static double freq_step = 1.0;
static double freq_scale = 1.0;
static int min_freq = 0;
static int max_freq = 4000;
static int n_freqs = 2;
static int specps = 0;
static FILE *spout;
void updcallb(char *str);

/* pmf score variables */
#define NSCBUTTS 6
static BSTRU scbut[NSCBUTTS];

#define NPBUTTS 1
static BSTRU pbut[NPBUTTS];

static double *pmfmn;
static double *pmfmx;
static double *pmflga;
static int *ipmfmn;
static int *ipmfmx;
static int *npmfmx;
static int *ialtyp = NULL;
static int *iscst;
static int *iocnt;
static int *ipmfm;
static int *ipmfh;
static int *levcol;

static int *ipart;
static int *imn;
static int *imx;
static int *idcur;

static int *logo;
static int *nscnd;
static int *dolabs;
static int *forces_yes_no;
static int *ifogl;
static int *ifdogl;
static int *itsrf = NULL;
static int *srfmap;
static int *srfloc;
static int *iams;
static int *ihets;
static int srfsep;
static int *doesp;

#define AVG(a,b) (((a) + (b))/2)
#define MIDDLEX(f,x,str) ((x)-XTextWidth(f,str,strlen(str))/2)
#define MIDDLEY(f,y) ((y)-((f->ascent+f->descent)/2)+f->ascent)
#define VIERKANT(x,y,rx,ry,rw,rh) \
           ((x)>=(rx) && (y)>=(ry) && (x)<=(rx)+(rw) && (y)<=(ry)+(rh))
#define SPACING 3
#define ASCENT   (mfinfo->ascent)
#define DESCENT  (mfinfo->descent)
#define CHIGH    (ASCENT + DESCENT)
#define LINEHIGH (CHIGH + SPACING)
#define WINCWIDE  260
#define WINCHIGH  435
#define DEFWINCGEOM "-130+80"

#define CNTCOL -15
#ifdef DOGL
#define NBUTTS   32 
#else
#define NBUTTS   31 
#endif

#define BPSI     0
#define BHOMO    1
#define BLUMO    2
#define BNDEN    3
#define BBONDS   4
#define BATOM    5
#define BOVRLP   6
#define BPOST    7
#define BMOLMOD  8
#define BQUIT    9
#define BEUCL    10
#define B3D      11
#define BINCRS   12
#define BDECRS   13
#define BCONT    14
#define BMOL     15
#define BCOMM    16
#define BORI     17
#define BSTEP    18
#define BCUT     19
#define BWRBAS   20
#define BRDBAS   21
#define B3DX     22
#define BSPACE   23
#define BFILL    24
#define BELPOT   25
#define BMAXMIN  26
#define BVRML2   27
#define BLAPL    28
#define BSRF2    29
#define BCUBE    30
#define BOGL     31

#define NBUTTS2  45 

#define BFIRST   0
#define BNEXT    1
#define BSOLID   2
#define BPOSTT   3 
#define BDENMOD  4 
#define BQUITT   5 
#define BFORC    6 
#define BINCRF   7 
#define BDECRF   8 
#define BUNSC    9
#define BDIST    10
#define BANGLE   11
#define BDIHED   12
#define BAUTH    13
#define BLABEL   14
#define BCONV    15
#define BGEOM    16
#define BZOOMIN  17
#define BZOOMOUT 18
#define BSHADE   19
#define BBACKB   20
#define BATCOL   21
#define BPERSP   22
#define BLEFT    23
#define BRIGHT   24
#define BUP      25
#define BDOWN    26
#define BMOVIE   27
#define BZMAT    28
#define BREADF   29
#define BHBOND   30
#define BPACE    31
#define BGIF     32
#define BPAL     33
#define BCELL    34
#define BORIG    35
#define BSURF    36
#define BVRML    37
#define BHYD     38
#define BWRITF   39
#define BALIGN   40
#define BBALL    41
#define BHOUR    42
#define BMOLF    43
#define BPREV    44

#define NBUTTR   4 

#define BDIR      0
#define BCAN      1
#define BREP      2
#define BADD      3


#define NQBOX   74

#define QORB     0
#define QCOMM    1
#define QPOST    2
#define QSPAC    3
#define QSTEP    4
#define QCUT     5
#define QPOSTT   6
#define QRESI    7
#define QHBOND   8
#define QREADF   9
#define QBZMAT  10
#define QFRAG   11
#define QVRML   12
#define QCSPACE 13
#define QMXYZ   14
#define QGLIN1  15
#define QGLIN2  16
#define QGTITL  17
#define QJNAME  18
#define QQNAME  19
#define QENAME  20
#define QTIME   21
#define QRADI   22
#define QCPA    23
#define QCPB    24
#define QCPC    25
#define QCPAL   26
#define QCPBE   27
#define QCPGA   28
#define QCPSPGN 29
#define QCPSPGS 30
#define QSRFW   31
#define QSRFR   32
#define QEDGE   33
#define QVALC1  34
#define QVALC2  35
#define QVALC3  36
#define QNPTS   37
#define QCHARG  38
#define QRSD    39
#define QPHI    40
#define QPSI    41
#define QPROT   42
#define QGRD    43
#define QARCH   44
#define QTNKJN  45
#define QMAXIT  46
#define QCUBE   47
#define QCTA    48
#define QCTB    49
#define QCTC    50
#define QNSCAL  51
#define QVFILE  52
#define QMFILE  53
#define QCNTVAL 54
#define QCOLVAL1 55
#define QCOLVAL2 56
#define QCOLVAL3 57
#define QCOLVAL4 58
#define QCOLVAL5 59
#define QSVFILE  60
#define QSCNT    61
#define QHW      62
#define QMINF    63
#define QMAXF    64
#define QSSCAL   65
#define QIMAX    66
#define QSFIL    67
#define QDEL     68
#define QCNT     69
#define QHBMIN   70
#define QHBMAX   71
#define QHAMIN   72
#define QHAMAX   73

#define NBUTSS  16

#define SMETH   0
#define SCLOS   1
#define SSUBM   2
#define STASK   3
#define SBASS   4
#define SCHAR   5
#define SSPIN   6
#define SMOLD   7
#define SDIRE   8
#define SBATC   9
#define SHESS  10
#define SREST  11
#define SQUEU  12
#define SZMAT  13
#define SWXYZ  14
#define SONI   15

#define NBUTCP  2
#define NBUTCT  4
#define BCPAPP  0
#define BCPCAN  1

#define NCLBUT  5
#define BMONI   0
#define BCLR    1
#define BCLOSE  2
#define BCNTCT  3
#define BCONN   4

static BSTRU dbut[NBUTTS];
static BSTRU cbut[NBUTTS2];
static BSTRU rbut[NBUTTR];
static BSTRU clbut[NCLBUT];
static BSTRU obut[2];
static BSTRU sbut[NBUTSS];
static BSTRU cpbut[NBUTCP];
static BSTRU ctbut[NBUTCT];
static LISTSTRU flist;
static LISTSTRU dirlist;
static LISTSTRU frlist;
static LISTSTRU elist;
static LISTSTRU fftlist;
static LISTSTRU pmflistmx;
static LISTSTRU pmflistmn;
static LISTSTRU flxlist;
static QBOXSTRU qboxes[NQBOX];

static int *Sinct;
static int *Sincp;

#define MAXDIRLEN 1024
#define MAXFILELEN 1024
#define MAXNAMES 10000
#define NFLS 13
static char  *files[MAXNAMES];
static int    nfiles = 0;
#ifdef VMS
static char   lastdir[MAXDIRLEN] = "[]";
#else
static char   lastdir[MAXDIRLEN] = "./";
#endif
static int    lpnt = 0;
static int    selfil = 0;
#define DIRX 35
#define DIRY 40
#define DIRW 255
#define DIRH 200

#define NDRS 4
#define MAXDIRS 500
static char  *dirs[MAXDIRS];
static int    ndirs = 0;
static int    seldir = 0;
#define DDIRX 35
#define DDIRY 250
#define DDIRW 255
#define DDIRH 76
static int Fwinopt = BREP;

#define BOFFX 14

#define PLOFFX 0
#define PLOFFY 0
#define MSOFFX 0
#define MSOFFY 219
#define SPOFFX 0
#define SPOFFY 342
#define PMOFFX 139
#define PMOFFY 0
#define D3OFFX 139
#define D3OFFY 94
#define CNOFFX 139
#define CNOFFY 219
#define BSOFFX 139
#define BSOFFY 293
#define QOFFX 139
#define QOFFY 367
#define S2OFFX 5
#define S2OFFY 403

#define POFFX 0
#define POFFY 0
#define MOFFX 0
#define MOFFY 100
#define DMOFFX 0
#define DMOFFY 224

#define MIOFFX 107
#define MIOFFY 0
#define MICONY 10
#define SOFFX 5
#define SOFFY 412

#define FOFFX 141
#define FOFFY 0
#define CLOFFX 141
#define CLOFFY 145
#define CVOFFX 141
#define CVOFFY 240
#define XOFFX 107
#define XOFFY 314

#define WINMCWIDE  248
#define WINMCHIGH  445
#define DEFWINMCGEOM "-130+80"
static int DowinC = 1;
static int DowinMC = 1;
static int DoactC = 1;
static int DoactMC = 1;
static Bool DEBUG = 0;

#define BUTTW   60
#define BUTTH   19
#define BUTTN   24
#define TOGGWH  19

static int dogif = 0;
static int picnum = 0;
static int *picmax;
static char *GifFile = "mol";
typedef struct { int iclon;
		 int iclpnt[4];
               } CELLSTRUC;
static CELLSTRUC *cellpnt;
static char *CellStr[] = {" O"," A"," B"," C"};
 
static Pixmap grayStip; 
static unsigned int  dispDEEP;

static Atom atom_DELWIN = 0;
static Atom atom_PROTOCOLS = 0;

void StoreDeleteWindowProp (win)
     Window win;
{
  if (! atom_DELWIN)
    atom_DELWIN = XInternAtom (display, "WM_DELETE_WINDOW", False);

  if (! atom_PROTOCOLS)
    atom_PROTOCOLS = XInternAtom (display, "WM_PROTOCOLS", False);

  if (atom_PROTOCOLS == None) return;

  XChangeProperty(display, win, atom_PROTOCOLS, XA_ATOM, 32,
                  PropModeReplace, (unsigned char *) &atom_DELWIN, 1);
}

int X_Error_Message_CB (Display *display, XErrorEvent *err)
{
   char msg[80];
   XGetErrorText(display, err->error_code, msg, 80);
   printf("X error code %s\n", msg);
/*
   Timer(10000000,0);
*/
/* you can Control-C here in the debugger */
   return 0;
}

Window CreateWindow(xname,geom,w,h,fg,bg,Parwin)
char         *xname, *geom;
unsigned int  w,h;
unsigned long fg, bg;
Window Parwin;
{
  Window               hwin;
  XSetWindowAttributes hxswa;
  unsigned int         xswamask;
  XWMHints             xwmh;
  XSizeHints           hints;
  int                  i,x,y;

  if (DEBUG) fprintf(stderr,"CreateWindow in\n");

  if (Parwin) {
	xswamask = CWBackPixel | CWBorderPixel | CWBackingStore | CWBackingPlanes;
	hxswa.background_pixel = bg;
	hxswa.border_pixel     = fg;
	hxswa.save_under       = False;
	hxswa.backing_store    = NotUseful;
	hxswa.backing_planes   = 0;
	x = 0; y = 0;

	if (has_opengl) {
	   hwin = XCreateWindow(display, Parwin, x, y, w, h, 
			2, vi->depth, InputOutput,
			vi->visual, xswamask, &hxswa);
	} else {
	   hwin = XCreateWindow(display, Parwin, x, y, w, h, 
			2, CopyFromParent, InputOutput,
			CopyFromParent, xswamask, &hxswa);
	}
	if (!hwin) return(hwin);   /* leave immediately if couldn't create */

	XSelectInput(display, hwin, ExposureMask | VisibilityChangeMask);
	XSetTransientForHint(display, hwin, Parwin);
  }
  else {
  /* note that only x,y are gotten from geom spec.  w,h are fixed */
	x = y = 1;
	i = XParseGeometry(geom,&x,&y,&w,&h);

	if (i&XValue || i&YValue) hints.flags = USPosition;  
                       else hints.flags = PPosition;

	hints.flags |= USSize;

	if (i&XValue && i&XNegative)
	  x = DisplayWidth(display,screen) - w - abs(x);
	if (i&YValue && i&YNegative)
	  y = DisplayHeight(display,screen) - h - abs(y);

	hints.x = x;                  hints.y = y;
	hints.width = w;              hints.height = h;
	hints.min_width  = w;         hints.min_height = h;
	hints.max_width  = w;         hints.max_height = h;
	hints.flags |= PMaxSize | PMinSize;
	xswa.background_pixel = bg;
	xswa.border_pixel     = fg;
	hxswa.background_pixel = bg;
	hxswa.border_pixel     = fg;
	hxswa.backing_store    = NotUseful;
	hxswa.backing_planes   = 0;

	if (has_opengl) {
	    hwin = XCreateWindow(display, RootWindow(display,vi->screen), 
			x, y, w, h, 2, vi->depth, InputOutput,
			vi->visual, 
			(CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWBackingStore | CWBackingPlanes), &xswa);
	} else {
	    hwin = XCreateWindow(display, RootWindow(display,screen), 
			x, y, w, h, 2, CopyFromParent, CopyFromParent,
			CopyFromParent, 
			(CWBorderPixel | CWBackPixel | CWBackingStore | CWBackingPlanes), &hxswa);
	}
	if (!hwin) return(hwin);   /* leave immediately if couldn't create */

	XSetStandardProperties(display, hwin, xname, xname, None, NULL, 0, &hints);

	xwmh.input = True;
	xwmh.flags = InputHint;
	XSetWMHints(display, hwin, &xwmh);

	StoreDeleteWindowProp(hwin);

  }

  if (setcmap) XSetWindowColormap(display,hwin,cmap);

  if (DEBUG) fprintf(stderr,"CreateWindow out\n");
  return(hwin);
}

#define PI   3.14159265358979323846
#include <math.h>

double lorentz(double rel_offset) {
  return 1.0 / (1.0 + rel_offset * rel_offset);
}

double gauss(double rel_offset) {
  const double nln2 = -log(2.0);
  return exp(nln2 * rel_offset * rel_offset);
}

static double Tsin[361],Tcos[361];

void SetupTable()
{
  int alpha;

  for ( alpha=0; alpha < 361; alpha++ ) {
	Tsin[alpha] = sin((PI*alpha)/180.0);
	Tcos[alpha] = cos((PI*alpha)/180.0);
  }
}

rotat(currx,curry)
int currx;
int curry;
{
    float tangy,rsqx,rsqy;

    hold = 1;
    holdt = 0;
    holdp = 0;
    rsqx = (int) (width / 2 - currx);
    rsqy = (int) (height / 2 - curry);
    if (rsqx*rsqx+rsqy*rsqy < 3000) {
	holdt = -1; holdp = 1;
	if ((event.xbutton.state & ControlMask) ||
	    (event.xbutton.state & ShiftMask)) holdp = -1;
	return;
    }
    if (rsqx == 0 && rsqy == 0){ hold = 0; return;}
    if (rsqx == 0) { 
	holdt = -2;
	if (rsqy > 0) holdp = -1;
	if (rsqy < 0) holdp =  1;
	return;
    }
    if (rsqy == 0) { 
	holdt = -3;
	if (rsqx > 0) holdp =  1;
	if (rsqx < 0) holdp = -1;
	return;
     }
     tangy = rsqy / rsqx;
     if (rsqx > 0) {
	if (tangy <= 1 && tangy >= -1) {
	    holdt = -3; holdp = -1;
	}
	else if (tangy > 1) {
	    holdt = -2; holdp = 1;
	}
	else { 
	    holdt = -2; holdp = -1;
	}
     } else if (rsqx < 0) {
	if (tangy <= 1 && tangy >= -1) {
	    holdt = -3; holdp = 1;
	}
	else if (tangy > 1) {
	    holdt = -2; holdp = -1;
	}
	else { 
	    holdt = -2; holdp = 1;
	}
     }
}

char *DOSpath(UNIXpath)
char *UNIXpath;
{
  char dospath[MAXDIRLEN] = "";
  char *pathptr;
  int i,n;

  if (strstr(UNIXpath,"/cygdrive/")) {
	pathptr = strstr(UNIXpath,"/cygdrive/");
	strcpy(dospath,"");
	strncpy(dospath,pathptr+10,1);
	strcat(dospath,":");
	strcat(dospath,pathptr+11);
	n = strlen(dospath);
	for (i=0; i<n; i++)
	   if (dospath[i] == '/') dospath[i] = '\\';
	strcpy(UNIXpath,dospath);
/*        fprintf(stderr,"DOSPath %s\n",dospath);*/
  }
  return UNIXpath;
}

void lViewer(ogfil)
char *ogfil;
{
    int pid;

    pid = fork();
    switch(pid) {
    case -1:
          fprintf(stderr,"Couldnt Fork\n");
          break;
    case 0:       /*child */
#ifdef __CYGWIN__
	  if (access("./mogl",F_OK) == 0) {
             execlp("./mogl","mogl",DOSpath(ogfil),NULL);
	  } else {
	     sprintf(cmdstr,"mogl \"%s\"",DOSpath(ogfil));
	     system(cmdstr);
	  }
#else
          execlp("moldenogl","moldenogl",ogfil,NULL);
#endif
	  exit(0);
          break;
    default:      /*parent*/
          break;
    }
}

#ifdef GCC_FORTRAN_H

extern int _gfortran_iargc(void);

#if defined(VMS) || defined(UNDERSC)
int iargc()
#else
#ifdef CRAY
int IARGC()
#else
int iargc_()
#endif
#endif
{
   return _gfortran_iargc();
}

#endif

#if defined(VMS) || defined(UNDERSC)
void tounx()
#else
#ifdef CRAY
void TOUNX()
#else
void tounx_()
#endif
#endif
{
    if (!DoCan(event.xbutton.x_root,event.xbutton.y_root,
	"Molden cant handle DOS files very well.\n Convert file to Unix format ?",1)) {
	dos2u(strname);
    }
}

int izz(i,j)
int i;
int j;
{
 int result;

 result = *(zmptr.iz + (i*4) + j);

 return(result);

}

int *pizz(i,j)
int i;
int j;
{
 int *result;

 result = (zmptr.iz + (i*4) + j);

 return(result);

}

int fndchr(line,chr)
char *line;
char chr;
{
   int n,i;

   n = strlen(line);
   for (i=0; i<n; i++)
	if (line[i] == chr) return(i);

   return(0);
}

/* shadow C routines for Fortran routines to pass Z-matrix pointers */

#if defined(VMS) || defined(UNDERSC)
plinzz(isel,istat)
#else
#ifdef CRAY
PLINZZ(isel,istat)
#else
plinzz_(isel,istat)
#endif
#endif
int *isel;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
   plinz(isel,istat,
#else
#ifdef CRAY
   PLINZ(isel,istat,
#else
   plinz_(isel,istat,
#endif
#endif
	zmptr.bl,zmptr.alph,zmptr.bet,zmptr.ibl,zmptr.ialph,zmptr.ibet,
	zmptr.imap,zmptr.ianz,zmptr.iz,xyz.lwrit,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
dumlin(isel,blv,alphv,betv)
#else
#ifdef CRAY
DUMLIN(isel,blv,alphv,betv)
#else
dumlin_(isel,blv,alphv,betv)
#endif
#endif
int *isel;
double *blv;
double *alphv;
double *betv;
{

#if defined(VMS) || defined(UNDERSC)
	dumliz(isel,blv,alphv,betv,
#else
#ifdef CRAY
	DUMLIZ(isel,blv,alphv,betv,
#else
	dumliz_(isel,blv,alphv,betv,
#endif
#endif
	zmptr.bl,zmptr.alph,zmptr.bet,zmptr.ibl,zmptr.ialph,zmptr.ibet,
	zmptr.imap,zmptr.ianz,zmptr.iz,xyz.lwrit,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
wline(iun,iopt,igamb)
#else
#ifdef CRAY
WLINE(iun,iopt,igamb)
#else
wline_(iun,iopt,igamb)
#endif
#endif
int *iun;
int *iopt;
int *igamb;
{

#if defined(VMS) || defined(UNDERSC)
	wlinz(iun,iopt,igamb,
#else
#ifdef CRAY
	WLINZ(iun,iopt,igamb,
#else
	wlinz_(iun,iopt,igamb,
#endif
#endif
	zmptr.bl,zmptr.alph,zmptr.bet,zmptr.ibl,zmptr.ialph,zmptr.ibet,
	zmptr.imap,zmptr.ianz,zmptr.iz,xyz.iconn,xyz.ianz,xyz.ityp,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
wrzmat(iun,iopt)
#else
#ifdef CRAY
WRZMAT(iun,iopt)
#else
wrzmat_(iun,iopt)
#endif
#endif
int *iun;
int *iopt;
{

#if defined(VMS) || defined(UNDERSC)
	wrzmaz(iun,iopt,
#else
#ifdef CRAY
	WRZMAZ(iun,iopt,
#else
	wrzmaz_(iun,iopt,
#endif
#endif
	zmptr.bl,zmptr.alph,zmptr.bet,zmptr.ibl,zmptr.ialph,zmptr.ibet,
	zmptr.imap,zmptr.ianz,zmptr.iz,geopntr.epoints,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
mapxzz(iun,imod,iff,izmtmp,istat)
#else
#ifdef CRAY
MAPXZZ(iun,imod,iff,izmtmp,istat)
#else
mapxzz_(iun,imod,iff,izmtmp,istat)
#endif
#endif
int *iun;
int *imod;
int *iff;
int *izmtmp;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	mapzzz(iun,imod,iff,izmtmp,istat,
#else
#ifdef CRAY
	MAPZZZ(iun,imod,iff,izmtmp,istat,
#else
	mapzzz_(iun,imod,iff,izmtmp,istat,
#endif
#endif
	zmptr.bl,zmptr.alph,zmptr.bet,zmptr.ibl,zmptr.ialph,zmptr.ibet,
	zmptr.imap,zmptr.ianz,zmptr.iz,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
fndmaz(ixyz,istat)
#else
#ifdef CRAY
FNDMAZ(ixyz,istat)
#else
fndmaz_(ixyz,istat)
#endif
#endif
int *ixyz;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	fndmzz(ixyz,istat,zmptr.imap);
#else
#ifdef CRAY
	FNDMZZ(ixyz,istat,zmptr.imap);
#else
	fndmzz_(ixyz,istat,zmptr.imap);
#endif
#endif

}

#if defined(VMS) || defined(UNDERSC)
chkmaz(istat)
#else
#ifdef CRAY
CHKMAZ(istat)
#else
chkmaz_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	chkmzz(istat,
#else
#ifdef CRAY
	CHKMZZ(istat,
#else
	chkmzz_(istat,
#endif
#endif
	xyz.qat,xyz.rzp,zmptr.ianz,zmptr.imap,xyz.ianz,xyz.lring,xyz.ityp,xyz.ipdbt);

}

#if defined(VMS) || defined(UNDERSC)
prtzm()
#else
#ifdef CRAY
PRTZM()
#else
prtzm_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	prtzz(
#else
#ifdef CRAY
	PRTZZ(
#else
	prtzz_(
#endif
#endif
	zmptr.bl,zmptr.alph,zmptr.bet,zmptr.ibl,zmptr.ialph,zmptr.ibet,
	zmptr.imap,zmptr.ianz,zmptr.iz);

}

#if defined(VMS) || defined(UNDERSC)
getzmz(istat)
#else
#ifdef CRAY
GETZMZ(istat)
#else
getzmz_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	getzzz(istat,
#else
#ifdef CRAY
	GETZZZ(istat,
#else
	getzzz_(istat,
#endif
#endif
	zmptr.bl,zmptr.alph,zmptr.bet,zmptr.ibl,zmptr.ialph,zmptr.ibet,
	zmptr.imap,zmptr.ianz,zmptr.iz);

}

#if defined(VMS) || defined(UNDERSC)
dumzm(cc,ianc,nnatoms)
#else
#ifdef CRAY
DUMZM(cc,ianc,nnatoms)
#else
dumzm_(cc,ianc,nnatoms)
#endif
#endif
double *cc;
int *ianc;
int *nnatoms;
{

#if defined(VMS) || defined(UNDERSC)
	dumzz(cc,ianc,nnatoms,
#else
#ifdef CRAY
	DUMZZ(cc,ianc,nnatoms,
#else
	dumzz_(cc,ianc,nnatoms,
#endif
#endif
	zmptr.bl,zmptr.alph,zmptr.bet,zmptr.ibl,zmptr.ialph,zmptr.ibet,
	zmptr.imap,zmptr.ianz,zmptr.iz,
	stoc.cstoc,stoc.czstoc,stoc.astoc,stoc.bstoc,stoc.ianstc,
	xyz.coo,xyz.iresid);

}

#if defined(VMS) || defined(UNDERSC)
convzmat(cc,ianc,nnatoms,igo,ico)
#else
#ifdef CRAY
CONVZMAT(cc,ianc,nnatoms,igo,ico)
#else
convzmat_(cc,ianc,nnatoms,igo,ico)
#endif
#endif
double *cc;
int *ianc;
int *nnatoms;
int *igo;
int *ico;
{

#if defined(VMS) || defined(UNDERSC)
	convzmzz(cc,ianc,nnatoms,igo,ico,
#else
#ifdef CRAY
	CONVZMZZ(cc,ianc,nnatoms,igo,ico,
#else
	convzmzz_(cc,ianc,nnatoms,igo,ico,
#endif
#endif
	zmptr.bl,zmptr.alph,zmptr.bet,zmptr.ibl,zmptr.ialph,zmptr.ibet,
	zmptr.imap,zmptr.ianz,zmptr.iz,
	stoc.cstoc,stoc.czstoc,stoc.astoc,stoc.bstoc,stoc.ianstc);

}

#if defined(VMS) || defined(UNDERSC)
getmop(nnatoms,heat,igo,ico,istat)
#else
#ifdef CRAY
GETMOP(nnatoms,heat,igo,ico,istat)
#else
getmop_(nnatoms,heat,igo,ico,istat)
#endif
#endif
int *nnatoms;
int *igo;
int *ico;
double *heat;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	getmdp(nnatoms,heat,igo,ico,istat,
#else
#ifdef CRAY
	GETMDP(nnatoms,heat,igo,ico,istat,
#else
	getmdp_(nnatoms,heat,igo,ico,istat,
#endif
#endif
        xyz.coo,xyz.ianz,
	zmptr.bl,zmptr.alph,zmptr.bet,zmptr.ibl,zmptr.ialph,zmptr.ibet,
	zmptr.imap,zmptr.ianz,zmptr.iz,
	stoc.cstoc,stoc.czstoc,stoc.astoc,stoc.bstoc,stoc.ianstc);

}

#if defined(VMS) || defined(UNDERSC)
getzm(nnatoms,igo,ico,istat)
#else
#ifdef CRAY
GETZM(nnatoms,igo,ico,istat)
#else
getzm_(nnatoms,igo,ico,istat)
#endif
#endif
int *nnatoms;
int *igo;
int *ico;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	getzd(nnatoms,igo,ico,istat,
#else
#ifdef CRAY
	GETZD(nnatoms,igo,ico,istat,
#else
	getzd_(nnatoms,igo,ico,istat,
#endif
#endif
	xyz.coo,xyz.ianz,
	zmptr.bl,zmptr.alph,zmptr.bet,zmptr.ibl,zmptr.ialph,zmptr.ibet,
	zmptr.imap,zmptr.ianz,zmptr.iz,
	stoc.cstoc,stoc.czstoc,stoc.astoc,stoc.bstoc,stoc.ianstc);

}

/* END shadow C routines for Fortran routines to pass Z-matrix pointers */

/* shadow C routines for Fortran routines to pass orbital pointers */

#if defined(VMS) || defined(UNDERSC)
adffun(x,y,z,psi)
#else
#ifdef CRAY
ADFFUN(x,y,z,psi)
#else
adffun_(x,y,z,psi)
#endif
#endif
double *x;
double *y;
double *z;
double *psi;
{

#if defined(VMS) || defined(UNDERSC)
	adffud(x,y,z,psi,
#else
#ifdef CRAY
	ADFFUD(x,y,z,psi,
#else
	adffud_(x,y,z,psi,
#endif
#endif
	dorb.stoalfa,dorb.stobnorm,dorb.istos,dorb.naorbs);

}

#if defined(VMS) || defined(UNDERSC)
atdd(imo,ipsi,iao)
#else
#ifdef CRAY
ATDD(imo,ipsi,iao)
#else
atdd_(imo,ipsi,iao)
#endif
#endif
int *imo;
int *ipsi;
int *iao;
{

#if defined(VMS) || defined(UNDERSC)
	addd(imo,ipsi,iao,
#else
#ifdef CRAY
	ADDD(imo,ipsi,iao,
#else
	addd_(imo,ipsi,iao,
#endif
#endif
	dorb.p,dorb.paa,orb.pd);

}

#if defined(VMS) || defined(UNDERSC)
denmad(ido)
#else
#ifdef CRAY
DENMAD(ido)
#else
denmad_(ido)
#endif
#endif
int *ido;
{

#if defined(VMS) || defined(UNDERSC)
	denmdd(ido,
#else
#ifdef CRAY
	DENMDD(ido,
#else
	denmdd_(ido,
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.focc,dorb.focb,dorb.p,dorb.paa,
	dorb.averag,orb.qd);

}

#if defined(VMS) || defined(UNDERSC)
densmat(ido)
#else
#ifdef CRAY
DENSMAT(ido)
#else
densmat_(ido)
#endif
#endif
int *ido;
{

#if defined(VMS) || defined(UNDERSC)
	densmad(ido,
#else
#ifdef CRAY
	DENSMAD(ido,
#else
	densmad_(ido,
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.focc,dorb.focb,dorb.p,dorb.nocc);

}

#if defined(VMS) || defined(UNDERSC)
densmto(ido)
#else
#ifdef CRAY
DENSMTO(ido)
#else
densmto_(ido)
#endif
#endif
int *ido;
{

#if defined(VMS) || defined(UNDERSC)
	densmtd(ido,
#else
#ifdef CRAY
	DENSMTD(ido,
#else
	densmtd_(ido,
#endif
#endif
	dorb.vectrs,dorb.focc,dorb.p,dorb.nocc);

}

#if defined(VMS) || defined(UNDERSC)
espot(x,y,z,epot,idebug)
#else
#ifdef CRAY
ESPOT(x,y,z,epot,idebug)
#else
espot_(x,y,z,epot,idebug)
#endif
#endif
double *x;
double *y;
double *z;
double *epot;
int *idebug;
{

#if defined(VMS) || defined(UNDERSC)
	espod(x,y,z,epot,idebug,
#else
#ifdef CRAY
	ESPOD(x,y,z,epot,idebug,
#else
	espod_(x,y,z,epot,idebug,
#endif
#endif
	dorb.p);

}

#if defined(VMS) || defined(UNDERSC)
newdenmak()
#else
#ifdef CRAY
NEWDENMAK()
#else
newdenmak_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	newdenmad(dorb.p,orb.qd);
#else
#ifdef CRAY
	NEWDENMAD(dorb.p,orb.qd);
#else
	newdenmad_(dorb.p,orb.qd);
#endif
#endif

}

#if defined(VMS) || defined(UNDERSC)
calhes(psi,grd,hess,den,g,hes)
#else
#ifdef CRAY
CALHES(psi,grd,hess,den,g,hes)
#else
calhes_(psi,grd,hess,den,g,hes)
#endif
#endif
double *psi;
double *grd;
double *hess;
double *den;
double *g;
double *hes;
{

#if defined(VMS) || defined(UNDERSC)
	calhed(psi,grd,hess,den,g,hes,
#else
#ifdef CRAY
	CALHED(psi,grd,hess,den,g,hes,
#else
	calhed_(psi,grd,hess,den,g,hes,
#endif
#endif
	dorb.p);

}

#if defined(VMS) || defined(UNDERSC)
grdcal(dens,npts1,npts2,iprnt,space)
#else
#ifdef CRAY
GRDCAL(dens,npts1,npts2,iprnt,space)
#else
grdcal_(dens,npts1,npts2,iprnt,space)
#endif
#endif
double *dens;
int *npts1;
int *npts2;
int *iprnt;
int *space;
{

#if defined(VMS) || defined(UNDERSC)
	grdcad(dens,npts1,npts2,iprnt,space,
#else
#ifdef CRAY
	GRDCAD(dens,npts1,npts2,iprnt,space,
#else
	grdcad_(dens,npts1,npts2,iprnt,space,
#endif
#endif
	dorb.p,dorb.paa,orb.pd,orb.gd,orb.hd);

}

#if defined(VMS) || defined(UNDERSC)
prtvec()
#else
#ifdef CRAY
PRTVEC()
#else
prtvec_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	prtved(
#else
#ifdef CRAY
	PRTVED(
#else
	prtved_(
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.eiga,dorb.eigb,dorb.ncols,dorb.ncolb);

}

#if defined(VMS) || defined(UNDERSC)
stint()
#else
#ifdef CRAY
STINT()
#else
stint_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	stind(dorb.p,xyz.qat);
#else
#ifdef CRAY
	STIND(dorb.p,xyz.qat);
#else
	stind_(dorb.p,xyz.qat);
#endif
#endif

}

#if defined(VMS) || defined(UNDERSC)
muldmd(vdwr,moddma,idm,idd)
#else
#ifdef CRAY
MULDMD(vdwr,moddma,idm,idd)
#else
muldmd_(vdwr,moddma,idm,idd)
#endif
#endif
double *vdwr;
int *moddma;
int *idm;
int *idd;
{

#if defined(VMS) || defined(UNDERSC)
	mulddd(vdwr,moddma,idm,idd,
#else
#ifdef CRAY
	MULDDD(vdwr,moddma,idm,idd,
#else
	mulddd_(vdwr,moddma,idm,idd,
#endif
#endif
	dorb.p,xyz.qat,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
mopid(istat,ibin,impas)
#else
#ifdef CRAY
MOPID(istat,ibin,impas)
#else
mopid_(istat,ibin,impas)
#endif
#endif
int *istat;
int *ibin;
int *impas;
{

#if defined(VMS) || defined(UNDERSC)
	mopdd(istat,ibin,impas,
#else
#ifdef CRAY
	MOPDD(istat,ibin,impas,
#else
	mopdd_(istat,ibin,impas,
#endif
#endif
	dorb.vectrs,dorb.averag,dorb.p,dorb.focc,dorb.eiga,orb.qd,orb.pd,
	dorb.nocc,dorb.ncols);

}


#if defined(VMS) || defined(UNDERSC)
rdgad(idebug,ibefo,istatio,ioxyz,irtype,istats)
#else
#ifdef CRAY
RDGAD(idebug,ibefo,istatio,ioxyz,irtype,istats)
#else
rdgad_(idebug,ibefo,istatio,ioxyz,irtype,istats)
#endif
#endif
int *idebug;
int *ibefo;
int *istatio;
int *ioxyz;
int *irtype;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdgdd(idebug,ibefo,istatio,ioxyz,irtype,istats,
#else
#ifdef CRAY
	RDGDD(idebug,ibefo,istatio,ioxyz,irtype,istats,
#else
	rdgdd_(idebug,ibefo,istatio,ioxyz,irtype,istats,
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.focc,dorb.focb,dorb.eiga,dorb.eigb,
	dorb.nocc,dorb.nocb,dorb.ncols,dorb.ncolb,xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
rdgamd(idebug,ibefo,istatio,irtype,ihsend,istats)
#else
#ifdef CRAY
RDGAMD(idebug,ibefo,istatio,irtype,ihsend,istats)
#else
rdgamd_(idebug,ibefo,istatio,irtype,ihsend,istats)
#endif
#endif
int *idebug;
int *ibefo;
int *istatio;
int *irtype;
int *ihsend;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdgadd(idebug,ibefo,istatio,irtype,ihsend,istats,
#else
#ifdef CRAY
	RDGADD(idebug,ibefo,istatio,irtype,ihsend,istats,
#else
	rdgadd_(idebug,ibefo,istatio,irtype,ihsend,istats,
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.focc,dorb.focb,dorb.eiga,dorb.eigb,
	dorb.nocc,dorb.nocb,dorb.ncols,dorb.ncolb);

}

#if defined(VMS) || defined(UNDERSC)
rdgaud(idebug,ibefo,istatio,irtype,istats)
#else
#ifdef CRAY
RDGAUD(idebug,ibefo,istatio,irtype,istats)
#else
rdgaud_(idebug,ibefo,istatio,irtype,istats)
#endif
#endif
int *idebug;
int *ibefo;
int *istatio;
int *irtype;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdgdud(idebug,ibefo,istatio,irtype,istats,
#else
#ifdef CRAY
	RDGDUD(idebug,ibefo,istatio,irtype,istats,
#else
	rdgdud_(idebug,ibefo,istatio,irtype,istats,
#endif
#endif
	dorb.focc,dorb.focb,dorb.nocc,dorb.nocb,dorb.ncols,dorb.ncolb,
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
rdqchm(idebug,irtype,istats)
#else
#ifdef CRAY
RDQCHM(idebug,irtype,istats)
#else
rdqchm_(idebug,irtype,istats)
#endif
#endif
int *idebug;
int *irtype;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdqchd(idebug,irtype,istats,
#else
#ifdef CRAY
	RDQCHD(idebug,irtype,istats,
#else
	rdqchd_(idebug,irtype,istats,
#endif
#endif
	dorb.focc,dorb.focb,dorb.nocc,dorb.nocb,dorb.ncols,dorb.ncolb);

}

#if defined(VMS) || defined(UNDERSC)
rdorca(idebug,irtype,istats)
#else
#ifdef CRAY
RDORCA(idebug,irtype,istats)
#else
rdorca_(idebug,irtype,istats)
#endif
#endif
int *idebug;
int *irtype;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdorcd(idebug,irtype,istats,
#else
#ifdef CRAY
	RDORCD(idebug,irtype,istats,
#else
	rdorcd_(idebug,irtype,istats,
#endif
#endif
	xyz.ianz,xyz.iatoms,
	dorb.focc,dorb.focb,dorb.nocc,dorb.nocb,dorb.ncols,dorb.ncolb);

}

#if defined(VMS) || defined(UNDERSC)
rdmaud(idebug,istatio,istats)
#else
#ifdef CRAY
RDMAUD(idebug,istatio,istats)
#else
rdmaud_(idebug,istatio,istats)
#endif
#endif
int *idebug;
int *istatio;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdmadd(idebug,istatio,istats,
#else
#ifdef CRAY
	RDMADD(idebug,istatio,istats,
#else
	rdmadd_(idebug,istatio,istats,
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.focc,dorb.focb,dorb.eiga,dorb.eigb,
	dorb.averag,dorb.p,orb.qd,orb.pd,
	dorb.nocc,dorb.nocb,dorb.ncols,dorb.ncolb,
	geopntr.formax,geopntr.forrms,geopntr.dismax,geopntr.disrms,
	geopntr.epoints,geopntr.isav,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
rdmold(idebug,istatio,irtype,iesp,istats)
#else
#ifdef CRAY
RDMOLD(idebug,istatio,irtype,iesp,istats)
#else
rdmold_(idebug,istatio,irtype,iesp,istats)
#endif
#endif
int *idebug;
int *istatio;
int *irtype;
int *iesp;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdmodd(idebug,istatio,irtype,iesp,istats,
#else
#ifdef CRAY
	RDMODD(idebug,istatio,irtype,iesp,istats,
#else
	rdmodd_(idebug,istatio,irtype,iesp,istats,
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.focc,dorb.focb,dorb.eiga,dorb.eigb,
	dorb.nocc,dorb.nocb,dorb.ncols,dorb.ncolb,
	dorb.stoalfa,dorb.stobnorm,dorb.istos,dorb.naorbs,
	geopntr.formax,geopntr.forrms,geopntr.dismax,geopntr.disrms,
	geopntr.epoints,geopntr.isav);

}

#if defined(VMS) || defined(UNDERSC)
prtmolf(iun,ihaszm,ipoints)
#else
#ifdef CRAY
PRTMOLF(iun,ihaszm,ipoints)
#else
prtmolf_(iun,ihaszm,ipoints)
#endif
#endif
int *iun;
int *ihaszm;
int *ipoints;
{

#if defined(VMS) || defined(UNDERSC)
	prtmold(iun,ihaszm,ipoints,
#else
#ifdef CRAY
	PRTMOLD(iun,ihaszm,ipoints,
#else
	prtmold_(iun,ihaszm,ipoints,
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.focc,dorb.focb,dorb.eiga,dorb.eigb,
	dorb.nocc,dorb.nocb,dorb.ncols,dorb.ncolb,
	dorb.stoalfa,dorb.stobnorm,dorb.istos,dorb.naorbs,
	geopntr.formax,geopntr.forrms,geopntr.dismax,geopntr.disrms,
	geopntr.epoints,geopntr.isav,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
rdvect(idebug,ig94,istats)
#else
#ifdef CRAY
RDVECT(idebug,ig94,istats)
#else
rdvect_(idebug,ig94,istats)
#endif
#endif
int *idebug;
int *ig94;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdvecd(idebug,ig94,istats,
#else
#ifdef CRAY
	RDVECD(idebug,ig94,istats,
#else
	rdvecd_(idebug,ig94,istats,
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.focc,dorb.eiga,dorb.eigb,
	dorb.ncols,dorb.ncolb);

}

#if defined(VMS) || defined(UNDERSC)
rdqvec(idebug,istats)
#else
#ifdef CRAY
RDQVEC(idebug,istats)
#else
rdqvec_(idebug,istats)
#endif
#endif
int *idebug;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdqvcd(idebug,istats,
#else
#ifdef CRAY
	RDQVCD(idebug,istats,
#else
	rdqvcd_(idebug,istats,
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.eiga,dorb.eigb,
	dorb.ncols,dorb.ncolb);

}

#if defined(VMS) || defined(UNDERSC)
denfst(summ,psi)
#else
#ifdef CRAY
DENFST(summ,psi)
#else
denfst_(summ,psi)
#endif
#endif
double *summ;
double *psi;
{

#if defined(VMS) || defined(UNDERSC)
	denfsd(summ,psi,
#else
#ifdef CRAY
	DENFSD(summ,psi,
#else
	denfsd_(summ,psi,
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.focc,dorb.focb);

}

#if defined(VMS) || defined(UNDERSC)
datin(npts1,npts2,npts3)
#else
#ifdef CRAY
DATIN(npts1,npts2,npts3)
#else
datin_(npts1,npts2,npts3)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
{

#if defined(VMS) || defined(UNDERSC)
	datid(npts1,npts2,npts3,
#else
#ifdef CRAY
	DATID(npts1,npts2,npts3,
#else
	datid_(npts1,npts2,npts3,
#endif
#endif
	dorb.ncols,dorb.ncolb,dorb.focc,dorb.focb,dorb.eiga,dorb.eigb);

}

#if defined(VMS) || defined(UNDERSC)
homo(ipsi)
#else
#ifdef CRAY
HOMO(ipsi)
#else
homo_(ipsi)
#endif
#endif
int *ipsi;
{

#if defined(VMS) || defined(UNDERSC)
	homod(ipsi,
#else
#ifdef CRAY
	HOMOD(ipsi,
#else
	homod_(ipsi,
#endif
#endif
	dorb.focc,dorb.focb,dorb.eiga,dorb.eigb);

}

#if defined(VMS) || defined(UNDERSC)
lumo(ipsi)
#else
#ifdef CRAY
LUMO(ipsi)
#else
lumo_(ipsi)
#endif
#endif
int *ipsi;
{

#if defined(VMS) || defined(UNDERSC)
	lumod(ipsi,
#else
#ifdef CRAY
	LUMOD(ipsi,
#else
	lumod_(ipsi,
#endif
#endif
	dorb.focc,dorb.focb,dorb.eiga,dorb.eigb);

}

#if defined(VMS) || defined(UNDERSC)
occup(istat)
#else
#ifdef CRAY
OCCUP(istat)
#else
occup_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	occupd(istat,
#else
#ifdef CRAY
	OCCUPD(istat,
#else
	occupd_(istat,
#endif
#endif
	dorb.focc,dorb.focb);

}

/* END shadow C routines for Fortran routines to pass orbital pointers */

/* shadow C routines for Fortran routines to pass grid pointers */

#if defined(VMS) || defined(UNDERSC)
asurf(idomap,idocal)
#else
#ifdef CRAY
ASURF(idomap,idocal)
#else
asurf_(idomap,idocal)
#endif
#endif
int *idomap;
int *idocal;
{
       int mapit,idum;
 
       mapit = 1;

#if defined(VMS) || defined(UNDERSC)
       if (*idomap) almgrd();
       if (*idocal) srfcal(idomap,sgrd.denn,mgrd.fmap,xyz.coo);
       else mapsrf(sgrd.denn,mgrd.fmap,&mapit);
#else
#ifdef CRAY
       if (*idomap) ALMGRD();
       if (*idocal) SRFCAL(idomap,sgrd.denn,mgrd.fmap,xyz.coo);
       else MAPSRF(sgrd.denn,mgrd.fmap,&mapit);
#else
       if (*idomap) almgrd_();
       if (*idocal) srfcal_(idomap,sgrd.denn,mgrd.fmap,xyz.coo);
       else mapsrf_(sgrd.denn,mgrd.fmap,&mapit);
#endif
#endif
}

#if defined(VMS) || defined(UNDERSC)
cntour(a,mdim,imax,jmax,pz,value,r11,id)
#else
#ifdef CRAY
CNTOUR(a,mdim,imax,jmax,pz,value,r11,id)
#else
cntour_(a,mdim,imax,jmax,pz,value,r11,id)
#endif
#endif
double *a;
int *mdim;
int *imax;
int *jmax;
double *pz;
double *value;
double *r11;
int *id;
{

#if defined(VMS) || defined(UNDERSC)
	cntoud(a,mdim,imax,jmax,pz,value,r11,id,
#else
#ifdef CRAY
	CNTOUD(a,mdim,imax,jmax,pz,value,r11,id,
#else
	cntoud_(a,mdim,imax,jmax,pz,value,r11,id,
#endif
#endif
	sgrd.ix);

}

#if defined(VMS) || defined(UNDERSC)
den3d(npts1,npts2,scale)
#else
#ifdef CRAY
DEN3D(npts1,npts2,scale)
#else
den3d_(npts1,npts2,scale)
#endif
#endif
int *npts1;
int *npts2;
double *scale;
{

#if defined(VMS) || defined(UNDERSC)
	dendd(npts1,npts2,scale,
#else
#ifdef CRAY
	DENDD(npts1,npts2,scale,
#else
	dendd_(npts1,npts2,scale,
#endif
#endif
	sgrd.dens,sgrd.edx,sgrd.edy,sgrd.iedlog);

}

#if defined(VMS) || defined(UNDERSC)
dencnt(npts1,npts2,fcnt)
#else
#ifdef CRAY
DENCNT(npts1,npts2,fcnt)
#else
dencnt_(npts1,npts2,fcnt)
#endif
#endif
int *npts1;
int *npts2;
double *fcnt;
{

#if defined(VMS) || defined(UNDERSC)
	dencnd(npts1,npts2,fcnt,
#else
#ifdef CRAY
	DENCND(npts1,npts2,fcnt,
#else
	dencnd_(npts1,npts2,fcnt,
#endif
#endif
	sgrd.dens,sgrd.iedlog);

}

#if defined(VMS) || defined(UNDERSC)
grdcl(npts1,npts2,iprnt,space)
#else
#ifdef CRAY
GRDCL(npts1,npts2,iprnt,space)
#else
grdcl_(npts1,npts2,iprnt,space)
#endif
#endif
int *npts1;
int *npts2;
int *iprnt;
double *space;
{

#if defined(VMS) || defined(UNDERSC)
	grdcd(npts1,npts2,iprnt,space,
#else
#ifdef CRAY
	GRDCD(npts1,npts2,iprnt,space,
#else
	grdcd_(npts1,npts2,iprnt,space,
#endif
#endif
	sgrd.dens);
}

#if defined(VMS) || defined(UNDERSC)
resedl()
#else
#ifdef CRAY
RESEDL()
#else
resedl_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	resedd(sgrd.iedlog);
#else
#ifdef CRAY
	RESEDD(sgrd.iedlog);
#else
	resedd_(sgrd.iedlog);
#endif
#endif

}

#if defined(VMS) || defined(UNDERSC)
maxmin(npts1,npts2,scale)
#else
#ifdef CRAY
MAXMIN(npts1,npts2,scale)
#else
maxmin_(npts1,npts2,scale)
#endif
#endif
int *npts1;
int *npts2;
double *scale;
{

#if defined(VMS) || defined(UNDERSC)
	maxmid(npts1,npts2,scale,
#else
#ifdef CRAY
	MAXMID(npts1,npts2,scale,
#else
	maxmid_(npts1,npts2,scale,
#endif
#endif
	sgrd.dens);
}

#if defined(VMS) || defined(UNDERSC)
plden(ndim1,ndim2,scale,icells,adjus,idisml)
#else
#ifdef CRAY
PLDEN(ndim1,ndim2,scale,icells,adjus,idisml)
#else
plden_(ndim1,ndim2,scale,icells,adjus,idisml)
#endif
#endif
int *ndim1;
int *ndim2;
double *scale;
int *icells;
double *adjus;
int *idisml;
{

#if defined(VMS) || defined(UNDERSC)
	plded(ndim1,ndim2,scale,icells,adjus,idisml,
#else
#ifdef CRAY
	PLDED(ndim1,ndim2,scale,icells,adjus,idisml,
#else
	plded_(ndim1,ndim2,scale,icells,adjus,idisml,
#endif
#endif
	sgrd.dens,sgrd.ix,sgrd.iy,sgrd.rz);
}

#if defined(VMS) || defined(UNDERSC)
p3dv(iun,scale,ndimx,ndimz,adjus)
#else
#ifdef CRAY
P3DV(iun,scale,ndimx,ndimz,adjus)
#else
p3dv_(iun,scale,ndimx,ndimz,adjus)
#endif
#endif
int *iun;
double *scale;
int *ndimx;
int *ndimz;
double *adjus;
{

#if defined(VMS) || defined(UNDERSC)
	p3dd(iun,scale,ndimx,ndimz,adjus,
#else
#ifdef CRAY
	P3DD(iun,scale,ndimx,ndimz,adjus,
#else
	p3dd_(iun,scale,ndimx,ndimz,adjus,
#endif
#endif
	sgrd.dens);
}

#if defined(VMS) || defined(UNDERSC)
rdcube(npts1,npts2,npts3,iposng,ipsi,istat,iun,idebug)
#else
#ifdef CRAY
RDCUBE(npts1,npts2,npts3,iposng,ipsi,istat,iun,idebug)
#else
rdcube_(npts1,npts2,npts3,iposng,ipsi,istat,iun,idebug)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
int *iposng;
int *ipsi;
int *istat;
int *iun;
int *idebug;
{

#if defined(VMS) || defined(UNDERSC)
	rdcubd(npts1,npts2,npts3,iposng,ipsi,istat,iun,idebug,
#else
#ifdef CRAY
	RDCUBD(npts1,npts2,npts3,iposng,ipsi,istat,iun,idebug,
#else
	rdcubd_(npts1,npts2,npts3,iposng,ipsi,istat,iun,idebug,
#endif
#endif
	sgrd.denn,sgrd.pmnn);

}

#if defined(VMS) || defined(UNDERSC)
wrcube(npts1,npts2,npts3,ipsi)
#else
#ifdef CRAY
WRCUBE(npts1,npts2,npts3,ipsi)
#else
wrcube_(npts1,npts2,npts3,ipsi)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
int *ipsi;
{

#if defined(VMS) || defined(UNDERSC)
	wrcubd(npts1,npts2,npts3,ipsi,
#else
#ifdef CRAY
	WRCUBD(npts1,npts2,npts3,ipsi,
#else
	wrcubd_(npts1,npts2,npts3,ipsi,
#endif
#endif
	sgrd.denn);

}

#if defined(VMS) || defined(UNDERSC)
rdgrd(npts1,npts2,npts3,iun,istat)
#else
#ifdef CRAY
RDGRD(npts1,npts2,npts3,iun,istat)
#else
rdgrd_(npts1,npts2,npts3,iun,istat)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
int *istat;
int *iun;
{

#if defined(VMS) || defined(UNDERSC)
	rdgrdd(npts1,npts2,npts3,iun,istat,
#else
#ifdef CRAY
	RDGRDD(npts1,npts2,npts3,iun,istat,
#else
	rdgrdd_(npts1,npts2,npts3,iun,istat,
#endif
#endif
	sgrd.denn,sgrd.dens,sgrd.pmnn,sgrd.denst);

}

#if defined(VMS) || defined(UNDERSC)
rdomap(npts1,npts2,npts3,iun,istat)
#else
#ifdef CRAY
RDOMAP(npts1,npts2,npts3,iun,istat)
#else
rdomap_(npts1,npts2,npts3,iun,istat)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
int *istat;
int *iun;
{

#if defined(VMS) || defined(UNDERSC)
	rdomad(npts1,npts2,npts3,iun,istat,
#else
#ifdef CRAY
	RDOMAD(npts1,npts2,npts3,iun,istat,
#else
	rdomad_(npts1,npts2,npts3,iun,istat,
#endif
#endif
	sgrd.denn,sgrd.dens,sgrd.pmnn);

}

#if defined(VMS) || defined(UNDERSC)
dpomap()
#else
#ifdef CRAY
DPOMAP()
#else
dpomap_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	dpomad(
#else
#ifdef CRAY
	DPOMAD(
#else
	dpomad_(
#endif
#endif
	sgrd.denn);

}

#if defined(VMS) || defined(UNDERSC)
rdvasp(npts1,npts2,npts3,iposng,istat,lenf,idocub,idebug)
#else
#ifdef CRAY
RDVASP(npts1,npts2,npts3,iposng,istat,lenf,idocub,idebug)
#else
rdvasp_(npts1,npts2,npts3,iposng,istat,lenf,idocub,idebug)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
int *iposng;
int *istat;
int *lenf;
int *idocub;
int *idebug;
{

#if defined(VMS) || defined(UNDERSC)
	rdvasd(npts1,npts2,npts3,iposng,istat,lenf,idocub,idebug,
#else
#ifdef CRAY
	RDVASD(npts1,npts2,npts3,iposng,istat,lenf,idocub,idebug,
#else
	rdvasd_(npts1,npts2,npts3,iposng,istat,lenf,idocub,idebug,
#endif
#endif
	sgrd.denn,sgrd.pmnn,sgrd.bucket,xyz.coo,xyz.ianz,xyz.iatclr,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
rdinfo(npts1,npts2,istat)
#else
#ifdef CRAY
RDINFO(npts1,npts2,istat)
#else
rdinfo_(npts1,npts2,istat)
#endif
#endif
int *npts1;
int *npts2;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	rdinfd(npts1,npts2,istat,
#else
#ifdef CRAY
	RDINFD(npts1,npts2,istat,
#else
	rdinfd_(npts1,npts2,istat,
#endif
#endif
	sgrd.dens,sgrd.denst);
}

#if defined(VMS) || defined(UNDERSC)
rd3inf(npts1,npts2,npts3,isubtr,adjus,istat)
#else
#ifdef CRAY
RD3INF(npts1,npts2,npts3,isubtr,adjus,istat)
#else
rd3inf_(npts1,npts2,npts3,isubtr,adjus,istat)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
int *isubtr;
double *adjus;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	rd3ind(npts1,npts2,npts3,isubtr,adjus,istat,
#else
#ifdef CRAY
	RD3IND(npts1,npts2,npts3,isubtr,adjus,istat,
#else
	rd3ind_(npts1,npts2,npts3,isubtr,adjus,istat,
#endif
#endif
	sgrd.denn,sgrd.pmnn,sgrd.denst);
}

#if defined(VMS) || defined(UNDERSC)
rd3chk(npts1,npts2,npts3,igauss,impas,istat)
#else
#ifdef CRAY
RD3CHK(npts1,npts2,npts3,igauss,impas,istat)
#else
rd3chk_(npts1,npts2,npts3,igauss,impas,istat)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
int *igauss;
int *impas;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	rd3chd(npts1,npts2,npts3,igauss,impas,istat,
#else
#ifdef CRAY
	RD3CHD(npts1,npts2,npts3,igauss,impas,istat,
#else
	rd3chd_(npts1,npts2,npts3,igauss,impas,istat,
#endif
#endif
	mgrd.fmap);
}

#if defined(VMS) || defined(UNDERSC)
void oginid(double *r, double *adjus, int *natoms, int *nat, int *icol,
#else
#ifdef CRAY
void OGINID(double *r, double *adjus, int *natoms, int *nat, int *icol,
#else
void oginid_(double *r, double *adjus, int *natoms, int *nat, int *icol,
#endif
#endif
       double *xsym, double *ysym, double *zsym, double *vdwr,
       double *cnst, int *nnpts1, int *nnpts2, double *dens);

#if defined(VMS) || defined(UNDERSC)
oginit(r,adjus,natoms,nat,icol,xsym,ysym,zsym,vdwr,cnst,npts1,npts2)
#else
#ifdef CRAY
OGINIT(r,adjus,natoms,nat,icol,xsym,ysym,zsym,vdwr,cnst,npts1,npts2)
#else
oginit_(r,adjus,natoms,nat,icol,xsym,ysym,zsym,vdwr,cnst,npts1,npts2)
#endif
#endif
double *r, *adjus;
int *natoms, *nat, *icol;
double *xsym, *ysym, *zsym;
double *vdwr;
double *cnst;
int *npts1;
int *npts2;
{

#if defined(VMS) || defined(UNDERSC)
        oginid(r,adjus,natoms,nat,icol,xsym,ysym,zsym,vdwr,cnst,npts1,
		npts2,sgrd.dens);
#else
#ifdef CRAY
        OGINID(r,adjus,natoms,nat,icol,xsym,ysym,zsym,vdwr,cnst,npts1,
		npts2,sgrd.dens);
#else
        oginid_(r,adjus,natoms,nat,icol,xsym,ysym,zsym,vdwr,cnst,npts1,
		npts2,sgrd.dens);
#endif
#endif

}

#if defined(VMS) || defined(UNDERSC)
wrinfo(npts1,npts2)
#else
#ifdef CRAY
WRINFO(npts1,npts2)
#else
wrinfo_(npts1,npts2)
#endif
#endif
int *npts1;
int *npts2;
{

#if defined(VMS) || defined(UNDERSC)
	wrinfd(npts1,npts2,
#else
#ifdef CRAY
	WRINFD(npts1,npts2,
#else
	wrinfd_(npts1,npts2,
#endif
#endif
	sgrd.dens);
}

#if defined(VMS) || defined(UNDERSC)
wr3inf(npts1,npts2,npts3,adjus)
#else
#ifdef CRAY
WR3INF(npts1,npts2,npts3,adjus)
#else
wr3inf_(npts1,npts2,npts3,adjus)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
double *adjus;
{

#if defined(VMS) || defined(UNDERSC)
	wr3ind(npts1,npts2,npts3,adjus,
#else
#ifdef CRAY
	WR3IND(npts1,npts2,npts3,adjus,
#else
	wr3ind_(npts1,npts2,npts3,adjus,
#endif
#endif
	sgrd.denn);
}

#if defined(VMS) || defined(UNDERSC)
spaced(npts1,npts2,npts3,valcnt,idofil,adjus,ipsprt,idisml,idvrml,mapit)
#else
#ifdef CRAY
SPACED(npts1,npts2,npts3,valcnt,idofil,adjus,ipsprt,idisml,idvrml,mapit)
#else
spaced_(npts1,npts2,npts3,valcnt,idofil,adjus,ipsprt,idisml,idvrml,mapit)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
double *valcnt;
int *idofil;
double *adjus;
int *ipsprt;
int *idisml;
int *idvrml;
int *mapit;
{

#if defined(VMS) || defined(UNDERSC)
   spacdd(npts1,npts2,npts3,valcnt,idofil,adjus,ipsprt,idisml,idvrml,mapit,
#else
#ifdef CRAY
   SPACDD(npts1,npts2,npts3,valcnt,idofil,adjus,ipsprt,idisml,idvrml,mapit,
#else
   spacdd_(npts1,npts2,npts3,valcnt,idofil,adjus,ipsprt,idisml,idvrml,mapit,
#endif
#endif
	sgrd.denn,sgrd.pmnn,sgrd.iedlog,mgrd.fmap);
}

#if defined(VMS) || defined(UNDERSC)
spasrf(npts1,npts2,npts3,valcnt)
#else
#ifdef CRAY
SPASRF(npts1,npts2,npts3,valcnt)
#else
spasrf_(npts1,npts2,npts3,valcnt)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
double *valcnt;
{

#if defined(VMS) || defined(UNDERSC)
	spasrd(npts1,npts2,npts3,valcnt,
#else
#ifdef CRAY
	SPASRD(npts1,npts2,npts3,valcnt,
#else
	spasrd_(npts1,npts2,npts3,valcnt,
#endif
#endif
	sgrd.denn,sgrd.pmnn,sgrd.dens,sgrd.iedlog);
}

#if defined(VMS) || defined(UNDERSC)
isoden(valc,nvalc,scincr,nespt,iwhere)
#else
#ifdef CRAY
ISODEN(valc,nvalc,scincr,nespt,iwhere)
#else
isoden_(valc,nvalc,scincr,nespt,iwhere)
#endif
#endif
double *valc;
int *nvalc;
double *scincr;
int *nespt;
int *iwhere;
{

#if defined(VMS) || defined(UNDERSC)
	isoded(valc,nvalc,scincr,nespt,iwhere,
#else
#ifdef CRAY
	ISODED(valc,nvalc,scincr,nespt,iwhere,
#else
	isoded_(valc,nvalc,scincr,nespt,iwhere,
#endif
#endif
	sgrd.dens,sgrd.iedlog);
}

#if defined(VMS) || defined(UNDERSC)
rdcpmdd(idebug,ibefo,istatio,ioxyz,irtype,ihsend,istats)
#else
#ifdef CRAY
RDCPMDD(idebug,ibefo,istatio,ioxyz,irtype,ihsend,istats)
#else
rdcpmdd_(idebug,ibefo,istatio,ioxyz,irtype,ihsend,istats)
#endif
#endif
int *idebug;
int *ibefo;
int *istatio;
int *ioxyz;
int *irtype;
int *ihsend;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdcpmddd(idebug,ibefo,istatio,ioxyz,irtype,ihsend,istats,
#else
#ifdef CRAY
	RDCPMDDD(idebug,ibefo,istatio,ioxyz,irtype,ihsend,istats,
#else
	rdcpmddd_(idebug,ibefo,istatio,ioxyz,irtype,ihsend,istats,
#endif
#endif
	dorb.vectrs,dorb.vectrb,dorb.focc,dorb.focb,dorb.eiga,dorb.eigb,
	dorb.nocc,dorb.nocb,dorb.ncols,dorb.ncolb);

}

/* END shadow C routines for Fortran routines to pass grid pointers */

/* shadow C routines for Fortran routines to pass coordinate pointers */

void anim()
{
#if defined(VMS) || defined(UNDERSC)
	anid(xyz.coo,xyz.ianz);
#else
#ifdef CRAY
	ANID(xyz.coo,xyz.ianz);
#else
	anid_(xyz.coo,xyz.ianz);
#endif
#endif
}

#if defined(VMS) || defined(UNDERSC)
actami(inum,ikleur,iopt,idosrf)
#else
#ifdef CRAY
ACTAMI(inum,ikleur,iopt,idosrf)
#else
actami_(inum,ikleur,iopt,idosrf)
#endif
#endif
int *inum;
int *ikleur;
int *iopt;
int *idosrf;
{

#if defined(VMS) || defined(UNDERSC)
	actamd(inum,ikleur,iopt,idosrf,
#else
#ifdef CRAY
	ACTAMD(inum,ikleur,iopt,idosrf,
#else
	actamd_(inum,ikleur,iopt,idosrf,
#endif
#endif
	xyz.iaton,xyz.iatclr,xyz.iresid,xyz.isurf);

}

#if defined(VMS) || defined(UNDERSC)
caldip()
#else
#ifdef CRAY
CALDIP()
#else
caldip_()
#endif
#endif
{
#if defined(VMS) || defined(UNDERSC)
	caldid(
#else
#ifdef CRAY
	CALDID(
#else
	caldid_(
#endif
#endif
	xyz.qat,xyz.coo);
}

#if defined(VMS) || defined(UNDERSC)
aacom(vrad,ires,str,nstr,istsrf)
#else
#ifdef CRAY
AACOM(vrad,ires,str,nstr,istsrf)
#else
aacom_(vrad,ires,str,nstr,istsrf)
#endif
#endif
double *vrad;
int *ires;
int *nstr;
int *istsrf;
char *str;
{

#if defined(VMS) || defined(UNDERSC)
	aacod(vrad,ires,str,nstr,istsrf,
#else
#ifdef CRAY
	AACOD(vrad,ires,str,nstr,istsrf,
#else
	aacod_(vrad,ires,str,nstr,istsrf,
#endif
#endif
	xyz.iresid,xyz.isurf);

}

#if defined(VMS) || defined(UNDERSC)
actcal(iopt)
#else
#ifdef CRAY
ACTCAL(iopt)
#else
actcal_(iopt)
#endif
#endif
int *iopt;
{

#if defined(VMS) || defined(UNDERSC)
	actcad(iopt,
#else
#ifdef CRAY
	ACTCAD(iopt,
#else
	actcad_(iopt,
#endif
#endif
	xyz.iaton,xyz.iatclr,xyz.iresid);

}

#if defined(VMS) || defined(UNDERSC)
acthel(iopt,iscnd,jcolsp,inclbb)
#else
#ifdef CRAY
ACTHEL(iopt,iscnd,jcolsp,inclbb)
#else
acthel_(iopt,iscnd,jcolsp,inclbb)
#endif
#endif
int *iopt;
int *iscnd;
int *jcolsp;
int *inclbb;
{

#if defined(VMS) || defined(UNDERSC)
	acthed(iopt,iscnd,jcolsp,inclbb,
#else
#ifdef CRAY
	ACTHED(iopt,iscnd,jcolsp,inclbb,
#else
	acthed_(iopt,iscnd,jcolsp,inclbb,
#endif
#endif
	xyz.iaton,xyz.iatclr,xyz.iresid,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
actss(iopt)
#else
#ifdef CRAY
ACTSS(iopt)
#else
actss_(iopt)
#endif
#endif
int *iopt;
{

#if defined(VMS) || defined(UNDERSC)
	actsd(iopt,
#else
#ifdef CRAY
	ACTSD(iopt,
#else
	actsd_(iopt,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
pmfass(iopt,dochg)
#else
#ifdef CRAY
PMFASS(iopt,dochg)
#else
pmfass_(iopt,dochg)
#endif
#endif
int *iopt;
int *dochg;
{

#if defined(VMS) || defined(UNDERSC)
	pmfasd(iopt,dochg,
#else
#ifdef CRAY
	PMFASD(iopt,dochg,
#else
	pmfasd_(iopt,dochg,
#endif
#endif
	xyz.ianz,xyz.iresid,xyz.iconn,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
dfiass()
#else
#ifdef CRAY
DFIASS()
#else
dfiass_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	dfiasd(
#else
#ifdef CRAY
	DFIASD(
#else
	dfiasd_(
#endif
#endif
	xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
updres()
#else
#ifdef CRAY
UPDRES()
#else
updres_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	updred(
#else
#ifdef CRAY
	UPDRED(
#else
	updred_(
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
dfires()
#else
#ifdef CRAY
DFIRES()
#else
dfires_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	dfired(
#else
#ifdef CRAY
	DFIRED(
#else
	dfired_(
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
twodfi(tdfi,ires1,ires2)
#else
#ifdef CRAY
TWODFI(tdfi,ires1,ires2)
#else
twodfi_(tdfi,ires1,ires2)
#endif
#endif
double *tdfi;
int *ires1;
int *ires2;
{

#if defined(VMS) || defined(UNDERSC)
	twodfd(tdfi,ires1,ires2,
#else
#ifdef CRAY
	TWODFD(tdfi,ires1,ires2,
#else
	twodfd_(tdfi,ires1,ires2,
#endif
#endif
	xyz.coo,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
twodfib(tdfi,ires1,ires2)
#else
#ifdef CRAY
TWODFIB(tdfi,ires1,ires2)
#else
twodfib_(tdfi,ires1,ires2)
#endif
#endif
double *tdfi;
int *ires1;
int *ires2;
{

#if defined(VMS) || defined(UNDERSC)
	twodfid(tdfi,ires1,ires2,
#else
#ifdef CRAY
	TWODFID(tdfi,ires1,ires2,
#else
	twodfid_(tdfi,ires1,ires2,
#endif
#endif
	xyz.coo,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
onedfi(tdfi,ires1)
#else
#ifdef CRAY
ONEDFI(tdfi,ires1)
#else
onedfi_(tdfi,ires1)
#endif
#endif
double *tdfi;
int *ires1;
{

#if defined(VMS) || defined(UNDERSC)
	onedfd(tdfi,ires1,
#else
#ifdef CRAY
	ONEDFD(tdfi,ires1,
#else
	onedfd_(tdfi,ires1,
#endif
#endif
	xyz.coo,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
totpmf(totpmf)
#else
#ifdef CRAY
TOTPMF(totpmf)
#else
totpmf_(totpmf)
#endif
#endif
double *totpmf;
{

#if defined(VMS) || defined(UNDERSC)
	totpmd(totpmf,
#else
#ifdef CRAY
	TOTPMD(totpmf,
#else
	totpmd_(totpmf,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
pmfinf(iatm)
#else
#ifdef CRAY
PMFINF(iatm)
#else
pmfinf_(iatm)
#endif
#endif
int *iatm;
{

#if defined(VMS) || defined(UNDERSC)
	pmfind(iatm,
#else
#ifdef CRAY
	PMFIND(iatm,
#else
	pmfind_(iatm,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
ipmtyp(iptm,iat,ian,idochg)
#else
#ifdef CRAY
IPMTYP(iptm,iat,ian,idochg)
#else
ipmtyp_(iptm,iat,ian,idochg)
#endif
#endif
int *iptm;
int *iat;
int *ian;
int *idochg;
{

#if defined(VMS) || defined(UNDERSC)
	ipmtyd(iptm,iat,ian,idochg,
#else
#ifdef CRAY
	IPMTYD(iptm,iat,ian,idochg,
#else
	ipmtyd_(iptm,iat,ian,idochg,
#endif
#endif
	xyz.ianz,xyz.iconn,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
clmon(car,pot)
#else
#ifdef CRAY
CLMON(car,pot)
#else
clmon_(car,pot)
#endif
#endif
double *car;
double *pot;
{

#if defined(VMS) || defined(UNDERSC)
	clmod(car,pot,
#else
#ifdef CRAY
	CLMOD(car,pot,
#else
	clmod_(car,pot,
#endif
#endif
	xyz.coo,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
clmons(car,pot,idoloc)
#else
#ifdef CRAY
CLMONS(car,pot,idoloc)
#else
clmons_(car,pot,idoloc)
#endif
#endif
double *car;
double *pot;
int *idoloc;
{

#if defined(VMS) || defined(UNDERSC)
	clmond(car,pot,idoloc,
#else
#ifdef CRAY
	CLMOND(car,pot,idoloc,
#else
	clmond_(car,pot,idoloc,
#endif
#endif
	xyz.coo,xyz.qat);
}

#if defined(VMS) || defined(UNDERSC)
calfa(istat,istpdb,iaddh,ioatms,nstrt,ioadd)
#else
#ifdef CRAY
CALFA(istat,istpdb,iaddh,ioatms,nstrt,ioadd)
#else
calfa_(istat,istpdb,iaddh,ioatms,nstrt,ioadd)
#endif
#endif
int *istat;
int *istpdb;
int *iaddh;
int *ioatms;
int *nstrt;
int *ioadd;
{

#if defined(VMS) || defined(UNDERSC)
	calfd(istat,istpdb,iaddh,ioatms,nstrt,ioadd,
#else
#ifdef CRAY
	CALFD(istat,istpdb,iaddh,ioatms,nstrt,ioadd,
#else
	calfd_(istat,istpdb,iaddh,ioatms,nstrt,ioadd,
#endif
#endif
	xyz.ianz,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
docct()
#else
#ifdef CRAY
DOCCT()
#else
docct_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	doccd(
#else
#ifdef CRAY
	DOCCD(
#else
	doccd_(
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
docent()
#else
#ifdef CRAY
DOCENT()
#else
docent_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	docend(
#else
#ifdef CRAY
	DOCEND(
#else
	docend_(
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
valdis(var,ipntr,numat,iop,iasel,istat)
#else
#ifdef CRAY
VALDIS(var,ipntr,numat,iop,iasel,istat)
#else
valdis_(var,ipntr,numat,iop,iasel,istat)
#endif
#endif
double *var;
int *ipntr;
int *numat;
int *iop;
int *iasel;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	valdid(var,ipntr,numat,iop,iasel,istat,
#else
#ifdef CRAY
	VALDID(var,ipntr,numat,iop,iasel,istat,
#else
	valdid_(var,ipntr,numat,iop,iasel,istat,
#endif
#endif
	xyz.ianz,xyz.iresid,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
eemcalc(var,ipntr,numat)
#else
#ifdef CRAY
EEMCALC(var,ipntr,numat)
#else
eemcalc_(var,ipntr,numat)
#endif
#endif
double *var;
int *numat;
int *ipntr;
{

#if defined(VMS) || defined(UNDERSC)
	eemcald(var,ipntr,numat,
#else
#ifdef CRAY
	EEMCALD(var,ipntr,numat,
#else
	eemcald_(var,ipntr,numat,
#endif
#endif
	xyz.coo,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
distchk()
#else
#ifdef CRAY
DISTCHK()
#else
distchk_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	distchd(
#else
#ifdef CRAY
	DISTCHD(
#else
	distchd_(
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
calgas()
#else
#ifdef CRAY
CALGAS()
#else
calgas_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	calgad(
#else
#ifdef CRAY
	CALGAD(
#else
	calgad_(
#endif
#endif
	xyz.qat,xyz.ianz,xyz.iconn,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
mkscon(c,rad,grdw,iptr,npts)
#else
#ifdef CRAY
MKSCON(c,rad,grdw,iptr,npts)
#else
mkscon_(c,rad,grdw,iptr,npts)
#endif
#endif
double *c;
double *rad;
double *grdw;
int *iptr;
int *npts;
{

#if defined(VMS) || defined(UNDERSC)
	mkscod(c,rad,grdw,iptr,npts,
#else
#ifdef CRAY
	MKSCOD(c,rad,grdw,iptr,npts,
#else
	mkscod_(c,rad,grdw,iptr,npts,
#endif
#endif
	xyz.coo,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
connlp(dens,idomap,isp)
#else
#ifdef CRAY
CONNLP(dens,idomap,isp)
#else
connlp_(dens,idomap,isp)
#endif
#endif
int *dens;
int *idomap;
int *isp;
{

#if defined(VMS) || defined(UNDERSC)
	connld(dens,idomap,isp,
#else
#ifdef CRAY
	CONNLD(dens,idomap,isp,
#else
	connld_(dens,idomap,isp,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,xyz.iconn,xyz.isurf);

}


#if defined(VMS) || defined(UNDERSC)
allsrf(docol,idomap,idocal,isp)
#else
#ifdef CRAY
ALLSRF(docol,idomap,idocal,isp)
#else
allsrf_(docol,idomap,idocal,isp)
#endif
#endif
int *docol;
int *idomap;
int *idocal;
int *isp;
{

#if defined(VMS) || defined(UNDERSC)
	allsrd(docol,idomap,idocal,isp,
#else
#ifdef CRAY
	ALLSRD(docol,idomap,idocal,isp,
#else
	allsrd_(docol,idomap,idocal,isp,
#endif
#endif
	xyz.isurf,xyz.iaton,xyz.ianz,xyz.iatclr);

}

#if defined(VMS) || defined(UNDERSC)
alasrf()
#else
#ifdef CRAY
ALASRF()
#else
alasrf_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	alasrd(
#else
#ifdef CRAY
	ALASRD(
#else
	alasrd_(
#endif
#endif
	xyz.iresid,xyz.isurf);

}

#if defined(VMS) || defined(UNDERSC)
clrsrf()
#else
#ifdef CRAY
CLRSRF()
#else
clrsrf_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	clrsrd(
#else
#ifdef CRAY
	CLRSRD(
#else
	clrsrd_(
#endif
#endif
	xyz.isurf);

}

#if defined(VMS) || defined(UNDERSC)
propnt(qx,qy,qz,ipen)
#else
#ifdef CRAY
PROPNT(qx,qy,qz,ipen)
#else
propnt_(qx,qy,qz,ipen)
#endif
#endif
double *qx;
double *qy;
double *qz;
int *ipen;
{

#if defined(VMS) || defined(UNDERSC)
	propnd(qx,qy,qz,ipen,
#else
#ifdef CRAY
	PROPND(qx,qy,qz,ipen,
#else
	propnd_(qx,qy,qz,ipen,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
getfr(istat)
#else
#ifdef CRAY
GETFR(istat)
#else
getfr_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	getfd(istat,
#else
#ifdef CRAY
	GETFD(istat,
#else
	getfd_(istat,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
ggetfr(istat)
#else
#ifdef CRAY
GGETFR(istat)
#else
ggetfr_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	ggetfd(istat,
#else
#ifdef CRAY
	GGETFD(istat,
#else
	ggetfd_(istat,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
getfrm(istat)
#else
#ifdef CRAY
GETFRM(istat)
#else
getfrm_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	getfrd(istat,
#else
#ifdef CRAY
	GETFRD(istat,
#else
	getfrd_(istat,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
getfra(istat)
#else
#ifdef CRAY
GETFRA(istat)
#else
getfra_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	getfrad(istat,
#else
#ifdef CRAY
	GETFRAD(istat,
#else
	getfrad_(istat,
#endif
#endif
	xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
nxtpnt(iopt,fancy,atcol,dolabs,backb,wpnt)
#else
#ifdef CRAY
NXTPNT(iopt,fancy,atcol,dolabs,backb,wpnt)
#else
nxtpnt_(iopt,fancy,atcol,dolabs,backb,wpnt)
#endif
#endif
int *iopt;
int *fancy;
int *atcol;
int *dolabs;
int *backb;
int *wpnt;
{

#if defined(VMS) || defined(UNDERSC)
	nxtpnd(iopt,fancy,atcol,dolabs,backb,wpnt,
#else
#ifdef CRAY
	NXTPND(iopt,fancy,atcol,dolabs,backb,wpnt,
#else
	nxtpnd_(iopt,fancy,atcol,dolabs,backb,wpnt,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
scalfr(iopt,fancy,atcol,dolabs,backb,wpnt)
#else
#ifdef CRAY
SCALFR(iopt,fancy,atcol,dolabs,backb,wpnt)
#else
scalfr_(iopt,fancy,atcol,dolabs,backb,wpnt)
#endif
#endif
int *iopt;
int *fancy;
int *atcol;
int *dolabs;
int *backb;
int *wpnt;
{

#if defined(VMS) || defined(UNDERSC)
	scalfd(iopt,fancy,atcol,dolabs,backb,wpnt,
#else
#ifdef CRAY
	SCALFD(iopt,fancy,atcol,dolabs,backb,wpnt,
#else
	scalfd_(iopt,fancy,atcol,dolabs,backb,wpnt,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
resfr()
#else
#ifdef CRAY
RESFR()
#else
resfr_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	resfd(
#else
#ifdef CRAY
	RESFD(
#else
	resfd_(
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
tofcoo()
#else
#ifdef CRAY
TOFCOO()
#else
tofcoo_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	tofcod(
#else
#ifdef CRAY
	TOFCOD(
#else
	tofcod_(
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
iatnox(iatnx)
#else
#ifdef CRAY
IATNOX(iatnx)
#else
iatnox_(iatnx)
#endif
#endif
int *iatnx;
{

#if defined(VMS) || defined(UNDERSC)
	iatnod(iatnx,
#else
#ifdef CRAY
	IATNOD(iatnx,
#else
	iatnod_(iatnx,
#endif
#endif
	xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
gampoi(ipoint,istat,oxyz)
#else
#ifdef CRAY
GAMPOI(ipoint,istat,oxyz)
#else
gampoi_(ipoint,istat,oxyz)
#endif
#endif
int *ipoint;
int *istat;
int *oxyz;
{

#if defined(VMS) || defined(UNDERSC)
	gampod(ipoint,istat,oxyz,
#else
#ifdef CRAY
	GAMPOD(ipoint,istat,oxyz,
#else
	gampod_(ipoint,istat,oxyz,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
gaupoi(istat)
#else
#ifdef CRAY
GAUPOI(istat)
#else
gaupoi_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	gaupod(istat,
#else
#ifdef CRAY
	GAUPOD(istat,
#else
	gaupod_(istat,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
getpoi(icomm,ifd,iff,doscl,ioatms,ioadd)
#else
#ifdef CRAY
GETPOI(icomm,ifd,iff,doscl,ioatms,ioadd)
#else
getpoi_(icomm,ifd,iff,doscl,ioatms,ioadd)
#endif
#endif
int *icomm;
int *ifd;
int *doscl;
int *ioatms;
int *ioadd;
{

#if defined(VMS) || defined(UNDERSC)
	getpod(icomm,ifd,iff,doscl,ioatms,ioadd,
#else
#ifdef CRAY
	GETPOD(icomm,ifd,iff,doscl,ioatms,ioadd,
#else
	getpod_(icomm,ifd,iff,doscl,ioatms,ioadd,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iaton,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
doconn()
#else
#ifdef CRAY
DOCONN()
#else
doconn_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	docond(
#else
#ifdef CRAY
	DOCOND(
#else
	docond_(
#endif
#endif
	xyz.coo,xyz.iconn,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
dohcon(ihflag)
#else
#ifdef CRAY
DOHCON(ihflag)
#else
dohcon_(ihflag)
#endif
#endif
int *ihflag;
{

#if defined(VMS) || defined(UNDERSC)
	dohcod(ihflag,
#else
#ifdef CRAY
	DOHCOD(ihflag,
#else
	dohcod_(ihflag,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iconn,xyz.isurf);

}

#if defined(VMS) || defined(UNDERSC)
nohcon()
#else
#ifdef CRAY
NOHCON()
#else
nohcon_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	nohcod(
#else
#ifdef CRAY
	NOHCOD(
#else
	nohcod_(
#endif
#endif
	xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
doscal()
#else
#ifdef CRAY
DOSCAL()
#else
doscal_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	doscad(
#else
#ifdef CRAY
	DOSCAD(
#else
	doscad_(
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
redcon()
#else
#ifdef CRAY
REDCON()
#else
redcon_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	redcod(
#else
#ifdef CRAY
	REDCOD(
#else
	redcod_(
#endif
#endif
	xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
domcon(ipt,idoall)
#else
#ifdef CRAY
DOMCON(ipt,idoall)
#else
domcon_(ipt,idoall)
#endif
#endif
int *ipt;
int *idoall;
{

#if defined(VMS) || defined(UNDERSC)
	domcod(ipt,idoall,
#else
#ifdef CRAY
	DOMCOD(ipt,idoall,
#else
	domcod_(ipt,idoall,
#endif
#endif
	xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
getxyz(igetxy,heat,iaddprv)
#else
#ifdef CRAY
GETXYZ(igetxy,heat,iaddprv)
#else
getxyz_(igetxy,heat,iaddprv)
#endif
#endif
int *igetxy;
double *heat;
int *iaddprv;
{

#if defined(VMS) || defined(UNDERSC)
	getxyd(igetxy,heat,iaddprv,
#else
#ifdef CRAY
	GETXYD(igetxy,heat,iaddprv,
#else
	getxyd_(igetxy,heat,iaddprv,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iconn,xyz.qat);

	if (*igetxy == -1) {
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat);
	   getxyd(igetxy,heat,iaddprv,
#else
#ifdef CRAY
	   ALLCOO(&addat);
	   GETXYD(igetxy,heat,iaddprv,
#else
	   allcoo_(&addat);
	   getxyd_(igetxy,heat,iaddprv,
#endif
#endif
	   xyz.coo,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iconn,xyz.qat);
        }
}

#if defined(VMS) || defined(UNDERSC)
aln2ml(iopt,istat)
#else
#ifdef CRAY
ALN2ML(iopt,istat)
#else
aln2ml_(iopt,istat)
#endif
#endif
int *iopt;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	aln2md(iopt,istat,
#else
#ifdef CRAY
	ALN2MD(iopt,istat,
#else
	aln2md_(iopt,istat,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid);

}

#if defined(VMS) || defined(UNDERSC)
alnrot(vec,irot)
#else
#ifdef CRAY
ALNROT(vec,irot)
#else
alnrot_(vec,irot)
#endif
#endif
double *vec;
int *irot;
{

#if defined(VMS) || defined(UNDERSC)
	alnrod(vec,irot,
#else
#ifdef CRAY
	ALNROD(vec,irot,
#else
	alnrod_(vec,irot,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
pckrot(istat,iatsel)
#else
#ifdef CRAY
PCKROT(istat,iatsel)
#else
pckrot_(istat,iatsel)
#endif
#endif
int *iatsel;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	pckrod(istat,iatsel,
#else
#ifdef CRAY
	PCKROD(istat,iatsel,
#else
	pckrod_(istat,iatsel,
#endif
#endif
	xyz.iresid,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
alnwrt()
#else
#ifdef CRAY
ALNWRT()
#else
alnwrt_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	alnwrd(
#else
#ifdef CRAY
	ALNWRD(
#else
	alnwrd_(
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
alnsel(isel)
#else
#ifdef CRAY
ALNSEL(isel)
#else
alnsel_(isel)
#endif
#endif
int *isel;
{

#if defined(VMS) || defined(UNDERSC)
	alnsed(isel,
#else
#ifdef CRAY
	ALNSED(isel,
#else
	alnsed_(isel,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
getchr(igetca)
#else
#ifdef CRAY
GETCHR(igetca)
#else
getchr_(igetca)
#endif
#endif
int *igetca;
{

#if defined(VMS) || defined(UNDERSC)
	getchd(igetca,
#else
#ifdef CRAY
	GETCHD(igetca,
#else
	getchd_(igetca,
#endif
#endif
	xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
getmol(igetmo)
#else
#ifdef CRAY
GETMOl(igetmo)
#else
getmol_(igetmo)
#endif
#endif
int *igetmo;
{

#if defined(VMS) || defined(UNDERSC)
	getmod(igetmo,
#else
#ifdef CRAY
	GETMOD(igetmo,
#else
	getmod_(igetmo,
#endif
#endif
	xyz.coo,xyz.qat,xyz.ianz,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
outmol(iun)
#else
#ifdef CRAY
OUTMOl(iun)
#else
outmol_(iun)
#endif
#endif
int *iun;
{

#if defined(VMS) || defined(UNDERSC)
	outmod(iun,
#else
#ifdef CRAY
	OUTMOD(iun,
#else
	outmod_(iun,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
mopaco(istats,mopopt,irtype)
#else
#ifdef CRAY
MOPACO(istats,mopopt,irtype)
#else
mopaco_(istats,mopopt,irtype)
#endif
#endif
int *istats;
int *mopopt;
int *irtype;
{

#if defined(VMS) || defined(UNDERSC)
	mopacd(istats,mopopt,irtype,
#else
#ifdef CRAY
	MOPACD(istats,mopopt,irtype,
#else
	mopacd_(istats,mopopt,irtype,
#endif
#endif
	xyz.ianz,xyz.iatclr,xyz.iconn,xyz.coo,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
parfc()
#else
#ifdef CRAY
PARFC()
#else
parfc_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	parfd(
#else
#ifdef CRAY
	PARFD(
#else
	parfd_(
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
plmol()
#else
#ifdef CRAY
PLMOL()
#else
plmol_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	plmod(
#else
#ifdef CRAY
	PLMOD(
#else
	plmod_(
#endif
#endif
	xyz.coo,xyz.qat,xyz.rzp,xyz.ixp,xyz.iyp,xyz.iconn,xyz.ianz,
	xyz.iaton,xyz.iatclr,xyz.iresid,xyz.inat);

}

#if defined(VMS) || defined(UNDERSC)
plmolp()
#else
#ifdef CRAY
PLMOLP()
#else
plmolp_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	plmold(
#else
#ifdef CRAY
	PLMOLD(
#else
	plmold_(
#endif
#endif
	xyz.coo,xyz.qat,xyz.rzp,xyz.ixp,xyz.iyp,xyz.iconn,xyz.ianz,
	xyz.iaton,xyz.iatclr,xyz.iresid,xyz.inat);

}

#if defined(VMS) || defined(UNDERSC)
plfc(shade,ixx,k,ihigh,colsc,icltan,zvect)
#else
#ifdef CRAY
PLFC(shade,ixx,k,ihigh,colsc,icltan,zvect)
#else
plfc_(shade,ixx,k,ihigh,colsc,icltan,zvect)
#endif
#endif
int *shade;
int *ixx;
int *k;
int *ihigh;
double *colsc;
int *icltan;
double *zvect;
{

#if defined(VMS) || defined(UNDERSC)
	plfd(shade,ixx,k,ihigh,colsc,icltan,zvect,
#else
#ifdef CRAY
	PLFD(shade,ixx,k,ihigh,colsc,icltan,zvect,
#else
	plfd_(shade,ixx,k,ihigh,colsc,icltan,zvect,
#endif
#endif
	xyz.coo,xyz.rzp,xyz.ixp,xyz.iyp);

}

#if defined(VMS) || defined(UNDERSC)
plfcp(shade,ixx,k,ihigh,colsc,icltan,zvect,scalp)
#else
#ifdef CRAY
PLFCP(shade,ixx,k,ihigh,colsc,icltan,zvect,scalp)
#else
plfcp_(shade,ixx,k,ihigh,colsc,icltan,zvect,scalp)
#endif
#endif
int *shade;
int *ixx;
int *k;
int *ihigh;
double *colsc;
int *icltan;
double *zvect;
double *scalp;
{

#if defined(VMS) || defined(UNDERSC)
	plfcd(shade,ixx,k,ihigh,colsc,icltan,zvect,scalp,
#else
#ifdef CRAY
	PLFCD(shade,ixx,k,ihigh,colsc,icltan,zvect,scalp,
#else
	plfcd_(shade,ixx,k,ihigh,colsc,icltan,zvect,scalp,
#endif
#endif
	xyz.coo,xyz.rzp,xyz.ixp,xyz.iyp);

}

#if defined(VMS) || defined(UNDERSC)
mstick(zvect,colsc,icltan,m,k,shade,idash)
#else
#ifdef CRAY
MSTICK(zvect,colsc,icltan,m,k,shade,idash)
#else
mstick_(zvect,colsc,icltan,m,k,shade,idash)
#endif
#endif
double *zvect;
double *colsc;
int *icltan;
int *m;
int *k;
int *shade;
int *idash;
{

#if defined(VMS) || defined(UNDERSC)
	msticd(zvect,colsc,icltan,m,k,shade,idash,
#else
#ifdef CRAY
	MSTICD(zvect,colsc,icltan,m,k,shade,idash,
#else
	msticd_(zvect,colsc,icltan,m,k,shade,idash,
#endif
#endif
	xyz.coo,xyz.rzp,xyz.ixp,xyz.iyp,xyz.iatclr);

}

#if defined(VMS) || defined(UNDERSC)
mstck(zvect,colsc,icltan,m,k,shade,idash)
#else
#ifdef CRAY
MSTCK(zvect,colsc,icltan,m,k,shade,idash)
#else
mstck_(zvect,colsc,icltan,m,k,shade,idash)
#endif
#endif
double *zvect;
double *colsc;
int *icltan;
int *m;
int *k;
int *shade;
int *idash;
{

#if defined(VMS) || defined(UNDERSC)
	mstcd(zvect,colsc,icltan,m,k,shade,idash,
#else
#ifdef CRAY
	MSTCD(zvect,colsc,icltan,m,k,shade,idash,
#else
	mstcd_(zvect,colsc,icltan,m,k,shade,idash,
#endif
#endif
	xyz.coo,xyz.rzp,xyz.ixp,xyz.iyp,xyz.iatclr);

}

#if defined(VMS) || defined(UNDERSC)
sstick()
#else
#ifdef CRAY
SSTICK()
#else
sstick_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	ssticd(
#else
#ifdef CRAY
	SSTICD(
#else
	ssticd_(
#endif
#endif
	xyz.coo,xyz.ixp,xyz.iyp,xyz.iaton,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
astick(zvect,colsc,icltan,m,k,ihigh,shade,idash,imon)
#else
#ifdef CRAY
ASTICK(zvect,colsc,icltan,m,k,ihigh,shade,idash,imon)
#else
astick_(zvect,colsc,icltan,m,k,ihigh,shade,idash,imon)
#endif
#endif
double *zvect;
double *colsc;
int *icltan;
int *m;
int *k;
int *ihigh;
int *shade;
int *idash;
int *imon;
{

#if defined(VMS) || defined(UNDERSC)
	asticd(zvect,colsc,icltan,m,k,ihigh,shade,idash,imon,
#else
#ifdef CRAY
	ASTICD(zvect,colsc,icltan,m,k,ihigh,shade,idash,imon,
#else
	asticd_(zvect,colsc,icltan,m,k,ihigh,shade,idash,imon,
#endif
#endif
	xyz.coo,xyz.rzp,xyz.ixp,xyz.iyp,xyz.ianz,xyz.iatclr);

}

#if defined(VMS) || defined(UNDERSC)
astck(zvect,colsc,scalp,icltan,m,k,ihigh,shade,idash,imon)
#else
#ifdef CRAY
ASTCK(zvect,colsc,scalp,icltan,m,k,ihigh,shade,idash,imon)
#else
astck_(zvect,colsc,scalp,icltan,m,k,ihigh,shade,idash,imon)
#endif
#endif
double *zvect;
double *colsc;
double *scalp;
int *icltan;
int *m;
int *k;
int *ihigh;
int *shade;
int *idash;
int *imon;
{

#if defined(VMS) || defined(UNDERSC)
	astcd(zvect,colsc,scalp,icltan,m,k,ihigh,shade,idash,imon,
#else
#ifdef CRAY
	ASTCD(zvect,colsc,scalp,icltan,m,k,ihigh,shade,idash,imon,
#else
	astcd_(zvect,colsc,scalp,icltan,m,k,ihigh,shade,idash,imon,
#endif
#endif
	xyz.coo,xyz.rzp,xyz.ixp,xyz.iyp,xyz.ianz,xyz.iatclr);

}

#if defined(VMS) || defined(UNDERSC)
snglat(zvect,scalp,colsc,icltan,k,ihigh,shade,atcol,ipersp,ipost,icolps)
#else
#ifdef CRAY
SNGLAT(zvect,scalp,colsc,icltan,k,ihigh,shade,atcol,ipersp,ipost,icolps)
#else
snglat_(zvect,scalp,colsc,icltan,k,ihigh,shade,atcol,ipersp,ipost,icolps)
#endif
#endif
double *zvect;
double *scalp;
double *colsc;
int *icltan;
int *k;
int *ihigh;
int *shade;
int *atcol;
int *ipersp;
int *ipost;
int *icolps;
{

#if defined(VMS) || defined(UNDERSC)
	snglad(zvect,scalp,colsc,icltan,k,ihigh,shade,atcol,ipersp,ipost,icolps,
#else
#ifdef CRAY
	SNGLAD(zvect,scalp,colsc,icltan,k,ihigh,shade,atcol,ipersp,ipost,icolps,
#else
	snglad_(zvect,scalp,colsc,icltan,k,ihigh,shade,atcol,ipersp,ipost,icolps,
#endif
#endif
	xyz.coo,xyz.rzp,xyz.ixp,xyz.iyp,xyz.ianz,xyz.iatclr);

}

#if defined(VMS) || defined(UNDERSC)
fstick(roddef,rfac,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd)
#else
#ifdef CRAY
FSTICK(roddef,rfac,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd)
#else
fstick_(roddef,rfac,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd)
#endif
#endif
double *roddef;
double *rfac;
double *zvect;
double *colsc;
int *icltan;
int *m;
int *k;
int *ihigh;
int *shade;
int *atcol;
int *scnd;
{

#if defined(VMS) || defined(UNDERSC)
	fsticd(roddef,rfac,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd,
#else
#ifdef CRAY
	FSTICD(roddef,rfac,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd,
#else
	fsticd_(roddef,rfac,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd,
#endif
#endif
	xyz.coo,xyz.rzp,xyz.ianz,xyz.iatclr);

}

#if defined(VMS) || defined(UNDERSC)
fstck(roddef,rfac,scalp,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd)
#else
#ifdef CRAY
FSTCK(roddef,rfac,scalp,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd)
#else
fstck_(roddef,rfac,scalp,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd)
#endif
#endif
double *roddef;
double *rfac;
double *scalp;
double *zvect;
double *colsc;
int *icltan;
int *m;
int *k;
int *ihigh;
int *shade;
int *atcol;
int *scnd;
{

#if defined(VMS) || defined(UNDERSC)
	fstcd(roddef,rfac,scalp,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd,
#else
#ifdef CRAY
	FSTCD(roddef,rfac,scalp,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd,
#else
	fstcd_(roddef,rfac,scalp,zvect,colsc,icltan,m,k,ihigh,shade,atcol,scnd,
#endif
#endif
	xyz.coo,xyz.rzp,xyz.ianz,xyz.iatclr);

}

#if defined(VMS) || defined(UNDERSC)
pldstg()
#else
#ifdef CRAY
PLDSTG()
#else
pldstg_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	pldstd(
#else
#ifdef CRAY
	PLDSTD(
#else
	pldstd_(
#endif
#endif
	xyz.ixp,xyz.iyp);

}

#if defined(VMS) || defined(UNDERSC)
plalab(iqon)
#else
#ifdef CRAY
PLALAB(iqon)
#else
plalab_(iqon)
#endif
#endif
int *iqon;
{

#if defined(VMS) || defined(UNDERSC)
	plalad(iqon,
#else
#ifdef CRAY
	PLALAD(iqon,
#else
	plalad_(iqon,
#endif
#endif
	xyz.rzp,xyz.ixp,xyz.iyp);

}

#if defined(VMS) || defined(UNDERSC)
plalb(iami)
#else
#ifdef CRAY
PLALB(iami)
#else
plalb_(iami)
#endif
#endif
int *iami;
{

#if defined(VMS) || defined(UNDERSC)
	plald(iami,
#else
#ifdef CRAY
	PLALD(iami,
#else
	plald_(iami,
#endif
#endif
	xyz.ixp,xyz.iyp);

}

#if defined(VMS) || defined(UNDERSC)
pllab(ixp,iyp,ianz,k,qat,inr,iqon,ires,ipost)
#else
#ifdef CRAY
PLLAB(ixp,iyp,ianz,k,qat,inr,iqon,ires,ipost)
#else
pllab_(ixp,iyp,ianz,k,qat,inr,iqon,ires,ipost)
#endif
#endif
int *ixp;
int *iyp;
int *ianz;
int *k;
double *qat;
int *inr;
int *iqon;
int *ires;
int *ipost;
{

#if defined(VMS) || defined(UNDERSC)
	pllad(ixp,iyp,ianz,k,qat,inr,iqon,ires,ipost,
#else
#ifdef CRAY
	PLLAD(ixp,iyp,ianz,k,qat,inr,iqon,ires,ipost,
#else
	pllad_(ixp,iyp,ianz,k,qat,inr,iqon,ires,ipost,
#endif
#endif
	xyz.ityp,xyz.ipdbt);

}

#if defined(VMS) || defined(UNDERSC)
plpost(backb,dolabs,icolps,fancy,atcol,persp,shade,idelx)
#else
#ifdef CRAY
PLPOST(backb,dolabs,icolps,fancy,atcol,persp,shade,idelx)
#else
plpost_(backb,dolabs,icolps,fancy,atcol,persp,shade,idelx)
#endif
#endif
int *backb;
int *dolabs;
int *icolps;
int *fancy;
int *atcol;
int *persp;
int *shade;
int *idelx;
{

#if defined(VMS) || defined(UNDERSC)
	plposd(backb,dolabs,icolps,fancy,atcol,persp,shade,idelx,
#else
#ifdef CRAY
	PLPOSD(backb,dolabs,icolps,fancy,atcol,persp,shade,idelx,
#else
	plposd_(backb,dolabs,icolps,fancy,atcol,persp,shade,idelx,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iaton,xyz.iresid,xyz.iatclr,xyz.iconn,
	xyz.ixp,xyz.iyp,xyz.rzp,xyz.inat,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
plvrml(iun,fancy,atcol,dolabs,ihnd,backb,dohead)
#else
#ifdef CRAY
PLVRML(iun,fancy,atcol,dolabs,ihnd,backb,dohead)
#else
plvrml_(iun,fancy,atcol,dolabs,ihnd,backb,dohead)
#endif
#endif
int *iun;
int *fancy;
int *atcol;
int *dolabs;
int *ihnd;
int *backb;
int *dohead;
{

#if defined(VMS) || defined(UNDERSC)
	plvrmd(iun,fancy,atcol,dolabs,ihnd,backb,dohead,
#else
#ifdef CRAY
	PLVRMD(iun,fancy,atcol,dolabs,ihnd,backb,dohead,
#else
	plvrmd_(iun,fancy,atcol,dolabs,ihnd,backb,dohead,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
plvst(iun,jcol,k,atcol,hndexl)
#else
#ifdef CRAY
PLVST(iun,jcol,k,atcol,hndexl)
#else
plvst_(iun,jcol,k,atcol,hndexl)
#endif
#endif
int *iun;
int *jcol;
int *k;
int *atcol;
int *hndexl;
{

#if defined(VMS) || defined(UNDERSC)
	plvsd(iun,jcol,k,atcol,hndexl,
#else
#ifdef CRAY
	PLVSD(iun,jcol,k,atcol,hndexl,
#else
	plvsd_(iun,jcol,k,atcol,hndexl,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
hcoord(ioatms,nstrt)
#else
#ifdef CRAY
HCOORD(ioatms,nstrt)
#else
hcoord_(ioatms,nstrt)
#endif
#endif
int *ioatms;
int *nstrt;
{
  int istat;

#if defined(VMS) || defined(UNDERSC)
	hcoodd(&istat,ioatms,nstrt,
#else
#ifdef CRAY
	HCOODD(&istat,ioatms,nstrt,
#else
	hcoodd_(&istat,ioatms,nstrt,
#endif
#endif
	xyz.ipdbt,xyz.coo,xyz.ianz,xyz.iaton,xyz.iresid,xyz.iconn);


	if (!istat) {
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat);
	   hcoodd(&istat,ioatms,nstrt,
#else
#ifdef CRAY
	   ALLCOO(&addat);
	   HCOODD(&istat,ioatms,nstrt,
#else
	   allcoo_(&addat);
	   hcoodd_(&istat,ioatms,nstrt,
#endif
#endif
	   xyz.ipdbt,xyz.coo,xyz.ianz,xyz.iaton,xyz.iresid,xyz.iconn);
        }
}

#if defined(VMS) || defined(UNDERSC)
hang(idx1,idx2,hang)
#else
#ifdef CRAY
HANG(idx1,idx2,hang)
#else
hang_(idx1,idx2,hang)
#endif
#endif
int *idx1;
int *idx2;
double *hang;
{

#if defined(VMS) || defined(UNDERSC)
	hand(idx1,idx2,hang,
#else
#ifdef CRAY
	HAND(idx1,idx2,hang,
#else
	hand_(idx1,idx2,hang,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
hbond(ioatms,nstrt)
#else
#ifdef CRAY
HBOND(ioatms,nstrt)
#else
hbond_(ioatms,nstrt)
#endif
#endif
int *ioatms;
int *nstrt;
{

#if defined(VMS) || defined(UNDERSC)
	hbodd(ioatms,nstrt,
#else
#ifdef CRAY
	HBODD(ioatms,nstrt,
#else
	hbodd_(ioatms,nstrt,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
acthb(iopt,hbfilt)
#else
#ifdef CRAY
ACTHB(iopt,hbfilt)
#else
acthb_(iopt,hbfilt)
#endif
#endif
int *iopt;
double *hbfilt;
{

#if defined(VMS) || defined(UNDERSC)
	acthd(iopt,hbfilt,
#else
#ifdef CRAY
	ACTHD(iopt,hbfilt,
#else
	acthd_(iopt,hbfilt,
#endif
#endif
	xyz.coo,xyz.iconn,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
disabh(iopt)
#else
#ifdef CRAY
DISABH(iopt)
#else
disabh_(iopt)
#endif
#endif
int *iopt;
{

#if defined(VMS) || defined(UNDERSC)
	disabd(iopt,
#else
#ifdef CRAY
	DISABD(iopt,
#else
	disabd_(iopt,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
hbconn(iopt,iat1,iat2)
#else
#ifdef CRAY
HBCONN(iopt,iat1,iat2)
#else
hbconn_(iopt,iat1,iat2)
#endif
#endif
int *iopt;
int *iat1;
int *iat2;
{

#if defined(VMS) || defined(UNDERSC)
	hbcond(iopt,iat1,iat2,
#else
#ifdef CRAY
	HBCOND(iopt,iat1,iat2,
#else
	hbcond_(iopt,iat1,iat2,
#endif
#endif
	xyz.ianz,xyz.iatclr,xyz.iaton,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
ribbon(iscnd,dogl,nr,iungl,tori)
#else
#ifdef CRAY
RIBBON(iscnd,dogl,nr,iungl,tori)
#else
ribbon_(iscnd,dogl,nr,iungl,tori)
#endif
#endif
int *iscnd;
int *dogl;
int *nr;
int *iungl;
double *tori;
{
 int istat;

#if defined(VMS) || defined(UNDERSC)
	ribbod(&istat,iscnd,dogl,nr,iungl,tori,
#else
#ifdef CRAY
	RIBBOD(&istat,iscnd,dogl,nr,iungl,tori,
#else
	ribbod_(&istat,iscnd,dogl,nr,iungl,tori,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,xyz.iconn);

	if (!istat) {
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat);
	   ribbod(&istat,iscnd,dogl,nr,iungl,tori,
#else
#ifdef CRAY
	   ALLCOO(&addat);
	   RIBBOD(&istat,iscnd,dogl,nr,iungl,tori,
#else
	   allcoo_(&addat);
	   ribbod_(&istat,iscnd,dogl,nr,iungl,tori,
#endif
#endif
	   xyz.coo,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,xyz.iconn);
        }
}

#if defined(VMS) || defined(UNDERSC)
ribbs()
#else
#ifdef CRAY
RIBBS()
#else
ribbs_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	ribbd(
#else
#ifdef CRAY
	RIBBD(
#else
	ribbd_(
#endif
#endif
	xyz.iaton);

}

#if defined(VMS) || defined(UNDERSC)
prnts()
#else
#ifdef CRAY
PRNTS()
#else
prnts_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	prntd(
#else
#ifdef CRAY
	PRNTD(
#else
	prntd_(
#endif
#endif
	xyz.iaton);

}
#if defined(VMS) || defined(UNDERSC)
proxim(itarg,thresh,ikleur,idosrf)
#else
#ifdef CRAY
PROXIM(itarg,thresh,ikleur,idosrf)
#else
proxim_(itarg,thresh,ikleur,idosrf)
#endif
#endif
int *itarg;
double *thresh;
int *ikleur;
int *idosrf;
{

#if defined(VMS) || defined(UNDERSC)
	proxid(itarg,thresh,ikleur,idosrf,
#else
#ifdef CRAY
	PROXID(itarg,thresh,ikleur,idosrf,
#else
	proxid_(itarg,thresh,ikleur,idosrf,
#endif
#endif
	xyz.coo,xyz.iresid);

}

#if defined(VMS) || defined(UNDERSC)
proxic(itarg,backb)
#else
#ifdef CRAY
PROXIC(itarg,backb)
#else
proxic_(itarg,backb)
#endif
#endif
int *itarg;
int *backb;
{

#if defined(VMS) || defined(UNDERSC)
	proxd(itarg,backb,
#else
#ifdef CRAY
	PROXD(itarg,backb,
#else
	proxd_(itarg,backb,
#endif
#endif
	xyz.coo,xyz.iresid,xyz.iaton,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
rdchx(idebug,iop,istdbd,useab,moddma,istat,icrtp,icssr)
#else
#ifdef CRAY
RDCHX(idebug,iop,istdbd,useab,moddma,istat,icrtp,icssr)
#else
rdchx_(idebug,iop,istdbd,useab,moddma,istat,icrtp,icssr)
#endif
#endif
int *idebug;
int *iop;
int *istdbd;
int *useab;
int *moddma;
int *istat;
int *icrtp;
int *icssr;
{

#if defined(VMS) || defined(UNDERSC)
	rdchd(idebug,iop,istdbd,useab,moddma,istat,icrtp,icssr,
#else
#ifdef CRAY
	RDCHD(idebug,iop,istdbd,useab,moddma,istat,icrtp,icssr,
#else
	rdchd_(idebug,iop,istdbd,useab,moddma,istat,icrtp,icssr,
#endif
#endif
	xyz.coo,xyz.iconn,xyz.ianz,xyz.iatclr,xyz.ityp,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
rfbio(idebug,ifrst,istat)
#else
#ifdef CRAY
RFBIO(idebug,ifrst,istat)
#else
rfbio_(idebug,ifrst,istat)
#endif
#endif
int *idebug;
int *ifrst;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	rfbid(idebug,ifrst,istat,
#else
#ifdef CRAY
	RFBID(idebug,ifrst,istat,
#else
	rfbid_(idebug,ifrst,istat,
#endif
#endif
	xyz.coo,xyz.qat,xyz.ianz,xyz.iatclr,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
getxdt(ipnt,istat)
#else
#ifdef CRAY
GETXDT(ipnt,istat)
#else
getxdt_(ipnt,istat)
#endif
#endif
int *ipnt;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	getxdd(ipnt,istat,
#else
#ifdef CRAY
	GETXDD(ipnt,istat,
#else
	getxdd_(ipnt,istat,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
rfdat(idebug,istat,refcod)
#else
#ifdef CRAY
RFDAT(idebug,istat,refcod)
#else
rfdat_(idebug,istat,refcod)
#endif
#endif
int *idebug;
int *istat;
int *refcod;
{

#if defined(VMS) || defined(UNDERSC)
	rfdad(idebug,istat,refcod,
#else
#ifdef CRAY
	RFDAD(idebug,istat,refcod,
#else
	rfdad_(idebug,istat,refcod,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iatclr,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
fdat(iop,ifrst,istdbd,useab,moddma,idebug)
#else
#ifdef CRAY
FDAT(iop,ifrst,istdbd,useab,moddma,idebug)
#else
fdat_(iop,ifrst,istdbd,useab,moddma,idebug)
#endif
#endif
int *iop;
int *ifrst;
int *istdbd;
int *useab;
int *moddma;
int *idebug;
{

#if defined(VMS) || defined(UNDERSC)
	fdad(iop,ifrst,istdbd,useab,moddma,idebug,
#else
#ifdef CRAY
	FDAD(iop,ifrst,istdbd,useab,moddma,idebug,
#else
	fdad_(iop,ifrst,istdbd,useab,moddma,idebug,
#endif
#endif
	xyz.coo,xyz.qat,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,
	xyz.iconn,xyz.lwrit,xyz.lring,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
delat(iat,iacn,iorg,mxdma)
#else
#ifdef CRAY
DELAT(iat,iacn,iorg,mxdma)
#else
delat_(iat,iacn,iorg,mxdma)
#endif
#endif
int *iat;
int *iacn;
int *iorg;
int *mxdma;
{

#if defined(VMS) || defined(UNDERSC)
	delad(iat,iacn,iorg,mxdma,
#else
#ifdef CRAY
	DELAD(iat,iacn,iorg,mxdma,
#else
	delad_(iat,iacn,iorg,mxdma,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iatclr,xyz.qat,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
polh(ipolh,iatom)
#else
#ifdef CRAY
POLH(ipolh,iatom)
#else
polh_(ipolh,iatom)
#endif
#endif
int *ipolh;
int *iatom;
{

#if defined(VMS) || defined(UNDERSC)
	pold(ipolh,iatom,
#else
#ifdef CRAY
	POLD(ipolh,iatom,
#else
	pold_(ipolh,iatom,
#endif
#endif
	xyz.ianz,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
ifnn(ifnn,noff,ia1,ia2)
#else
#ifdef CRAY
IFNN(ifnn,noff,ia1,ia2)
#else
ifnn_(ifnn,noff,ia1,ia2)
#endif
#endif
int *ifnn;
int *noff;
int *ia1;
int *ia2;
{

#if defined(VMS) || defined(UNDERSC)
	ifnd(ifnn,noff,ia1,ia2,
#else
#ifdef CRAY
	IFND(ifnn,noff,ia1,ia2,
#else
	ifnd_(ifnn,noff,ia1,ia2,
#endif
#endif
	xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
rdgro(idebug,istat)
#else
#ifdef CRAY
RDGRO(idebug,istat)
#else
rdgro_(idebug,istat)
#endif
#endif
int *idebug;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	rdgrod(idebug,istat,
#else
#ifdef CRAY
	RDGROD(idebug,istat,
#else
	rdgrod_(idebug,istat,
#endif
#endif
	xyz.coo,xyz.qat,xyz.ianz,xyz.iatclr,xyz.iresid,xyz.iconn,
	xyz.ityp,xyz.ipdbt);

	if (*istat == -1) {
           NHetAtm = 0;
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat);
	   rdgrod(idebug,istat,
#else
#ifdef CRAY
	   ALLCOO(&addat);
	   RDGROD(idebug,istat,
#else
	   allcoo_(&addat);
	   rdgrod_(idebug,istat,
#endif
#endif
	   xyz.coo,xyz.qat,xyz.ianz,xyz.iatclr,xyz.iresid,xyz.iconn,
	   xyz.ityp,xyz.ipdbt);
        }
}

#if defined(VMS) || defined(UNDERSC)
addbox(v1,v2,v3)
#else
#ifdef CRAY
ADDBOX(v1,v2,v3)
#else
addbox_(v1,v2,v3)
#endif
#endif
double *v1;
double *v2;
double *v3;
{

#if defined(VMS) || defined(UNDERSC)
	addbod(v1,v2,v3,
#else
#ifdef CRAY
	ADDBOD(v1,v2,v3,
#else
	addbod_(v1,v2,v3,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iatclr,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
gropt(ipnt)
#else
#ifdef CRAY
GROPT(ipnt)
#else
gropt_(ipnt)
#endif
#endif
int *ipnt;
{

#if defined(VMS) || defined(UNDERSC)
	gropd(ipnt,
#else
#ifdef CRAY
	GROPD(ipnt,
#else
	gropd_(ipnt,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
rdmol(idebug,ipdbon,ioadd,istat)
#else
#ifdef CRAY
RDMOL(idebug,ipdbon,ioadd,istat)
#else
rdmol_(idebug,ipdbon,ioadd,istat)
#endif
#endif
int *idebug;
int *ipdbon;
int *ioadd;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	rdmod(idebug,ipdbon,ioadd,istat,
#else
#ifdef CRAY
	RDMOD(idebug,ipdbon,ioadd,istat,
#else
	rdmod_(idebug,ipdbon,ioadd,istat,
#endif
#endif
	xyz.coo,xyz.qat,xyz.ianz,xyz.iatclr,xyz.iresid,xyz.iconn,
	xyz.ityp,xyz.ipdbt);

	if (*istat == -1) {
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat);
	   rdmod(idebug,ipdbon,ioadd,istat,
#else
#ifdef CRAY
	   ALLCOO(&addat);
	   RDMOD(idebug,ipdbon,ioadd,istat,
#else
	   allcoo_(&addat);
	   rdmod_(idebug,ipdbon,ioadd,istat,
#endif
#endif
	   xyz.coo,xyz.qat,xyz.ianz,xyz.iatclr,xyz.iresid,xyz.iconn,
   	   xyz.ityp,xyz.ipdbt);
        }
}

#if defined(VMS) || defined(UNDERSC)
wrmol(iun,icel)
#else
#ifdef CRAY
WRMOL(iun,icel)
#else
wrmol_(iun,icel)
#endif
#endif
int *iun;
int *icel;
{

#if defined(VMS) || defined(UNDERSC)
	wrmod(iun,icel,
#else
#ifdef CRAY
	WRMOD(iun,icel,
#else
	wrmod_(iun,icel,
#endif
#endif
	xyz.coo,xyz.qat,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iconn,
	xyz.iresid,xyz.lring,xyz.inat,xyz.ityp,xyz.ipdbt);

}

#if defined(VMS) || defined(UNDERSC)
ispn(ispn,iat,irng,idochg,ifive)
#else
#ifdef CRAY
ISPN(ispn,iat,irng,idochg,ifive)
#else
ispn_(ispn,iat,irng,idochg,ifive)
#endif
#endif
int *ispn;
int *iat;
int *irng;
int *idochg;
int *ifive;
{

#if defined(VMS) || defined(UNDERSC)
	ispd(ispn,iat,irng,idochg,ifive,
#else
#ifdef CRAY
	ISPD(ispn,iat,irng,idochg,ifive,
#else
	ispd_(ispn,iat,irng,idochg,ifive,
#endif
#endif
	xyz.qat,xyz.ianz,xyz.iaton,xyz.iconn,xyz.lwrit,xyz.lring);

}

#if defined(VMS) || defined(UNDERSC)
wrcrys(iun,icel)
#else
#ifdef CRAY
WRCRYS(iun,icel)
#else
wrcrys_(iun,icel)
#endif
#endif
int *iun;
int *icel;
{

#if defined(VMS) || defined(UNDERSC)
	wrcryd(iun,icel,
#else
#ifdef CRAY
	WRCRYD(iun,icel,
#else
	wrcryd_(iun,icel,
#endif
#endif
	xyz.ianz,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
rdshlx(idebug,istat)
#else
#ifdef CRAY
RDSHLX(idebug,istat)
#else
rdshlx_(idebug,istat)
#endif
#endif
int *idebug;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	rdshld(idebug,istat,
#else
#ifdef CRAY
	RDSHLD(idebug,istat,
#else
	rdshld_(idebug,istat,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iconn,xyz.iatclr);

}

#if defined(VMS) || defined(UNDERSC)
rdcif(idebug,istat)
#else
#ifdef CRAY
RDCIF(idebug,istat)
#else
rdcif_(idebug,istat)
#endif
#endif
int *idebug;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	rdcifd(idebug,istat,
#else
#ifdef CRAY
	RDCIFD(idebug,istat,
#else
	rdcifd_(idebug,istat,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iconn,xyz.iatclr);

}

#if defined(VMS) || defined(UNDERSC)
wrshlx(iun,icel,idospf)
#else
#ifdef CRAY
WRSHLX(iun,icel,idospf)
#else
wrshlx_(iun,icel,idospf)
#endif
#endif
int *iun;
int *icel;
int *idospf;
{

#if defined(VMS) || defined(UNDERSC)
	wrshld(iun,icel,idospf,
#else
#ifdef CRAY
	WRSHLD(iun,icel,idospf,
#else
	wrshld_(iun,icel,idospf,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
wrcif(iun,icel)
#else
#ifdef CRAY
WRCIF(iun,icel)
#else
wrcif_(iun,icel)
#endif
#endif
int *iun;
int *icel;
{

#if defined(VMS) || defined(UNDERSC)
	wrcifd(iun,icel,
#else
#ifdef CRAY
	WRCIFD(iun,icel,
#else
	wrcifd_(iun,icel,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
cllrot(vec,irot,ifd)
#else
#ifdef CRAY
CLLROT(vec,irot,ifd)
#else
cllrot_(vec,irot,ifd)
#endif
#endif
double *vec;
int *irot;
int *ifd;
{

#if defined(VMS) || defined(UNDERSC)
	cllrod(vec,irot,ifd,
#else
#ifdef CRAY
	CLLROD(vec,irot,ifd,
#else
	cllrod_(vec,irot,ifd,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
zm2fr(cm,ctmp,imkeep)
#else
#ifdef CRAY
ZM2FR(cm,ctmp,imkeep)
#else
zm2fr_(cm,ctmp,imkeep)
#endif
#endif
double *cm;
double *ctmp;
int *imkeep;
{

#if defined(VMS) || defined(UNDERSC)
	zm2fd(cm,ctmp,imkeep,
#else
#ifdef CRAY
	ZM2FD(cm,ctmp,imkeep,
#else
	zm2fd_(cm,ctmp,imkeep,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iatclr,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
wrchx(iun,icel)
#else
#ifdef CRAY
WRCHX(iun,icel)
#else
wrchx_(iun,icel)
#endif
#endif
int *iun;
int *icel;
{

#if defined(VMS) || defined(UNDERSC)
	wrchd(iun,icel,
#else
#ifdef CRAY
	WRCHD(iun,icel,
#else
	wrchd_(iun,icel,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iatclr,xyz.iconn,xyz.qat,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
rdmsi(idebug,istat)
#else
#ifdef CRAY
RDMSI(idebug,istat)
#else
rdmsi_(idebug,istat)
#endif
#endif
int *idebug;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	rdmsd(idebug,istat,
#else
#ifdef CRAY
	RDMSD(idebug,istat,
#else
	rdmsd_(idebug,istat,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iatclr,xyz.iconn,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
wrmsi(iun,icel)
#else
#ifdef CRAY
WRMSI(iun,icel)
#else
wrmsi_(iun,icel)
#endif
#endif
int *iun;
int *icel;
{

#if defined(VMS) || defined(UNDERSC)
	wrmsd(iun,icel,
#else
#ifdef CRAY
	WRMSD(iun,icel,
#else
	wrmsd_(iun,icel,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iconn,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
rdcpmolu(istats)
#else
#ifdef CRAY
RDCPMOLU(istats)
#else
rdcpmolu_(istats)
#endif
#endif
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdcpmold(istats,
#else
#ifdef CRAY
	RDCPMOLD(istats,
#else
	rdcpmold_(istats,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
cpmdpt(ipnt,istat)
#else
#ifdef CRAY
CPMDPT(ipnt,istat)
#else
cpmdpt_(ipnt,istat)
#endif
#endif
int *ipnt;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	cpmdpd(ipnt,istat,
#else
#ifdef CRAY
	CPMDPD(ipnt,istat,
#else
	cpmdpd_(ipnt,istat,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
cpmdgetfr(istat)
#else
#ifdef CRAY
CPMDGETFR(istat)
#else
cpmdgetfr_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	cpmdgetfd(istat,
#else
#ifdef CRAY
	CPMDGETFD(istat,
#else
	cpmdgetfd_(istat,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
cpmdptdyn(ipnt,istat)
#else
#ifdef CRAY
CPMDPTDYN(ipnt,istat)
#else
cpmdptdyn_(ipnt,istat)
#endif
#endif
int *ipnt;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	cpmdptdyd(ipnt,istat,
#else
#ifdef CRAY
	CPMDPTDYD(ipnt,istat,
#else
	cpmdptdyd_(ipnt,istat,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
wrcpmd(iun,icel)
#else
#ifdef CRAY
WRCPMD(iun,icel)
#else
wrcpmd_(iun,icel)
#endif
#endif
int *iun;
int *icel;
{

#if defined(VMS) || defined(UNDERSC)
	wrcpdd(iun,icel,
#else
#ifdef CRAY
	WRCPDD(iun,icel,
#else
	wrcpdd_(iun,icel,
#endif
#endif
	xyz.ianz,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
rdmolu(sline,iemlin,idocoo,idobohr,istats)
#else
#ifdef CRAY
RDMOLU(sline,iemlin,idocoo,idobohr,istats)
#else
rdmolu_(sline,iemlin,idocoo,idobohr,istats)
#endif
#endif
int *sline;
int *iemlin;
int *idocoo;
int *idobohr;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdmodu(sline,iemlin,idocoo,idobohr,istats,
#else
#ifdef CRAY
	RDMODU(sline,iemlin,idocoo,idobohr,istats,
#else
	rdmodu_(sline,iemlin,idocoo,idobohr,istats,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
gamupt(ipnt,istat)
#else
#ifdef CRAY
GAMUPT(ipnt,istat)
#else
gamupt_(ipnt,istat)
#endif
#endif
int *ipnt;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	gamupd(ipnt,istat,
#else
#ifdef CRAY
	GAMUPD(ipnt,istat,
#else
	gamupd_(ipnt,istat,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
ugetfr(istat)
#else
#ifdef CRAY
UGETFR(istat)
#else
ugetfr_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	ugetfd(istat,
#else
#ifdef CRAY
	ugetfd(istat,
#else
	ugetfd_(istat,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
wrvasp(iun)
#else
#ifdef CRAY
WRVASP(iun)
#else
wrvasp_(iun)
#endif
#endif
int *iun;
{

#if defined(VMS) || defined(UNDERSC)
	wrvasd(iun,
#else
#ifdef CRAY
	WRVASD(iun,
#else
	wrvasd_(iun,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
wrmopa(iun)
#else
#ifdef CRAY
WRMOPA(iun)
#else
wrmopa_(iun)
#endif
#endif
int *iun;
{

#if defined(VMS) || defined(UNDERSC)
	wrmopd(iun,
#else
#ifdef CRAY
	WRMOPD(iun,
#else
	wrmopd_(iun,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
wrfc(iun3)
#else
#ifdef CRAY
WRFC(iun3)
#else
wrfc_(iun3)
#endif
#endif
int *iun3;
{

#if defined(VMS) || defined(UNDERSC)
	wrfd(iun3,
#else
#ifdef CRAY
	WRFD(iun3,
#else
	wrfd_(iun3,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
rdfc(ipnt,istats)
#else
#ifdef CRAY
RDFC(ipnt,istats)
#else
rdfc_(ipnt,istats)
#endif
#endif
int *ipnt;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdfd(ipnt,istats,
#else
#ifdef CRAY
	RDFD(ipnt,istats,
#else
	rdfd_(ipnt,istats,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
rdmsf(idebug,istat)
#else
#ifdef CRAY
RDMSF(idebug,istat)
#else
rdmsf_(idebug,istat)
#endif
#endif
int *idebug;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	rdmdf(idebug,istat,
#else
#ifdef CRAY
	RDMDF(idebug,istat,
#else
	rdmdf_(idebug,istat,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iatclr,xyz.iconn,xyz.qat,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
rdpdb(istat)
#else
#ifdef CRAY
RDPDB(istat)
#else
rdpdb_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	rdpdd(istat,
#else
#ifdef CRAY
	RDPDD(istat,
#else
	rdpdd_(istat,
#endif
#endif
	xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
pdbstd(istat,doscnd,ioadd)
#else
#ifdef CRAY
PDBSTD(istat,doscnd,ioadd)
#else
pdbstd_(istat,doscnd,ioadd)
#endif
#endif
int *istat;
int *doscnd;
int *ioadd;
{

#if defined(VMS) || defined(UNDERSC)
	pdbsdd(istat,doscnd,ioadd,
#else
#ifdef CRAY
	PDBSDD(istat,doscnd,ioadd,
#else
	pdbsdd_(istat,doscnd,ioadd,
#endif
#endif
	xyz.coo,xyz.ianz,xyz.iaton,xyz.iresid,xyz.iconn,xyz.ityp);

	if (*istat == -1) {
	   NHetAtm = 0;
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat);
	   pdbsdd(istat,doscnd,ioadd,
#else
#ifdef CRAY
	   ALLCOO(&addat);
	   PDBSDD(istat,doscnd,ioadd,
#else
	   allcoo_(&addat);
	   pdbsdd_(istat,doscnd,ioadd,
#endif
#endif
	   xyz.coo,xyz.ianz,xyz.iaton,xyz.iresid,xyz.iconn,xyz.ityp);
        }
}

#if defined(VMS) || defined(UNDERSC)
conpdb()
#else
#ifdef CRAY
CONPDB()
#else
conpdb_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	conpdd(
#else
#ifdef CRAY
	CONPDD(
#else
	conpdd_(
#endif
#endif
	xyz.ianz,xyz.iconn,xyz.iresid);

}

#if defined(VMS) || defined(UNDERSC)
convpdb()
#else
#ifdef CRAY
CONVPDB()
#else
convpdb_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	convpdd(
#else
#ifdef CRAY
	CONVPDD(
#else
	convpdd_(
#endif
#endif
	xyz.ianz,xyz.iconn,xyz.iresid);

}

#if defined(VMS) || defined(UNDERSC)
conslv()
#else
#ifdef CRAY
CONSLV()
#else
conslv_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	consld(
#else
#ifdef CRAY
	CONSLD(
#else
	consld_(
#endif
#endif
	xyz.iconn,xyz.iresid);

}

#if defined(VMS) || defined(UNDERSC)
connij(idcon,i,j,idoconv)
#else
#ifdef CRAY
CONNIJ(idcon,i,j,idoconv)
#else
connij_(idcon,i,j,idoconv)
#endif
#endif
int *idcon;
int *i;
int *j;
int *idoconv;
{

#if defined(VMS) || defined(UNDERSC)
	connid(idcon,i,j,idoconv,
#else
#ifdef CRAY
	CONNID(idcon,i,j,idoconv,
#else
	connid_(idcon,i,j,idoconv,
#endif
#endif
	xyz.iconn,xyz.ianz,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
setchg(iat,iopt)
#else
#ifdef CRAY
SETCHG(iat,iopt)
#else
setchg_(iat,iopt)
#endif
#endif
int *iat;
int *iopt;
{

#if defined(VMS) || defined(UNDERSC)
	setchd(iat,iopt,
#else
#ifdef CRAY
	SETCHD(iat,iopt,
#else
	setchd_(iat,iopt,
#endif
#endif
	xyz.qat,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
flagh(ihpdb,iat)
#else
#ifdef CRAY
FLAGH(ihpdb,iat)
#else
flagh_(ihpdb,iat)
#endif
#endif
int *ihpdb;
int *iat;
{

#if defined(VMS) || defined(UNDERSC)
	flagd(ihpdb,iat,
#else
#ifdef CRAY
	FLAGD(ihpdb,iat,
#else
	flagd_(ihpdb,iat,
#endif
#endif
	xyz.isurf);

}

#if defined(VMS) || defined(UNDERSC)
conat(ipdb,iat1,iat2,iop)
#else
#ifdef CRAY
CONAT(ipdb,iat1,iat2,iop)
#else
conat_(ipdb,iat1,iat2,iop)
#endif
#endif
int *ipdb;
int *iat1;
int *iat2;
int *iop;
{

#if defined(VMS) || defined(UNDERSC)
	conad(ipdb,iat1,iat2,iop,
#else
#ifdef CRAY
	CONAD(ipdb,iat1,iat2,iop,
#else
	conad_(ipdb,iat1,iat2,iop,
#endif
#endif
	xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
conath(ipdb,ihpdb,iat1,iat2)
#else
#ifdef CRAY
CONATH(ipdb,ihpdb,iat1,iat2)
#else
conath_(ipdb,ihpdb,iat1,iat2)
#endif
#endif
int *ipdb;
int *ihpdb;
int *iat1;
int *iat2;
{

#if defined(VMS) || defined(UNDERSC)
	conatd(ipdb,ihpdb,iat1,iat2,
#else
#ifdef CRAY
	CONATD(ipdb,ihpdb,iat1,iat2,
#else
	conatd_(ipdb,ihpdb,iat1,iat2,
#endif
#endif
	xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
pdbtyp(ipdb,ihpdb,jres,ihashy)
#else
#ifdef CRAY
PDBTYP(ipdb,ihpdb,jres,ihashy)
#else
pdbtyp_(ipdb,ihpdb,jres,ihashy)
#endif
#endif
int *ipdb;
int *ihpdb;
int *jres;
int *ihashy;
{

#if defined(VMS) || defined(UNDERSC)
	pdbtyd(ipdb,ihpdb,jres,ihashy,
#else
#ifdef CRAY
	PDBTYD(ipdb,ihpdb,jres,ihashy,
#else
	pdbtyd_(ipdb,ihpdb,jres,ihashy,
#endif
#endif
	xyz.ipdbt);

}

#if defined(VMS) || defined(UNDERSC)
typeit(ipdb,jres,ihpdb,ihashy)
#else
#ifdef CRAY
TYPEIT(ipdb,jres,ihpdb,ihashy)
#else
typeit_(ipdb,jres,ihpdb,ihashy)
#endif
#endif
int *ipdb;
int *ihpdb;
int *jres;
int *ihashy;
{

#if defined(VMS) || defined(UNDERSC)
	typeid(ipdb,jres,ihpdb,ihashy,
#else
#ifdef CRAY
	TYPEID(ipdb,jres,ihpdb,ihashy,
#else
	typeid_(ipdb,jres,ihpdb,ihashy,
#endif
#endif
	xyz.ianz,xyz.iconn,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
typamb(ipdb,jres,ihpdb,ihashy)
#else
#ifdef CRAY
TYPAMB(ipdb,jres,ihpdb,ihashy)
#else
typamb_(ipdb,jres,ihpdb,ihashy)
#endif
#endif
int *ipdb;
int *ihpdb;
int *jres;
int *ihashy;
{

#if defined(VMS) || defined(UNDERSC)
	typamd(ipdb,jres,ihpdb,ihashy,
#else
#ifdef CRAY
	TYPAMD(ipdb,jres,ihpdb,ihashy,
#else
	typamd_(ipdb,jres,ihpdb,ihashy,
#endif
#endif
	xyz.ianz,xyz.iconn,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
typamo(ipdb,jres,ihpdb,ihashy)
#else
#ifdef CRAY
TYPAMO(ipdb,jres,ihpdb,ihashy)
#else
typamo_(ipdb,jres,ihpdb,ihashy)
#endif
#endif
int *ipdb;
int *ihpdb;
int *jres;
int *ihashy;
{

#if defined(VMS) || defined(UNDERSC)
	typado(ipdb,jres,ihpdb,ihashy,
#else
#ifdef CRAY
	TYPADO(ipdb,jres,ihpdb,ihashy,
#else
	typado_(ipdb,jres,ihpdb,ihashy,
#endif
#endif
	xyz.ianz,xyz.iconn,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
mkback(ipdb,ihpdb,jres,icres,ihashy,idoconv)
#else
#ifdef CRAY
MKBACK(ipdb,ihpdb,jres,icres,ihashy,idoconv)
#else
mkback_(ipdb,ihpdb,jres,icres,ihashy,idoconv)
#endif
#endif
int *ipdb;
int *ihpdb;
int *jres;
int *icres;
int *ihashy;
int *idoconv;
{

#if defined(VMS) || defined(UNDERSC)
	mkbacd(ipdb,ihpdb,jres,icres,ihashy,idoconv,
#else
#ifdef CRAY
	MKBACD(ipdb,ihpdb,jres,icres,ihashy,idoconv,
#else
	mkbacd_(ipdb,ihpdb,jres,icres,ihashy,idoconv,
#endif
#endif
	xyz.iconn,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
mknbck(ipdb,ihpdb,jres,icres,ihashy,idoconv)
#else
#ifdef CRAY
MKNBCK(ipdb,ihpdb,jres,icres,ihashy,idoconv)
#else
mknbck_(ipdb,ihpdb,jres,icres,ihashy,idoconv)
#endif
#endif
int *ipdb;
int *ihpdb;
int *jres;
int *icres;
int *ihashy;
int *idoconv;
{

#if defined(VMS) || defined(UNDERSC)
	mknbcd(ipdb,ihpdb,jres,icres,ihashy,idoconv,
#else
#ifdef CRAY
	MKNBCD(ipdb,ihpdb,jres,icres,ihashy,idoconv,
#else
	mknbcd_(ipdb,ihpdb,jres,icres,ihashy,idoconv,
#endif
#endif
	xyz.iconn,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
addhs(ires,jres,ipdb,ihpdb,nterm)
#else
#ifdef CRAY
ADDHS(ires,jres,ipdb,ihpdb,nterm)
#else
addhs_(ires,jres,ipdb,ihpdb,nterm)
#endif
#endif
int *ires;
int *jres;
int *ipdb;
int *ihpdb;
int *nterm;
{

#if defined(VMS) || defined(UNDERSC)
	addhd(ires,jres,ipdb,ihpdb,nterm,
#else
#ifdef CRAY
	ADDHD(ires,jres,ipdb,ihpdb,nterm,
#else
	addhd_(ires,jres,ipdb,ihpdb,nterm,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,xyz.iconn,
	xyz.isurf,xyz.ipdbt,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
numhet(num)
#else
#ifdef CRAY
NUMHET(num)
#else
numhet_(num)
#endif
#endif
int *num;
{

#if defined(VMS) || defined(UNDERSC)
	numhed(num,
#else
#ifdef CRAY
	NUMHED(num,
#else
	numhed_(num,
#endif
#endif
	xyz.iresid);

}

#if defined(VMS) || defined(UNDERSC)
qcxyz(idebug,nuclear,ipnt,istat)
#else
#ifdef CRAY
QCXYZ(idebug,nuclear,ipnt,istat)
#else
qcxyz_(idebug,nuclear,ipnt,istat)
#endif
#endif
int *idebug;
int *nuclear;
int *ipnt;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	qcxyd(idebug,nuclear,ipnt,istat,
#else
#ifdef CRAY
	QCXYD(idebug,nuclear,ipnt,istat,
#else
	qcxyd_(idebug,nuclear,ipnt,istat,
#endif
#endif
	xyz.ianz,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
orcxyz(idebug,ipnt,istat)
#else
#ifdef CRAY
ORCXYZ(idebug,ipnt,istat)
#else
orcxyz_(idebug,ipnt,istat)
#endif
#endif
int *idebug;
int *ipnt;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	orcxyd(idebug,ipnt,istat,
#else
#ifdef CRAY
	ORCXYD(idebug,ipnt,istat,
#else
	orcxyd_(idebug,ipnt,istat,
#endif
#endif
	xyz.ianz,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
getqfr(istat)
#else
#ifdef CRAY
GETQFR(istat)
#else
getqfr_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	getqfd(istat,
#else
#ifdef CRAY
	GETQFD(istat,
#else
	getqfd_(istat,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
getofr(istat)
#else
#ifdef CRAY
GETOFR(istat)
#else
getofr_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	getofd(istat,
#else
#ifdef CRAY
	GETOFD(istat,
#else
	getofd_(istat,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
rotcor(b)
#else
#ifdef CRAY
ROTCOR(b)
#else
rotcor_(b)
#endif
#endif
double *b;
{

#if defined(VMS) || defined(UNDERSC)
	rotcod(b,
#else
#ifdef CRAY
	ROTCOD(b,
#else
	rotcod_(b,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
rotmom(ipoint,favail)
#else
#ifdef CRAY
ROTMOM(ipoint,favail)
#else
rotmom_(ipoint,favail)
#endif
#endif
int *ipoint;
int *favail;
{

#if defined(VMS) || defined(UNDERSC)
	rotmod(ipoint,favail,
#else
#ifdef CRAY
	ROTMOD(ipoint,favail,
#else
	rotmod_(ipoint,favail,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
rotfir(oxyz)
#else
#ifdef CRAY
ROTFIR(oxyz)
#else
rotfir_(oxyz)
#endif
#endif
int *oxyz;
{

#if defined(VMS) || defined(UNDERSC)
	rotfid(oxyz,
#else
#ifdef CRAY
	ROTFID(oxyz,
#else
	rotfid_(oxyz,
#endif
#endif
	xyz.ianz,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
setorg(iatom)
#else
#ifdef CRAY
SETORG(iatom)
#else
setorg_(iatom)
#endif
#endif
int *iatom;
{

#if defined(VMS) || defined(UNDERSC)
	setord(iatom,
#else
#ifdef CRAY
	SETORD(iatom,
#else
	setord_(iatom,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
samino(istat)
#else
#ifdef CRAY
SAMINO(istat)
#else
samino_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	samind(istat,
#else
#ifdef CRAY
	SAMIND(istat,
#else
	samind_(istat,
#endif
#endif
	xyz.ianz,xyz.iresid,xyz.iconn,xyz.ipdbt);

}

#if defined(VMS) || defined(UNDERSC)
getpdb(ires,ipdb,ihpdb)
#else
#ifdef CRAY
GETPDB(ires,ipdb,ihpdb)
#else
getpdb_(ires,ipdb,ihpdb)
#endif
#endif
int *ires;
int *ipdb;
int *ihpdb;
{

#if defined(VMS) || defined(UNDERSC)
	getpdd(ires,ipdb,ihpdb,
#else
#ifdef CRAY
	GETPDD(ires,ipdb,ihpdb,
#else
	getpdd_(ires,ipdb,ihpdb,
#endif
#endif
	xyz.ianz,xyz.iresid,xyz.ipdbt);

}

#if defined(VMS) || defined(UNDERSC)
bckok(ibckok,ires,iop)
#else
#ifdef CRAY
BCKOK(ibckok,ires,iop)
#else
bckok_(ibckok,ires,iop)
#endif
#endif
int *ibckok;
int *ires;
int *iop;
{

#if defined(VMS) || defined(UNDERSC)
	bckod(ibckok,ires,iop,
#else
#ifdef CRAY
	BCKOD(ibckok,ires,iop,
#else
	bckod_(ibckok,ires,iop,
#endif
#endif
	xyz.ianz,xyz.iresid,xyz.ipdbt);

}

#if defined(VMS) || defined(UNDERSC)
wrsrf(iun,nesp,iesp)
#else
#ifdef CRAY
WRSRF(iun,nesp,iesp)
#else
wrsrf_(iun,nesp,iesp)
#endif
#endif
int *iun;
int *nesp;
int *iesp;
{

#if defined(VMS) || defined(UNDERSC)
	wrsrd(iun,nesp,iesp,
#else
#ifdef CRAY
	WRSRD(iun,nesp,iesp,
#else
	wrsrd_(iun,nesp,iesp,
#endif
#endif
	xyz.ianz,xyz.iatclr,xyz.iconn,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
rdsrf(iun,istats,iesp,iaddprv,idebug)
#else
#ifdef CRAY
RDSRF(iun,istats,iesp,iaddprv,idebug)
#else
rdsrf_(iun,istats,iesp,iaddprv,idebug)
#endif
#endif
int *iun;
int *istats;
int *iesp;
int *iaddprv;
int *idebug;
{

#if defined(VMS) || defined(UNDERSC)
	rdsrd(iun,istats,iesp,iaddprv,idebug,
#else
#ifdef CRAY
	RDSRD(iun,istats,iesp,iaddprv,idebug,
#else
	rdsrd_(iun,istats,iesp,iaddprv,idebug,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,xyz.iconn,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
srfden(x,y,z,f)
#else
#ifdef CRAY
SRFDEN(x,y,z,f)
#else
srfden_(x,y,z,f)
#endif
#endif
double *x;
double *y;
double *z;
double *f;
{

#if defined(VMS) || defined(UNDERSC)
	srfded(x,y,z,f,
#else
#ifdef CRAY
	SRFDED(x,y,z,f,
#else
	srfded_(x,y,z,f,
#endif
#endif
	xyz.ianz,xyz.isurf,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
defsrf()
#else
#ifdef CRAY
DEFSRF()
#else
defsrf_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	defsrd(
#else
#ifdef CRAY
	DEFSRD(
#else
	defsrd_(
#endif
#endif
	xyz.isurf,xyz.ianz,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
clrmon()
#else
#ifdef CRAY
CLRMON()
#else
clrmon_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	clrmod(
#else
#ifdef CRAY
	CLRMOD(
#else
	clrmod_(
#endif
#endif
	xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
intcor(intc,rout,isel,inum)
#else
#ifdef CRAY
INTCOR(intc,rout,isel,inum)
#else
intcor_(intc,rout,isel,inum)
#endif
#endif
int *intc;
short int *rout;
int *isel;
int *inum;
{

#if defined(VMS) || defined(UNDERSC)
	intcod(intc,rout,isel,inum,
#else
#ifdef CRAY
	INTCOD(intc,rout,isel,inum,
#else
	intcod_(intc,rout,isel,inum,
#endif
#endif
	xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
xyzcoo(idocopy,idoconv,ioadd)
#else
#ifdef CRAY
XYZCOO(idocopy,idoconv,ioadd)
#else
xyzcoo_(idocopy,idoconv,ioadd)
#endif
#endif
int *idocopy;
int *idoconv;
int *ioadd;
{

#if defined(VMS) || defined(UNDERSC)
	xyzcod(idocopy,idoconv,ioadd,
#else
#ifdef CRAY
	XYZCOD(idocopy,idoconv,ioadd,
#else
	xyzcod_(idocopy,idoconv,ioadd,
#endif
#endif
	xyz.ianz,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
wrmsf(iun,icel)
#else
#ifdef CRAY
WRMSF(iun,icel)
#else
wrmsf_(iun,icel)
#endif
#endif
int *iun;
int *icel;
{

#if defined(VMS) || defined(UNDERSC)
	wrmsfd(iun,icel,
#else
#ifdef CRAY
	WRMSFD(iun,icel,
#else
	wrmsfd_(iun,icel,
#endif
#endif
	xyz.coo,xyz.qat,xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,
	xyz.iconn,xyz.lring,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
wrtnk(iun)
#else
#ifdef CRAY
WRTNK(iun)
#else
wrtnk_(iun)
#endif
#endif
int *iun;
{

#if defined(VMS) || defined(UNDERSC)
	wrtnd(iun,
#else
#ifdef CRAY
	WRTND(iun,
#else
	wrtnd_(iun,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iconn,xyz.lring,xyz.ityp,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
wrgff(iun)
#else
#ifdef CRAY
WRGFF(iun)
#else
wrgff_(iun)
#endif
#endif
int *iun;
{

#if defined(VMS) || defined(UNDERSC)
	wrgfd(iun,
#else
#ifdef CRAY
	WRGFD(iun,
#else
	wrgfd_(iun,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iconn,xyz.ityp,xyz.coo,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
wrogl(iun)
#else
#ifdef CRAY
WROGL(iun)
#else
wrogl_(iun)
#endif
#endif
int *iun;
{

#if defined(VMS) || defined(UNDERSC)
	wrogd(iun,
#else
#ifdef CRAY
	WROGD(iun,
#else
	wrogd_(iun,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,xyz.iconn,
	xyz.lring,xyz.coo,xyz.rzp);

}

#if defined(VMS) || defined(UNDERSC)
gettnk(igttnk,idebug,ipdbon,iffset,iheat,heat)
#else
#ifdef CRAY
GETTNK(igttnk,idebug,ipdbon,iffset,iheat,heat)
#else
gettnk_(igttnk,idebug,ipdbon,iffset,iheat,heat)
#endif
#endif
int *igttnk;
int *idebug;
int *ipdbon;
int *iffset;
int *iheat;
double *heat;
{

#if defined(VMS) || defined(UNDERSC)
	gettnd(igttnk,idebug,ipdbon,iffset,iheat,heat,
#else
#ifdef CRAY
	GETTND(igttnk,idebug,ipdbon,iffset,iheat,heat,
#else
	gettnd_(igttnk,idebug,ipdbon,iffset,iheat,heat,
#endif
#endif
	xyz.ianz,xyz.iconn,xyz.ityp,xyz.coo,xyz.qat);

	if (*igttnk == -1) {
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat);
	   gettnd(igttnk,idebug,ipdbon,iffset,iheat,heat,
#else
#ifdef CRAY
	   ALLCOO(&addat);
	   GETTND(igttnk,idebug,ipdbon,iffset,iheat,heat,
#else
	   allcoo_(&addat);
	   gettnd_(igttnk,idebug,ipdbon,iffset,iheat,heat,
#endif
#endif
	   xyz.ianz,xyz.iconn,xyz.ityp,xyz.coo,xyz.qat);
        }
}

#if defined(VMS) || defined(UNDERSC)
dotyp(icel)
#else
#ifdef CRAY
DOTYP(icel)
#else
dotyp_(icel)
#endif
#endif
int *icel;
{

#if defined(VMS) || defined(UNDERSC)
	dotyd(icel,
#else
#ifdef CRAY
	DOTYD(icel,
#else
	dotyd_(icel,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iconn,xyz.iresid,xyz.lwrit,xyz.lring,
	xyz.ityp,xyz.coo,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
espfit(idip,nesp,esp,connl,dx,dy,dz,iz,dmachg,ichadd)
#else
#ifdef CRAY
ESPFIT(idip,nesp,esp,connl,dx,dy,dz,iz,dmachg,ichadd)
#else
espfit_(idip,nesp,esp,connl,dx,dy,dz,iz,dmachg,ichadd)
#endif
#endif
int *idip;
int *nesp;
double *esp;
double *connl;
double *dx;
double *dy;
double *dz;
int *iz;
int *dmachg;
int *ichadd;
{

#if defined(VMS) || defined(UNDERSC)
	espfid(idip,nesp,esp,connl,dx,dy,dz,iz,dmachg,ichadd,
#else
#ifdef CRAY
	ESPFID(idip,nesp,esp,connl,dx,dy,dz,iz,dmachg,ichadd,
#else
	espfid_(idip,nesp,esp,connl,dx,dy,dz,iz,dmachg,ichadd,
#endif
#endif
	xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
allzmt(ipdbon)
#else
#ifdef CRAY
ALLZMT(ipdbon)
#else
allzmt_(ipdbon)
#endif
#endif
int *ipdbon;
{

#if defined(VMS) || defined(UNDERSC)
	allzmd(ipdbon,
#else
#ifdef CRAY
	ALLZMD(ipdbon,
#else
	allzmd_(ipdbon,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
ligzmt()
#else
#ifdef CRAY
LIGZMT()
#else
ligzmt_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	ligzmd(
#else
#ifdef CRAY
	LIGZMD(
#else
	ligzmd_(
#endif
#endif
	xyz.ianz,xyz.iaton);

}

#if defined(VMS) || defined(UNDERSC)
pdbzmt()
#else
#ifdef CRAY
PDBZMT()
#else
pdbzmt_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	pdbzmd(
#else
#ifdef CRAY
	PDBZMD(
#else
	pdbzmd_(
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iresid,xyz.iconn);

}

#if defined(VMS) || defined(UNDERSC)
intzmt(ispdb)
#else
#ifdef CRAY
INTZMT(ispdb)
#else
intzmt_(ispdb)
#endif
#endif
int *ispdb;
{

#if defined(VMS) || defined(UNDERSC)
	intzmd(ispdb,
#else
#ifdef CRAY
	INTZMD(ispdb,
#else
	intzmd_(ispdb,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iresid,xyz.iconn,xyz.lwrit,xyz.lring);

}

#if defined(VMS) || defined(UNDERSC)
icrcon(icrcon,isel,idisc,ndisc,nanz,ispdb)
#else
#ifdef CRAY
ICRCON(icrcon,isel,idisc,ndisc,nanz,ispdb)
#else
icrcon_(icrcon,isel,idisc,ndisc,nanz,ispdb)
#endif
#endif
int *icrcon;
int *isel;
int *idisc;
int *ndisc;
int *nanz;
int *ispdb;
{

#if defined(VMS) || defined(UNDERSC)
	icrcod(icrcon,isel,idisc,ndisc,nanz,ispdb,
#else
#ifdef CRAY
	ICRCOD(icrcon,isel,idisc,ndisc,nanz,ispdb,
#else
	icrcod_(icrcon,isel,idisc,ndisc,nanz,ispdb,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iconn,xyz.lwrit,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
calcx(ical,isel,nx)
#else
#ifdef CRAY
CALCX(ical,isel,nx)
#else
calcx_(ical,isel,nx)
#endif
#endif
int *ical;
int *isel;
int *nx;
{

#if defined(VMS) || defined(UNDERSC)
	calcd(ical,isel,nx,
#else
#ifdef CRAY
	CALCD(ical,isel,nx,
#else
	calcd_(ical,isel,nx,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iconn,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
prelea(iprel,ilead,isel,ispdb,ithree)
#else
#ifdef CRAY
PRELEA(iprel,ilead,isel,ispdb,ithree)
#else
prelea_(iprel,ilead,isel,ispdb,ithree)
#endif
#endif
int *iprel;
int *ilead;
int *isel;
int *ispdb;
int *ithree;
{

#if defined(VMS) || defined(UNDERSC)
	prelead(iprel,ilead,isel,ispdb,ithree,
#else
#ifdef CRAY
	PRELEAD(iprel,ilead,isel,ispdb,ithree,
#else
	prelead_(iprel,ilead,isel,ispdb,ithree,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iresid,xyz.iconn,xyz.lwrit);

}

#if defined(VMS) || defined(UNDERSC)
preleh(iprel,ilead,isel,ispdb,ithree)
#else
#ifdef CRAY
PRELEH(iprel,ilead,isel,ispdb,ithree)
#else
preleh_(iprel,ilead,isel,ispdb,ithree)
#endif
#endif
int *iprel;
int *ilead;
int *isel;
int *ispdb;
int *ithree;
{

#if defined(VMS) || defined(UNDERSC)
	prelehd(iprel,ilead,isel,ispdb,ithree,
#else
#ifdef CRAY
	PRELEHD(iprel,ilead,isel,ispdb,ithree,
#else
	prelehd_(iprel,ilead,isel,ispdb,ithree,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iresid,xyz.iconn,xyz.lwrit);

}

#if defined(VMS) || defined(UNDERSC)
rdbas(idebug,dfree,istats)
#else
#ifdef CRAY
RDBAS(idebug,dfree,istats)
#else
rdbas_(idebug,dfree,istats)
#endif
#endif
int *idebug;
int *dfree;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdbad(idebug,dfree,istats,
#else
#ifdef CRAY
	RDBAD(idebug,dfree,istats,
#else
	rdbad_(idebug,dfree,istats,
#endif
#endif
	xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
setis(nset,istart)
#else
#ifdef CRAY
setis(nset,istart)
#else
setis_(nset,istart)
#endif
#endif
int *nset;
int *istart;
{

#if defined(VMS) || defined(UNDERSC)
	setid(nset,istart,
#else
#ifdef CRAY
	SETID(nset,istart,
#else
	setid_(nset,istart,
#endif
#endif
	xyz.isurf,xyz.iresid,xyz.ipdbt);

}

#if defined(VMS) || defined(UNDERSC)
clkbck(istsurf,incp,ifogl)
#else
#ifdef CRAY
CLKBCK(istsurf,incp,ifogl)
#else
clkbck_(istsurf,incp,ifogl)
#endif
#endif
int *istsurf;
int *incp;
int *ifogl;
{

#if defined(VMS) || defined(UNDERSC)
	clkbcd(istsurf,incp,ifogl,
#else
#ifdef CRAY
	CLKBCD(istsurf,incp,ifogl,
#else
	clkbcd_(istsurf,incp,ifogl,
#endif
#endif
	xyz.iresid,xyz.coo);

}

#if defined(VMS) || defined(UNDERSC)
newfil(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls)
#else
#ifdef CRAY
NEWFIL(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls)
#else
newfil_(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls)
#endif
#endif
int *idebug;
int *istat;
int *inc;
int *ioadd;
int *ioatms;
int *nstrt;
int *namols;
int *nxtmf;
int *ipdbon;
int *namls;
{

#if defined(VMS) || defined(UNDERSC)
	newfid(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls,
#else
#ifdef CRAY
	NEWFID(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls,
#else
	newfid_(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls,
#endif
#endif
	xyz.iaton,xyz.iatclr,xyz.iresid);

}

#if defined(VMS) || defined(UNDERSC)
setarr(iop,iopval,ioatms)
#else
#ifdef CRAY
SETARR(iop,iopval,ioatms)
#else
setarr_(iop,iopval,ioatms)
#endif
#endif
int *iop;
int *iopval;
int *ioatms;
{

#if defined(VMS) || defined(UNDERSC)
	setard(iop,iopval,ioatms,
#else
#ifdef CRAY
	SETARD(iop,iopval,ioatms,
#else
	setard_(iop,iopval,ioatms,
#endif
#endif
	xyz.ianz,xyz.iaton,xyz.iatclr,xyz.iresid,xyz.iconn,xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
epvrml(vdwr,moddma,natoms,norbs,idops)
#else
#ifdef CRAY
EPVRML(vdwr,moddma,natoms,norbs,idops)
#else
epvrml_(vdwr,moddma,natoms,norbs,idops)
#endif
#endif
double *vdwr;
int *moddma;
int *natoms;
int *norbs;
int *idops;
{

#if defined(VMS) || defined(UNDERSC)
	epvrmd(vdwr,moddma,natoms,norbs,idops,
#else
#ifdef CRAY
	EPVRMD(vdwr,moddma,natoms,norbs,idops,
#else
	epvrmd_(vdwr,moddma,natoms,norbs,idops,
#endif
#endif
	xyz.iaton);

}

#if defined(VMS) || defined(UNDERSC)
clrcod(natorg,natoms,idebug)
#else
#ifdef CRAY
CLRCOD(natorg,natoms,idebug)
#else
clrcod_(natorg,natoms,idebug)
#endif
#endif
int *natorg;
int *natoms;
int *idebug;
{

#if defined(VMS) || defined(UNDERSC)
	clrcdd(natorg,natoms,idebug,
#else
#ifdef CRAY
	CLRCDD(natorg,natoms,idebug,
#else
	clrcdd_(natorg,natoms,idebug,
#endif
#endif
	xyz.iatclr);

}

#if defined(VMS) || defined(UNDERSC)
wrxyz(jmod)
#else
#ifdef CRAY
WRXYZ(jmod)
#else
wrxyz_(jmod)
#endif
#endif
int *jmod;
{

#if defined(VMS) || defined(UNDERSC)
	wrxyd(jmod,
#else
#ifdef CRAY
	WRXYD(jmod,
#else
	wrxyd_(jmod,
#endif
#endif
	xyz.qat);

}

#if defined(VMS) || defined(UNDERSC)
progeo(ipoints,iff,istat)
#else
#ifdef CRAY
PROGEO(ipoints,iff,istat)
#else
progeo_(ipoints,iff,istat)
#endif
#endif
int *ipoints;
int *iff;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	proged(ipoints,iff,istat,
#else
#ifdef CRAY
	PROGED(ipoints,iff,istat,
#else
	proged_(ipoints,iff,istat,
#endif
#endif
	geopntr.formax,geopntr.forrms,geopntr.dismax,geopntr.disrms,
	geopntr.epoints,geopntr.isav,xyz.coo,xyz.ianz);

}

#if defined(VMS) || defined(UNDERSC)
wrcart(iun,dopdb,idogau,ipdbwh)
#else
#ifdef CRAY
WRCART(iun,dopdb,idogau,ipdbwh)
#else
wrcart_(iun,dopdb,idogau,ipdbwh)
#endif
#endif
int *iun;
int *dopdb;
int *idogau;
int *ipdbwh;
{

#if defined(VMS) || defined(UNDERSC)
	wrcard(iun,dopdb,idogau,ipdbwh,
#else
#ifdef CRAY
	WRCARD(iun,dopdb,idogau,ipdbwh,
#else
	wrcard_(iun,dopdb,idogau,ipdbwh,
#endif
#endif
	geopntr.epoints,
	xyz.coo,xyz.qat,xyz.ianz,xyz.iaton,xyz.iresid,xyz.iconn,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
dyncpmd(ipoints)
#else
#ifdef CRAY
DYNCPMD(ipoints)
#else
dyncpmd_(ipoints)
#endif
#endif
int *ipoints;
{

#if defined(VMS) || defined(UNDERSC)
	dyncpdd(ipoints,
#else
#ifdef CRAY
	DYNCPDD(ipoints,
#else
	dyncpdd_(ipoints,
#endif
#endif
	geopntr.isav,geopntr.epoints);

}

#if defined(VMS) || defined(UNDERSC)
plvend(iun,loop)
#else
#ifdef CRAY
PLVEND(iun,loop)
#else
plvend_(iun,loop)
#endif
#endif
int *iun;
int *loop;
{

#if defined(VMS) || defined(UNDERSC)
	plvedd(iun,loop,
#else
#ifdef CRAY
	PLVEDD(iun,loop,
#else
	plvedd_(iun,loop,
#endif
#endif
	geopntr.epoints);

}

/* END shadow C routines for Fortran routines to pass coordinate pointers */

#if defined(VMS) || defined(UNDERSC)
qupd()
{
    int oglon;

    rsold = RESUND;
    oglon = *fancy;
    if (denmode) oglon = *ifdogl;
#ifdef DOGL
    if (oglon && has_opengl) {
	if (update_res > 0) {
	   ogres(update_res,1,1);
        } else {
           if (update_model || *irtcel) ogind();
	   else dispsf();
	}
        if (dogif) {
           picnum++;
           if (picnum < *picmax) {
		glXWaitGL();
		sprintf(stemp, "%s%03d.gif",GifFile,picnum);
		WOGLGIF(stemp);
		glXSwapBuffers(display, win);
	   }
	}
    } else {
#endif
      if (!denmode) {
	if (*persp) {
	   plmolp();
	} else {
	   plmol();
	}
      }
      if (*logo) dlogo();
      doexp();
#ifdef DOGL
    }
#endif

}
#else
#ifdef CRAY
QUPD()
{
    int oglon;

    oglon = *fancy;
    if (denmode) oglon = *ifdogl;
#ifdef DOGL
    if (oglon && has_opengl) {
	if (update_res > 0) {
	   ogres(update_res,1,1);
        } else {
           if (update_model || *irtcel) ogind();
	   else dispsf();
	}
        if (dogif) {
           picnum++;
           if (picnum < *picmax) {
		glXWaitGL();
		sprintf(stemp, "%s%03d.gif",GifFile,picnum);
		WOGLGIF(stemp);
		glXSwapBuffers(display, win);
	   }
	}
    } else {
#endif
      if (!denmode) {
	if (*persp) {
	   PLMOLP();
	} else {
	   PLMOL();
	}
      }
      if (*logo) DLOGO();
      DOEXP();
#ifdef DOGL
    }
#endif
}

#else
qupd_()
{
    int oglon;

    oglon = *fancy;
    if (denmode) oglon = *ifdogl;
#ifdef DOGL
    if (oglon && has_opengl) {
	if (update_res > 0) {
	   ogres(update_res,1,1);
        } else {
           if (update_model || *irtcel) ogind(); 
	   else dispsf();
	}
        if (dogif) {
           picnum++;
           if (picnum < *picmax) {
		glXWaitGL();
		sprintf(stemp, "%s%03d.gif",GifFile,picnum);
		WOGLGIF(stemp);
		glXSwapBuffers(display, win);
	   }
	}
    } else {
#endif
      if (!denmode) {
	if (*persp) {
	   plmolp_();
	} else {
	   plmol_();
	}
      }
      if (*logo) dlogo_();
      doexp_();
#ifdef DOGL
    }
#endif
}
#endif
#endif

void update_struct()
{
#if defined(VMS) || defined(UNDERSC)
   qupd();
#else
#ifdef CRAY
   QUPD();
#else
   qupd_();
#endif
#endif
}

SetSurfColor(i,j)
int i;
int j;
{
#ifdef DOGL
   diffuseColor[i][0] = ((GLfloat) colorr[j]) / 65535.0 ;
   diffuseColor[i][1] = ((GLfloat) colorg[j]) / 65535.0 ;
   diffuseColor[i][2] = ((GLfloat) colorb[j]) / 65535.0 ;
#endif
}

sizz(i,j,iset)
int i;
int j;
int iset;
{

 *(zmptr.iz + (i*4) + j) = iset;

}

void dummyproc();

static int *Snstr;
#ifdef VMS
static struct dsc$descriptor_s *Sstr;
#else
#ifdef CRAY
static _fcd Sstr;
#else
static char *Sstr;
#endif
#endif

static int *scndcol;
/*static int scndcol[4] = {3,9,10,8};*/

void presetp()
{
        int iop;

	if (NHetAtm) {

	    if (!calfptr->issdon) {
#if defined(VMS) || defined(UNDERSC)
		ribbs();
#else
#ifdef CRAY
		RIBBS();
#else
		ribbs_();
#endif
#endif
	    }

            for (iop=0;iop<4;iop++) {
		if (calfptr->ihet[iop]) {
#if defined(VMS) || defined(UNDERSC)
                acthel(&ONE,&iop,&scndcol[iop],&ZERO);
#else
#ifdef CRAY
                ACTHEL(&ONE,&iop,&scndcol[iop],&ZERO);
#else
                acthel_(&ONE,&iop,&scndcol[iop],&ZERO);
#endif
#endif
		}
	    }
	}
}

void preset()
{
        int i,iop;

	if (NHetAtm) {

	    if (!calfptr->issdon) {
#if defined(VMS) || defined(UNDERSC)
		ribbs();
#else
#ifdef CRAY
		RIBBS();
#else
		ribbs_();
#endif
#endif
         	for (i=0;i<4;i++) calfptr->ihet[i] = 0;
	    }

/* red 1, orange 2, green 3 (helix), ... purple 9 (beta), grey 8 (coil) */				 
#if defined(VMS) || defined(UNDERSC)
	    actcal(&ZERO);
#else
#ifdef CRAY
	    ACTCAL(&ZERO);
#else
	    actcal_(&ZERO);
#endif
#endif
	    for (i=0; i < calfptr->ncalf; i++) 
		calfptr->reson[i] = 0;
	    for (i=0; i < *xyz.iatoms; i++ ) xyz.iaton[i] = 0;
	    update_sel = 1;

	    for (i=0; i < MXHETA; i++) 
		calfptr->ihet[i] = 0;

            for (iop=0;iop<4;iop++) {
		calfptr->ihet[iop] = 1;
#if defined(VMS) || defined(UNDERSC)
                acthel(&ONE,&iop,&scndcol[iop],&ZERO);
#else
#ifdef CRAY
                ACTHEL(&ONE,&iop,&scndcol[iop],&ZERO);
#else
                acthel_(&ONE,&iop,&scndcol[iop],&ZERO);
#endif
#endif
		if (iop == 0 || iop == 1) {

		   if (iop == 0) {
			SetSurfColor(0,scndcol[iop]);
		   } else if (iop == 1) {
		      for (i=0; i < 4; i++) 
			SetSurfColor(4+i,scndcol[iop]);
		   }
		   for (i=0; i < 4; i++) 
			SSon[iop*4+i] = 1;

		} else if (iop == 2 || iop == 3) {

		   SSon[iop+6] = 1;
		   SetSurfColor(iop+6,scndcol[iop]);
		}
	    }
	}
}

void NewDir()
{
char* p;
char  tmpdir[MAXDIRLEN];

	seldir = dirlist.select;
	if (seldir > ndirs - 1) seldir = ndirs - 1;

	if (strcmp(dirs[seldir],"..") == 0) {
	    strcpy(tmpdir,lastdir);
	    if (lastdir[0] != '/') {

		if (getcwd(lastdir,MAXDIRLEN) == NULL) 
		   strcpy(lastdir,"./");
		if (lastdir[strlen(lastdir)-1] != '/') 
		   strcat(lastdir,"/");

		p = tmpdir;
		if (p[0] == '.') p++;
		if (p[0] == '/') p++;
		strcat(lastdir,p);
	    }

	    if (lastdir[strlen(lastdir)-1] == '/') 
		lastdir[strlen(lastdir)-1] = '\0';

	    if ((p = strrchr(lastdir, '/'))) {
		p++; *p = '\0';
	    }

	} else {
	    if (strcmp(dirs[seldir],".") != 0) {
		strcat(lastdir,dirs[seldir]);
		strcat(lastdir,"/");
	    }
	}
}

#if defined(VMS) || defined(UNDERSC)
xwin(x, y, icomm, str, nstr, inct, incp)
#else
#ifdef CRAY
XWIN(x, y, icomm, str, nstr, inct, incp)
#else
xwin_(x, y, icomm, str, nstr, inct, incp)
#endif
#endif

float *x;
float *y;
int *icomm;
#ifdef VMS
struct dsc$descriptor_s *str;
#else
#ifdef CRAY
_fcd str;
#else
char *str;
#endif
#endif
int *nstr;
int *inct;
int *incp;


{

  int done;
  int i,j;

  float Arg1;
  float Arg2;
  int Command;

  if (*icomm == 15 || *icomm == 0) update_model = 1;

  Arg1 = *x;
  Arg2 = *y;
  Command = *icomm;
  if (Command == DenWindow || Command == MolWindow) {
     Sstr = str; Snstr = nstr; Sinct = inct; Sincp = incp;
  }


  switch(Command) {
  case DenWindow : 
  {




    while(XCheckTypedWindowEvent(display,win,Expose,&report));

    if ( DowinC ) {
       DirBox(winC,1);    
       DowinC = 0;
       ZoomEnable = True;
       ZoomSelection = False;
       xoff = 0.0;
       yoff = 0.0;
       scale = 1.0;
       XFlush(display);
    }
    if ( DoactC ) {actde(*inct,*incp,1);DoactC = 0;}

    done = 0;
    *inct = 0;
    *incp = 0;
    if (hold) {
       XSync(display, False);
       if (XPending(display)>0){
          if (XCheckMaskEvent(display,ButtonReleaseMask,&event))
                        { hold = 0; goto XXLOOP;}
       }
       if (!*ifdogl) {
	   *inct = holdt;
	   *incp = holdp;
	   count = 0; scount = 0;
	   return(0);
       } else {
#if defined(VMS) || defined(UNDERSC)
           mktrn(&holdt,&holdp);
#else
#ifdef CRAY
           MKTRN(&holdt,&holdp);
#else
           mktrn_(&holdt,&holdp);
#endif
#endif
	   if (update_model) ogind();
	   else dispsf();
       }
    }
XXLOOP:

    while (!done) {
  

	XNextEvent(display, &event);

        switch (event.type) {

           case KeyPress:    {
              XKeyEvent *key_event = (XKeyEvent *) &event;
              char buf[1];  KeySym ks;  XComposeStatus status;  int stlen;

              stlen = XLookupString(key_event,buf,1,&ks,&status);
	      /*if (!stlen) break;*/

              for (i=0; i<NQBOX; i++) 
		if (key_event->window == qboxes[i].win && qboxes[i].active) 
		   if (KeyChk(&qboxes[i],buf[0])) 
		       if (key_event->window != Fwin) {
				if (*Sinct != 150) count = 0; scount = 0;
				return(0);
			}

              /* do non-character processing (arrow-keys, that is) */
              if (key_event->window == win || key_event->window == winMC) {
                 if      (ks==XK_Left  || ks==XK_KP_4)
                   { *inct = 1; }
                 else if (ks==XK_Right || ks==XK_KP_6)
                   { *inct = -1; }
                 else if (ks==XK_Up    || ks==XK_KP_8)
                   { *incp = -1; }
                 else if (ks==XK_Down  || ks==XK_KP_2)
                   { *incp = 1; }
                 else if (buf[0]=='i')
                   { *inct = 30;
                     *incp = 1; }
                 else if (buf[0]=='d')
                   { *inct = 30;
                     *incp = -1; }
                 else if (buf[0]=='m')
                   { *inct = 45; }
                 else if (buf[0]=='c')
                   { *inct = 80; }
                 else if (buf[0]=='e')
                   { *inct = 85; }
/*
                 else if (buf[0]=='3')
                   { *inct = 90; }
                 else if (buf[0]=='p')
                   { *inct = 150; }
                 else if (buf[0]=='t') {
                   { sprintf(stemp,"Orbital number (1-%d)? ",norbs);
		     qboxstr(&qboxes[QORB],NULL,1,0,-1,DEFQX,DEFQY,
		     QBOXWIDE,QBOXHIGH, 0,stemp,NULL,0,1,160,dummyproc);
		    }
		 }
*/
                 else if (buf[0]=='n')
                   { *inct = 170; }
                 else if (buf[0]=='b')
                   { *inct = 180; }
                 else if (buf[0]=='a')
                   { *inct = 190; }
                 else if (buf[0]=='o')
                   { *inct = 200; }
                 else if (buf[0]=='r')
                   { *inct = 210; }
                 else if (buf[0]=='u')
		   { OnTop(); }
                 if ((*ifdogl && has_opengl) && key_event->window == win) 				{Key(buf[0]);}
                 cnt = 0;
                 count = 0;
                 scount = 0;
                 if (!(*ifdogl && has_opengl)) return(0);
              }
           }
           break;

           case ButtonPress: {

              if(DEBUG)fprintf(stderr,"ButtonPress\n");

              if(event.xbutton.window == win && event.xbutton.button == 2
                 && ZoomEnable && !do3dx && !*ifdogl) {
        
                 ZoomEnable = False;
                 ZoomSelection = True;
                 MotionCount = 0; 
         
                 XDefineCursor(display, win, ZoomCursor);
                 XSetFunction(display, gc, GXxor);
                 XSetForeground(display, gc, colors[11]);
                 ZoomX1 = event.xbutton.x;
                 ZoomY1 = event.xbutton.y;
                 ZoomW = 1;
                 ZoomH = 1;
                 XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);
         
              } else if(event.xbutton.window == win && event.xbutton.button == 2
                      && !ZoomEnable && !ZoomSelection && !*ifdogl) {

                 ZoomEnable = True;
                 scale = 1.0;
                 xoff = 0.0;
                 yoff = 0.0;

                 RedrawWin();
              } else if(event.xbutton.window == win && 
                      event.xbutton.button == 3) {

                 DirBox(winC,1);
                 if (qbcomm) DirBox(COMMwin,1);
                 if (DoEig) DirBox(EBox,1);
                 for (i=0; i<NQBOX; i++) 
   		   if (qboxes[i].pop && qboxes[i].active) 
			XMapRaised(display,qboxes[i].win);

              }

              if (event.xbutton.window == EBox) {
	       if (PressList(&elist,event.xbutton.x, event.xbutton.y)) {
		 update_model = 1;
		 *ivtwo = -1;
		 count = 0; scount = 0;
                 *inct = 160; 
		 if (*iuhf && ibeta) {
			*incp = -1*(elist.select+1);
		 } else {
			*incp = elist.select+1;
		 }
                 return(0);
	       }
	      } else if(event.xbutton.window == win &&
                      event.xbutton.button == 1 ) {
              
                 int curtx = event.xbutton.x;
                 int curty = event.xbutton.y;
                 float dangy,tsqx,tsqy;

                 if (!ZoomEnable && *dospa  && !*ifdogl) {
                    ZoomEnable = True;
                    scale = 1.0;
                    xoff = 0.0;
                    yoff = 0.0;
                    return(0);
                 }

		 if (*ifdogl) {
		    moving = 1;
		    startx = event.xbutton.x;
		    starty = event.xbutton.y;
		    btype = 0;
		    if (event.xbutton.state & ShiftMask) btype = 1;
		    if (event.xbutton.state & ControlMask) btype = 2;
		    if ((event.xbutton.state & ControlMask) 
			  && (event.xbutton.state & ShiftMask)) btype = 3;
		    if (has_opengl) 
			  moused(event.xbutton.button,event.xbutton.state, 
					  event.xbutton.x, event.xbutton.y);
		    break;

                 } else {
		   hold = 1;
		   holdt = 0;
		   holdp = 0;
                   tsqx = (int) (width / 2 - curtx);
                   tsqy = (int) (height / 2 - curty);
                   cnt = 0;
                   count = 0;
                   scount = 0;
                   if (tsqx == 0 && tsqy == 0) return(0);
                   if (tsqx == 0 && tsqy > 0) { *incp = -1; holdp = *incp; return(0);}
                   if (tsqx == 0 && tsqy < 0) { *incp =  1; holdp = *incp; return(0);}
                   if (tsqy == 0 && tsqx > 0) { *inct = -1; holdt = *inct; return(0);}
                   if (tsqy == 0 && tsqx < 0) { *inct =  1; holdt = *inct; return(0);}
                   dangy = tsqy / tsqx;
                   if (tsqx > 0) {
                    if (dangy <= 1 && dangy >= -1) {
                        *inct = 1; holdt = *inct; return(0);}
                    else if (dangy > 1) {
                        *incp = 1; holdp = *incp; return(0);}
                    else { *incp = -1; holdp = *incp; return(0);}
                   }
                   if (tsqx < 0) {
                    if (dangy <= 1 && dangy >= -1) {
                        *inct = -1; holdt = *inct; return(0);}
                    else if (dangy > 1) {
                        *incp = -1; holdp = *incp; return(0);}
                    else { *incp = 1; holdp = *incp; return(0);}
                   }
                 }
              }


              if (event.xbutton.window == QBox)  {
		for (j=0; j<NQBOX; j++) 
		    if (qboxes[j].win == QBox && qboxes[j].active) break;
		i = Clickwin(qboxclose,2,event.xbutton.x,event.xbutton.y,1);
		if (i == 0) {
		   if (KeyChk(&qboxes[j],'\012')) return(0);
		} else if (i == 1) {
		   XDestroyWindow(display,QBox);
		   XSync(display, False);
		   qboxup = 0;
		}
	      }

	      if (event.xbutton.button  == 3) 
			QBoxPaste(event.xbutton.window,qboxes,NQBOX);

              if (event.xbutton.window == MAPwin) {
		 i = Clickwin(mapbut,NBUTSM,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsMAP(i)) return(0);
		 } else {
			i = ClickBox(&qboxes[QVFILE],8,
				event.xbutton.x,event.xbutton.y);
			if (i>=0) {
				for (j=0; j<8; j++) qboxes[QVFILE+j].active = 0;
				qboxes[QVFILE+i].active = 1;
				RedrawMAP();
			}
		 }
	      }

              if (event.xbutton.window == VIRwin) {
		 i = Clickwin(virbut,2,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsVIR(i)) return(0);
		 } else {
			i = ClickBox(&qboxes[QSVFILE],2,
				event.xbutton.x,event.xbutton.y);
			if (i>=0) {
				for (j=0; j<2; j++) 
					qboxes[QSVFILE+j].active = 0;
				qboxes[QSVFILE+i].active = 1;
				RedrawVIR();
			}
		 }
	      }

              if (event.xbutton.window == winC) {
		 int doret = 1;
		 *ivtwo = -1;
                 i=Clickwin(dbut,NBUTTS,event.xbutton.x, event.xbutton.y,1);

		 update_model = 1;
                 if (i>=0) {
                 switch (i) {
                 case BPSI: 
			update_model = 0;
			doret = 0;
			if (TogBut(&dbut[BPSI])) {
			   XDestroyWindow(display,EBox);
			   *inct = 160; *incp = 0;
			   DoEig = 0;
			}
			else {
			   LSSTRU List;
			   List.list = alphbet; List.nents = 2;
			   if (*iuhf) {
				if (DoPopUp(winC,dbut[BPSI].x+1,
					dbut[BPSI].y+BUTTH,&List,&ibeta,0) == -1) break;
			   }
			   EBox = CreateWindow("Molden Orbital Select","-80-80",QBOXWIDE,QBOXRF,infobg,infofg,(Window)0);
			   XSelectInput(display, EBox, ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask);
			   if ((*iuhf && !ibeta) || !*iuhf) 
      				DefList(&elist,EBox,DIRX,DIRY,DIRW,DIRH,
				" Nr.        Eigenvalue   Occupation",
				NFLS,NULL,dorb.eiga,dorb.focc,dorb.ncols);
			   if (*iuhf && ibeta) 
      				DefList(&elist,EBox,DIRX,DIRY,DIRW,DIRH,
				" Nr.        Eigenvalue   Occupation",
				NFLS,NULL,dorb.eigb,dorb.focb,dorb.ncolb);
			   XMapWindow(display,EBox);
			   DoEig = 1;
			}
			break;
                 case BHOMO: *inct = 230; break;
                 case BLUMO: *inct = 240; break;
                 case BNDEN: if (*iuhf)
				{LSSTRU List;
				 List.list = spdopt; List.nents = 2;
				 if (DoPopUp(winC,dbut[BNDEN].x+1,
					dbut[BNDEN].y+BUTTH,&List,ispd,0) == -1) break;
				}
			     *inct = 170;
			     break;
                 case BLAPL: *inct = 171; break;
                 case BBONDS: *inct = 180; break;
                 case BATOM: *inct = 190; break;
                 case BOVRLP: *inct = 200; break;
                 case BELPOT: {
				int itmp;
				LSSTRU List;
				List.list = pots2; List.nents = 3;
				if (DoPopUp(winC,dbut[BELPOT].x+1,
					dbut[BELPOT].y+BUTTH,&List,&itmp,0) == -1) break;
				*inct = 350+itmp;
				break;}
                 case BMAXMIN: *inct = 360; break;
                 case BPOST:   {
				LSSTRU List;
				if (do3dx) {
			           if (DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
				"Postcript is not supported vor this drawing mode",0)) {}
				   break;
				}
				List.list = postopt; List.nents = 2;
				if (DoPopUp(winC,dbut[BPOST].x+1,
					dbut[BPOST].y+BUTTH,&List,icolps,0) == -1) break;
				qboxstr(&qboxes[QPOST],NULL,1,0,-1,DEFQX,DEFQY,
					QBOXWIDE,QBOXHIGH,0,"Filename ? ",NULL,
					0,0,150,dummyproc);
				}
				break;
                 case BMOLMOD: *inct = 75; DirBox(winC,0);
                                DowinMC =1;DoactMC = 1;
				denmode = 0;
		 		empty_model();
				update_model = 1;
				ZoomEnable = True;
				ZoomSelection = False;
				xoff = 0.0;
				yoff = 0.0;
				scale = 1.0;
				if (qbcomm) {
			   	   TogUp(&dbut[BCOMM]);
			   	   qbcomm = 0;
			   	   XUnmapWindow(display,COMMwin);
				}
		 		if (DoEig) {
				    TogUp(&dbut[BPSI]);
				    XDestroyWindow(display,EBox);
				    DoEig = 0;
				}
                                break;
                 case BEUCL: *inct = 85; do3dx = 0; *do3d = 0;*dospa = 0;
                             ActBut(&dbut[BCONT],1);
                             ActBut(&dbut[BINCRS],1);
                             ActBut(&dbut[BDECRS],1);
                             ActBut(&dbut[BSTEP],1);
                             ActBut(&dbut[BCUT],1);
                             ActBut(&dbut[BFILL],0);
                             DrwBut(&dbut[BCONT]);
                             DrwBut(&dbut[BFILL]);
                             DrwBut(&dbut[BSTEP]);
                             DrwBut(&dbut[BCUT]);
                             DrwBut(&dbut[BINCRS]);
                             DrwBut(&dbut[BDECRS]);
#ifdef DOGL
			     if (*ifdogl) {
				*ifdogl = 0;
				TogUp(&dbut[BOGL]);
			     } 
#endif
                             break;
                 case B3D:   
			     *inct = 90; do3dx = 0; *do3d = 1; *dospa = 0;
                             ActBut(&dbut[BCONT],1);
                             ActBut(&dbut[BINCRS],1);
                             ActBut(&dbut[BDECRS],1);
                             ActBut(&dbut[BSTEP],1);
                             ActBut(&dbut[BCUT],1);
                             ActBut(&dbut[BFILL],0);
                             DrwBut(&dbut[BCONT]);
                             DrwBut(&dbut[BFILL]);
                             DrwBut(&dbut[BSTEP]);
                             DrwBut(&dbut[BCUT]);
                             DrwBut(&dbut[BINCRS]);
                             DrwBut(&dbut[BDECRS]);
#if defined(VMS) || defined(UNDERSC)
			     bldlst();
#else
#ifdef CRAY
			     BLDLST();
#else
			     bldlst_();
#endif
#endif
			     if (*ifdogl) doret = 0;
                             break;
                 case B3DX:  
			     *inct = 91; do3dx = 1; *do3d = 0; *dospa = 0;
                             ActBut(&dbut[BINCRS],1);
                             ActBut(&dbut[BDECRS],1);
                             ActBut(&dbut[BCONT],0);
                             ActBut(&dbut[BFILL],0);
                             ActBut(&dbut[BSTEP],0);
                             ActBut(&dbut[BCUT],0);
                             DrwBut(&dbut[BCONT]);
                             DrwBut(&dbut[BFILL]);
                             DrwBut(&dbut[BSTEP]);
                             DrwBut(&dbut[BCUT]);
                             DrwBut(&dbut[BINCRS]);
                             DrwBut(&dbut[BDECRS]);
#if defined(VMS) || defined(UNDERSC)
			     bldlst();
#else
#ifdef CRAY
			     BLDLST();
#else
			     bldlst_();
#endif
#endif
			     if (*ifdogl) doret = 0;
                             break;
                 case BSRF2: 
			     if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
				"Go to Mol. Mode to view this\nUse the Surface icon to save the surface",0)) {
				}
			     linmax = 2;
                 case BVRML2:
			     if ((do3dx || *do3d) && i == BVRML2 && ! *dospa) {
				int optie;
				LSSTRU List;
				List.list = vrml2dopt; List.nents = 2;

				if (DoPopUp(winC,dbut[BVRML2].x+1,
					dbut[BVRML2].y+BUTTH,&List,&optie,0) == -1) break;
				if (optie) {
				   *inct = 651;
				} else {
				   qboxstr(&qboxes[QVRML],NULL,1,0,-1,
				   DEFQX,DEFQY, QBOXWIDE,QBOXHIGH,0,
				   "VRML Filename ? ",NULL,0,0,
				   650,dummyproc);
				}
				break;
			     }
                 case BSPACE: 
			     *ivtwo = -1;
/* check */
			     if (i == BVRML2) {
				LSSTRU List; LSSTRU MList;
				if (!*ipsi) {
				   MList.list = denopt; MList.nents = 2;
				   if (DoPopUp(winC,dbut[BVRML2].x-25,
					dbut[BVRML2].y+BUTTH,&MList,mapit,0) == -1) break;
				}
				if (! *mapit) {
				   List.list = vrmlopt; List.nents = 4;
				   if (DoPopUp(winC,dbut[BVRML2].x+1,
					dbut[BVRML2].y+BUTTH,&List,ivtwo,0) == -1) break;
				}
			      }
			     do3dx = 0; *do3d = 0;
                             ActBut(&dbut[BCONT],0);
                             ActBut(&dbut[BINCRS],0);
                             ActBut(&dbut[BDECRS],0);
                             ActBut(&dbut[BSTEP],0);
                             ActBut(&dbut[BCUT],0);
                             ActBut(&dbut[BFILL],1);
                             DrwBut(&dbut[BCONT]);
                             DrwBut(&dbut[BFILL]);
                             DrwBut(&dbut[BSTEP]);
                             DrwBut(&dbut[BCUT]);
                             DrwBut(&dbut[BINCRS]);
                             DrwBut(&dbut[BDECRS]);
			     if (*mapit) {
				InitMAP();
			     } else {
				if (i == BVRML2) 
				   InitVIR();
				else if (i == BSPACE && 
				(*natoms || (*cubetyp == 2 || *cubetyp == 3))) {
		    		   qboxstr(&qboxes[QSPAC],NULL,1,0,-1,DEFQX,DEFQY,
				   QBOXWIDE,QBOXHIGH, 0,"Contour Value ? ",NULL,
				   0,3,92,dummyproc);
				   doret = 0;
				}
				else if (i == BSPACE) *inct = 92;
				else if (i == BSRF2) *inct = 94;
			     }
                             break;
                 case BFILL : *inct = 93;TogBut(&dbut[BFILL]);break;
                 case BINCRS: *inct = 30;*incp = 1;break;
                 case BDECRS: *inct = 30;*incp = -1;break;
                 case BCONT:  *inct = 80;TogBut(&dbut[BCONT]); break;
                 case BMOL:   *inct = 45;TogBut(&dbut[BMOL]); break;
                 case BCOMM: 
			*ivtwo = -1;
			if (qbcomm) {
			   TogUp(&dbut[BCOMM]);
			   qbcomm = 0;
			   XUnmapWindow(display,COMMwin);
			}
			else {
			   TogDown(&dbut[BCOMM]);
			   XMapWindow(display,COMMwin); qbcomm = 1;
			   qboxstr(&qboxes[QCOMM],&COMMwin,1,0,-1,DEFQX,DEFQY,
				QBOXWIDE,QBOXHIGH,0,"Command Line ? ",NULL,
				0,0,220,dummyproc);
			}
			if (*ifdogl) doret = 0;
			break;
                 case BQUIT: {
			if (!DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
					" Are you sure to quit?  ",1)) {
                          XFreeGC(display, gc);
                          XCloseDisplay(display);
		          FreeAll();
                          *inct = 15; 
			} }
			break;
                 case BCUBE: 
			{int irwopt; LSSTRU List;
			 List.list = rwopt; List.nents = 2;
			 if (DoPopUp(winC,dbut[BCUBE].x+1,
				dbut[BCUBE].y+BUTTH-30,&List,&irwopt,0) == -1) break;
			 if (irwopt) {
			    qboxstr(&qboxes[QCUBE],NULL,1,0,-1,DEFQX,DEFQY,
				QBOXWIDE,QBOXHIGH,0,"Filename ? ",NULL,
				0,0,282,dummyproc);
			 } else {
			    List.list = cubeopt; List.nents = 4;
			    if (DoPopUp(winC,dbut[BCUBE].x+1,
				dbut[BCUBE].y+BUTTH-30,&List,cubetyp,0) == -1) break;
			    *do3d = 0; do3dx = 0;
			    qboxstr(&qboxes[QCUBE],NULL,1,0,-1,DEFQX,DEFQY,
				QBOXWIDE,QBOXHIGH,0,"Filename ? ",NULL,
				0,0,281,dummyproc);
			 }
        		 XSync(display, False);
			}
			break;
                 case BOGL: 
#ifdef DOGL
			if (*ifdogl) {
			   *ifdogl = 0;
			   TogUp(&dbut[BOGL]);
			} else {
			   if (has_opengl) {
			      *ifdogl = 1;
			      TogDown(&dbut[BOGL]);
			      if (!do3dx && !*do3d && !*dospa) *do3d = 1;
			      dispsf();
			   }
			}
			doret = 1;
#endif
			break;
                 case BORI: *inct = 210; TogBut(&dbut[BORI]); break;
                 case BSTEP: {
		      qboxstr(&qboxes[QSTEP],NULL,1,0,-1,DEFQX,DEFQY,
			QBOXWIDE,QBOXHIGH,0,"Step ? ",NULL,0,3,250,
				dummyproc);
		      break;}
                 case BCUT: {
		      qboxstr(&qboxes[QCUT],NULL,1,0,-1,DEFQX,DEFQY,
			QBOXWIDE,QBOXHIGH,0,"Cut (0.0 > cut <= 1.0) ? ",NULL,
			0,3,260,dummyproc);
		      break;}
                 case BWRBAS: *inct = 270; break;
                 case BRDBAS:  if (*dospa) {
				 LSSTRU List;
				 List.list = readgrd; List.nents = 2;
				 if (DoPopUp(winC,dbut[BRDBAS].x+1,
					dbut[BRDBAS].y+BUTTH,&List,incp,0) == -1) break;
				}
				*inct = 280;
				break;
                 }
                 cnt = 0;
                 count = 0;
                 scount = 0;
                 if (doret) return(0);
                 }
              }
 
           }
           break;


           case MotionNotify: {


              if(DEBUG)fprintf(stderr,"MotionNotify\n");

	      SetExplButton(event.xmotion.window,
		event.xmotion.x,event.xmotion.y);

              if(event.xmotion.window == win && ZoomSelection) {
                 int NewX, NewY;
   
   
                 while(XCheckTypedWindowEvent(display, win, MotionNotify,
                                        &event));
   
                 MotionCount++;

                 XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);
   
                 /* get the location of the pointer */
   
                 NewX = event.xmotion.x;
                 NewY = event.xmotion.y;
                                                                                   
                 ZoomX2 = MAXI(ZoomX1, NewX);
                 ZoomY2 = MAXI(ZoomY1, NewY);
                 ZoomW = MAXI(ABS(ZoomX2 - ZoomX1),1);
                 ZoomH = MAXI(ABS(ZoomY2 - ZoomY1),1);
                 XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);

              } /* end ZoomSelection */
              if (event.xmotion.window == win && *ifdogl && (moving || gmoving)) {
	        /*update_model = 0;*/
		if (XCheckMaskEvent(display,ButtonReleaseMask,&event)) {
		   if (has_opengl) motion(event.xmotion.x, event.xmotion.y, 1);
		   moving = 0;
		} else {
		   while (XCheckMaskEvent(display,ButtonMotionMask,&event));
		   *incp = (event.xmotion.x - startx);
		   if (btype == 0) { 
			*inct = 421;
		   } else if (btype == 1) {
			*inct = 415;
		   } else if (btype == 2) {
			*inct = 417;
		   } else if (btype == 3) {
			*inct = 422;
		   }
#if defined(VMS) || defined(UNDERSC)
		   mktrn(inct,incp);
#else
#ifdef CRAY
        	   MKTRN(inct,incp);
#else
        	   mktrn_(inct,incp);
#endif
#endif
		   *incp = (event.xmotion.y - starty);
		   if (btype == 0) { 
			*inct = -421;
		   } else if (btype == 1) {
			*inct = 416;
		   }

#if defined(VMS) || defined(UNDERSC)
		   mktrn(inct,incp);
                   if (*ifdogl) motion(event.xmotion.x, event.xmotion.y, 0);
		   else qupd();
#else
#ifdef CRAY
        	   MKTRN(inct,incp);
                   if (*ifdogl) motion(event.xmotion.x, event.xmotion.y, 0);
		   else QUPD();
#else
        	   mktrn_(inct,incp);
                   if (*ifdogl) motion(event.xmotion.x, event.xmotion.y, 0);
		   else qupd_();
#endif
#endif
		   startx = event.xmotion.x;
		   starty = event.xmotion.y;
		   *inct = 0;
		   XFlush(display);
		   XSync(display, False);
                }
	      } 
           } /* end MotionNotify */
           break;


           case ButtonRelease: {


              if(DEBUG)fprintf(stderr,"ButtonRelease\n");

              if (!*ifdogl && event.xbutton.window == win) {
		 moving = 0;
		 gmoving = 0;
	      }

              if (event.xbutton.window == win && 
		  (event.xbutton.button == 1 || event.xbutton.button == 2) &&
                  !ZoomSelection ) moving = 0;

              if(event.xbutton.window == win && event.xbutton.button == 2 
                 && ZoomSelection ) {

                 ZoomSelection = False;
                 XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);
                 XSetFunction(display, gc, GXcopy);
                 XUndefineCursor(display, win);


                 ZoomX2 = event.xbutton.x;
                 ZoomY2 = event.xbutton.y;
                
                 if (MotionCount >=3 ) {

                    scale   = height*1.0 /MAXI(ABS(ZoomY2 - ZoomY1),1);
                    xoff = ZoomX1*1.0 / height;
                    yoff = ZoomY1*1.0 / height;

                    RedrawWin();
                 }
                 else
                 {ZoomEnable = True;}



              } /* end zoom */

              if (*ifdogl && event.xbutton.window == win) {
		 mouseu(event.xbutton.button,event.xbutton.state, event.xbutton.x, event.xbutton.y);
                 dispsf();
		 break;
	      }

           } /* end ButtonRelease */
           break;
                                                                                
  	
	   case ClientMessage: {
		Atom proto, delwin;
		XClientMessageEvent *client_event = 
			(XClientMessageEvent *) &event;

		proto = XInternAtom(display, "WM_PROTOCOLS", False);
		delwin = XInternAtom(display, "WM_DELETE_WINDOW", False);

		if (client_event->message_type == proto &&
		    client_event->data.l[0] == delwin) {
		    if (client_event->window == COMMwin) {
			if (qbcomm) {
			   TogUp(&dbut[BCOMM]);
			   qbcomm = 0;
			   XUnmapWindow(display,COMMwin);
			}
		    } else if (client_event->window == EBox) {
			if (DoEig) {
			   TogUp(&dbut[BPSI]);
			   DoEig = 0;
			   XUnmapWindow(display,EBox);
			}
		    } else if (client_event->window == QBox) {
			XDestroyWindow(display,QBox);
			XSync(display, False);
		        qboxup = 0;
		    }
		}
	   }
	   break;

           case Expose: {


              if(DEBUG)fprintf(stderr,"Expose\n");

        /* if the window doesn't do intelligent redraw, drop all-1 exposes */
         if (event.xexpose.count>0 && event.xexpose.window != win) break;


              if (event.xexpose.window == win && !ZoomSelection && !*ifdogl) {
                   if (!CheckForConfig()) {
                       if ( molback == molcur) {
                          XCopyArea(display,molcur,win,gc,0,0,width,height,0,0);
                       }
                       else {
                          RedrawWin();
                       }
                   }
              }
              else
              {
                   if (event.xexpose.window == winC) {
                   RedrawwinC(0,0,WINCWIDE,WINCHIGH);}
              }

              if (*ifdogl && event.xexpose.window == win) {
                 dispsf();
              }

              for (i=0; i<NQBOX; i++) 
		if (event.xexpose.window == qboxes[i].win)
			PromptBox(&qboxes[i]);

	      if (event.xexpose.window == COMMwin) RedrawCOMMwin();
	      if (event.xexpose.window == EBox) RedrawList(&elist);
	      if (event.xexpose.window == MAPwin) RedrawMAP();
	      if (event.xexpose.window == VIRwin) RedrawVIR();
           }
           break;

	   case EnterNotify: {
	      if (event.xcrossing.subwindow == expldat.win) DoExpl();
           }
           break;

	   case LeaveNotify: {
		expldat.win = -1;
		signal(SIGALRM,SIG_IGN);
           }
           break;

           case ConfigureNotify: {

              if(DEBUG)fprintf(stderr,"ConfigureNotify\n");

              /* you want to increase or decrease the size of the window*/
              /* get the new width and height*/

              if (event.xconfigure.window == win) {

                   if (event.xconfigure.width == width &&
                       event.xconfigure.height == height) {
			if (has_opengl && *ifdogl) {
#ifdef DOGL
			    glXSwapBuffers(display, win);
#endif
			} else {
			    if ( molback == molcur) {
				XCopyArea(display,molcur,win,gc,
					0,0,width,height,0,0);
			    } else {
				RedrawWin();
			    }
                        }
			break;
		   }

                   width  = event.xconfigure.width;
                   height = event.xconfigure.height;

                   /* now resize the Graphics window, this will generate an 
                      expose event*/

                   if (!CheckForConfig()) {
                      XEvent xev;
                      xwa.width = width;
                      xwa.height = height;
                      XResizeWindow(display, 
                                    win,
                                    width,
                                    height);

                   while (XCheckTypedWindowEvent(display, win, Expose, &xev)) {
                      XExposeEvent *exp = (XExposeEvent *) &xev;}

		   if (has_opengl && *ifdogl) Reshape();
		   else {
                      if (do3dx || *dospa) return(0);
                      else RedrawWin();
		   }

                   }
              }
           }
           break;

           case UnmapNotify:         break;

           default: break;		/* ignore unexpected events */

        }  /* end switch event type*/

    }/* end while */

    XFreeGC(display, gc);
    XCloseDisplay(display);
    *inct = 15;
    return(0);

  } /* end DenWindow */
  break;

  case MolWindow : 
  {


    if ( DowinMC ) {
       DirBox(winMC,1);    
       DowinMC = 0;
       ZoomEnable = False;
       ZoomSelection = False;
       if (nfiles == 0) getfiles(lastdir);
    }
    if ( DoactMC ) {XUndefineCursor(display, win);
                    XUndefineCursor(display, winMC);
                    XUndefineCursor(display, Fwin);
                    actde(*inct,*incp,0); DoactMC = 0;}

    done = 0;
    *inct = 0;
    *incp = 0;



    if (hold) {
       update_model = 0;
       while (1){
        XSync(display, False);
        if (XCheckMaskEvent(display,ButtonReleaseMask,&event))
          		{ hold = 0; goto XLOOP;}
	doclr();
#if defined(VMS) || defined(UNDERSC)
        mktrn(&holdt,&holdp);
	qupd();
#else
#ifdef CRAY
        MKTRN(&holdt,&holdp);
	QUPD();
#else
        mktrn_(&holdt,&holdp);
	qupd_();
#endif
#endif
       }
    } 
XLOOP:

    if (animptr.on) {
       while (1){
	int i;
	double vartmp;

        XSync(display, False);
	if (update_res == -1) update_model = 1;
	doclr();
        if (XCheckMaskEvent(display,ButtonPressMask,&event)) {
           if (event.xbutton.window == ZMEwin) {
		SwitchOffAnim();
		goto ALOOP;
	   } else if (event.xbutton.window == win) {
		hold = 0; 
		XSendEvent(display, win, False, NoEventMask, &event);
		goto ALOOP;
	   }
        }
	i = 0;
	animptr.frame = animptr.frame + animptr.vdirection;
	if (animptr.frame >= animptr.nframe || 
	    animptr.frame <= -animptr.nframe) {
		animptr.vdirection = -1*animptr.vdirection;
		i = 1;
	}
	vartmp = animptr.varinit + 
		animptr.frame * animptr.varincr[animptr.vartype];
	if (animptr.vartype == 0 && vartmp <= 0.0) {
		vartmp = *animptr.variable; 
		animptr.vdirection = -1*animptr.vdirection;
	}
	if (animptr.vartype == 1 && (vartmp <= 0.0 || vartmp >= 180.0)) {
		vartmp = *animptr.variable;
		if (!i) animptr.vdirection = -1*animptr.vdirection;
	}
	*animptr.variable = vartmp;
	AnimLinks(vartmp);
	if (animptr.part) *ipart = animptr.part;
	anim();
       }
     }
ALOOP:

    while (!done) {
  
	XFlush(display);
	if (XPending(display) == 0  && DoFreq ) {
		XSync(display,False) ;return (0);
	}
	if (aflag && !cflag && !dflag) {
           XSetForeground(display, gc, colors[2]);
           for (i = 0; i <acnt-1; i++) {
               XDrawLine(display,win,gc,xyz.iyp[asel[i]-1],xyz.ixp[asel[i]-1],
                         xyz.iyp[asel[i+1]-1],xyz.ixp[asel[i+1]-1]);
           }
        }

        XNextEvent(display, &event);
        switch (event.type) {

           case KeyPress:    {
              XKeyEvent *key_event = (XKeyEvent *) &event;
              char buf[10];  KeySym ks;  XComposeStatus status;  int stlen,istat;

              if(DEBUG)fprintf(stderr,"KeyPress\n");

              stlen = XLookupString(key_event,buf,10,&ks,&status);
	      /*if (!stlen) break;*/


              for (i=0; i<NQBOX; i++) 
		if (key_event->window == qboxes[i].win && qboxes[i].active) 
		   if (KeyChk(&qboxes[i],buf[0])) 
		       if (key_event->window != Fwin) return(0);

              if (key_event->window == ZMEwin) {
		int isl;

		istat = 0; isl = 0;
		for (i=0; i<*zmptr.nz; i++) {
			if (IANZbox[i].active) {
			   istat = KeyChk(&IANZbox[i],buf[0]);
			   isl = i;
			}
			if (BLbox[i].active) {
			   istat = KeyChk(&BLbox[i],buf[0]); 
			   isl = i;
			}
			if (ALPHbox[i].active) {
			   istat = KeyChk(&ALPHbox[i],buf[0]); 
			   isl = i;
			}
			if (BETbox[i].active) {
			   istat = KeyChk(&BETbox[i],buf[0]); 
			   isl = i;
			}
			for (j=0; j<4; j++) {
				if (IZbox[i*4+j].active) {
				   istat = KeyChk(&IZbox[i*4+j],buf[0]); 
			   	   isl = i;
				}
			}
		}
          	if (istat && !Selecting && !ZMEsel) {
		    if (!mapchk()) map_prop();
		    DeActZME(); GetQZME(); UpdateZME(); 
		    FindZRangeFromBox(isl);
		    update_model = 1;
		    *Sinct = 530; return(0); 
		}
		if (EXPbox[0].active)
			if (KeyChk(&EXPbox[0],buf[0])) 
				aaexp(EXPbox[0].str,strlen(EXPbox[0].str));
	      }

              if (key_event->window == win || key_event->window == winMC) {
		 update_model = 0;
                 if      (ks==XK_Left)
                   { *inct = -3; *incp = 1; }
                 else if (ks==XK_Right)
                   { *inct = -3; *incp = -1; }
                 else if (ks==XK_Up)
                   { *inct = -2; *incp = 1;}
                 else if (ks==XK_Down)
                   { *inct = -2; *incp = -1;}
                 else if (ks==XK_KP_7)
                   { *inct = -1; *incp = 1;}
                 else if (ks==XK_KP_9)
                   { *inct = -1; *incp = -1;}
                 else if (ks==XK_KP_1)
                   { *inct = 290; *incp = -1;}
                 else if (ks==XK_KP_3)
                   { *inct = 290; *incp = 1;}
                 else if (ks==XK_KP_4)
                   { *inct = 420; }
                 else if (ks==XK_KP_6)
                   { *inct = 430; }
                 else if (ks==XK_KP_8)
                   { *inct = 440;}
                 else if (ks==XK_KP_2)
                   { *inct = 450;}
                 else if (buf[0]=='a' || buf[0]=='A')
		   {
			if (!gijsup) {
			   createauthor();gijsup = 1;
			} else {
			   XFreePixmap(display,gijs);
			   XDestroyWindow(display,winau);gijsup = 0;
			}
		   }
                 else if (buf[0]=='s')
                   { *inct = 75; DowinC = 1;DoactC = 1; }
                 else if (buf[0]=='f')
                   { update_model = 1; *inct = 100; }
                 else if (buf[0]=='n')
                   { update_model = 1; *inct = 110; }
                 else if (buf[0]=='l')
                   { *inct = 120; }
                 else if (buf[0]=='k')
                   { *inct = 130; }
                 else if (buf[0]=='b')
                   { *ball = 1; hold = 0;}
                 else if (buf[0]=='p')
                   { *inct = 150; }
                 else if (buf[0]=='x')
                   { *inct = 610; }
                 else if (buf[0]=='m')
                   {update_model = 1;  
		     qboxstr(&qboxes[QMXYZ],NULL,1,0,-1,DEFQX,DEFQY,QBOXWIDE,
			QBOXHIGH, 0,"XYZ file ? ",NULL,0,0,151,dummyproc);
		   }
                 else if (buf[0]=='h')
                   {update_model = 1;  
		     qboxstr(&qboxes[QMXYZ],NULL,1,0,-1,DEFQX,DEFQY,QBOXWIDE,
			QBOXHIGH, 0,"XYZ file ? ",NULL,0,0,152,dummyproc);
		   }
                 else if (buf[0]=='u')
		   { OnTop(); }
                 else if (buf[0]=='c')
		   { *igtfil = 1;update_model = 1;  
		     DeActZME(); GetQZME(); UpdateZME(); 
		     *Sinct = 530; return(0); 
		   }
                 else if (buf[0]==' ')
                   { 
			*inct = 155;
		   }
                 else if (ks==XK_Escape)
                   { if (dflag) {
			dflag = 0;aflag = 0;
			Selecting = 0; ZMEsel = 0;
/*
			for ( i = 0; i < *xyz.iatoms; i++ ) {
				if (xyz.iaton[i] >= 2) xyz.iaton[i] = 1;
			}
	    		update_sel = 1;
			XUndefineCursor(display,win);
			RedrawZME();
*/
			XUndefineCursor(display,win);
			if (*ialtyp == 1) {
                           for (i=0; i<*iscst; i++) xyz.iaton[i] = 1;
                           for (i=*iscst; i<(*iscst)+(*nscnd); i++) 
				xyz.iaton[i] = 2;
			} else {
                           for (i=0; i<*xyz.iatoms; i++) xyz.iaton[i] = 2;
			}
	    		update_sel = 1;
                        *isimpl = 4;
                        ApplSel(0);
		        update_model = 1;
                        return(0);
		     } else {
			if (*irtcel) {
		           update_model = 1;
			   i = *irtcel; *irtcel = 0;
			   ogmoll(0);
			   *irtcel = i;
			}
			DoFreq = 0;
		        update_model = 0;
			*inct = 153;
                        return(0);
		     }
		   }
                 else if (ks==XK_Tab) 
		   { if (!Selecting && !cflag && !dflag) {
			acnt = 0;
			if (doalign) {
			   cflag = 1;aflag = 6;anum = 6;
			} else {
			   cflag = 2;
			   aflag = 2;anum = 2;
			   if (event.xbutton.state & ShiftMask) 
				aflag = 4;anum = 4;
			}
		        XDefineCursor(display,win,AtomCursor);
		     }
		   }
                   if ((*fancy && has_opengl) && key_event->window == win) 				{Key(buf[0]);}
                 return(0);
              }
           }
           break;

           case ButtonPress: {

              if(DEBUG)fprintf(stderr,"ButtonPress\n");

	      expldat.win = -1;
	      signal(SIGALRM,SIG_IGN);

	      update_model = 1;

              if(event.xbutton.window == win && !ZoomEnable && 
                (event.xbutton.button == 1 || event.xbutton.button == 2)) {
                 int curx = event.xbutton.x;
                 int cury = event.xbutton.y;
                 if (bflag) {
                    XUndefineCursor(display,win);
                    bflag = 0;
                    *inct = bretval;
		    if (bretval == 320) {
			if (ScreenPDB(curx,cury)) {
			   int ires=-1;
			   ires = CurAmino + 1;
#if defined(VMS) || defined(UNDERSC)
			   actami(&ires,&ZERO,&ONE,&ZERO);
#else
#ifdef CRAY
			   ACTAMI(&ires,&ZERO,&ONE,&ZERO);
#else
			   actami_(&ires,&ZERO,&ONE,&ZERO);
#endif
#endif
			   *inct = 0;
			   rsold = RESUND;
#ifdef DOGL
			   ogres(ires,ONE,1);
#else
			   return(0);
#endif
			}
		    }
		    *incp = 1+FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
				curx,cury,MINDIFF);
		    if (bretval == 321) {
			*inct = 530;
			idum1 = DelAmino(xyz.iresid[*incp-1]);
		    }
		    if (bretval == 322) {
			*inct = 530;
			InsertAmino = xyz.iresid[*incp-1];
			if (SEQup) {
			   XMapRaised(display,SEQwin);
			   RedrawSEQ();
			} else {
			   InitSEQ(event.xbutton.x_root,
				event.xbutton.y_root);
			}
		    }
		    if (bretval == 561) {
			for ( i = 0; i < *xyz.iatoms; i++ ) xyz.iaton[i] = 1;
			xyz.iaton[*incp-1] = 2;
	    		update_sel = 1;
		    }
		    return(0);
                 }
                 if (aflag && ! bflag && !(event.xbutton.state & ControlMask)) {
                    int ia,ib,floke;

		    ib = FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
				curx,cury,MINDIFF);
		    if (ib < 0) ib = -2;
                    floke = 1;
                    for (ia = 0; ia <acnt; ia++) {
			if (dflag) {
			   if (ia < *xyz.mxnat) if (jring[ia] == ib+1 ) floke = 0;
			} else {
                           if (asel[ia] == ib+1 ) floke = 0;
			}
		    }
                    if (floke && ib >= 0) {
		       if (dflag) {
			  if (acnt < *xyz.mxnat) jring[acnt] = ib+1;
		       } else {
			  asel[acnt] = ib+1;
		       }
                       aflag--;
                       acnt++;
                       if (*ibell) XBell(display,0);

		       if (cflag) {
			xyz.iaton[ib] = 3 + (acnt-1)/2;
	    		update_sel = 1;
			if (aflag) return(0);
		       }

		       if (dflag) {
			xyz.iaton[ib] = 3;
			sprintf(stemp,"%d Atoms to go",aflag);
			strcpy(ZMEerr,stemp);
			RedrawStatus();
		        update_model = 0;
	    		update_sel = 1;
			if (aflag) return(0);
		       }
                    }
		    if (!cflag && !dflag) {
			XSetForeground(display, gc, colors[2]);
			for (i = 0; i <acnt-1; i++) {
			   XDrawLine(display,win,gc,
			    xyz.iyp[asel[i]-1]  ,xyz.ixp[asel[i]-1], 
			    xyz.iyp[asel[i+1]-1],xyz.ixp[asel[i+1]-1]);
			}
		    }
                    if (!aflag) {

                       XUndefineCursor(display,win);
		       if (cflag) {
			  for (i=0; i<*xyz.iatoms; i++) xyz.iaton[i] = 1;
	    		  update_sel = 1;
			  if (cflag == 1) {
#if defined(VMS) || defined(UNDERSC)
				alnsel(asel);
#else
#ifdef CRAY
				ALNSEL(asel);
#else
				alnsel_(asel);
#endif
#endif
			  } else {
#if defined(VMS) || defined(UNDERSC)
				cllvec(asel,&anum,xyz.coo);
#else
#ifdef CRAY
				CLLVEC(asel,&anum,xyz.coo);
#else
				cllvec_(asel,&anum,xyz.coo);
#endif
#endif
			  }
			  cflag = 0;
			  return(0);
		       } else if (dflag) {
			  dflag = 0; Selecting = 0; ZMEsel = 0;
			  for (i=0; i<*xyz.iatoms; i++) xyz.iaton[i] = 2;
	    		  update_sel = 1;
			  *isimpl = 4;
			  ApplSel(0);
			  return(0);
		       } else if (SelZME(asel)) {
			  return(0);
		       } else {
#if defined(VMS) || defined(UNDERSC)
			  tomold(&aret,asel,&anum);
#else
#ifdef CRAY
			  TOMOLD(&aret,asel,&anum);
#else
			  tomold_(&aret,asel,&anum);
#endif
#endif
			  MkDistWin(asel,anum,aret);
	                  update_model = 0;
		       }
                    }
                 }
		 else {
                 
		 int k;

		 if (!Selecting) {
		    if (ScreenZME(event.xbutton.x,event.xbutton.y) && ZMEup) {
			if (event.xbutton.button == 2) 
			  {int iret; 
			     if (ZMEAA) {
				if ( AmiCom(1,event.xbutton.x,event.xbutton.y)) return(0);
			     } else {
	 			iret = GetFrag(1,event.xbutton.x,event.xbutton.y);
				if (iret != -1) return(iret);
			     }
			  }
	                update_model = 0;
			return(0);
		    }
		    if (ScreenPDB(event.xbutton.x,event.xbutton.y) && 
			!((event.xbutton.state & ShiftMask) || 
			  (event.xbutton.state & ControlMask)) && 
			event.xbutton.button == 2) {
			moving = 0; gmoving = 0;
			if (AmiCom(1,event.xbutton.x,event.xbutton.y)) {
				    while(XCheckTypedWindowEvent(display, win, 
					ButtonRelease,&event));
				    return(0);
			}
			while(XCheckTypedWindowEvent(display, win, 
				ButtonRelease,&event));
	                update_model = 0;
			break;
			/*return(0);*/
		    }
		 }

		 if (!Selecting) {
		    if (*itsrf) {
			if (has_opengl && *fancy) {
			   if (ChangeLevel(event.xbutton.button,
				event.xbutton.x,event.xbutton.y)) return(0);
			}
		    } else {
			if (FindEsp(event.xbutton.button,
				event.xbutton.x,event.xbutton.y)) return(0);
		    }
		 }

		if (event.xbutton.button == 1 && ATMup && !ZMEup &&
			!((event.xbutton.state & ShiftMask) || 
			  (event.xbutton.state & ControlMask)) ) {
		    k = FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
			curx,cury,MINDIFF);
		    if (k != -1) {
			if (xyz.iaton[ATMsel] == 2) xyz.iaton[ATMsel] = 1;
	    		update_sel = 1;
			ATMsel = k;
			xyz.iaton[ATMsel] = 2;
			if (ATMup) {
			   UpdateATM();
			   XMapRaised(display,ATMwin);
			   RedrawATM();
			} else {
			   InitATM(event.xbutton.x_root,event.xbutton.y_root);
			   *iqon = 2;
			   if (cbut[BLABEL].toggle) {
			      TogDown(&cbut[BLABEL]);
			      *Sinct = 180;
			   }
			}
	                update_model = 0;
			return(0);
		    }
		 }

		 if (*ball && !dflag) {
		    moving = 1;
		    startx = event.xbutton.x;
		    starty = event.xbutton.y;
		    btype = 0;
		    if (event.xbutton.state & ShiftMask) btype = 1;
		    if (event.xbutton.state & ControlMask) btype = 2;
		    if ((event.xbutton.state & ControlMask) 
			  && (event.xbutton.state & ShiftMask)) btype = 3;
		    if (*fancy && has_opengl) 
			  moused(event.xbutton.button,event.xbutton.state, 
					  event.xbutton.x, event.xbutton.y);
		    break;
		 } else {
		    rotat(event.xbutton.x,event.xbutton.y);
		    *inct = holdt; *incp = holdp; 
		    return(0);
		 }

                 }
              }
              else if(event.xbutton.window == win && (event.xbutton.button == 1
                  || event.xbutton.button == 2) && ZoomEnable ) {
        
		 moving = 0;
                 ZoomEnable = False;
                 ZoomSelection = True;
                 MotionCount = 0; 
         
                 XDefineCursor(display, win, ZoomCursor);
                 XSetFunction(display, gc, GXxor);
                 XSetForeground(display, gc, colors[11]);
                 ZoomX1 = event.xbutton.x;
                 ZoomY1 = event.xbutton.y;
                 ZoomW = 1;
                 ZoomH = 1;
                 XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);
         
              }

              if (event.xbutton.window == win && event.xbutton.button == 3)  {
	        update_model = 0;
		OnTop();
	      }

              if (event.xbutton.window == QBox)  {
		for (j=0; j<NQBOX; j++) 
		    if (qboxes[j].win == QBox && qboxes[j].active) break;
		i = Clickwin(qboxclose,2,event.xbutton.x,event.xbutton.y,1);
		if (i == 0) {
		   if (KeyChk(&qboxes[j],'\012')) return(0);
		} else if (i == 1) {
		   XDestroyWindow(display,QBox);
		   XSync(display, False);
		   qboxup = 0;
		}
	      }

	      if (event.xbutton.button  == 3) {
	         update_model = 0;
		 QBoxPaste(event.xbutton.window,qboxes,NQBOX);
	      }

              if (event.xbutton.window == winau) {
	         update_model = 0;
                 XFreePixmap(display,gijs);
                 XDestroyWindow(display,winau);gijsup = 0;}

              if (event.xbutton.window == wincnv) {
	         update_model = 0;
                 XDestroyWindow(display,wincnv);cnvup = 0;}

              if (event.xbutton.window == winsco) {
	         update_model = 0;
		 i = Clickwin(scbut,NSCBUTTS,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsSCO(i)) return(0);
		 }
	      }

              if (event.xbutton.window == winpmf) {
	         update_model = 0;
		 i = Clickwin(pbut,NPBUTTS,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsPMF(i)) return(0);
		 }
	      }


              if (event.xbutton.window == winspec && specup) {
		 if (event.xbutton.button == 1 || event.xbutton.button == 2) {
			*inct = 510; *incp = 0;
			if (spect.current != -1) {
				*incp = 1 + spect.index[spect.current];
				frlist.select = spect.index[spect.current];
				if (DoFreq) RedrawList(&frlist);
			}
			if (*incp) {
			   drwspec();
			   return (0);
			} else {
			   /* dummy inct */
			   *inct = 1000;
			}
		 }
	      }

              if (event.xbutton.window == wingeo && geoup) {
		 if (event.xbutton.button == 1 || event.xbutton.button == 2) {
			*inct = 117; *incp = 0;
			if (*geopntr.ifmxav && geoFmax.current != -1) {
				*incp = 1 + geoFmax.index[geoFmax.current];
			}
			if (*geopntr.ifrmav && geoFrms.current != -1) {
				*incp = 1 + geoFrms.index[geoFrms.current];
			}
			if (*geopntr.idmxav && geoSmax.current != -1) {
				*incp = 1 + geoSmax.index[geoSmax.current];
			}
			if (*geopntr.idrmav && geoSrms.current != -1) {
				*incp = 1 + geoSrms.index[geoSrms.current];
			}
			if (*geopntr.ieav && geoE.current != -1) {
				*incp = 1 + geoE.index[geoE.current];
			}
			if (*incp) {
			   *ipnt = *incp;
#if defined(VMS) || defined(UNDERSC)
			   drwgeo();
#else
#ifdef CRAY
			   DRWGEO();
#else
			   drwgeo_();
#endif
#endif
			   return (0);
			}
		 }
		 else if(event.xbutton.button == 3) {
	                update_model = 0;
			XDestroyWindow(display,wingeo);geoup = 0;
			TogUp(&cbut[BGEOM]);
		 }
	      }

              if (event.xbutton.window == FrBox) {
	       if (PressList(&frlist,event.xbutton.x, event.xbutton.y)) {
                 *inct = 510; *incp = frlist.select+1;
                 return(0);
	       }
	      }

              if (event.xbutton.window == FLXwin) {
	       if (PressList(&flxlist,event.xbutton.x, event.xbutton.y)) {
		   showresrot(flxlist.select);
	       }
	      }

              if (event.xbutton.window == ZMEwin) {
		if (PressZME(event.xbutton.button, event.xbutton.x, event.xbutton.y)) return(0);
	      }

              if (event.xbutton.window == ATMwin ) {
		if (PressList(&fftlist,event.xbutton.x, event.xbutton.y)) {
		 if (fftlist.list.ilst == NULL) {
		    if (ffatnr[*fftyp] ==  NULL) {
			xyz.ityp[ATMsel] = ffsgn[*fftyp]*(fftlist.select + 1);
		    } else {
			if (xyz.ianz[ATMsel] == 
				ffatnr[*fftyp][fftlist.select]) {
			   xyz.ityp[ATMsel] = ffsgn[*fftyp]*(fftlist.select + 1);
			} else {
		  	   if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
				"Wrong type for this atom",0)) fftlist.select = -1;
				fftlist.select = -1;
				RedrawList(&fftlist);
			   
			}
		    }
		 } else {
			if (xyz.ianz[ATMsel] == 
				ffatnr[*fftyp][fftlist.select]) {
			   xyz.ityp[ATMsel] =  ffsgn[*fftyp]*
				(fftlist.list.ilst[fftlist.select] + 1);
			} else {
		  	   if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
				"Wrong type for this atom",0)) fftlist.select = -1;
				fftlist.select = -1;
				RedrawList(&fftlist);
			   
			}
		 }
		 return(0);
		}
	      }

              if (event.xbutton.window == winpmf) {
	       if (PressList(&pmflistmn,event.xbutton.x, event.xbutton.y)) {
		 int pmfat1;

		 pmfat1 = ipmfmn[pmflistmn.select]-1;
                 if (xyz.iaton[pmfat1] == 1) xyz.iaton[pmfat1] = 3;
		 else xyz.iaton[pmfat1] = 1;
	    	 update_sel = 1;
                 return(0);
	       }
	       if (PressList(&pmflistmx,event.xbutton.x, event.xbutton.y)) {
		 int pmfat2;

		 pmfat2 = ipmfmx[pmflistmx.select]-1;
                 if (xyz.iaton[pmfat2] == 1) xyz.iaton[pmfat2] = 4;
		 else xyz.iaton[pmfat2] = 1;
	    	 update_sel = 1;
                 return(0);
	       }
	      }

              if (event.xbutton.window == Fwin ) {

#ifndef VMS
	       if (PressList(&dirlist,event.xbutton.x, event.xbutton.y)) {

		 if (ndirs > 0) {
		     NewDir();
		     getfiles(lastdir);
		     RedrawFwin();
	             update_model = 0;
		 }
	       }
#endif

	       if (PressList(&flist,event.xbutton.x, event.xbutton.y)) {
		 selfil = flist.select;
		 if (selfil > nfiles - 1) selfil = nfiles - 1;
		 lpnt = flist.lpnt;
                 XFlush(display);
                 XSync(display, True);
                 RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
                 XSync(display, True);

                 if (files[selfil][0] != '/') {
                    strcpy(strname,lastdir);
#ifndef VMS
                    if (strname[strlen(strname)-1] != '/') strcat(strname,"/");
#endif
                    strcat(strname,files[selfil]);
		 }
		 else strcpy(strname,files[selfil]);

		 if (strstr(strname,".ogl")) {
		    lViewer(strname);
                    return(0);
		 }
#ifdef VMS
                 for (ihlp=0; ihlp<strlen(strname); ihlp++)
                      {str->dsc$a_pointer[ihlp] = strname[ihlp];}
#else
#ifdef CRAY
                 strncpy(_fcdtocp(str),strname,strlen(strname));
#else
                 strcpy(str,strname);
#endif
#endif
                 *nstr = strlen(strname);

                 XDefineCursor(display, win, WaitCursor);
                 XDefineCursor(display, winMC, WaitCursor);
                 XDefineCursor(display, Fwin, WaitCursor);
                 *inct = qboxes[QREADF].qbinct;
		 *incp = addfile;
		 doalign = 0;
		 *irtcel = 0;
		 ntits = 0;
		 if (!addfile) poszset = 0;
		 WinName(win,strname);
		 if (qbres) {
		    TogUp(&cbut[BFORC]);
		    qbres = 0;
		    XUnmapWindow(display,RESwin);
		 }
		 if (frfor && FRup) {
		    TogUp(&cbut[BFORC]);
		    XDestroyWindow(display,FrBox);
		    DoFreq = 0;
		    FRup = 0;
		 }
		 if (frfor && specup) {
		    XDestroyWindow(display,winspec);
		    specup = 0;
		 }
		 if (geoup) {
		    TogUp(&cbut[BGEOM]);
		    XDestroyWindow(display,wingeo);
		    geoup = 0;
		 }
		 if (cnvup) {
		    XDestroyWindow(display,wincnv);
		    cnvup = 0;
		 }
		 if (specup) {
		    XDestroyWindow(display,winspec);
		    specup = 0;
		 }
		 if (scoup) {
		    XDestroyWindow(display,winsco);
		    scoup = 0;
		 }
		 if (pmfup) {
		    XDestroyWindow(display,winpmf);
		    pmfup = 0;
		 }
		 ZMEswitch[0].toggle = 1; ZMEAA = 0; EXPbox[0].fake = 1; 
		 RedrawZME(); XSync(display,False);
		 pdb = 0; oqlen = 0; oqpos = 0; backb = 0;

		 if (!addfile) NHetAtm = 0;

                 DowinC = 1; DoactC = 1; DoactMC = 1;
		 TogUp(&cbut[BHYD]);
                 XFlush(display);
		 aflag = 0; bflag = 0; cflag = 0; dflag = 0;
		 LastAmino = -1;
		 CurAmino = -1;
		 do3dx = 0; *do3d = 1;
		 if (strx.fpos != NULL) {
			free(strx.fpos);
			strx.fpos = NULL;
		 }
		 if (strx.fptr) {
			cltrr();
			strx.fptr = NULL;
		 }
		 Ngrostr = 0;
		 empty_model();
  		 update_sel = 1;

		 RedrawFwin();
                 return(0);
                 }
               else {

	         update_model = 0;

                 i=Clickwin(rbut,NBUTTR,event.xbutton.x, event.xbutton.y,1);

                 if (i>=0) {
                    switch (i) {
                    case BDIR : getfiles(qboxes[QREADF].str);
				RedrawFwin();
				break;
                    case BCAN : XUnmapWindow(display,Fwin);
				TogUp(&cbut[BREADF]);
                                qbrfile = 0; break;
                    case BREP : TogBut(&rbut[Fwinopt]);
				ActBut(&rbut[Fwinopt],1);
				Fwinopt = BREP;
				TogBut(&rbut[Fwinopt]);
				ActBut(&rbut[Fwinopt],-1);
				addfile = 0;
				break;
                    case BADD : TogBut(&rbut[Fwinopt]);
				ActBut(&rbut[Fwinopt],1);
				Fwinopt = BADD;
				TogBut(&rbut[Fwinopt]);
				ActBut(&rbut[Fwinopt],-1);
				addfile = 1;
				if (DoCan(event.xbutton.x_root, 
					event.xbutton.y_root,
				"The ADD file is only functional for file types:\n  - Mol2, PDB and XYZ files",0)) {}
				break;
                    }
                 }

               }
              }

	      if (event.xbutton.window == DISTwin) {
	         update_model = 0;
		 i = Clickwin(clbut,NCLBUT,event.xbutton.x, event.xbutton.y,1);

		 if (i>=0) {
		     if (ButtonsDIST(i)) return(0);
		 }
	      }

	      if (event.xbutton.window == COLwin) {
		 i = Clickwin(colbut,NBUTSC,event.xbutton.x, event.xbutton.y,1);
                 if (i>=0) {
			RButtonsCOL(i);
		 } else {
			i = Clickwin(AtmBut,TABBUTN,
				event.xbutton.x,event.xbutton.y,1);
			if (i>=0) {
			    ButtonsCOL(i);
			    return(0);
			}
		 }
	      }


	      if (event.xbutton.window == SEQwin) {
		 i = Clickwin(butSEQ,NBUTSEQ,event.xbutton.x, event.xbutton.y,1);
                 if (i>=0) {
			if (ButtonsSEQ(i)) return(0);
		 } else {
			i = ClickBox(&qboxes[QPHI],2,
				event.xbutton.x,event.xbutton.y);
                 	if (i>=0) {
				qboxes[QPHI].active = 0;
				qboxes[QPSI].active = 0;
				qboxes[QPHI+i].active = 1;
				RedrawSEQ();
			}
		 }
	      }

	      if (event.xbutton.window == TNKwin) {
	         update_model = 0;
		 i = Clickwin(butTNK,NBUTTNK,event.xbutton.x, event.xbutton.y,1);
                 if (i>=0) {
			if (ButtonsTNK(i)) return(0);
		 } else {
			i = ClickBox(&qboxes[QGRD],4,
				event.xbutton.x,event.xbutton.y);
                 	if (i>=0) {
				qboxes[QGRD].active = 0;
				qboxes[QARCH].active = 0;
				qboxes[QTNKJN].active = 0;
				qboxes[QMAXIT].active = 0;
				qboxes[QGRD+i].active = 1;
				RedrawTNK();
			}
		 }
	      }

	      if (event.xbutton.window == CPwin) {
		  if (ButtonsCP(event.xbutton.x, event.xbutton.y)) {
			*Sinct = 154; return(0);
		  }
	      }

	      if (event.xbutton.window == CTwin) {
		  int CTtmp;
		  CTtmp = ButtonsCT(event.xbutton.x, event.xbutton.y);
		  if (CTtmp) {
			*Sinct = 550; 
			if (CTtmp == 2) *Sincp = 17; 
			else *Sincp = 2;
			return(0);
		  }
	      }

	      if (event.xbutton.window == ISOwin) {
		 i = Clickwin(isobut,NBUTISO,event.xbutton.x, event.xbutton.y,1);
                 if (i>=0) {
			if (ButtonsISO(i)) {
				return(0);
			}
		 } else {
			i = ClickBox(&qboxes[QEDGE],5,
				event.xbutton.x,event.xbutton.y);
                 	if (i>=0) {
				qboxes[QEDGE].active = 0;
				qboxes[QVALC1].active = 0;
				qboxes[QVALC2].active = 0;
				qboxes[QVALC3].active = 0;
				qboxes[QNPTS].active = 0;
				qboxes[QEDGE+i].active = 1;
				RedrawISO();
			}
		 }
	      }

	      if (event.xbutton.window == ATMwin) {
		 i = Clickwin(butATM,NBUTATM,event.xbutton.x, event.xbutton.y,1);
                 if (i>=0) {
			if (ButtonsATM(i)) {
				return(0);
			}
                 } else {
                        i = ClickBox(&qboxes[QCHARG],2,
                                event.xbutton.x,event.xbutton.y);
                        if (i>=0) {
			    if ( i == 1 && (event.xbutton.state & ShiftMask) ) {
			        if (DoCan(event.xbutton.x_root,
					event.xbutton.y_root,selstr,0)) {
				}
				Selecting = 1; ZoomEnable = True;Select = True;
				SelRes = *qboxes[QRSD].iflt;
			    } else {
                                qboxes[QCHARG].active = 0;
                                qboxes[QRSD].active = 0;
                                qboxes[QCHARG+i].active = 1;
                                RedrawATM();
			    }
                        }
		 }
	      }

	      if (event.xbutton.window == winspec) {
		 i = Clickwin(spbut,NSBUTTS,event.xbutton.x, event.xbutton.y,1);
                 if (i>=0) {
			if (ButtonsSPC(i)) {
				*Sinct = 1000; return(0);
		 	}
                 } else {
                        i = ClickBox(&qboxes[QHW],5,
                                event.xbutton.x,event.xbutton.y);
                        if (i>=0) {
			    int j;
			    for (j=0; j<5; j++) qboxes[QHW+j].active = 0;
			    qboxes[QHW+i].active = 1;
			    drwspec();
                        }
		 }
	      }

	      if (event.xbutton.window == ONIwin) {
		 i = Clickwin(onbut,NBUTSO,event.xbutton.x, event.xbutton.y,1);
                 if (i>=0) {
			if (ButtonsONI(i)) {
				*Sinct = 1000; return(0);
			}
		 }
	      }

	      if (event.xbutton.window == SUBwin) {
	         update_model = 0;
		 i = Clickwin(sbut,NBUTSS,event.xbutton.x, event.xbutton.y,1);
                 if (i>=0) {
			if (ButtonsSUB(i)) {
				*Sinct = 151; *iixyz = 7+jmode; return(0);
			}
		 } else {
			i = ClickBox(&qboxes[QGLIN1],7,
				event.xbutton.x,event.xbutton.y);
                 	if (i>=0) {
				qboxes[QGLIN1].active = 0;
				qboxes[QGLIN2].active = 0;
				qboxes[QGTITL].active = 0;
				qboxes[QJNAME].active = 0;
#ifndef DOQUEUE
				qboxes[QQNAME].active = 0;
				qboxes[QTIME].active = 0;
#endif
				qboxes[QENAME].active = 0;
				qboxes[QGLIN1+i].active = 1;
				RedrawSUB();
			}

		 }
	      }

	      if (event.xbutton.window == DPTwin) {
		    update_model = 0;
		    i = Clickwin(butdpt,2,event.xbutton.x, event.xbutton.y,1); 
		    if (i>=0) {
                        switch (i) {
			case 0:
			   XSync(display, False);
			   XDestroyWindow(display,DPTwin);
			   XSync(display, False);
			   DPTup = 0;
			   break;
			case 1: { LSSTRU List; 
			   List.list = ChainLength; List.nents = 10;
			   if (DoPopUp(DPTwin,butdpt[1].x+1,
				   butdpt[1].y,&List,&linmax,0) == -1) break;
			   linmax++;
			   }
			   break;
			}
			return(0);
		    }
		    if (ScrollPage(NULL,&dptscr[0],event.xbutton.x,
			event.xbutton.y)) {
			UpdateDPT();
			return(0);
		    }
	      }

	      if (event.xbutton.window == ECOLwin) {
		    if (Clickwin(butecol,1,event.xbutton.x, event.xbutton.y,1) != -1) {
			SetPalCol(1);
			XSync(display, False);
			XDestroyWindow(display,ECOLwin);
			XSync(display, False);
			ECOLup = 0;
			return(0);
		    }
		    if (ScrollPage(NULL,&ecolscr[0],event.xbutton.x,event.xbutton.y)) {
			SetPalCol(0);
		    }
		    if (ScrollPage(NULL,&ecolscr[1],event.xbutton.x,event.xbutton.y)) {
			SetPalCol(0);
		    }
		    if (ScrollPage(NULL,&ecolscr[2],event.xbutton.x,event.xbutton.y)) {
			SetPalCol(0);
		    }
	      }

              if (event.xbutton.window == DELAYwin) {
	         update_model = 0;
		 i = Clickwin(delbut,3,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsDEL(i)) idum1 = 0;
		 }
	      }

              if (event.xbutton.window == SRFwin) {
	         update_model = 0;
		 i = Clickwin(srfbut,5,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsSRF(i)) idum1 = 0;
		 }
	      }

              if (event.xbutton.window == FLXwin) {
	         update_model = 0;
		 i = Clickwin(flxbut,8,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsFLX(i)) idum1 = 0;
		 }
	      }

              if (event.xbutton.window == CHGwin) {
	         update_model = 0;
		 i = Clickwin(chgbut,2,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsCHG(i)) return(0);
		 }
	      }

              if (event.xbutton.window == PARwin) {
	         update_model = 0;
		 i = Clickwin(parbut,3,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsPAR(i)) return(0);
		 } else {
			i = ClickBox(&qboxes[QHBMIN],4,
				event.xbutton.x,event.xbutton.y);
                 	if (i>=0) {
				qboxes[QHBMIN].active = 0;
				qboxes[QHBMAX].active = 0;
				qboxes[QHAMIN].active = 0;
				qboxes[QHAMAX].active = 0;
				qboxes[QHBMIN+i].active = 1;
				RedrawPAR();
			}
		 }
	      }

              if (event.xbutton.window == winMC &&  !ZoomEnable && !ZoomSelection) {
		 int doret;
		 doret = 1;

                 i=Clickwin(cbut,NBUTTS2,event.xbutton.x, event.xbutton.y,1);

                 if (i>=0) {
                 switch (i) {

                 case BFIRST: *inct = 100; break;
                 case BPREV:  *inct = 109; break;
                 case BNEXT:  *inct = 110; break;
                 case BMOVIE: *inct = 115; DoFreq = 1; break;
                 case BHOUR:  update_model = 0; InitDelay(); break;
                 case BMOLF:  
				{LSSTRU List;
				 List.list = mlftit; List.nents = ntits;
				 if (DoPopUp(winMC,cbut[BMOLF].x+1,
					cbut[BMOLF].y+BUTTH-10,&List,imol,0) == -1) break;
				 WinName(win,mlftit[*imol]);
				 *imol = *imol + 1;
				 if (geoup) {
				    TogUp(&cbut[BGEOM]);
				    XDestroyWindow(display,wingeo);
				    geoup = 0;
				 }
				 if (cnvup) {
				    XDestroyWindow(display,wincnv);
				    cnvup = 0;
		 		 }
				 DowinC = 1; DoactC = 1; DoactMC = 1;
				 *inct = 700;
				}
				break;
                 case BSOLID: 
			      if (!TogBut(&cbut[BSOLID])){
				LSSTRU List;
				List.list = vdwstr ; List.nents = 2;
				if (DoPopUp(winMC,
				    cbut[BSOLID].x+1,cbut[BSOLID].y+BUTTH,
					&List,ivdwpl,0) == -1) {
				   TogBut(&cbut[BSOLID]);
				   break;
				}
				*incp = 0;
				if (has_opengl) {
				   int ndmtmp;
				   *ifogl = 1;
				   ndmtmp = monptr->ndm;
#if defined(VMS) || defined(UNDERSC)
				   clrmon();
#else
#ifdef CRAY
				   CLRMON();
#else
				   clrmon_();
#endif
#endif
				   monptr->ndm = ndmtmp;
				}
			      } else {
				*incp = 1;
				*ifogl = 0;
				if (has_opengl) {
#if defined(VMS) || defined(UNDERSC)
				   domcon(&ONE,&ONE);
#else
#ifdef CRAY
				   DOMCON(&ONE,&ONE);
#else
				   domcon_(&ONE,&ONE);
#endif
#endif
				}
			      }
			      *inct = 140;
                              break;
                 case BZOOMIN:   hold = 1; holdt = 290; holdp = -1;
				 *inct = 290;*incp = -1; break;
                 case BZOOMOUT:  hold = 1; holdt = 290; holdp = 1;
				 *inct = 290;*incp = 1; break;
                 case BPOSTT: {
				int idums;
				LSSTRU List;
				update_model = 0;
				List.list = postopt; List.nents = 2;
				if (DoPopUp(winMC,
					cbut[BPOSTT].x+1,cbut[BPOSTT].y+BUTTH,
					&List,icolps,0) == -1) break;
		/* check for dummies */
				idums = 0;
				for (i=0; i<*xyz.iatoms; i++) 
				   if (xyz.ianz[i] == 99)  idums = 1;
				if (idums) {
				   List.list = dumopt; List.nents = 2;
				   if (DoPopUp(winMC,
					cbut[BPOSTT].x+1,cbut[BPOSTT].y+BUTTH,
					&List,idelx,0) == -1) break;
				}
				qboxstr(&qboxes[QPOSTT],NULL,1,0,-1,DEFQX,DEFQY,
					QBOXWIDE,QBOXHIGH,0,"Filename ? ",NULL,
					0,0,150,dummyproc);
				break;}
                 case BDENMOD:  *inct = 75; DirBox(winMC,0);
                                DowinC =1; DoactC = 1;
				denmode = 1;
				*ifdogl = 0;
				*ivdwpl = 0;
#ifdef DOGL
				TogUp(&dbut[BOGL]);
#endif
				cursrfcol[0][0] = 0.0 ;
				cursrfcol[0][1] = 0.0 ;
				cursrfcol[0][2] = 1.0 ;
		                empty_model();
				if (qbrfile) {
				   TogUp(&cbut[BREADF]);
				   qbrfile = 0;
				   XUnmapWindow(display,Fwin);
				}
				if (ZMEup) UnMapZME();
				if (frfor && FRup) {
				   TogUp(&cbut[BFORC]);
				   XDestroyWindow(display,FrBox);
				   DoFreq = 0;
				   FRup = 0;
				}
				if (frfor && specup) {
				   XDestroyWindow(display,winspec);
				   specup = 0;
				}
				if (distup) {
				   distup = 0;
				   XUnmapWindow(display,DISTwin);
				}
				break;
                 case BQUITT: 
				update_model = 0;
				if (!DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
					" Are you sure to quit?  ",1)) {
				   XFreeGC(display, gc);
				   XCloseDisplay(display);
				   FreeAll();
				   exit(0);
				   *inct = 15;
				}
				break;
                 case BSURF: {
				int itmp;
				LSSTRU List;
				if (ISOup) break;
#ifdef MPFIT
				List.list = pots; List.nents = 16;
#else
				List.list = pots; List.nents = 15;
#endif
				if (DoPopUp(winMC,
				   cbut[BSURF].x+1,cbut[BSURF].y+BUTTH,
				   &List,&itmp,0) == -1) break;
				RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
				if (itmp == 6) {
				   if (DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
					"This will take a while",1)) {
					break;
				   }
				}
				if (itmp == 0 || itmp == 1 || itmp == 6 || itmp == 7) {
				   List.list = surftyp; List.nents = 2;
				   if (DoPopUp(winMC,
					cbut[BSURF].x+1,cbut[BSURF].y+BUTTH,
					&List,&surface->istyp,0) == -1) break;
				   if (surface->istyp == 1) {
                             		if (itmp == 0 || itmp == 1) {
						surface->nvalc = 1;
					}
                             		if (itmp == 6 || itmp == 7) {
						surface->nvalc = 3;
					}
					if (!ISOup) {
					   InitISO(event.xbutton.x_root,
						event.xbutton.y_root);
					   ISOt = 570+itmp;
                             		   if (itmp == 0 || itmp ==1) {
						 ActBut(&isobut[0],0);
					   }
					   break;
					} else {
                             		   if (itmp == 0 || itmp ==1) {
						isobut[0].str = 
						   ChainLength[surface->nvalc];
						ActBut(&isobut[0],0);
						RedrawISO();
					   }
					}
				   }
				   RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
				}
				if (itmp == 3) {
				   qboxstr(&qboxes[QSRFW],NULL,1,0,-1,
				    DEFQX,DEFQY,QBOXWIDE,QBOXHIGH,0,
				    "Surface Filename ? ",NULL,0,0,
				    573,dummyproc);
				    break;
				}
				if (itmp == 4) {
				   qboxstr(&qboxes[QSRFW],NULL,1,0,-1,
				    DEFQX,DEFQY,QBOXWIDE,QBOXHIGH,0,
				    "Surface Filename ? ",NULL,0,0,
				    574,dummyproc);
				    break;
				}
				if (itmp == 10) {
				   int ieemopt = 1;
				   List.list = eems; List.nents = 4;
				   if (DoPopUp(winMC,
					cbut[BSURF].x+50,
					cbut[BSURF].y+11*LINEHIGH,
					&List,&ieemopt,0) == -1) break;
				   RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
				   inichg(ieemopt);
				   break;
				}
				if (itmp == 13) {
				    int iii;
				    if (DoPopUp(winMC,
					      cbut[BSURF].x-8,cbut[BPAL].y+BUTTH,
					      NULL,&iii,0) == -1) break;
				    iii++;
				    molsrf(iii);
				    break;
				}
				if (itmp == 14) {
				   qboxstr(&qboxes[QSRFW],NULL,1,0,-1,
				    DEFQX,DEFQY,QBOXWIDE,QBOXHIGH,0,
				    "Omap/DSN6 Filename ? ",NULL,0,0,
				    583,dummyproc);
				    break;
				}
				*incp = 0;
#ifdef DOGL
				if (itmp == 5) 
#if defined(VMS) || defined(UNDERSC)
				srfclr();
#else

#ifdef CRAY
				SRFCLR();
#else
				srfclr_();
#endif

#endif
#endif
				if (itmp == 12) {
				   if (qdpptr->ihsdp) {
					if (qdpptr->idipon) {
					   qdpptr->idipon = 0;
					} else {
					   qdpptr->idipon = 1;
#if defined(VMS) || defined(UNDERSC)
					   putxyz();
#else

#ifdef CRAY
					   PUTXYZ();
#else
					   putxyz_();
#endif

#endif
					}
				   } else {
#if defined(VMS) || defined(UNDERSC)
					calelt();
#else

#ifdef CRAY
					CALELT();
#else
					calelt_();
#endif

#endif
				   	if (qdpptr->ihsdp) qdpptr->idipon = 1;
				   }
#ifdef DOGL
				   if (qdpptr->idipon) ogdipole();
#endif
				   if (qdpptr->idipon) 
#if defined(VMS) || defined(UNDERSC)
					   prtdip();
#else

#ifdef CRAY
					   PRTDIP();
#else
					   prtdip_();
#endif

#endif
				   update_struct();
				}
#ifdef MPFIT
				if (itmp == 15) {
				    List.nents = 2;
				    if (DoPopUp(winMC,
					cbut[BSURF].x+1,cbut[BSURF].y+BUTTH,
					&List,incp,0) == -1) *incp = 0;
				}
#endif
				*inct = 570+itmp;
			      break;}
                 case BHYD: {
				   if (!cbut[BHYD].toggle) {
					TogUp(&cbut[BHYD]);
					*inct = 620;
				   } else {
					int itmp;
					LSSTRU List;
					List.list = hyds; List.nents = 4;
					if (DoPopUp(winMC,
					     cbut[BHYD].x+1,cbut[BHYD].y+BUTTH,
					     &List,&itmp,0) == -1) break;
					if (itmp != 2 && itmp != 3) TogDown(&cbut[BHYD]);
					if (itmp == 3) InitPar();
					else *inct = 621+itmp;
				   }
			      break;}
                 case BVRML: {
				LSSTRU List;
				List.list = vrmlopt; List.nents = 4;
				if (DoPopUp(winMC,
					cbut[BVRML].x+1,cbut[BVRML].y+BUTTH,
					&List,ivtwo,0) == -1) break;
				update_model = 0;
				if (*ivtwo == 3 || (*ivtwo == 2 && *ipdbon && backb)) {
				   *inct = 116;
				} else {
				   qboxstr(&qboxes[QVRML],NULL,1,0,-1,DEFQX,
					DEFQY, QBOXWIDE,QBOXHIGH,0,
					"VRML Filename ? ",NULL,0,0,
					586,dummyproc);
				}
			      }
			      break;
                 case BALIGN: {
				LSSTRU List; int ial;
				List.list = alnopt; List.nents = 2;
				if (DoPopUp(winMC,
					cbut[BALIGN].x+1,cbut[BALIGN].y+BUTTH,
					&List,&ial,0) == -1) break;
			if (ial == 0) {
				if (!DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
	"Supply the name of the XYZ file containing the structure\n\
to align to the current molecule.\n \n\
 - Use the standard rotation, translation and zoom in/out.\n\
 - Use the Esc to switch between rotation of part or the whole structure\n\
 - Use the Tab to enter the select mode; select 3 couples of atoms to align\n\
   A couple= atom structure1 (red), atom structure2 (white)",1)) {
				 qboxstr(&qboxes[QMXYZ],NULL,1,0,-1,DEFQX,DEFQY,
				   QBOXWIDE,QBOXHIGH, 0,"XYZ file ? ",NULL,0,0,
				   152,dummyproc);
				}
			} else {
			    LSSTRU List; int ibl;
			    List.list = dckopt; List.nents = 2;
			    if (DoPopUp(winMC,
				cbut[BALIGN].x+1,cbut[BALIGN].y+BUTTH,
				&List,&ibl,0) == -1) break;
			    if (ibl == 0) {
				*iocnt = 0;
				if (!DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
	"To you want to overlay the centers of the two molecules ? \n\
Click Cancel if you want to keep the original coordinates",1)) {
				   *iocnt = 1;
				}
				if (!DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
	"Supply the name of the PDB file containing the ligand\n\
to align to the current molecule.\n \n\
 - Use the standard rotation, translation and zoom in/out.\n\
     Cntrl+mouse       = Zoom / Z-translation,\n\
     Shift+mouse       = X/Y-translation\n\
     Cntrl+Shift+mouse = Z-rotation\n\
 - Use the Esc to switch between rotation of part or the whole structure\n\
 - Use the arrow keys  in addition to the mouse for rotation\n\
 - Use the Keypad keys in addition to the mouse for translation\n\n\
   Translation X-axis:      KP_4, KP_6  \n\
   Translation Y-axis:      KP_8, KP_2  \n\
   Translation Z-axis:      KP_1, KP_3  \n\
   Rotation    Z-axis:      KP_7, KP_9  \n\n\
 - DONT FORGET to switch on the NUMLOCK key when using the Keypad keys\n\
 - Use the Coarse icon (between the arrow buttons) to change the step/angle\n\
   increment ",1)) {
				 qboxstr(&qboxes[QMXYZ],NULL,1,0,-1,DEFQX,DEFQY,
				   QBOXWIDE,QBOXHIGH, 0,"PDB file ? ",NULL,0,0,
				   1520,dummyproc);
				 }
			    } else {
				if (!DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
	"Select a ligand Molecule on screen by clicking one of its atoms\n\n\
 - Use the standard rotation, translation and zoom in/out.\n\
     Cntrl+mouse       = Zoom / Z-translation,\n\
     Shift+mouse       = X/Y-translation\n\
     Cntrl+Shift+mouse = Z-rotation\n\
 - Use the Esc to switch between rotation of part or the whole structure\n\
 - Use the arrow keys  in addition to the mouse for rotation\n\
 - Use the Keypad keys in addition to the mouse for translation\n\n\
   Translation X-axis:      KP_4, KP_6  \n\
   Translation Y-axis:      KP_8, KP_2  \n\
   Translation Z-axis:      KP_1, KP_3  \n\
   Rotation    Z-axis:      KP_7, KP_9  \n\n\
 - DONT FORGET to switch on the NUMLOCK key when using the Keypad keys\n\
 - Use the Coarse icon (between the arrow buttons) to change the step/angle\n\
   increment ",1)) {
				   *iocnt = 0;
				   bflag = 1; doret = 1; bretval = 562;
			           XDefineCursor(display,win,AtomCursor);
				 }
			    }
			}
				 doalign = 1;
			      }
			      break;
                 case BORIG: {bflag = 1; doret = 0; bretval = 560;
			      strcpy(molwstr,"Click on atom to set Origin !");
			      StatusStr(0,1);
			      XDefineCursor(display,win,AtomCursor);
			      break;}
                 case BCELL: { int icell; int iwcell; LSSTRU List;
				List.list = cellopts; List.nents = ncell;
				if (DoPopUp(winMC,
					cbut[BCELL].x-8,cbut[BCELL].y-BUTTH,
					&List,&icell,0) == -1) break;
                                if (! *ichx) {
#if defined(VMS) || defined(UNDERSC)
					mkcell(xyz.coo,xyz.ianz,xyz.iatclr,xyz.iconn);
#else
#ifdef CRAY
					MKCELL(xyz.coo,xyz.ianz,xyz.iatclr,xyz.iconn);
#else
					mkcell_(xyz.coo,xyz.ianz,xyz.iatclr,xyz.iconn);
#endif
#endif
					*ichx = 1;
				}
				*incp = icell + 1;
				if (icell == 19) {
				   List.list = cellwopts; List.nents = nwcell;
				   RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
				   XFlush(display); XSync(display,False);
				   if (DoPopUp(winMC,
					cbut[BCELL].x-8,cbut[BCELL].y+7*BUTTH,
					&List,&iwcell,0) == -1) break;
				   *incp = 20 + iwcell;
				}
                                *inct = 550;
		 		TogUp(&cbut[BHYD]);
				if (icell == 13) {
				   if (DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
	" - Use the standard rotation, translation and zoom in/out.\n\
 - Use the Esc to switch between rotation of part or the whole structure",1)) {
					*inct = 0;
				   } else {
					doalign = 0;
				   }
				}
				if (icell == 14) {
				   CreateCellPar();
				   doret = 0;
				   *inct = 0;
				}
				if (icell == 18) {
				   RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
				   List.list = xtinkopts; List.nents = 2;
				   if (DoPopUp(winMC,
					cbut[BCELL].x-8,cbut[BCELL].y+BUTTH,
					&List,iqopt,0) == -1) break;
				}
				if (icell == 15 || icell == 16) {
				   InitCellDelTrans();
				   *incp = 2;
				   if (icell == 15) InitCellDelTrans(1);
				   else InitCellDelTrans(0);
				}
			   }
			   break;
                 case BFORC:  if (pdb) {
				 if (qbres) {
				    TogUp(&cbut[BFORC]);
				    qbres = 0;
				    XUnmapWindow(display,RESwin);
				 } else {
				    XMapWindow(display,RESwin); qbres = 1;
				    TogDown(&cbut[BFORC]);
		                    qboxstr(&qboxes[QRESI],&RESwin,1,0,-1,DEFQX,DEFQY,
				    QBOXWIDE,QBOXHIGH,0,"Display residue(s) ? ",
				    NULL,0,0,460,dummyproc);
				 }
				update_model = 0;
		              } else { 
				if (frfor) {
				   if (FRup) {
                                           XDestroyWindow(display,FrBox);
					   if (specup) {
					      XDestroyWindow(display,winspec);
					      specup = 0;					
					   }
					   *inct = 520;
					   DoFreq = 0;
					   FRup = 0;
				           TogUp(&cbut[BFORC]);
				   } else {
					   createfr();
					   createspec();
					   DoFreq = 1;
					   FRup = 1;
				           TogDown(&cbut[BFORC]);
				   }
				} else {
				   *incp = TogBut(&cbut[BFORC]);
				   *inct = 130;
				}
				update_model = 0;
			      }
                              break;
                 case BINCRF: if (pdb) {
				bflag = 1; doret = 0; bretval = 320;
				strcpy(molwstr,"Click on the backbone to activate !");
				StatusStr(0,1);
				XDefineCursor(display,win,AtomCursor);}
                              else {
				*inct = 160;*incp = 1;
			      }
                              break;
                 case BDECRF: if (pdb) {
				if (NHetAtm) {
				 LSSTRU List; int iop; 
				 if (!calfptr->issdon) {
#if defined(VMS) || defined(UNDERSC)
					ribbs();
#else
#ifdef CRAY
					RIBBS();
#else
					ribbs_();
#endif
#endif
					calfptr->ihet[0] = 0;
					calfptr->ihet[1] = 0;
					calfptr->ihet[2] = 0;
					calfptr->ihet[3] = 0;
				 }

				 List.list = HetAtm; List.nents = NHetAtm;
				 if (DoPopUp(winMC,
					cbut[BDECRF].x+1,cbut[BDECRF].y+BUTTH,
					&List,&iop,0) == -1) break;
				 *incp = -1*iop;

                		 if (!monoscr && calfptr->ihet[iop] == 0) {

/* switch ON helix/strand/.. or hetatm */

					if (DoPopUp(winMC,
					  cbut[BDECRF].x-8,cbut[BDECRF].y+BUTTH,
					  NULL,Snstr,0) == -1) break;
					*Snstr = *Snstr + 1;

					if (iop == 0 || iop == 1) {
					   if (iop == 0) {
						SetSurfColor(0,*Snstr);
					   } else if (iop == 1) {
					      for (i=0; i < 4; i++) 
						SetSurfColor(4+i,*Snstr);
					   }
					   for (i=0; i < 4; i++) 
						SSon[iop*4+i] = 1;
					} else if (iop == 2 || iop == 3) {
					   SSon[iop+6] = 1;
					   SetSurfColor(iop+6,*Snstr);
					}
				 } else {

/* switch OFF helix/strand/.. or hetatm */

					*Snstr = 1;
					if (iop == 0 || iop == 1) {
					   for (i=0; i < 4; i++)
						SSon[iop*4+i] = 0;
					} else if (iop == 2 || iop == 3) {
					   SSon[iop+6] = 0;
					}
#ifdef DOGL
					ogbck(iop);
#endif
				 }
				 *inct = 330; 
				}
			      }
                              else {*inct = 160;*incp = -1;}
			      break; 
                 case BUNSC:  if (pdb) {*inct = 340;
					TogBut(&cbut[BUNSC]);}
                              else {*inct = 160;*incp = 0; }
                              break;
                 case BHBOND: if (pdb) {
                                int ict;

			        TogBut(&cbut[BHBOND]);
				if (!hbon) { 
				   hbon = 1;
				   ict = 490;
				   if (*ipdbon && *zmptr.ihaszm) ict = 625;
				   qboxstr(&qboxes[QHBOND],NULL,1,0,-1,
					DEFQX, DEFQY, QBOXWIDE,QBOXHIGH, 0,
					"Maximum H-bond distance (Angs.) ? ",
					NULL, 0,2,ict,dummyproc);
				} else {
				   hbon = 0;
				   if (*ipdbon && *zmptr.ihaszm) {
					*inct = 624;
				   } else {
					*inct = 490;*incp = -1;
				   }
				}
                              }
                              break;
                 case BWRITF: { LSSTRU List; 
			      List.list = wropt; List.nents = 15;
			      if (DoPopUp(winMC,
					cbut[BWRITF].x+1,cbut[BWRITF].y+BUTTH,
					&List,iwropt,0) == -1) break;
			      if (*iwropt == 8) {
				List.list = pdbwh; List.nents = 3;
				if (DoPopUp(winMC,
					cbut[BWRITF].x+1,cbut[BWRITF].y+BUTTH,
					&List,ipdbwh,0) == -1) break;
			      }
			      if (*iwropt == 13) {
				   WriteCML();
				   strcpy(molwstr,"Wrote file molecule.cml");
				   StatusStr(0,1);
				   break;
			      }
			      if (*iwropt >= 3) *ixyz = *iwropt - 3;
			      *iwropt = *iwropt + 1;
			      if (*iwropt > 4) *iwropt = 4;
			      qboxstr(&qboxes[QPOST],NULL,1,0,-1,DEFQX,DEFQY,
					QBOXWIDE,QBOXHIGH,0,"Filename ? ",NULL,
					0,0,470,dummyproc);
			      update_model = 0;
			      }
                              break;
                 case BREADF: 
				if (qbrfile) {
				   TogUp(&cbut[BREADF]);
				   qbrfile = 0;
				   XUnmapWindow(display,Fwin);
				}
				else {
				   TogDown(&cbut[BREADF]);
				   qbrfile = 1;
    				   DefList(&flist,Fwin,DIRX,DIRY,DIRW,DIRH,NULL,
					NFLS,files,NULL,NULL,&nfiles);
				   flist.select = selfil;
				   flist.lpnt = lpnt;
    				   DefList(&dirlist,Fwin,DDIRX,DDIRY,DDIRW,
					DDIRH,NULL,NDRS,dirs,NULL,NULL,&ndirs);
				   dirlist.select = seldir;
				   dirlist.lpnt = 0;
				   XMapWindow(display,Fwin);
		                   qboxstr(&qboxes[QREADF],&Fwin,1,0,-1,DEFQX,DEFQY,
				    QBOXWIDE,QBOXHIGH,0,"Directory: ",lastdir,0,
				    0,480,fwincall);
				   TogDown(&dbut[BMOL]);
				   TogDown(&dbut[BCONT]);
				   TogUp(&dbut[BFILL]);
				   TogUp(&dbut[BORI]);
				}
			        update_model = 0;
				break;
                 case BZMAT:    if (ZMEup) {
				   UnMapZME();
				}
				else {
				   if (pdb && !*zmptr.ihaszm) {
					if (!DoPDB()) break;
				   }
#if defined(VMS) || defined(UNDERSC)
				   clrmon();
#else
#ifdef CRAY
				   CLRMON();
#else
				   clrmon_();
#endif
#endif
				   TogDown(&cbut[BZMAT]);
        			   if (denm) ActBut(&cbut[BDENMOD],0);
				   if (pdb) {
				      if (ialtyp == NULL) ZMEAA = 1;
				      else if (*ialtyp == 1) ZMEAA = 0;
				      else ZMEAA = 1;
				   }
				   InitZME(); 
				   if (pdb) {
				      if (ialtyp == NULL) ZMEAA = 1;
				      else if (*ialtyp == 1) ZMEAA = 0;
				      else if (calfptr->ncalf <= 0) ZMEAA = 0;
				      else ZMEAA = 1;
				   }
				}
				*inct = 630;
			        update_model = 0;
				break;
                 case BDIST:  
			        update_model = 0;
                                if (!Selecting && !cflag && !dflag) {
				   *inct = 170;*incp = 1; 
				   aflag = 2;anum = 2;acnt = 0;
				   XDefineCursor(display,win,AtomCursor);
				}
                                break;
                 case BANGLE:  
			        update_model = 0;
                                if (!Selecting && !cflag && !dflag) {
				   *inct = 170;*incp = 2; 
				   aflag = 3;anum = 3;acnt = 0;
				   XDefineCursor(display,win,AtomCursor);
				}
                                break;
                 case BDIHED:  
			        update_model = 0;
                                if (!Selecting && !cflag && !dflag) {
				   *inct = 170;*incp = 3;
				   aflag = 4;anum = 4;acnt = 0;
				   XDefineCursor(display,win,AtomCursor);
				}
				break;
                 case BAUTH:
				if (!ATMup) InitATM(event.xbutton.x_root,
						    event.xbutton.y_root);
			        update_model = 0;
				break;
                 case BPAL:
			       { int iii, clopt;
				 LSSTRU List;
				 List.list = palopt; List.nents = 7;
				 if (DoPopUp(winMC,
					cbut[BPAL].x+1,cbut[BPAL].y+BUTTH,
					&List,&clopt,0) == -1) {
			        	update_model = 0;
					break;
				 }
				 if (clopt == 0) {
				   List.list = bgopt; List.nents = 2;
				   if (DoPopUp(winMC,
					cbut[BPAL].x+1,cbut[BPAL].y+BUTTH,
					&List,&BGmode,0) == -1) break;
				   WriteRes();
				 } else if (clopt == 1 || clopt == 2) {
				   if (!monoscr) {
					int colt;
			                update_model = 0;
					if (clopt == 1) {
					   if (DoPopUp(winMC,
					      cbut[BPAL].x-8,cbut[BPAL].y+BUTTH,
					      NULL,&iii,0) == -1) break;
					   colt = iii+1;
					} else {
					   if (has_opengl && *fancy) {
						colt = 13; BGmode = 1;
					   } else colt = 0;
					}
					if (has_opengl && *fancy) {
					   OBGcolor = colt;
					} else {
					   IBGcolor = colt;
					}
					XSetBackground(display, gc, 
						colors[IBGcolor]);
#ifdef DOGL
					if (has_opengl) {
					   setobg();

					   fogColor[0] = ((GLfloat) colorr[OBGcolor]) / 65535.0 ;
					   fogColor[1] = ((GLfloat) colorg[OBGcolor]) / 65535.0 ;
					   fogColor[2] = ((GLfloat) colorb[OBGcolor]) / 65535.0 ;
					}
#endif
					WriteRes();
				   }
				 } else if (clopt == 3) {
			           update_model = 0;
				   if (!COLup) InitCOL();
				   else XMapRaised(display,COLwin);
				 } else if (clopt == 4) {
				   if (!monoscr) {
					if (DoPopUp(winMC,
					    cbut[BPAL].x-8,cbut[BPAL].y+BUTTH,
					    NULL,&iii,0) == -1) break;
					activecolor = iii + 1;
			                update_model = 0;
					if (!ECOLup) EditCOL();
					else XMapRaised(display,ECOLwin);
				   }
				 } else if (clopt == 5) {
					ResetColors();
				 } else if (clopt == 6) {
			                update_model = 0;
					if (!DPTup) InitDPT();
					else XMapRaised(display,DPTwin);
				 }
			       }
			       break;
                 case BGIF:
                              { if (dogif) {
				   dogif = 0;
				   TogBut(&cbut[BGIF]);
				} else {
/*				   if (DisplayPlanes(display, screen) > 8) {*/
  if (DisplayCells(display, screen) > 256) {;
				 	strcpy(molwstr,"GIF file only for 8-bits screen");
				 	StatusStr(0,1);
				   } else {
					dogif = 1;
#ifdef DOGL
					if (has_opengl && *fancy) {
				 	   strcpy(molwstr,"a Gif file per screen update");
				 	   StatusStr(0,1);
				           if (dogif) {
				              picnum++;
				              if (picnum < *picmax) {
				   		glXWaitGL();
				   		sprintf(stemp, "%s%03d.gif",GifFile,picnum);
						WOGLGIF(stemp);
				   		glXSwapBuffers(display, win);
				   	      }
				   	   }
					} else {
				 	   strcpy(molwstr,"a GIF file per screen update");
				 	   StatusStr(0,1);
#endif
#if defined(VMS) || defined(UNDERSC)
					   doexp();
#else
#ifdef CRAY
					   DOEXP();
#else
					   doexp_();
#endif
#endif
#ifdef DOGL
					}
#endif
					TogBut(&cbut[BGIF]);
				   }
				}
			        update_model = 0;
				doret = 0;
				break;}
                 case BLABEL:  
				if (cbut[BLABEL].toggle) {
				   LSSTRU List;
				   List.list = labels; 
				   List.nents = 6;
				   if (DoPopUp(winMC,
					cbut[BLABEL].x+1,cbut[BLABEL].y,
					&List,iqon,0) == -1) break;
				   if (*iqon == 3 && !*ihasq) {
					strcpy(molwstr,
					     "Click on atom to set Origin !");
					StatusStr(0,1);
				   }
				}
				*inct = 180;*incp = 0;
				update_model = 0;
				TogBut(&cbut[BLABEL]);
				break;
                 case BSHADE:  
				if (*shade) {
				   *shade = 0;
				   TogUp(&cbut[BSHADE]);
				   if (DPTup) XUnmapWindow(display,DPTwin);
				} else {
				   if (colcells >= 256) *shade = 1;
				   if (*shade) TogDown(&cbut[BSHADE]);
				   if (!DPTup) InitDPT();
				   else XMapRaised(display,DPTwin);
				}
#ifdef DOGL
			        EnableFog();
#endif
			        update_model = 0;
				break;

                 case BBACKB:  *inct = 310;*incp = 0; 
				TogBut(&cbut[BBACKB]);
                               if (!backb) {
                                   backb = 1; 
                                   ActBut(&cbut[BFORC],1);
                                   ActBut(&cbut[BINCRF],1);
                                   ActBut(&cbut[BHBOND],1);
			/*	   if (!backb) {*/
                                      ActBut(&cbut[BDECRF],1);
                                      ActBut(&cbut[BUNSC],1);
                                      DrwBut(&cbut[BDECRF]);
                                      DrwBut(&cbut[BUNSC]);
                        /*           } */
                                   DrwBut(&cbut[BFORC]);
                                   DrwBut(&cbut[BINCRF]);
                                   DrwBut(&cbut[BHBOND]);
			           preset();
                               }
                               else {
                                   backb = 0;
                                   ActBut(&cbut[BFORC],0);
                                   ActBut(&cbut[BINCRF],0);
                                   ActBut(&cbut[BDECRF],0);
                                   ActBut(&cbut[BUNSC],0);
                                   ActBut(&cbut[BHBOND],0);
                                   DrwBut(&cbut[BFORC]);
                                   DrwBut(&cbut[BINCRF]);
                                   DrwBut(&cbut[BDECRF]);
                                   DrwBut(&cbut[BUNSC]);
				   for (j=0; j < MXHETA; j++) 
					calfptr->ihet[j] = 0;
				   for (j=0; j < calfptr->ncalf; j++) 
					calfptr->reson[j] = 1;
				   for (i=0; i < *xyz.iatoms; i++ ) 
					xyz.iaton[i] = 1;
	    	 		   update_sel = 1;
                               }
                               break;
                 case BATCOL:  *inct = 400;*incp = 0; 
				TogBut(&cbut[BATCOL]); break;
                 case BPERSP:  *inct = 410;*incp = 0; 
			       update_model = 0;
				TogBut(&cbut[BPERSP]); break;
                 case BLEFT:    hold = 1; holdt = 420; holdp = 0;
			       update_model = 0;
				*inct = 420;*incp = 0; break;
                 case BRIGHT:   hold = 1; holdt = 430; holdp = 0;
			       update_model = 0;
				*inct = 430;*incp = 0; break;
                 case BUP:      hold = 1; holdt = 440; holdp = 0;
			       update_model = 0;
				*inct = 440;*incp = 0; break;
                 case BDOWN:    hold = 1; holdt = 450; holdp = 0;
			       update_model = 0;
				*inct = 450;*incp = 0; break;
		 case BBALL:    
				if (*ball) {
				   *ball = 0;
				   strcpy(molwstr,"Old Style rotation");
				   StatusStr(0,1);
				} else {
				   *ball = 1;
				   strcpy(molwstr,"Sticky Pointer rotation");
				   StatusStr(0,1);
				}
				WriteRes();
				TogBut(&cbut[BBALL]);
				hold = 0;
			        update_model = 0;
				break;
                 case BPACE:   {
                                *inct = 500;
			       update_model = 0;
                               if (coarse == 2) {
                                  coarse = 0;
                                  cbut[BPACE].pix = slowPix;
                               }
                               else if(coarse == 1) {
                                  coarse = 2;
                                  cbut[BPACE].pix = blastPix;
                               }
                               else {
                                  coarse = 1;
                                  cbut[BPACE].pix = fastPix;
                               }
                               DrwBut(&cbut[BPACE]);
                               *incp = coarse; break;
                               }
                 case BCONV: 
                              {
			       update_model = 0;
                               if (!cnvup)
                                    {createconv();cnvup = 1;}
                               else {
                                    XDestroyWindow(display,wincnv);cnvup = 0;}
                               break;}
                 case BGEOM: 
                              {
			       update_model = 0;
                               if (!geoup) {
                                    if (*geopntr.gcvav) {
				        TogDown(&cbut[BGEOM]);
					creategeom();
					geoup = 1;
				    }
			       }
                               else {
				    TogUp(&cbut[BGEOM]);
                                    XDestroyWindow(display,wingeo);geoup = 0;}
                               break;}


                 }/*end switch*/
                 if (doret) return(0);
                 }
              }/* end if*/
 

           }/*end buttonpress*/
           break;


           case MotionNotify: {


              if(DEBUG)fprintf(stderr,"MotionNotify\n");

	      motion_screen(inct,incp);

	      SetExplButton(event.xmotion.window,
		event.xmotion.x,event.xmotion.y);

              if(event.xmotion.window == wincnv) {
		if (cnvptr->icvav1) 
			parse_motion(&scfEfirst);
		if (cnvptr->icvav2) 
			parse_motion(&scfElast);
	      }

              if (event.xmotion.window == winspec) {
			parse_motion(&spect);
	      }

              if (event.xmotion.window == winsco && scoup) {
			parse_motion(&docksco);
	      }

              if(event.xmotion.window == wingeo) {
		if (*geopntr.gcvav) {
			if (*geopntr.ifmxav) parse_motion(&geoFmax);
      			if (*geopntr.ifrmav) parse_motion(&geoFrms);
			if (*geopntr.idmxav) parse_motion(&geoSmax);
			if (*geopntr.idrmav) parse_motion(&geoSrms);
			if (*geopntr.ieav) parse_motion(&geoE);
		}
	      }

              if(event.xmotion.window == win && ZoomSelection) {


                 while(XCheckTypedWindowEvent(display, win, MotionNotify,
                                        &event));

                 MotionCount++;

                 XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);

                 /* get the location of the pointer */

                 ZoomX2 = MAXI(ZoomX1, event.xmotion.x);
                 ZoomY2 = MAXI(ZoomY1, event.xmotion.y);
                 ZoomW = MAXI(ABS(ZoomX2 - ZoomX1),1);
                 ZoomH = MAXI(ABS(ZoomY2 - ZoomY1),1);
                 XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);

              } /* end ZoomSelection */

                                                                                
           } /* end MotionNotify */
           break;


           case ButtonRelease: {

              if (!(*fancy  && has_opengl) && event.xbutton.window == win) {
		 moving = 0;
		 gmoving = 0;
	      }

              if (event.xbutton.window == win && 
		  (event.xbutton.button == 1 || event.xbutton.button == 2) &&
                  !ZoomSelection ) moving = 0;

              if (event.xbutton.window == win && (event.xbutton.button == 1 ||
                 event.xbutton.button == 2) && ZoomSelection ) {

                 ZoomSelection = False;
                 XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);
                 XSetFunction(display, gc, GXcopy);
                 XUndefineCursor(display, win);

                 if (MotionCount >=3 ) {
                    for ( i = 0; i < *xyz.iatoms; i++ ) {
                      if (xyz.iaton[i] >= 1 && 
                      VIERKANT(xyz.iyp[i], xyz.ixp[i], 
				ZoomX1, ZoomY1, ZoomW, ZoomH)) {
                         if (Select && xyz.ianz[i] != 100) xyz.iaton[i] = 2;
                         else xyz.iaton[i] = 1;
                      }
                    }
		    if (SelRes != -3) {
			for ( i = 0; i < *xyz.iatoms; i++ ) {
			   if (xyz.iaton[i] > 1) {
				xyz.iresid[i] = SelRes;
	   			xyz.iatclr[i] = xyz.iatclr[ATMsel];
				xyz.iaton[i] = 1;
			   }
			}
			SelRes = -3;
		    }
	    	    update_model = 0;
	    	    update_sel = 1;
                    return(0);
                 }

              } /* end zoom */

              if ((*fancy  && has_opengl) && event.xbutton.window == win) {
		 mouseu(event.xbutton.button,event.xbutton.state, event.xbutton.x, event.xbutton.y);
                 dispsf();
		 break;
	      }

           } /* end ButtonRelease */
           break;
                                                                                
  	
           case Expose: {


	      update_model = 0;
              if (DEBUG) fprintf(stderr,"Expose\n");

	      while (XCheckWindowEvent(display, event.xexpose.window, 
			ExposureMask, &event));

              if ( !(*fancy && has_opengl)  && event.xexpose.window == win) {
                 if ( molback == molcur ) {
                    XCopyArea(display,molcur,win,gc,0,0,width,height,0,0);
                 }
              }

              if ((*fancy && has_opengl) && event.xexpose.window == win) {
                dispsf();
		break;
              }
              for (i=0; i<NQBOX; i++) { 
		if (event.xexpose.window == qboxes[i].win)
			PromptBox(&qboxes[i]);
	      }	
	      if (event.xexpose.window == ONIwin) RedrawONI();
	      if (event.xexpose.window == RESwin) RedrawRESwin();
	      if (event.xexpose.window == Fwin) RedrawFwin();
	      if (event.xexpose.window == ZMEwin) RedrawZME();
	      if (event.xexpose.window == COLwin) RedrawCOL();
	      if (event.xexpose.window == ECOLwin) RedrawECOL();
	      if (event.xexpose.window == DPTwin) RedrawDPT();
              if (event.xexpose.window == DISTwin) RedrawDIST();
              if (event.xexpose.window == SUBwin) RedrawSUB();
              if (event.xexpose.window == ISOwin) RedrawISO();
              if (event.xexpose.window == ATMwin) RedrawATM();
	      if (event.xexpose.window == CPwin) RedrawCP();
	      if (event.xexpose.window == CTwin) RedrawCT();
	      if (event.xexpose.window == SEQwin) RedrawSEQ();
	      if (event.xexpose.window == TNKwin) RedrawTNK();
	      if (event.xexpose.window == DELAYwin) RedrawDEL();
	      if (event.xexpose.window == SRFwin) RedrawSRF();
	      if (event.xexpose.window == FLXwin) RedrawFLX();
	      if (event.xexpose.window == CHGwin) RedrawCHG();
	      if (event.xexpose.window == PARwin) RedrawPAR();

	      if (event.xexpose.window == FrBox) RedrawList(&frlist);

              if (event.xexpose.window == winMC) {
                   RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);}


              if (event.xexpose.window == winau && gijsup) {
                   XSetForeground(display, gc, infobg);
                   XSetBackground(display, gc, infofg);
                   XCopyPlane(display, gijs, winau, gc, 0, 0, gijsface_width,
                   gijsface_height, 0, 0, (unsigned long)1);}

              if (event.xexpose.window == wincnv && cnvup)
		   drwcnv();

              if (event.xexpose.window == winspec && specup)
		   drwspec();

              if (event.xexpose.window == winsco && scoup)
		   drwsco();

              if (event.xexpose.window == winpmf && pmfup)
		   drwpmf();

              if (event.xexpose.window == FLXwin && FLXup)
	           RedrawList(&flxlist);

              if (event.xexpose.window == PARwin && PARup)
	           RedrawPAR();

              if (event.xexpose.window == CHGwin && CHGup)
	           RedrawCHG();

              if (event.xexpose.window == wingeo && geoup) 
		   XClearWindow(display,wingeo);

#if defined(VMS) || defined(UNDERSC)
                   drwgeo();
#else
#ifdef CRAY
                   DRWGEO();
#else
                   drwgeo_();
#endif
#endif

           }
           break;

	   case EnterNotify: {
	      if (event.xcrossing.subwindow == expldat.win) DoExpl();
           }
           break;

	   case ClientMessage: {
		Atom proto, delwin;
		XClientMessageEvent *client_event = 
			(XClientMessageEvent *) &event;

		proto = XInternAtom(display, "WM_PROTOCOLS", False);
		delwin = XInternAtom(display, "WM_DELETE_WINDOW", False);

		if (client_event->message_type == proto &&
		    client_event->data.l[0] == delwin) {
		    if (client_event->window == ZMEwin) {
			UnMapZME();
		    } else if (client_event->window == RESwin) {
			if (qbres) {
			    TogUp(&cbut[BFORC]);
			    qbres = 0;
			    XUnmapWindow(display,RESwin);
			}
		    } else if (client_event->window == Fwin) {
			if (qbrfile) {
			    TogUp(&cbut[BREADF]);
			    qbrfile = 0;
			    XUnmapWindow(display,Fwin);
			}
		    } else if (client_event->window == DISTwin) {
			if (distup) {
			    distup = 0;
			    XUnmapWindow(display,DISTwin);
			}
		    } else if (client_event->window == FrBox) {
			if (frfor && FRup) {
			    TogUp(&cbut[BFORC]);
			    XDestroyWindow(display,FrBox);
			    DoFreq = 0;
			    FRup = 0;
			}
		    } else if (client_event->window == winspec) {
			if (frfor && specup) {
			    XDestroyWindow(display,winspec);
			    specup = 0;
			}
		    } else if (client_event->window == wingeo) {
			if (geoup) {
			    TogUp(&cbut[BGEOM]);
			    XDestroyWindow(display,wingeo);
			    geoup = 0;
			}
		    } else if (client_event->window == wincnv) {
			if (cnvup) {
			    XDestroyWindow(display,wincnv);
			    cnvup = 0;
			}
		    } else if (client_event->window == winsco) {
			if (scoup) {
			    XDestroyWindow(display,winsco);
			    scoup = 0;
			}
		    } else if (client_event->window == winpmf) {
			if (pmfup) {
			    XDestroyWindow(display,winpmf);
			    pmfup = 0;
			}
		    } else if (client_event->window == winspec) {
			if (specup) {
			    XDestroyWindow(display,winspec);
			    specup = 0;
			}
		    } else if (client_event->window == CPwin) {
			if (CPup) {
			    XDestroyWindow(display,CPwin);
			    CPup = 0;
			}
		    } else if (client_event->window == ATMwin) {
			if (ATMup) {
			    XDestroyWindow(display,ATMwin);
			    ATMup = 0;
			}
		    } else if (client_event->window == COLwin) {
			if (COLup) {
			    XDestroyWindow(display,COLwin);
			    COLup = 0;
			}
		    } else if (client_event->window == ECOLwin) {
			if (ECOLup) {
			    XDestroyWindow(display,ECOLwin);
			    ECOLup = 0;
			}
		    } else if (client_event->window == CTwin) {
			if (CTup) {
			    XDestroyWindow(display,CTwin);
			    CTup = 0;
			}
		    } else if (client_event->window == DPTwin) {
			if (DPTup) {
			    XDestroyWindow(display,DPTwin);
			    DPTup = 0;
			}
		    } else if (client_event->window == SUBwin) {
			if (SUBup) {
			    XDestroyWindow(display,SUBwin);
			    SUBup = 0;
			}
		    } else if (client_event->window == SEQwin) {
			if (SEQup) {
			    XDestroyWindow(display,SEQwin);
			    SEQup = 0;
			}
		    } else if (client_event->window == TNKwin) {
			if (TNKup) {
			    XDestroyWindow(display,TNKwin);
			    TNKup = 0;
			}
		    } else if (client_event->window == winau) {
			if (gijsup) {
			    XFreePixmap(display,gijs);
			    XDestroyWindow(display,winau);
			    gijsup = 0;
			}
		    } else if (client_event->window == QBox) {
			XDestroyWindow(display,QBox);
			XSync(display, False);
		        qboxup = 0;
		    } else if (client_event->window == winMC ||
				client_event->window == win) {
			if (DoCan(width/2, height/2,
				"Use the Skull Icon to quit Molden",0)) {}
		    }
		}
	   }
	   break;

           case ConfigureNotify: {

              if(DEBUG)fprintf(stderr,"ConfigureNotify\n");

              /* you want to increase or decrease the size of the window*/
              /* get the new width and height*/

              if (event.xconfigure.window == win) {

		   /* check for real resize */

                   if (event.xconfigure.width == width &&
                       event.xconfigure.height == height) {
			if (has_opengl && *fancy) {
#ifdef DOGL
			    glXSwapBuffers(display, win);
#endif
			    break;
			} else return(0);
		   }

                   width  = event.xconfigure.width;
                   height = event.xconfigure.height;

                   /* now resize the Graphics window, this will generate an 
                      expose event*/

                   size_hints.flags  = USSize;
                   size_hints.width  =  width;
                   size_hints.height  =  height;
                   XSetNormalHints(display, win, &size_hints);
		   if (has_opengl && *fancy) Reshape();
                   return(0);
              }

              if (event.xconfigure.window == winspec) {
		   int i, spold,spoldw;

		   spold = SPECHIGH;
		   spoldw = SPECWIDE;
		   SPECWIDE = event.xconfigure.width;
		   SPECHIGH = event.xconfigure.height - SPBHIGH;
		   if (SPECHIGH < 0) SPECHIGH = 0;

                   /* now resize the Graphics window, this will generate an 
                      expose event*/

                   size_hints.flags  = USSize;
                   size_hints.width  =  SPECWIDE;
		   if (event.xconfigure.height < SPBHIGH) {
			size_hints.height  =  SPBHIGH;
		   } else {
			size_hints.height  =  event.xconfigure.height;
		   }
                   XSetNormalHints(display, winspec, &size_hints);
		   for (i=0; i<NSBUTTS; i++) {
			spbut[i].y = SPECHIGH + (spbut[i].y - spold);
		   }
		   spbut[2].x = SPECWIDE + (spbut[2].x - spoldw);
		   spbut[3].x = SPECWIDE + (spbut[3].x - spoldw);
		   spbut[4].x = SPECWIDE + (spbut[4].x - spoldw);
		   for (i=0; i<5; i++) 
			qboxes[QHW+i].y = SPECHIGH + (qboxes[QHW+i].y - spold);
		   drwspec();
              }

              if (event.xconfigure.window == wingeo) {

		   gwi = event.xconfigure.width;
		   ghi = event.xconfigure.height;

		   if (nwframes == 2) {
			CNVWIDE = gwi / 2;
		   } else {
			CNVWIDE = gwi;
		   }
		   if (nhframes == 2) {
			CNVHIGH = ghi / 2;
		   } else {
			CNVHIGH = ghi;
		   }

                   /* now resize the Graphics window, this will generate an 
                      expose event*/

                   size_hints.flags  = USSize;
                   size_hints.width  =  gwi;
                   size_hints.height  =  ghi;
                   XSetNormalHints(display, wingeo, &size_hints);
		   XClearWindow(display,wingeo);
#if defined(VMS) || defined(UNDERSC)
		   drwgeo();
#else
#ifdef CRAY
		   DRWGEO();
#else
		   drwgeo_();
#endif
#endif
                   return(0);
              }
           }
           break;

           case UnmapNotify:         break;

           default: break;		/* ignore unexpected events */

        }  /* end switch event type*/


    }/* end while */

#ifdef DOGL
    if ((has_opengl && ((!*fancy && !moving) || (*fancy && !gmoving))) || !has_opengl) {
	    return(0);
    } else dispsf();
#else
    return(0);
#endif

  } /* end MolWindow */
  break;

  case OpenWindow :
  {
    int ig;
#ifdef DOGL
    int dummy;
#endif

    SetupTable();

#ifdef __CYGWIN__
    if (getenv("DISPLAY") == NULL) putenv("DISPLAY=localhost:0.0");
#endif
    if (( display = XOpenDisplay(NULL)) == NULL )
    {
      fprintf( stderr, "Molden: cannot connect to X server %s\n",
               XDisplayName(display_name));
      exit(-1);
    }

    if (strstr(ServerVendor(display),"StarNet")) StarNet = 1;

    xison = 1;

    if (DEBUG) XSynchronize(display,1);
    XSetErrorHandler (X_Error_Message_CB);

    width  = 800;	
    height = 800;

    screen         = DefaultScreen(display);
    Mwidth  = DisplayWidth(display, screen);
    Mheight = DisplayHeight(display, screen);

    if (GEOMset) {
	ig = XParseGeometry(GEOMstr,&wx,&wy,&width,&height);
    }

    xswa.background_pixel = BlackPixel(display,screen);
    xswa.border_pixel     = WhitePixel(display,screen);
    xswa.backing_store    = NotUseful;
    xswa.backing_planes   = 0;
    xswa.save_under       = False;
    IBGcolor = 0;

    rootW = RootWindow(display,screen);
    dispDEEP  = DisplayPlanes(display,screen);

#ifdef DOGL
    if (glXQueryExtension(display, &dummy, &dummy)) has_opengl = 1;

    if (has_opengl) {
	if ((vi = glXChooseVisual(display, DefaultScreen(display),attributeList))) {
	    screen = vi->screen;

	    if (vi->class != TrueColor) fprintf(stderr,"TRuecolor required\n");
            if (!(cx = glXCreateContext(display, vi, 0, GL_TRUE))) fprintf(stderr,"no context\n");
            cmap = XCreateColormap(display,RootWindow(display,vi->screen),vi->visual,AllocNone);
            xswa.colormap = cmap;
        } else {
	    has_opengl = 0;
        }
    }

#endif

    if (has_opengl) {
       win = XCreateWindow(display,
                        RootWindow(display,screen),
                        wx,
                        wy,
                        width,
                        height,
                        0,
                        vi->depth,
                        InputOutput,
                        vi->visual,
                        (CWBorderPixel | CWColormap | CWEventMask | CWBackingStore | CWBackingPlanes | CWSaveUnder),
                        &xswa);
    } else {
       win = XCreateWindow(display,
                        RootWindow(display,screen),
                        wx,
                        wy,
                        width,
                        height,
                        border_width,
                        CopyFromParent,
                        InputOutput,
                        CopyFromParent,
                        (CWBackPixel | CWBorderPixel | CWBackingStore | CWBackingPlanes),
                        &xswa);
    }


    StoreDeleteWindowProp(win);

    icon_pixmap = XCreateBitmapFromData(display,
                                        win,
                                        icon_bitmap_bits,
                                        icon_bitmap_width,
                                        icon_bitmap_height);


    size_hints.flags 	  = PPosition | PSize | PMinSize;
    size_hints.x 	  = wx;
    size_hints.y 	  = wy;
    size_hints.width 	  = width;
    size_hints.height 	  = height;
    size_hints.min_width  = 0;
    size_hints.min_height = 0;

    XSetStandardProperties(display,
                           win,
                           window_name,
                           icon_name, 
                           icon_pixmap,
                           0, 0,
                           &size_hints);

    XSelectInput(display,
                 win,
                 (StructureNotifyMask|ExposureMask|ButtonPressMask 
                 |ButtonReleaseMask|ButtonMotionMask|KeyPressMask
		 |KeyReleaseMask|PointerMotionMask));

    region = XCreateRegion();

    values.foreground = WhitePixel(display,screen);
    values.background = BlackPixel(display,screen);

    gc = XCreateGC(display,
                   win,
                   (GCForeground|GCBackground|GCArcMode),
                   &values);
    XSetArcMode(display,gc,ArcPieSlice);

    if ( (mfinfo = XLoadQueryFont(display,FONT))== 0) {
       mfinfo = XQueryFont(display,XGContextFromGC(gc));}
    else {

       XSetFont(display,gc,mfinfo->fid);
    }


    if (Arg1 >= 0.0) coloff = Arg1;

    def_colors();			/* define colors	*/

    *inct = colcells;

    stipple = XCreateBitmapFromData(display, win, stipple_bits, stipple_width,
                                        stipple_height);

    qwgrey = XCreateBitmapFromData(display, win, qwgrey_bits, qwgrey_width,
                                        qwgrey_height);
    tqwgrey = XCreateBitmapFromData(display, win, tqwgrey_bits, tqwgrey_width,
                                        tqwgrey_height);

    grayStip = XCreatePixmapFromBitmapData(display, win, gray50_bits,
             gray50_width, gray50_height, 1, 0, 1);

    molPix     = XCreateBitmapFromData(display, win,
                mol_bits, mol_width, mol_height);
    upPix      = XCreateBitmapFromData(display, win,
                up_bits, up_width, up_height);
    downPix    = XCreateBitmapFromData(display, win,
                down_bits, down_width, down_height);
    lPix       = XCreateBitmapFromData(display, win,
                l_bits, l_width, l_height);
    rPix       = XCreateBitmapFromData(display, win,
                r_bits, r_width, r_height);
    ballPix    = XCreateBitmapFromData(display, win,
                ball_bits, ball_width, ball_height);
    HourPix    = XCreateBitmapFromData(display, win,
                hourglass_bits, hourglass_width, hourglass_height);
    gPix       = XCreateBitmapFromData(display, win,
                g_bits, g_width, g_height);
    SkullPix   = XCreateBitmapFromData(display, win,
                skull_bits, skull_width, skull_height);
    FFPix      = XCreateBitmapFromData(display, win,
                ff_bits, ff_width, ff_height);
    MLFPix     = XCreateBitmapFromData(display, win,
                mlf_bits, mlf_width, mlf_height);
    HPix       = XCreateBitmapFromData(display, win,
                hbit_bits, hbit_width, hbit_height);
    VRMLPix    = XCreateBitmapFromData(display, win,
                vrml_bits, vrml_width, vrml_height);
    AlignPix   = XCreateBitmapFromData(display, win,
                align_bits, align_width, align_height);
    OrigPix    = XCreateBitmapFromData(display, win,
                orig_bits, orig_width, orig_height);
    CellPix    = XCreateBitmapFromData(display, win,
                cell_bits, cell_width, cell_height);
    SurfPix    = XCreateBitmapFromData(display, win,
                surf_bits, surf_width, surf_height);
    FotoPix    = XCreateBitmapFromData(display, win,
                foto_bits, foto_width, foto_height);
    ColPix     = XCreateBitmapFromData(display, win,
                palette_bits, palette_width, palette_height);
    slowPix    = XCreateBitmapFromData(display, win,
                slow_bits, pace_width, pace_height);
    fastPix    = XCreateBitmapFromData(display, win,
                fast_bits, pace_width, pace_height);
    blastPix   = XCreateBitmapFromData(display, win,
                blast_bits, pace_width, pace_height);
    BigPix     = XCreateBitmapFromData(display, win,
                bigsmall_bits, bigsmall_width, bigsmall_height);
    OGLPix     = XCreateBitmapFromData(display, win,
                ogl_bits, ogl_width, ogl_height);

#ifdef DOBACK
#ifdef VMS
    molback = XCreatePixmap(display, win,Mwidth,Mheight,
        DefaultDepth(display,screen));
#else
    if (has_opengl) {
        if (( molback = XCreatePixmap(display, win,Mwidth,Mheight,
            vi->depth)) == (Pixmap) NULL )
        {
            fprintf( stderr, "Molden: cannot create pixmap \n");
        }
        if (( bckwin = XCreatePixmap(display, win,BckW,BckH,
            vi->depth)) == (Pixmap) NULL )
        {
            fprintf( stderr, "Molden: cannot create pixmap \n");
        }
        if (( colmap = XCreatePixmap(display, win,256,1,
            vi->depth)) == (Pixmap) NULL )
        {
            fprintf( stderr, "Molden: cannot create pixmap \n");
        }
    } else {
	if (( molback = XCreatePixmap(display, win,Mwidth,Mheight,
	    DefaultDepth(display,screen))) == (Pixmap) NULL )
        {
            fprintf( stderr, "Molden: cannot create pixmap \n");
        }
        if (( bckwin = XCreatePixmap(display, win,BckW,BckH,
	    DefaultDepth(display,screen))) == (Pixmap) NULL )
        {
            fprintf( stderr, "Molden: cannot create pixmap \n");
        }
        if (( colmap = XCreatePixmap(display, win,256,1,
	    DefaultDepth(display,screen))) == (Pixmap) NULL )
        {
            fprintf( stderr, "Molden: cannot create pixmap \n");
        }
    }
    FakeCMap();
#endif
#else
    molback = NULL;
#endif


    if ( molback ) {
        molcur = molback;
    }
    else {
        molcur = win;
    }

    XSetStipple(display,gc,stipple);


    ZoomCursor = XCreateFontCursor(display, 120);
    AtomCursor = XCreateFontCursor(display, 40);
    WaitCursor = XCreateFontCursor(display, XC_watch);

    for (i=0; i<MAXAT; i++) {
	IANZboxes[i].win = (Window) NULL;
	BLboxes[i].win = (Window) NULL;
	ALPHboxes[i].win = (Window) NULL;
	BETboxes[i].win = (Window) NULL;
        for (j=0; j<4; j++)
	   IZboxes[i][j].win = (Window) NULL;
    }

    XMapWindow(display, win);

/* use event to display window! since event loop is in the FORTRAN code
   we have to fudge the X to do anything */

    XCheckTypedWindowEvent(display,
                           win,
                           ExposureMask,
                           &report) ;


    done = 0;

    while (!done) {

        XNextEvent(display, &event);
        switch (event.type) {
              case MapNotify: {
                                 done = 1;
              }
        break;

        default: break;    
        }  
    }

    XGetWindowAttributes(display, win, &xwa);

    if ( (xwa.width  != width ) || (xwa.height != height) )
       {
            width  = xwa.width;
            height = xwa.height;
       }                      

    XCheckTypedWindowEvent(display,
                           win,
                           ExposureMask,
                           &report) ;

#ifdef DOGL
    if (has_opengl) {
       glXMakeCurrent(display,win,cx);
       glClear(GL_COLOR_BUFFER_BIT);
       makeRasterFont(display);
       initOpengl();
    }
#endif

    CreatewinC(DEFWINCGEOM);
    XSelectInput(display, winC, ExposureMask | ButtonPressMask | 
				KeyPressMask | PointerMotionMask | 
				PointerMotionMask  |
				EnterWindowMask | LeaveWindowMask);
    CreatewinMC(DEFWINMCGEOM);
    XSelectInput(display, winMC, StructureNotifyMask |ExposureMask | 
                                 ButtonPressMask | ButtonReleaseMask | 
				 KeyPressMask | PointerMotionMask | 
				 EnterWindowMask | LeaveWindowMask);
    DowinC = 1;
    DowinMC = 1;
    DoactC = 1;
    DoactMC = 1;


    RESwin  = CreateWindow("Molden Query Box","-10-10",QBOXWIDE,QBOXTX+20,
                            infobg,infofg,(Window)0);
    XSelectInput(display, RESwin, ExposureMask | KeyPressMask);

    COMMwin = CreateWindow("Molden Query Box",DEFQBOXGEOM,QBOXWIDE,QBOXTX,
                            infobg,infofg,(Window)0);
    XSelectInput(display, COMMwin, ExposureMask | KeyPressMask);

    Fwin    = CreateWindow("Molden File Select","-80-80",QBOXWIDE,QBOXRFD,
                            infobg,infofg,(Window)0);
    XSelectInput(display, Fwin, ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask);

    ZMEwin = CreateWindow("Zmatrix Editor","-0+0",ZMEWINW,ZMEWINH,infobg,infofg,(Window)0);
    XSelectInput(display, ZMEwin, ExposureMask | KeyPressMask | 
		ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | 
		LeaveWindowMask | PointerMotionMask | EnterWindowMask);
    subZM = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],ZMEwin);

    DefBut(&rbut[BDIR],  Fwin, 325, 275            , 110, BUTTH, 
        	   "Update Directory", infobg, CNTCOL);
    DefBut(&rbut[BCAN],  Fwin, 325, 275+BUTTN      , 50, BUTTH, 
        	   "Close", infobg, CNTCOL);
    DefBut(&rbut[BREP],  Fwin, 325, 75            , 15, 15, 
        	   " ", infobg, CNTCOL);
    DefBut(&rbut[BADD],  Fwin, 325, 100            ,15, 15, 
        	   " ", infobg, CNTCOL);


    ActBut(&rbut[Fwinopt],-1);
    TogDown(&rbut[Fwinopt]);
    DISTwin = CreateWindow("Molden Calculate","-20-80",
	DBWIDE,DBHIGH+2*BUTTH, infobg,infofg,(Window)0);

    subDIST = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],DISTwin);
    if (has_opengl) {
        if (( distpix = XCreatePixmap(display, DISTwin,DBWIDE,DBHIGH,
            vi->depth)) == (Pixmap) NULL )
        {
            fprintf( stderr, "Molden: cannot create pixmap \n");
        }
    } else {
	if (( distpix = XCreatePixmap(display, DISTwin,DBWIDE,DBHIGH,
	    DefaultDepth(display,screen))) == (Pixmap) NULL )
        {
            fprintf( stderr, "Molden: cannot create pixmap \n");
        }
    }

    XSelectInput(display, DISTwin, ExposureMask | ButtonPressMask 
	| SubstructureNotifyMask | PointerMotionMask 
	| EnterWindowMask | LeaveWindowMask);

    DefBut(&clbut[BMONI], DISTwin, 0, DBHIGH , DBWIDE/4, BUTTH, 
        	   "Monitor", infobg, 0);
    clbut[BMONI].explstr = "Update distance on screen\nwith each new structure";

    DefBut(&clbut[BCLR],  DISTwin, DBWIDE/4, DBHIGH , DBWIDE/2, BUTTH, 
        	   "Clear Mon/Cont", infobg, 0);
    clbut[BCLR].explstr = "clear distance monitors,\nclosest contacts";

    DefBut(&clbut[BCNTCT],DISTwin, (3*DBWIDE)/4, DBHIGH , DBWIDE/4, BUTTH, 
        	   "Contact", infobg, 0);
    clbut[BCNTCT].explstr = "show closest contacts\nof selected atom";

    DefBut(&clbut[BCLOSE],DISTwin, (3*DBWIDE)/4, DBHIGH+BUTTH , DBWIDE/4, BUTTH, 
        	   "Close", infobg, 0);
    clbut[BCLOSE].explstr = "close the window";

    DefBut(&clbut[BCONN],DISTwin, 0, DBHIGH+BUTTH , (3*DBWIDE)/4, BUTTH, 
        	   "Connect/DISconnect", infobg, 0);
    clbut[BCONN].explstr = "(dis)connect atoms measured distance";


    return(0) ;
  } /* end OpenWindow */ 
  break;

  case MovePen :			/* move pen to x,y	*/
  {
    if ( count < MAXSAVE-1 ) {
       count++;
       savecom[count].evtype = Command;
       savecom[count].xxval = Arg1;
       savecom[count].yyval = Arg2;
    }
    movexy(Arg1,Arg2);
    return(0);
  } /* end MovePen */
  break;

  case DrawLine :
  {
    if ( count < MAXSAVE-1 ) {
       count++;
       savecom[count].evtype = Command;
       savecom[count].xxval = Arg1;
       savecom[count].yyval = Arg2;
    }
    drawxy(Arg1,Arg2);
    return(0);
  } /* end DrawLine */
  break;

  case DrawString :
  {
    if ( count < MAXSAVE-1 ) {
       count++;
       savecom[count].evtype = Command;
       savecom[count].xxval = Arg1;
       savecom[count].yyval = Arg2;
    }
    if ( scount < MXSAVESTR-1 ) {
       int ns;
       scount++;
       ns = *nstr;
       if (*nstr > 254 ) ns = 254;
       strcp(str,savestr[scount],ns);
       savestr[scount][ns] = '\0';
       nsavestr[scount] = ns;
    }
    drawstring(Arg1,Arg2,&savestr[scount][0],nsavestr[scount]);
    return(0);
  } /* end DrawString */
  break;

  case 5 :			/* do nothing		*/
  {
    return(0);
  }
  break;

  case ClearScreen :
  {
    doclr();
    return(0);
  } /* end ClearScreen */
  break;

  case SolidLine :
  {
    if ( count < MAXSAVE-1 ) {
       count++;
       savecom[count].evtype = Command;
    }
#if defined(VMS) || defined(UNDERSC)
    sollin();
#else
#ifdef CRAY
    SOLLIN();
#else
    sollin_();
#endif
#endif
    return(0);
  } /* end SolidLine */
  break;

  case DashedLine :
  {
    if ( count < MAXSAVE-1 ) {
       count++;
       savecom[count].evtype = Command;
    }
    dashline();
    return(0);
  } /* end DashedLine */
  break;

  case LineWidth :
  {
    if ( count < MAXSAVE-1 ) {
       count++;
       savecom[count].evtype = Command;
       savecom[count].xxval = Arg1;
    }
#if defined(VMS) || defined(UNDERSC)
    cwidth(&Arg1);
#else
#ifdef CRAY
    CWIDTH(&Arg1);
#else
    cwidth_(&Arg1);
#endif
#endif

    return(0);
  } /* end LineWidth */
  break;

  case ParseNorbs:
  {
    norbs = *inct;
    return(0);
  }
  break;

  case ChangeColor :
  {
    if ( count < MAXSAVE-1 ) {
       count++;
       savecom[count].evtype = Command;
       savecom[count].xxval = Arg1;
    }
    changepen(Arg1);
    return(0);
  } /* end ChangeColor */
  break;

  default: 
  {
    fprintf(stderr,"ERROR in Command= %d", Command);
    return(0);
  }
  break;

 } /* end main command switch */
    exit(-1);		

} 

static char *name[] =				/* colors here	*/
	{"Black", "#FF1010", "goldenrod1", "Green", "Aquamarine", "#80FFFF", "Gold", 
         "LightBlue", "Grey", "Magenta", "Lime Green", "Wheat",
         "Orange", "#0000E0", "Chocolate", "White"};

static char *nameback[] =				/* colors here	*/
	{"#000000","#FF1010","#FF9F09","#00FF00","#7FFFD4","#80FFFF",
	 "#FFBF00","#84C1D6","#9B9B9B","#FF00FF","#10B010","#EFCA8C",
         "#FF7A00","#0000E0","#B83806","#FFFFFF"};


ParseBasicColor(activecolor,docmap)
int activecolor;
int docmap;
{
  XColor exact_def;
  float rslice,gslice,bslice;
  int i;

   rslice = colorr[activecolor]*(1.0-coloff) / 10.0;
   gslice = colorg[activecolor]*(1.0-coloff) / 10.0;
   bslice = colorb[activecolor]*(1.0-coloff) / 10.0;

   if (!docmap) XFreeColors(display, cmap,&colors[16+(activecolor-1)*10],10,0);

   for (i = 1; i < 11; i++ ) {
	exact_def.red = colorr[activecolor]*coloff + i * rslice;
	exact_def.green = colorg[activecolor]*coloff + i * gslice;
	exact_def.blue = colorb[activecolor]*coloff + i * bslice;
      
	if ( !XAllocColor(display, cmap, &exact_def) ) {
	   if (docmap) {
             cmap =  XCopyColormapAndFree(display,cmap);
             XSetWindowColormap(display,win,cmap);
             setcmap = 1;
	     i--;
	   }
	} else {
	   colors[15+(activecolor-1)*10+i] = exact_def.pixel;
	}
         
   }
}

ParseMapColors(docmap)
int docmap;
{
  XColor exact_def;
  int i;

   if (!docmap) XFreeColors(display, cmap,mappedcols,5,0);

   for (i = 0; i < 5; i++ ) {
	exact_def.red   = (int )(mapcol[i].r)*65535;
	exact_def.green = (int )(mapcol[i].g)*65535;
	exact_def.blue  = (int )(mapcol[i].b)*65535;
      
	if ( !XAllocColor(display, cmap, &exact_def) ) {
	   if (docmap) {
             cmap =  XCopyColormapAndFree(display,cmap);
             XSetWindowColormap(display,win,cmap);
             setcmap = 1;
	     i--;
	   }
	} else {
	   mappedcols[i] = exact_def.pixel;
	}
         
   }
}

def_col16(colnam)
char **colnam;
{
  int i;
  XColor exact_def;

    for (i = 0; i < 16; i++ ) {

      if ( !XParseColor(display, cmap, colnam[i], &exact_def) ) {
	if ( !XParseColor(display, cmap, nameback[i], &exact_def) ) {
           fprintf( stderr, "Xwin: color %s not in database\n", nameback[i]);
           exit(-1);
	}
      }

      if ( !XAllocColor(display, cmap, &exact_def) ) {
       cmap = XCopyColormapAndFree(display,cmap);
       XSetWindowColormap(display,win,cmap);
       setcmap = 1;
       i--;
      } else {
	colors[i] = exact_def.pixel;
	colorr[i] = exact_def.red;
	colorg[i] = exact_def.green;
	colorb[i] = exact_def.blue;
      }
      
    }
}

ResetColors()
{
   int j;

   XFreeColors(display, cmap,&colors[0],16,0);
   def_col16(name);
   for (j = 1; j < 16; j++ ) ParseBasicColor(j,0);
   WriteRes();
}

def_colors()
{
  int depth;
  int ncells;
  XColor exact_def;
  int i,j;
  static char **colnam;

/* #80ffff used to be Cyan */


  static char *shcol[SHCOLNUM][3] = 
	{{"#729FFF","#C4D7FF","#3E578C"},
	 {"#A59F80","#DAD7CA","#5B5746"},
	 {"#FFC494","#CC9D76","#8C6C51"},
	 {"#F74F41","#FCB0AA","#802921"},
	 {"#FFBF00","#FFE69C","#916D00"},
	 {"#5F985F","#B6D0B6","#314F31"},
	 {"#56B2F7","#B8DFFC","#2F6288"}
  };
/*         medium   light    dark */

  if (NColNam == 16) colnam = ColNam;
  else colnam = name;

  depth  = DisplayPlanes(display, screen);
  ncells = DisplayCells(display, screen);

  if (depth >= 8) ncells = 256;

  if (!has_opengl) cmap   = DefaultColormap(display, screen);
  
  if ( ncells <= 2 )		/* mono screen	*/
  {
    colcells = 2;
    monoscr = 1;
    colors[0] = BlackPixel(display, screen);
    for ( i = 1; i < MAX_COLORS; i++ )
    {
       colors[i] = WhitePixel(display, screen);
    }
  }

  else
  {
    def_col16(colnam);

    if ( ncells >= 256 )
    {
       colcells = 256;
       for (j = 1; j < 16; j++ ) ParseBasicColor(j,1);
       for (j = 0; j < SHCOLNUM; j++ )
       for (i = 0; i < 3; i++ ) {
		XParseColor(display, cmap, shcol[j][i], &exact_def);
		if ( !XAllocColor(display, cmap, &exact_def) ) {
		  cmap =  XCopyColormapAndFree(display,cmap);
		  XSetWindowColormap(display,win,cmap);
		  setcmap = 1;
		  XAllocColor(display, cmap, &exact_def);
		}
		colors[190+3*j+i] = exact_def.pixel;
       }
#ifdef DOGL
       ParseMapColors(1);
#endif
    }
    else if ( ncells >= 32 )
    {
       colcells = 32;
       for (i = 1; i < 11; i++ )
       {
         exact_def.red = i * 6553;
         exact_def.green = i * 4250;
         exact_def.blue = 0;
   
         if ( !XAllocColor(display, cmap, &exact_def) )
         {
           cmap = XCopyColormapAndFree(display,cmap);
           XSetWindowColormap(display,win,cmap);
           setcmap = 1;
/*           fprintf(stderr,"Xwin: all colorcells allocated, read/write\n");
           exit(-1);*/
         }
         
         colors[125+i] = exact_def.pixel;
       }
    }

  }


  if (monoscr || colcells <= 32) {
     infofg = WhitePixel(display,screen);
     infobg = BlackPixel(display,screen); 
     White = WhitePixel(display,screen);
     Black = BlackPixel(display,screen); }
  else {
     infofg = colors[15];
     infobg = colors[0];
     White = WhitePixel(display,screen);
     Black = BlackPixel(display,screen); 
  }
  if (*ibgcol) IBGcolor = *ibgcol;
  if (*ibgclo) OBGcolor = *ibgclo;
  if (*ibgmod) BGmode = *ibgmod;
}     

FakeCMap()
{
   int i;
   unsigned long pixl;
   XImage *img;
   
   for (i=0; i<256; i++) {
	XSetForeground(display,gc,colors[i]);
	XDrawPoint(display,colmap,gc,i,0);
   }
   img = XGetImage(display,colmap,0,0,256,1,AllPlanes,ZPixmap);
   for (i=0; i<256; i++) {
	pixl = XGetPixel(img,i,0);
	colors[i] = pixl;
   }
}

movexy(xval,yval)

float xval;
float yval;
{
  start_xlx = (xval-xoff) * height * scale;
  start_yly = (1.0- yval -yoff) * height * scale;
}

drawxy(xval,yval)

float xval;
float yval;
{
  xlx = (xval-xoff) * height * scale;
  yly = (1.0 - yval - yoff) * height * scale;
  XDrawLine(display, molcur, gc, xlx, yly, start_xlx, start_yly);

  start_xlx = xlx;
  start_yly = yly;

}

drawstring(xval,yval,strval,nval)

float xval;
float yval;
char *strval;
int nval;
{
  xlx = (xval-xoff) * height * scale;
  yly = (1.0 - yval -yoff) * height * scale;
  XDrawString(display, molcur, gc, xlx, yly, strval, nval);

}

#if defined(VMS) || defined(UNDERSC)
sollin()
#else
#ifdef CRAY
SOLLIN()
#else
sollin_()
#endif
#endif

{
   isdash = 0;
   XSetLineAttributes(display, gc, linwid, LineSolid, CapButt, JoinMiter);

} 

dashline()
{
   isdash = 1;
   if ( monoscr ) {
        XSetBackground(display, gc, BlackPixel(display,screen));
        XSetLineAttributes(display, gc, linwid, LineDoubleDash,
                                      CapButt, JoinMiter);
   }
}

#if defined(VMS) || defined(UNDERSC)
dash(on)
#else
#ifdef CRAY
DASH(on)
#else
dash_(on)
#endif
#endif
int *on;
{
   if (*on) XSetLineAttributes(display, gc, linwid, LineOnOffDash, 
                               CapButt, JoinMiter);
   else XSetLineAttributes(display, gc, linwid, LineSolid,
                               CapButt, JoinMiter);
}

#if defined(VMS) || defined(UNDERSC)
cwidth(linpass)
#else
#ifdef CRAY
CWIDTH(linpass)
#else
cwidth_(linpass)
#endif
#endif

float *linpass;
{
  linwid = (int) *linpass;
  if (linwid > linmax) linwid = linmax;
}

changepen(pen)

float pen;
{
  foreground_pixel = colors[(int)pen];

  XSetForeground(display, gc, foreground_pixel);

}

#if defined(VMS) || defined(UNDERSC)
setcol(pen)
#else
#ifdef CRAY
SETCOL(pen)
#else
setcol_(pen)
#endif
#endif
int *pen;
{
unsigned long f_pixel;

  if (*pen < MAX_COLORS && *pen >= 0) {
	f_pixel = colors[*pen];
	XSetForeground(display, gc, f_pixel);
  }

}

static int CheckForConfig()
{
  XEvent ev;
  char   foo;

  /* returns true if there's a config event in which mainW changes size
     in the event queue */

  foo = 0;
  XCheckIfEvent(display, &ev, IsConfig, &foo);
  return foo;
}

static Bool IsConfig(dpy, ev, arg)
Display *dpy;
XEvent  *ev;
char    *arg;
{
  XConfigureEvent *cev;

  if (ev->type == ConfigureNotify) {
    cev = (XConfigureEvent *) ev;
    if (cev->window == win && (cev->width != width || cev->height != height))
      *arg = 1;
  }
  return False;
}

RedrawWin()
{
     int cnt = 0;
     int i;

     if ( molback ==  molcur ) {
	  if (denmode) XSetForeground(display, gc, colors[0]);
	  else XSetForeground(display, gc, colors[IBGcolor]);
          XFillRectangle(display,molcur,gc,0,0,width,height);
          XSetForeground(display, gc, WhitePixel(display,screen));
     }
     else {
          XClearWindow(display,win);
     }

     for (i=1; i<=count; i++)  
     {
       switch(savecom[i].evtype){

       case MovePen : {
          movexy(savecom[i].xxval,savecom[i].yyval);
          }
       break;

       case DrawLine : {
          drawxy(savecom[i].xxval,savecom[i].yyval);
          }
       break;


       case DrawString : {
          cnt++;
          drawstring(savecom[i].xxval,savecom[i].yyval,
                     &savestr[cnt][0],nsavestr[cnt]);
          }
       break;
 

       case SolidLine : {
#if defined(VMS) || defined(UNDERSC)
          sollin();
#else
#ifdef CRAY
	  SOLLIN();
#else
	  sollin_();
#endif
#endif
          }
       break;

       case DashedLine : {
          dashline();
          }
       break;

       case LineWidth : {
#if defined(VMS) || defined(UNDERSC)
          cwidth(&savecom[i].xxval);
#else
#ifdef CRAY
          CWIDTH(&savecom[i].xxval);
#else
          cwidth_(&savecom[i].xxval);
#endif
#endif

          }
       break;

       case ChangeColor : {
          changepen(savecom[i].xxval);
          }
       break;

       default: break;
       } /* end command switch */
     } /*end for */
     if ( molback == molcur ) XCopyArea(display,molcur,win,gc,0,0,width,height,0,0);
} /* end ReDraw */

#if defined(VMS) || defined(UNDERSC)
gethei(hei)
#else
#ifdef CRAY
GETHEI(hei)
#else
gethei_(hei)
#endif
#endif
int *hei;
{ 
  *hei = height;
  return(0);
}

#if defined(VMS) || defined(UNDERSC)
drawseg(segments,npoints,iinv)
#else
#ifdef CRAY
DRAWSEG(segments,npoints,iinv)
#else
drawseg_(segments,npoints,iinv)
#endif
#endif

XSegment *segments;
int *npoints;
int *iinv;
{
  int con1,con2;

  if (*npoints == 1) {
     con1 = ((segments[0].x1 >= 0 && segments[0].y1 >= 0)  && 
             (segments[0].x1 <= (int) width && segments[0].y1 <= (int) height));
     con2 = ((segments[0].x2 >= 0 && segments[0].y2 >= 0)  && 
             (segments[0].x2 <= (int) width && segments[0].y2 <= (int) height));
     if (con1 || con2) {
	if (monoscr && *iinv) XSetFunction(display,gc,GXxor);
	XDrawSegments(display, molcur, gc, segments, *npoints);
	if (monoscr && *iinv) XSetFunction(display,gc,GXcopy);
     }
     return;
  }
  if (monoscr && *iinv) XSetFunction(display,gc,GXxor);
  XDrawSegments(display, molcur, gc, segments, *npoints);
  if (monoscr && *iinv) XSetFunction(display,gc,GXcopy);

}

#if defined(VMS) || defined(UNDERSC)
drwseg(segments,npoints,iinv)
#else
#ifdef CRAY
DRWSEG(segments,npoints,iinv)
#else
drwseg_(segments,npoints,iinv)
#endif
#endif

XSegment *segments;
int *npoints;
int *iinv;
{
  XDrawSegments(display, win, gc, segments, *npoints);

}

#if defined(VMS) || defined(UNDERSC)
drwpol(points,npoints,icol,icon,isgrey)
#else
#ifdef CRAY
DRWPOL(points,npoints,icol,icon,isgrey)
#else
drwpol_(points,npoints,icol,icon,isgrey)
#endif
#endif

XPoint *points;
int *npoints;
int *icol;
int *icon;
int *isgrey;
{
/*  XPoint *tempp;*/

  XSetForeground(display, gc, colors[*icol]);
  if (*icon == 1) XFillPolygon(display,molcur,gc,points,*npoints,Convex,CoordModeOrigin);
  else {
#if defined(VMS) || defined(UNDERSC)
        if (*isgrey == 1) ststip();
#else
#ifdef CRAY
        if (*isgrey == 1) STSTIP();
#else
        if (*isgrey == 1) ststip_();
#endif
#endif
       XFillPolygon(display,molcur,gc,points,*npoints,Nonconvex,CoordModeOrigin);
#if defined(VMS) || defined(UNDERSC)
        if (*isgrey == 1) unstip();
#else
#ifdef CRAY
        if (*isgrey == 1) UNSTIP();
#else
        if (*isgrey == 1) unstip_();
#endif
#endif
  }
  if (colcells < 256 || (*icon == 0 && colcells >= 256) ) {
     if (monoscr) {
         XSetForeground(display, gc, colors[0]);
         if (isdash) XSetLineAttributes(display, gc, linwid, LineSolid, CapButt, JoinMiter);
     }
     else XSetForeground(display, gc, colors[2]);
     if (*icon == 0 && *isgrey == 1 && !monoscr) XSetForeground(display, gc, colors[1]);
     XDrawLines(display,molcur,gc,points,*npoints,CoordModeOrigin);
     if (monoscr && isdash) dashline();
/*     tempp = points;
     XDrawSegments(display, molcur, gc, tempp, 1);
     tempp++;
     XDrawSegments(display, molcur, gc, tempp, 1);
     tempp++;
     XDrawSegments(display, molcur, gc, tempp, 1);*/
  }

}

#if defined(VMS) || defined(UNDERSC)
plsph(xori,yori,fwidth,ia)
#else
#ifdef CRAY
PLSPH(xori,yori,fwidth,ia)
#else
plsph_(xori,yori,fwidth,ia)
#endif
#endif

int *xori;
int *yori;
int *fwidth;
int *ia;
{
  int xc,yc,xce,yce;
  unsigned int wi,hi,wi1;

  wi = (unsigned int) *fwidth;
  hi = wi;

  xc = *xori - wi/2;
  yc = *yori - hi/2;
  xce = *xori + wi/2;
  yce = *yori + hi/2;

  if (xce < 0 && yce < 0) return;
  if (xc > (int) width && yc > (int) height) return;

  XFillArc(display, molcur, gc, xc,yc, wi, hi, 0,360*64);

  XSetBackground(display, gc, BlackPixel(display,screen));
  XSetFillStyle(display,gc,FillOpaqueStippled);
  XSetStipple(display,gc,stipple);
  XFillArc(display, molcur, gc, xc,yc, wi, hi, 90*64,180*64);

  XSetFillStyle(display,gc,FillSolid);
  wi1 =  wi*0.50;
  XFillArc(display, molcur, gc, *xori - wi1/2,yc, wi1, hi, 0,360*64);
  if (*ia >= 2 && (ZMEup || cflag || ATMup || SelDel || ONIup || scoup)) {
     XSetForeground(display, gc, colors[rimcols[*ia]]);
     XDrawArc(display, molcur, gc, xc,yc, wi, hi, 0,360*64);
  }

}

#if defined(VMS) || defined(UNDERSC)
plsel(xori,yori,ia)
#else
#ifdef CRAY
PLSEL(xori,yori,ia)
#else
plsel_(xori,yori,ia)
#endif
#endif

int *xori;
int *yori;
int *ia;
{
  int xc,yc;
  unsigned int wi;

  wi = 20;

  xc = *xori - wi/2;
  yc = *yori - wi/2;

  if (*ia >= 2 && (ZMEup || cflag || ATMup || SelDel || ONIup || scoup)) {
     XSetForeground(display, gc, colors[rimcols[*ia]]);
     XFillArc(display, molcur, gc, xc,yc, wi, wi, 0,360*64);
  }

}


#if defined(VMS) || defined(UNDERSC)
ststip()
#else
#ifdef CRAY
STSTIP()
#else
ststip_()
#endif
#endif
{
  if (monoscr) {
     XSetFillStyle(display,gc,FillOpaqueStippled);
     XSetStipple(display,gc,stipple);
  }
}


#if defined(VMS) || defined(UNDERSC)
unstip()
#else
#ifdef CRAY
UNSTIP()
#else
unstip_()
#endif
#endif
{
  if (monoscr) {
     XSetFillStyle(display,gc,FillSolid);
  }
}

#if defined(VMS) || defined(UNDERSC)
doexp()
#else
#ifdef CRAY
DOEXP()
#else
doexp_()
#endif
#endif
{
     if (*doesp && !denmode) PlotColIndex();

     if ( molback == molcur ) {
          XCopyArea(display,molcur,win,gc,0,0,width,height,0,0);
     }
     if (dogif) {
        picnum++;
	if (picnum < *picmax) {
/*
	    sprintf(stemp, "convert X:MOLDEN gif87:%s%d.gif",GifFile,picnum);
	    system(stemp);
*/
	   sprintf(stemp, "%s%03d.gif",GifFile,picnum);
	   ToGIF(molcur,stemp);
	}
     }
}

doclr()
{

    if (denmode && *ifdogl) return;

    if ( molback ==  molcur ) {

       if (denmode) XSetForeground(display, gc, colors[0]);
       else XSetForeground(display, gc, colors[IBGcolor]);
       XFillRectangle(display,molcur,gc,0,0,width,height);
       XSetForeground(display, gc, WhitePixel(display,screen));
         
    }
    else {
       XGetWindowAttributes(display, win, &xwa);

       if ( (xwa.width  != width ) || (xwa.height != height) )
       {
            width  = xwa.width;
            height = xwa.height;
       }                      

       XClearArea(display, win, 0,0,0,0,0);
    }
} 

#if defined(VMS) || defined(UNDERSC)
dlogo()
#else
#ifdef CRAY
DLOGO()
#else
dlogo_()
#endif
#endif
{
     XSetBackground(display, gc, infobg);
     XSetForeground(display, gc, infofg);
     XCopyPlane(display,molPix,molcur,gc,0,0,mol_width,mol_height,15,15,(unsigned long)1);
}


#define QPOSINT  1
#define QPOSREAL 2
#define QREAL    3
#define QSTRING  0

TrmStr(qp)
QBOXSTRU        *qp;
{
  int len,i,j;

  len = strlen(qp->str);

  j = len;
  for (i=len-1; i >= 0; i--) {
	if (qp->str[i] != ' ') {
	   j = i+1;
	   break;  
	}
  }
  
  len = j;
  qp->str[len] = '\0';
}

int DirKey(qp,c)
QBOXSTRU	*qp;
int c;
{
  int len, retval;

  if(DEBUG)fprintf(stderr,"DirKey in\n");

  if (qp->fake) return(-1);

  retval = -1;
  len = strlen(qp->str);
 
  if (qp->qbopt > QSTRING ) { 
    if ((c>='\060' && c<='\071') || (c=='+' && qp->qbopt == QREAL) 
    || (c=='-' && qp->qbopt == QREAL) || (c=='.' && qp->qbopt >= QPOSREAL)) {
            if (len >= qp->strmax) {
		if (*ibell) XBell(display,0); 
		return(-1);
	    }
            qp->str[len]=c;  qp->str[len+1]='\0'; retval = 0;
    }
  }
  else 
  {
   if (c>=' ' && c<'\177') { 
    if (len >= qp->strmax) {
	if (*ibell) XBell(display,0); 
	return(-1);
    }
    qp->str[len]=c;  qp->str[len+1]='\0'; retval = 0;
   }
  }

  if (retval) {
     if (c=='\010' || c=='\177') {
        if (len==0) {
	   if (*ibell) XBell(display,0); 
	   return(-1);
	}
	qp->str[len-1]='\0';
     }

     else if (c=='\025' || c=='\013') {
       qp->str[0] = '\0';
     }

     else if (c=='\012' || c=='\015') {
       return(-2);
     }

     else {
	if (*ibell) XBell(display,0); 
	return(-1);
     }
  }

  PromptBox(qp);
  return(0);
}

int ChkKey(qp,c)
QBOXSTRU	*qp;
int c;
{
  int retval;

  if (qp->fake) return(-1);

  retval = -1;
 
  if (qp->qbopt > QSTRING ) { 
    if ((c>='\060' && c<='\071') || (c=='+' && qp->qbopt == QREAL) 
    || (c=='-' && qp->qbopt == QREAL) || (c=='.' && qp->qbopt >= QPOSREAL))
             retval = 0;
  } else if (c>=' ' && c<'\177') retval = 0;

  return(retval);
}

int KeyChk(qp,c)
QBOXSTRU	*qp;
int c;
{
     int retval;

     if (DEBUG) fprintf(stderr,"KeyChk in\n");

     if (qp->fake) return(0);

     qp->changed = 1;

     retval = 0;

     if (DirKey(qp,c) == -2) {

          retval = 1;
          if (qp->pop) {
		XDestroyWindow(display,qp->win);
		XSync(display, False);
		qp->active = 0;
	  }

          *Sinct = qp->qbinct;
          if (qp->qbopt == 1) *Sincp = atoi(qp->str);
          else {
		cpstr(qp->str,Sstr,strlen(qp->str));
                *Snstr = strlen(qp->str);
          }
	  if (qp->iflt != NULL) *qp->iflt = atoi(qp->str);
	  if (qp->i2flt != NULL) *qp->i2flt = atoi(qp->str);
	  if (qp->qflt != NULL) *qp->qflt = atof(qp->str);
	  if (qp->dflt != NULL) *qp->dflt = atof(qp->str);

          if (qp->win == ZMEwin) {
             if (backb) {ActBut(&cbut[BDECRF],1); ActBut(&cbut[BUNSC],1);}
             ActBut(&cbut[BDIST],1);
             ActBut(&cbut[BANGLE],1);
             ActBut(&cbut[BDIHED],1);
             ActBut(&cbut[BREADF],1);
             if (denm) ActBut(&cbut[BDENMOD],1);
             *iwropt = ZMEopt-ZMEGAM + 1; 
          }

          if (qp->win == ATMwin && qp->qbopt == QREAL) *ihasq = 1;

          qp->callback(qp->str);

          if (qp->win == COMMwin ) {
	     update_model = 1;
	  }

          if (qp->win == RESwin ) {
             if (strstr(qp->str,"neigh")) {
		bflag = 1; retval = 0; bretval = 460;
		strcpy(molwstr,"Click on residu/hetatm to activate !");
		StatusStr(0,1);
		XDefineCursor(display,win,AtomCursor);
             } else if (strstr(qp->str,"col")) {
                if (!monoscr) {
		    if (DoPopUp(RESwin,0,0,NULL,Sincp,0) == -1) *Sincp = 0;
		    else *Sincp = *Sincp + 1;
		}
                else *Sincp = 0;
	     }
             else *Sincp = 0;
	     strcpy(qp->str,DEFSTRNAME);
	     PromptBox(qp);
	     update_model = 1;
          }
     }

     return(retval);
}

PFake(win,x,y,w,h,bgcol)
Window win;
int x;
int y;
int w;
int h;
int bgcol;
{
   XSetLineAttributes(display, gc, 2, LineSolid, CapButt, JoinMiter);
   if (bgcol == -1) XSetForeground(display, gc, White);
   else XSetForeground(display, gc, colors[bgcol]);
   XDrawRectangle(display, win, gc, x, y, w-QBOXFR, h-14);
   XFillRectangle(display, win, gc, x, y, w-QBOXFR, h-14);
   XSetLineAttributes(display, gc, 1, LineSolid, CapButt, JoinMiter);
   XSetForeground(display, gc, Black);
}

PromptBox(qp)
QBOXSTRU	*qp;
{
  int qlen,tpos;
  int RectThick;

  if (DEBUG) fprintf(stderr,"PromptBox in\n");

  if (qp->fake) {
	PFake(qp->win,qp->x,qp->y,qp->w,qp->h,qp->bgcol);
	return;
  }

  if (qp->prompt != NULL) {
	qlen = XTextWidth(mfinfo,qp->prompt, strlen(qp->prompt));
	qlen = qlen + 5;
  }
  else qlen = 0;

  RectThick = 2;
  if (!qp->active) RectThick = -1*RectThick;
  tpos = (qp->h-14-10)/2; tpos = 10 + tpos;
  if (tpos < 0) tpos = 0;
  butje(qp->win,qp->x+qlen,qp->y,qp->w-qlen-QBOXFR,qp->h-14,QBOXFR,qp->bgcol,qp->col,0,None,0,0,RectThick);
  if (qp->prompt != NULL) XDrawString(display, qp->win, gc, qp->x, qp->y+tpos, qp->prompt, strlen(qp->prompt));
  XDrawString(display, qp->win, gc, qp->x+qlen+QBOXFR+QBOXBORD, qp->y+tpos, qp->str, strlen(qp->str));
  if (qp->win == QBox) {
	DrwBut(&qboxclose[0]);
	DrwBut(&qboxclose[1]);
  }
  XFlush(display);

  if (DEBUG) fprintf(stderr,"PromptBox out\n");
}

int ClickBox(qbox,num,x,y)
QBOXSTRU	*qbox;
int x,y,num;
{
  int qlen;
  int bnum;
  QBOXSTRU *qp;

  bnum = -1;

  for (bnum=0; bnum<num; bnum++) {
    qp = &qbox[bnum];
    if (!qp->fake) {
	if (qp->prompt != NULL) {
	    qlen = XTextWidth(mfinfo,qp->prompt, strlen(qp->prompt));
	    qlen = qlen + 5;
	}
	else qlen = 0;

	if (VIERKANT(x, y, qp->x+qlen, qp->y, qp->w-qlen-QBOXFR, 27)) break;
    }
  }

  if (bnum<num && bnum != -1)  return (bnum);

  return -1;

}

int CheckBox(qbox,num,win,x,y)
QBOXSTRU	*qbox;
Window win;
int x,y,num;
{
  int qlen;
  int bnum;
  QBOXSTRU *qp;

  bnum = -1;

  for (bnum=0; bnum<num; bnum++) {
    qp = &qbox[bnum];
    if (!qp->fake && win == qp->win && !qp->active) {
	if (qp->prompt != NULL) {
	    qlen = XTextWidth(mfinfo,qp->prompt, strlen(qp->prompt));
	    qlen = qlen + 5;
	}
	else qlen = 0;

	if (VIERKANT(x, y, qp->x+qlen, qp->y, qp->w-qlen-QBOXFR, 27)) break;
    }
  }

  if (bnum<num && bnum != -1)  return (bnum);

  return -1;

}

qboxstr(qp,win,active,fake,bgcol,x,y,w,h,col,prompt,defstr,strmax,iopt,qinct,callback)
QBOXSTRU	*qp;
Window		*win;
int		active;
int		fake;
int		bgcol;
int		x,y,w,h;
int		col;
char		*prompt;
char		*defstr;
int		strmax;
int		iopt;
int		qinct;
ptr_void_proc	callback;
{

  qp->active = active;
  qp->fake = fake;
  qp->bgcol = bgcol;
  qp->x = x;  qp->y = y;  qp->w = w;  qp->h = h;
  qp->col = col;
  qp->iflt = NULL;
  qp->i2flt = NULL;
  qp->qflt = NULL;
  qp->dflt = NULL;
  qp->changed = 0;

  if (win == NULL) {
       if (qboxup) {
	   XDestroyWindow(display,QBox);
	   XSync(display, False);
       }
       QBox = CreateWindow("Molden Query Box",DEFQBOXGEOM,QBOXWIDE,QBOXHIGH+30,
                            infobg,infofg,(Window)0);
       qboxup = 1;
       qp->win = QBox;
       qp->pop = 1;
       XSelectInput(display, QBox, ExposureMask | KeyPressMask | ButtonPressMask);
       XMapWindow(display,QBox);
  }
  else {qp->win = *win; qp->pop = 0;}

  if (defstr == NULL) strcpy(qp->str,DEFSTRNAME);
  else strcpy(qp->str,defstr);
  if (strmax) {
	qp->strmax = strmax;
	if (strmax > MAXSTRLEN)
	  fprintf(stderr,"qboxstr: strmax longer than allowed\n");
  } else qp->strmax = MAXSTRLEN;

  qp->prompt = prompt;

  qp->qbopt = iopt;
  qp->qbinct = qinct;
  qp->callback = callback;

  if (qp->win == QBox) {
	DefBut(&qboxclose[0], QBox, 10, QBOXHIGH, 50, 23,
	"Apply", infobg, -15);
	DefBut(&qboxclose[1], QBox, 70, QBOXHIGH, 50, 23,
	"Cancel", infobg, -15);
  }


}

void dummyproc()
{
 int i;

 i = 1;
/*
 fprintf(stderr,"I am a dummy\n");
*/
}


int QBoxPaste(ParWin,qp,nboxes)
Window ParWin;
QBOXSTRU *qp;
int nboxes;
{
int i, j, ret_val, is_ok;

   ret_val = 0;
   for (i=0; i<nboxes; i++) {
	if (ParWin == qp[i].win && qp[i].active) {
		ret_val = 1;
		select_pointer = XFetchBytes(display, &nbytes_select);
		if (nbytes_select >= MAXSTRLEN) 
			nbytes_select = MAXSTRLEN-1;
		if (nbytes_select >= qp[i].strmax) 
			nbytes_select = qp[i].strmax;
		if (select_pointer != NULL) {
			is_ok = 1;
			for (j=0; j<nbytes_select; j++)
			   if (ChkKey(&qp[i],select_pointer[j])) is_ok = 0;
			if (is_ok) {
			   strncpy(qp[i].str,select_pointer,nbytes_select);
			   qp[i].str[nbytes_select] = '\0';
			   PromptBox(&qp[i]);
			} else if (*ibell)  XBell(display,0);
		}
	}
   }
   return (ret_val);
}

#define BARR1	0
#define BARR2	1
#define BARRW	23
#define BARRH	23

RedrawList(lp)
LISTSTRU *lp;
{
 int itm;
 
 itm  = QBOXWIDE;
 if (lp->wwin) itm = lp->wwin;

/* Label Box */

      XSetForeground(display, gc, infobg);
      if (lp->label != NULL) {
	  butje(lp->win,0,0,itm,lp->y-4,4,0,0,1,None,0,0,0);
	  LineString(lp->win,lp->label,lp->x+5,lp->y-15);
      }

/* List Box 3d BackGround */

      if (monoscr) {
          XSetFillStyle(display, gc, FillStippled);
          XSetStipple(display, gc, hlfgrey);
          XSetForeground(display, gc, infobg);
          XFillRectangle(display, lp->win, gc, 0, lp->y, itm, lp->h+1);
          XSetFillStyle(display,gc,FillSolid);}
      else butje(lp->win,0,lp->y-5,itm,lp->h+10,4,0,0,1,None,0,0,0);

/* the central ListBox */

      RedrawLBox(lp);

/* The scrollbar */

      RedrawScroll(&lp->scrbar);

      DrwBut(&lp->arrbut[0]);
      DrwBut(&lp->arrbut[1]);
}

int CreateSUB(imd)
int imd;
{
  jmode = imd;
  if (jmode > 2) {
	if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
	"Not Implemented",0)) {
	}
	return(0);
  }

  SUBup = 1;
  topt = toph[jmode];
  tkey = tkeyh[jmode];
  toptn = topn[jmode];

  mopt = moph[jmode];
  mkey = mkeyh[jmode];
  moptn = mopn[jmode];

  bopt = boph[jmode];
  bkey = bkeyh[jmode];
  boptn = bopn[jmode];

  if (jmode == 2) {
     molopt = molopt2;
  } else {
     molopt = molopt1;
  }

  SUBwin = CreateWindow(subwname[jmode],"-80-80",
			 SBOXWIDE,SBOXHIGH,infobg,infofg,(Window)0);
  XSelectInput(display, SUBwin, 
	ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask);

  XMapWindow(display,SUBwin);
  DefBut(&sbut[STASK], SUBwin, SBOXOFFX, 20, SBOXBLEN, 23, 
	"Task", infobg, -15);
  DefBut(&sbut[SMETH], SUBwin, SBOXOFFX, 20+BUTTN, SBOXBLEN, 23, 
	"Method", infobg, -15);
  DefBut(&sbut[SBASS], SUBwin, SBOXOFFX, 20+2*BUTTN, SBOXBLEN, 23, 
	"Basis Set", infobg, -15);
  if (jmode == 2) ActBut(&sbut[SBASS],2);
  DefBut(&sbut[SCHAR], SUBwin, SBOXOFFX, 20+4*BUTTN, SBOXBLEN, 23, 
	"Charge", infobg, -15);
  DefBut(&sbut[SSPIN], SUBwin, SBOXOFFX, 20+5*BUTTN, SBOXBLEN, 23, 
	"Spin", infobg, -15);
  DefBut(&sbut[SMOLD], SUBwin, SBOXOFFL+100, 20+BUTTN, 110, 23, 
	"Molden", infobg, -15);
  if (!jmode) ActBut(&sbut[SMOLD],2);
  DefBut(&sbut[SREST], SUBwin, SBOXOFFL+100, 20+BUTTN, 110, 23, 
	"Restart", infobg, -15);
  if (jmode) ActBut(&sbut[SREST],2);
  DefBut(&sbut[SDIRE], SUBwin, SBOXOFFL+100, 24+2*BUTTN, 15, 15, 
	" ", infobg, -15);
  DefBut(&sbut[SZMAT], SUBwin, SBOXOFFL+200, 24+2*BUTTN, 15, 15, 
	" ", infobg, -15);
  DefBut(&sbut[SWXYZ], SUBwin, SBOXOFFL+230, 24+3*BUTTN, 15, 15, 
	" ", infobg, -15);
  DefBut(&sbut[SHESS], SUBwin, SBOXOFFL+100, 24+2*BUTTN, 15, 15, 
	" ", infobg, -15);
  if (jmode != 1) ActBut(&sbut[SDIRE],2);
  if (jmode != 1) ActBut(&sbut[SZMAT],2);
  if (jmode != 1) ActBut(&sbut[SWXYZ],2);
  if (jmode) ActBut(&sbut[SHESS],2);

  DefBut(&sbut[SBATC], SUBwin, SBOXOFFL+100, 24+3*BUTTN, 15, 15, 
	" ", infobg, -15);
  DefBut(&sbut[SONI], SUBwin, SBOXOFFL+165, 24+3*BUTTN, 15, 15, 
	" ", infobg, -15);
  if (jmode != 1) ActBut(&sbut[SONI],2);
  DefBut(&sbut[SQUEU], SUBwin, SBOXOFFL+173, 15+6*BUTTN, 110,23, 
	"short", infobg, -15);
#ifndef DOQUEUE
  ActBut(&sbut[SQUEU],2);
#endif
  DefBut(&sbut[SSUBM], SUBwin, SBOXOFFX, 30+12*BUTTN, 110, 23, 
	"Submit", infobg, -4);
  DefBut(&sbut[SCLOS], SUBwin, SBOXOFFX+120, 30+12*BUTTN, 110, 23, 
	"Close", infobg, -4);
  if (jmode) {
	qboxstr(&qboxes[QGLIN1],&SUBwin,1,0,190,10,20+7*BUTTN, 
		SBOXWIDE-20,QBOXHIGH,2,"Keywrd",NULL,SUBLEN1,0,2000,
		dummyproc);
	qboxstr(&qboxes[QGLIN2],&SUBwin,0,0,190,10,25+8*BUTTN, 
		SBOXWIDE-20,QBOXHIGH,2,"      ",NULL,SUBLEN1,0,2000,
		dummyproc);
  }
  qboxstr(&qboxes[QGTITL],&SUBwin,0,0,190,10,30+10*BUTTN, 
	SBOXWIDE-20,QBOXHIGH,2,"Title ","title",SUBLEN1,0,2000,
	dummyproc);
  qboxstr(&qboxes[QJNAME],&SUBwin,0,0,190,SBOXOFFL+100,24+4*BUTTN, 
	230,QBOXHIGH,2,"Job Name   ","test",SUBLEN2,0,2000,
	dummyproc);

#ifndef DOQUEUE
  qboxstr(&qboxes[QQNAME],&SUBwin,0,0,190,SBOXOFFL+100,30+5*BUTTN, 
	230,QBOXHIGH,2,"Queue Name ","short",SUBLEN2,0,2000,
	dummyproc);
#endif

  if (!jmode) {
#ifndef DOQUEUE
	qboxstr(&qboxes[QTIME],&SUBwin,0,0,190,SBOXOFFL+100,36+6*BUTTN, 
		230,QBOXHIGH,2,"Job Time   ","10",SUBLEN2,1,2000,
		dummyproc);
#endif
	qboxstr(&qboxes[QENAME],&SUBwin,0,0,190,SBOXOFFL+100,42+7*BUTTN, 
		230,QBOXHIGH,2,"ED Name    ","edtest",SUBLEN2,0,2000,
		dummyproc);
  }

  sbut[STASK].str = topt[itopt[jmode]];
  sbut[SMETH].str = mopt[imopt[jmode]];
  if (jmode != 2) sbut[SBASS].str = bopt[ibopt[jmode]];
  sbut[SSPIN].str = spopt[ispopt];
  sbut[SCHAR].str = copt[icopt];
  if (jmode) sbut[SMOLD].str = molopt[imolopt[jmode]];
  if (!jmode) sbut[SREST].str = resopt[iresopt];
  if (jmode == 1) {
     if (iscfd) {
	TogUp(&sbut[SDIRE]);
     } else {
	TogDown(&sbut[SDIRE]);
     }
     if (izmat) {
	TogUp(&sbut[SZMAT]);
	tkey = tkey2;
     } else {
	TogDown(&sbut[SZMAT]);
	tkey = tkey2b;
     }
     if (ionon == 0) {
	TogUp(&sbut[SONI]);
     } else {
	TogDown(&sbut[SONI]);
     }
  }
  if (!jmode) {
     if (ihess) {
	TogUp(&sbut[SHESS]);
     } else {
	TogDown(&sbut[SHESS]);
     }
  }
  if (*ibatch) {
	TogUp(&sbut[SBATC]);
  } else {
	TogDown(&sbut[SBATC]);
  }

  if (*iwxyz) {
	TogDown(&sbut[SWXYZ]);
  } else {
	TogUp(&sbut[SWXYZ]);
  }

#ifdef DOQUEUE
  sbut[SQUEU].str = ques[qopt];
#endif

  if (jmode) ParseLine();

  return(1);
}

RedrawSUB()
{
  int i;

  butje(SUBwin,0,0,SBOXWIDE,SBOXHIGH,4,0,0,1,None,0,0,0);
  for (i=0; i<NBUTSS; i++) DrwBut(&sbut[i]);
  LineString(SUBwin, "Task", SBOXOFFL, 35);
  if (jmode) ULineString(SUBwin, "Extra print keys for Molden",SBOXOFFL+100, 35);
  else ULineString(SUBwin, "Dumpfile Control",SBOXOFFL+100, 35);
  if (jmode == 1) LineString(SUBwin, "Direct Mode", SBOXOFFL+125, 35+2*BUTTN);
  if (jmode == 1) LineString(SUBwin, "Opt. Z-matrix", SBOXOFFL+225, 35+2*BUTTN);
  if (jmode == 1) LineString(SUBwin, "Write XYZ", SBOXOFFL+250, 35+3*BUTTN);
  if (jmode == 0) LineString(SUBwin, "PickUp Hessian", SBOXOFFL+125, 35+2*BUTTN);
  if (jmode == 1) LineString(SUBwin, "ONIOM", SBOXOFFL+185, 35+3*BUTTN);
  LineString(SUBwin, "Batch", SBOXOFFL+125, 35+3*BUTTN);
#ifdef DOQUEUE
  LineString(SUBwin, "Queue Name", SBOXOFFL+100, 30+6*BUTTN);
#endif
  LineString(SUBwin, "Method", SBOXOFFL, 35+BUTTN);
  if (jmode != 2) LineString(SUBwin, "Basis Set", SBOXOFFL, 35+2*BUTTN);
  LineString(SUBwin, "Charge", SBOXOFFL, 35+4*BUTTN);
  LineString(SUBwin, "Spin", SBOXOFFL, 35+5*BUTTN);
  if (jmode) {
     PromptBox(&qboxes[QGLIN1]);
     PromptBox(&qboxes[QGLIN2]);
  }
  PromptBox(&qboxes[QGTITL]);
  PromptBox(&qboxes[QJNAME]);
#ifndef DOQUEUE
  PromptBox(&qboxes[QQNAME]);
#endif
  if (!jmode) {
#ifndef DOQUEUE
     PromptBox(&qboxes[QTIME]);
#endif
     PromptBox(&qboxes[QENAME]);
  }
}

int ButtonsSUB(i)
int i;
{
  LSSTRU List;
  int redraw=0;
  int j,k,ionij,nconn;

  switch (i) {
  case STASK:	
		List.list = topt; List.nents = toptn;
		if (DoPopUp(SUBwin,
			sbut[STASK].x+SBOXBLEN/2,sbut[STASK].y+BUTTH,
			&List,&itopt[jmode],1) == -1) break;
		sbut[STASK].str = topt[itopt[jmode]];
		if (!jmode && itopt[jmode] == 12) {
		   iresopt = 1;
		   sbut[SREST].str = resopt[iresopt];
		   DrwBut(&sbut[SREST]);
		}
		redraw = 1;
		break;
  case SMETH: 
		List.list = mopt; List.nents = moptn;
		if (DoPopUp(SUBwin,
			sbut[SMETH].x+SBOXBLEN/2,sbut[SMETH].y+BUTTH,
			&List,&imopt[jmode],1) == -1) break;
		sbut[SMETH].str = mopt[imopt[jmode]];
		redraw = 1;
		break;
  case SBASS: 
		List.list = bopt; List.nents = boptn;
		if (DoPopUp(SUBwin,
			sbut[SBASS].x+SBOXBLEN/2,sbut[SBASS].y+BUTTH,
			&List,&ibopt[jmode],1) == -1) break;
		sbut[SBASS].str = bopt[ibopt[jmode]];
		redraw = 1;
		break;
#ifdef DOQUEUE
  case SQUEU: 
		List.list = ques; List.nents = nques;
		if (DoPopUp(SUBwin,
			sbut[SQUEU].x+110/2,sbut[SQUEU].y+BUTTH,
			&List,&qopt,1) == -1) break;
		sbut[SQUEU].str = ques[qopt];
		redraw = 1;
		break;
#endif
  case SCHAR: 
		List.list = copt; List.nents = 7;
		if (DoPopUp(SUBwin,
			sbut[SCHAR].x+SBOXBLEN/2,sbut[SCHAR].y+BUTTH,
			&List,&icopt,1) == -1) break;
		sbut[SCHAR].str = copt[icopt];
		redraw = 1;
		break;
  case SSPIN: 
		List.list = spopt; List.nents = 8;
		if (DoPopUp(SUBwin,
			sbut[SSPIN].x+SBOXBLEN/2,sbut[SSPIN].y+BUTTH,
			&List,&ispopt,1) == -1) break;
		sbut[SSPIN].str = spopt[ispopt];
		redraw = 1;
		break;
  case SMOLD: 
		List.list = molopt; 
		if (jmode == 2) {
		   List.nents = 2;
		} else {
		   List.nents = 3;
		}
		if (DoPopUp(SUBwin,
			sbut[SMOLD].x+110/2,sbut[SMOLD].y+BUTTH,
			&List,&imolopt[jmode],1) == -1) break;
		sbut[SMOLD].str = molopt[imolopt[jmode]];
		redraw = 1;
		break;
  case SREST: 
		List.list = resopt; 
		List.nents = 10;
		if (DoPopUp(SUBwin,
			sbut[SREST].x+110/2,sbut[SREST].y+BUTTH,
			&List,&iresopt,1) == -1) break;
		sbut[SREST].str = resopt[iresopt];
		redraw = 1;
		break;
  case SDIRE: 
		iscfd = TogBut(&sbut[SDIRE]);
		redraw = 1;
		break;
  case SHESS: 
		ihess = TogBut(&sbut[SHESS]);
		if (ihess) {
		   iresopt = 0;
		} else {
		   iresopt = 1;
		}
		sbut[SREST].str = resopt[iresopt];
		DrwBut(&sbut[SREST]);
		redraw = 1;
		break;
  case SBATC: 
		*ibatch = TogBut(&sbut[SBATC]);
		break;
  case SSUBM: 

		/* If ONIOM, should check the charge/mult for levels H, H+M 
		   and eventually H+M+L */

		if (ioniom == 1) {
		  int ism, isl;

		  my_linkat = 0;

		  /* Counting the number of Link atoms between H and lower 
		     levels*/

		  ism = isl = 0;
		  for (j=0;j<*xyz.iatoms;j++) {
	   	     if (xyz.ityp[j] >= 20000) isl = 1;
	   	     if (xyz.ityp[j] >= 10000 && xyz.ityp[j] < 20000) ism = 1;
		     ionij = xyz.ityp[j] / 10000;
		     if (ionij != 0) continue;
		     nconn = xyz.iconn[j*(MXCON+1)];
		     for (k=1;k<=nconn;k++) {
		       if (xyz.ityp[xyz.iconn[j*(MXCON+1)+k]-1]/10000 > 0) my_linkat++;
		     }
		  }
		  my_linkat += 20000;
		  *itotc = *icopth;
		  *imult = *ispopth;
		  if (CheckChargeMult()) {
	           if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
		       "WARNING: inconsistent multiplicity and charge for H level",0)) {
		       i = 0;
	           }
/*
	           break;
*/
		  }
		  icopt = *icoptm+3;
		  ispopt = *ispoptm-1;
		  if (ism == 0 && isl == 1) {
		     icopt = *icoptl+3;
		     ispopt = *ispoptl-1;
		  }

		}  else if (ioniom == 2) {

	          my_linkat = 0;

		  /* Counting the number of Link atoms between H and 
		       lower levels*/

		 for (j=0;j<*xyz.iatoms;j++) {
		         ionij = xyz.ityp[j] / 10000;
			 if(ionij != 0) continue;
		         nconn = xyz.iconn[j*(MXCON+1)];
		         for (k=1;k<=nconn;k++) {
		           if (xyz.ityp[xyz.iconn[j*(MXCON+1)+k]-1]/10000 > 0) my_linkat++;
		         }
		  }
		  my_linkat += 20000;
		  *itotc = *icopth;
		  *imult = *ispopth;
		  if (CheckChargeMult()) {
	               if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
			"WARNING: inconsistent multiplicity and charge for H level",0)) {
		           i = 0;
	               }
/*
	               break;
*/
		  }
	          my_linkat = 0;

		  /* Counting the number of Link atoms between H+M and 
		     lower levels*/

		  for (j=0;j<*xyz.iatoms;j++) {
			ionij = xyz.ityp[j] / 10000;
			if (ionij == 2) continue;
			nconn = xyz.iconn[j*(MXCON+1)];
			for (k=1;k<=nconn;k++) {
			   if (xyz.ityp[xyz.iconn[j*(MXCON+1)+k]-1]/10000 == 2) my_linkat++;
			}
		  }
		  my_linkat += 20000;
		  *itotc = *icoptm;
		  *imult = *ispoptm;
		  if (CheckChargeMult()) {
		     if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
			"WARNING: inconsistent multiplicity and charge for M level",0)) {
		           i = 0;
		     }
/*
		     break;
*/
		  }
		  icopt = *icoptl+3;
		  ispopt = *ispoptl-1;
		}
		my_linkat = 0;
		*itotc = icopt - 3;
		*imult = ispopt + 1;
		*ito = itopt[jmode] + 1;
		*imo = imopt[jmode] + 1;
		*ibo = ibopt[jmode] + 1;
		*ihs = ihess;
#ifdef DOQUEUE
		*itm = quetims[qopt];
#else
		*itm = atoi(qboxes[QTIME].str);
#endif

		if (CheckChargeMult()) {
		   if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
			"WARNING: inconsistent multiplicity and charge",0)) {
			i = 0;
		   }
/*
		   break;
*/
		}
		
		if (!jmode) ParseLGAM();

		if (jmode) {
		   cpstr(qboxes[QGLIN1].str,glin1,SUBLEN1);
		   cpstr(qboxes[QGLIN2].str,glin2,SUBLEN1);
		}
		cpstr(qboxes[QGTITL].str,gtitl,SUBLEN1);
		cpstr(qboxes[QJNAME].str,jname,SUBLEN2);
#ifdef DOQUEUE
		cpstr(ques[qopt],qname,SUBLEN2);
#else
		cpstr(qboxes[QQNAME].str,qname,SUBLEN2);
#endif
		if (!jmode) cpstr(rungam,ename,SUBLEN1);
		if (TogBut(&ZMEbut[ZMESUB])) {
		   XDestroyWindow(display,SUBwin);
		   SUBup = 0;
		}
		return(1);
		break;
  case SZMAT: 
		izmat = TogBut(&sbut[SZMAT]);
		if (izmat) {
		   tkey = tkey2;
		} else {
		   tkey = tkey2b;
		}
		redraw = 1;
		break;
  case SWXYZ: 
		*iwxyz = 1 - TogBut(&sbut[SWXYZ]);
		break;
  case SONI: 
		ionon = 1 - TogBut(&sbut[SONI]);

		if (ionon == 0) {
	           if (ONIup) {
			XDestroyWindow(display,ONIwin);
			ONIup = 0;
		   }
		} else {
		   if (!ONIup) {
			CreateONI();
			*Sinct = 401; return(0);
		   }
		}
		redraw = 1;
		break;
   case SCLOS: 
		if (TogBut(&ZMEbut[ZMESUB])) {
		   XDestroyWindow(display,SUBwin);
		   SUBup = 0;
		}
		break;
  default: break;
  }

  if (redraw && jmode) {
  	RedrawSUB();
	ParseLine();
	PromptBox(&qboxes[QGLIN1]);
	PromptBox(&qboxes[QGLIN2]);
  }
  if (redraw && !jmode) ParseLGAM();

  return(0);

}

ParseLine()
{
   char *scfd;
   char *mopo;
   int i, isl, ism;


   if (jmode == 1 && ONIup) {

	ism = isl = 0;
	for (i=0;i<*xyz.iatoms;i++) {
	   if (xyz.ityp[i] >= 20000) isl = 1;
	   if (xyz.ityp[i] >= 10000 && xyz.ityp[i] < 20000) ism = 1;
	}
	ioniom = 0;
	if (isl && ism) ioniom = 2;
	if ( (isl && ! ism) || (ism && ! isl) ) ioniom = 1;

	if (mkey[imopth] == "AM1" || mkey[imopth] == "dreiding" || 
		mkey[imopth] == "Amber") {
   	   sprintf(*olev,"%s",mkey[imopth]);
	} else {
   	   sprintf(*olev,"%s/%s",mkey[imopth],bkey[ibopth]);
	}
	if (mkey[imoptm] == "AM1" || mkey[imoptm] == "dreiding" || 
		mkey[imoptm] == "Amber") {
   	   sprintf(*(olev+1),"%s",mkey[imoptm]);
	} else {
   	   sprintf(*(olev+1),"%s/%s",mkey[imoptm],bkey[iboptm]);
	}
	if (mkey[imoptl] == "AM1" || mkey[imoptl] == "dreiding" || 
		mkey[imoptl] == "Amber") {
   	   sprintf(*(olev+2),"%s",mkey[imoptl]);
	} else {
   	   sprintf(*(olev+2),"%s/%s",mkey[imoptl],bkey[iboptl]);
	}
/*
	if (ioniom == 0) DeActOButs();
	if (ioniom >= 1) ActOButs();
*/
   }

   if (imolopt[jmode] && jmode != 2) {

	if (ioniom == 0) {
	   sprintf(qboxes[QGLIN1].str,"#P %s/%s %s",
		mkey[imopt[jmode]],bkey[ibopt[jmode]],tkey[itopt[jmode]]);
	} else if(ioniom == 1) {
	   sprintf(qboxes[QGLIN1].str,"#P ONIOM(%s:%s) %s",
	      olev[0],olev[2],tkey[itopt[jmode]]);
	} else {
	   sprintf(qboxes[QGLIN1].str,"#P ONIOM(%s:%s:%s) %s",
	      olev[0],olev[1],olev[2],tkey[itopt[jmode]]);
	}  
   } else {
	if (jmode == 2) {

	   mopo = tkey[itopt[2]];
	   if (!imolopt[2] && itopt[2] == 1) mopo = nullstr;

           if (ispopt) {
	      if (icopt != 3) {
	        sprintf(qboxes[QGLIN1].str,"%s %s %s CHARGE=%s T=24.0H NOINTER +",
		mkey[imopt[jmode]],mopo,spopt[ispopt],copt[icopt]);
	      } else {
	        sprintf(qboxes[QGLIN1].str,"%s %s %s T=24.0H NOINTER +",
		mkey[imopt[jmode]],mopo,spopt[ispopt]);
	      }
	   } else {
	      if (icopt != 3) {
	        sprintf(qboxes[QGLIN1].str,"%s %s CHARGE=%s T=24.0H NOINTER +",
		mkey[imopt[jmode]],mopo,copt[icopt]);
	      } else {
	        sprintf(qboxes[QGLIN1].str,"%s %s T=24.0H NOINTER +",
		mkey[imopt[jmode]],mopo);
	      }
	   }
	} else {
	   if (ioniom == 0) {
	      sprintf(qboxes[QGLIN1].str,"# %s/%s %s",
		   mkey[imopt[jmode]],bkey[ibopt[jmode]],tkey[itopt[jmode]]);
	   } else if(ioniom == 1) {
	      sprintf(qboxes[QGLIN1].str,"# ONIOM(%s:%s) %s",
	         olev[0],olev[2],tkey[itopt[jmode]]);
	   } else {
	      sprintf(qboxes[QGLIN1].str,"# ONIOM(%s:%s:%s) %s",
	         olev[0],olev[1],olev[2],tkey[itopt[jmode]]);
	   }
 	}
   }
 
   if (iscfd) {
	scfd = nullstr;
   } else {
	scfd = scfdir;
   }

   if (imolopt[jmode]) {
     if (jmode == 1) {
	if (imolopt[jmode] == 1) {
	   sprintf(qboxes[QGLIN2].str,"# GFINPUT IOP(6/7=3) 6D 10F %s",scfd);
	} else {
	   sprintf(qboxes[QGLIN2].str,"# GFINPUT IOP(6/7=1) 6D 10F %s",scfd);
	}
     } else if (jmode == 2) {
	if (imolopt[jmode] == 1) {
	   sprintf(qboxes[QGLIN2].str,"GRAPH NOXYZ PRNT=2 COMPFG");
	}
     }
   } else {
	if (jmode == 2) {
	   sprintf(qboxes[QGLIN2].str," ");
	} else {
	   sprintf(qboxes[QGLIN2].str,"# %s",scfd);
	}
   }

}

ParseLGAM()
{
   if (*ibatch) {
      if (iresopt) {
	sprintf(rungam,"$GAMESS_ROOT/utilities/rungamess %s -n %s %s",
		reskey[iresopt],qboxes[QENAME].str,qboxes[QJNAME].str);
      } else {
	sprintf(rungam,"$GAMESS_ROOT/utilities/rungamess %s",
		qboxes[QJNAME].str);
      }
   } else {
      if (iresopt) {
	sprintf(rungam,
	   "$GAMESS_ROOT/utilities/rungamess %s -n %s %s -nqs -q %s",
	   reskey[iresopt],qboxes[QENAME].str,qboxes[QJNAME].str,
#ifdef DOQUEUE
	   ques[qopt]);
#else
	   qboxes[QQNAME].str);
#endif
      } else {
	sprintf(rungam,"$GAMESS_ROOT/utilities/rungamess %s -nqs -q %s",
		qboxes[QJNAME].str,
#ifdef DOQUEUE
		ques[qopt]);
#else
		qboxes[QQNAME].str);
#endif
      }
   }
}

int CheckChargeMult()
{
   int i,ne,ionil;

   ne = 0;

   ionil = 0;

   if (ioniom) {
     ionil = 3 - (my_linkat / 10000);
     my_linkat -= (my_linkat / 10000) * 10000;
   } else {
     my_linkat = 0;
   }

   if (*zmptr.ihaszm) {
	for (i=0; i<*zmptr.nz; i++) {
	   if (ioniom && (xyz.ityp[i]/10000 >= ionil)) continue;
	   if (zmptr.ianz[i] >= 0 && zmptr.ianz[i] < 99) {
		ne = ne + zmptr.ianz[i];
	   }
	}
   } else {
      if (*iwxyz) {
	for (i=0; i<*xyz.iatoms; i++) {
	   if (ioniom && (xyz.ityp[i]/10000 >= ionil)) continue;
	   if (xyz.ianz[i] >= 0 && xyz.ianz[i] < 99) {
		ne = ne + xyz.ianz[i];
	   }
	}
      } else {
	return(0);
      }
   }
/*
   fprintf(stderr,"ionil %d ne %d itotc %d my_linkat %d mult %d\n",
                   ionil,ne,*itotc,my_linkat,*imult);
*/
   ne = ne - *itotc + my_linkat;
   if (ne % 2 == *imult % 2) return(1);
   return(0);
}

RedrawLBox(lp)
LISTSTRU *lp;
{
      int i;
      char drawstrc[43];

      drawstrc[42] = '\0';

      XSetForeground(display, gc, infofg);
      XFillRectangle(display, lp->win, gc, lp->x+1, lp->y+1, lp->w-1, lp->h-1);

      XSetForeground(display, gc, infobg);
      XDrawRectangle(display, lp->win, gc, lp->x, lp->y, lp->w, lp->h);

      for (i=0; i<MINI(lp->mxents,*lp->list.nents); i++) {
         if (i+lp->lpnt == lp->select) {
              XFillRectangle(display, lp->win, gc, lp->x, lp->y+i*lp->h/lp->mxents, lp->w, lp->h/lp->mxents);
              XSetForeground(display, gc, infofg);
	      if (lp->list.list == NULL) {
		  if (lp->list.flst == NULL)
			sprintf(drawstrc,"%4d      %11.6f",lp->lpnt+i+1,
			lp->list.rlst[lp->lpnt+i]);
		  else if (lp->list.rlst == NULL)
		  	sprintf(drawstrc,"%4d      %3.2lf",lp->lpnt+i+1,
			lp->list.flst[lp->lpnt+i]);
		  else
		  	sprintf(drawstrc,"%4d      %11.6f      %3.2lf",lp->lpnt+i+1,
			lp->list.rlst[lp->lpnt+i],lp->list.flst[lp->lpnt+i]);
	      } else {
		  if (lp->list.ilst == NULL) {
		  	if (lp->list.rlst != NULL) 
		  	   sprintf(drawstrc,"%4d      %11.6f      %s",
				lp->lpnt+i+1,lp->list.rlst[lp->lpnt+i],
				lp->list.list[lp->lpnt+i]);
			else
			   strncpy(drawstrc,lp->list.list[lp->lpnt+i],42);
		  } else {
			strncpy(drawstrc,lp->list.list[lp->list.ilst[lp->lpnt+i]],42);
		  }
	      }
              LineString(lp->win,drawstrc,lp->x+5,lp->y+12+i*lp->h/lp->mxents);
              XSetForeground(display, gc, infobg);}
         else {
	      if (lp->list.list == NULL) {
		  if (lp->list.flst == NULL) {
		  	sprintf(drawstrc,"%4d      %11.6f",lp->lpnt+i+1,
			lp->list.rlst[lp->lpnt+i]);
		  }
		  else if (lp->list.rlst == NULL) {
		  	sprintf(drawstrc,"%4d      %3.2lf",lp->lpnt+i+1,
			lp->list.flst[lp->lpnt+i]);
		  }
		  else {
		  	sprintf(drawstrc,"%4d      %11.6f      %3.2lf",lp->lpnt+i+1,
			lp->list.rlst[lp->lpnt+i],lp->list.flst[lp->lpnt+i]);
		  }
	      }
	      else {
		  if (lp->list.ilst == NULL) {
		  	if (lp->list.rlst != NULL) 
		  	   sprintf(drawstrc,"%4d      %11.6f      %s",
				lp->lpnt+i+1,lp->list.rlst[lp->lpnt+i],
				lp->list.list[lp->lpnt+i]);
			else
			   strncpy(drawstrc,lp->list.list[lp->lpnt+i],42);
		  } else {
			strncpy(drawstrc,lp->list.list[lp->list.ilst[lp->lpnt+i]],42);
		  }
	      }
	      LineString(lp->win,drawstrc,lp->x+5,lp->y+12+i*lp->h/lp->mxents);}
      }
}

DefList(lp,win,x,y,w,h,label,mx,lstr,rlist,flst,nentries)
LISTSTRU	*lp;
Window		win;
int		x,y;
unsigned int	w,h;
int		mx;
char		*label;
char         **lstr;
float		*rlist;
double		*flst;
int		*nentries;
{
  int ggx, ggy;
  unsigned int ggw, ggh, ggb, ggd;
  Window rt;

  lp->win = win;
  lp->x = x;  lp->y = y;  lp->w = w;  lp->h = h;
  lp->mxents = mx;
  lp->list.list = lstr;
  lp->list.rlst = rlist;
  lp->list.flst = flst;
  lp->list.ilst = NULL;
  lp->list.nents = nentries;
  lp->lpnt = 0;
  lp->select = 0;
  lp->label = label;

  lp->wwin = 0;
  if (XGetGeometry(display,lp->win,&rt,
	&ggx, &ggy, &ggw, &ggh, &ggb, &ggd) == True ) lp->wwin = ggw;

  DefScroll(&lp->scrbar,lp->win,lp->x+lp->w,lp->y+BARRH,BARRW,
             lp->h-2*BARRH,lp->list.nents,&lp->lpnt,lp->mxents);

  DefBut(&lp->arrbut[0], lp->win, lp->x+lp->w, lp->y            ,
	BARRW, BARRH, " ", infobg, 0);
  DefBut(&lp->arrbut[1], lp->win, lp->x+lp->w, lp->y+lp->h-BARRH+1, 
	BARRW, BARRH, " ", infobg, 0);

  lp->arrbut[0].pix = upPix;
  lp->arrbut[0].pw  = up_width;
  lp->arrbut[0].ph  = up_height;

  lp->arrbut[1].pix = downPix;
  lp->arrbut[1].pw  = down_width;
  lp->arrbut[1].ph  = down_height;
}

int PressList(lp,x,y)
LISTSTRU	*lp;
int		x;
int		y;
{
      int i;

  if (VIERKANT(x, y,lp->x,lp->y,lp->w,lp->h)){
      lp->select = lp->lpnt + lp->mxents*(y - lp->y) / lp->h;
      RedrawList(lp);
      return 1;
  }
  else {

      i=Clickwin(lp->arrbut,2,x,y,1);

      if (i>=0) {
	  switch (i) {
          case BARR1: if (*lp->list.nents > lp->mxents) 
		if (lp->lpnt) {
			lp->lpnt--;RedrawLBox(lp); RedrawScroll(&lp->scrbar);
		}
#ifdef HASTIMER
		Timer(100,0);
		while (!XCheckWindowEvent(display, lp->win, ButtonReleaseMask, &event)) {
			if (*lp->list.nents > lp->mxents) 
			   if (lp->lpnt) {
				lp->lpnt--;
				RedrawLBox(lp); RedrawScroll(&lp->scrbar);
				Timer(50,0);
			   }
			}
#endif
                        break;
          case BARR2:	if (*lp->list.nents > lp->mxents) {
				lp->lpnt++; 
				if (lp->lpnt > *lp->list.nents-lp->mxents) 
					lp->lpnt = *lp->list.nents-lp->mxents;
				RedrawLBox(lp); RedrawScroll(&lp->scrbar);
			}
#ifdef HASTIMER
			Timer(100,0);
			while (!XCheckWindowEvent(display, lp->win, ButtonReleaseMask, &event)) {
                    		if (*lp->list.nents > lp->mxents) {
                               		lp->lpnt++; 
                               		if (lp->lpnt > *lp->list.nents-lp->mxents) {
						lp->lpnt = *lp->list.nents-lp->mxents;
                               		} else {
						RedrawLBox(lp);
						RedrawScroll(&lp->scrbar);
					}
					Timer(50,0);
                               	}
			}
#endif
			break;
          }
      }
      ScrollPage(lp,&lp->scrbar,x,y);
      return 0;
  }

}

/**********************************************/
DefBut(bp,win,x,y,w,h,str,bg,fg)
BSTRU         *bp;
Window        win;
int           x,y,w,h;
char         *str;
unsigned long bg;
int fg;
{
  bp->win = win;
  bp->x = x;  bp->y = y;  bp->w = w;  bp->h = h;
  if (!w) {
	bp->w = XTextWidth(mfinfo,str,strlen(str)) + 2*SPACING;
  } else {
	bp->w = w;
  }
  bp->str = str;
  if (monoscr || colcells <= 32) {bp->fg = infobg; bp->bg = infofg;}
  else {bp->fg = fg;  bp->bg = bg;}
  bp->lit = 0;
  bp->active = 1;
  bp->toggle = 1;
  bp->pix = None;
  bp->style = 0;
  bp->fwidth = 3;
  bp->lastused = 0;
  bp->explstr = NULL;

  if (!hlfgrey) {
    hlfgrey = XCreatePixmapFromBitmapData(display, win, hlfgrey_bits,
		       hlfgrey_width, hlfgrey_height, 1, 0, 1);
    if (!hlfgrey) fprintf(stderr,"Unable to create hlfgrey bitmap\n");
  }
}



ActBut(bp,act)
BSTRU *bp;
int           act;
{
  if (bp->active != act) {
    bp->active = act;
    DrwBut(bp);
  }
}

int TogBut(bp)
BSTRU *bp;
{
  if (bp->toggle) bp->toggle = 0;
  else bp->toggle = 1;
  DrwBut(bp);
  return (bp->toggle);
}


TogDown(bp)
BSTRU *bp;
{
  bp->toggle = 0;
  DrwBut(bp);
}

TogUp(bp)
BSTRU *bp;
{
  bp->toggle = 1;
  DrwBut(bp);
}

/**********************************************/
DrwBut(bp)
BSTRU *bp;
{
  int x,y,w,h,r,x1,y1;

  if (bp->active == 2) return;

  x = bp->x;  y=bp->y;  w=bp->w;  h=bp->h;  r=bp->fwidth;

  if (bp->active < 1) bp->lit = 0;
  if (bp->lit) {
    r -= 1;
    if (r<0) r = 0;
  }

  if (bp->lastused == 1) {
	butje(bp->win,x,y,w,h,r,0,bp->fg,bp->toggle,bp->pix,bp->pw,bp->ph,2);
  } else if (bp->lastused == -1) {
	butje(bp->win,x,y,w,h,r,bp->bg,bp->fg,bp->toggle,bp->pix,bp->pw,bp->ph,-2);
  } else butje(bp->win,x,y,w,h,r,0,bp->fg,bp->toggle,bp->pix,bp->pw,bp->ph,0);

  if (bp->lit) {
      if (monoscr || colcells <= 32) {
           XDrawRectangle(display, bp->win, gc, x+2, y+2, w-4, h-4);
           XDrawRectangle(display, bp->win, gc, x+1, y+1, w-2, h-2);
      }
      else XDrawRectangle(display, bp->win, gc, x+1, y+1, w-2, h-2);
  }

  if (bp->pix == None) { 
    x1 = MIDDLEX(mfinfo, x + w/2, bp->str);
    y1 = MIDDLEY(mfinfo, y + h/2);

    if (bp->active == 1) {
      XDrawString(display, bp->win, gc, x1,y1, bp->str, strlen(bp->str));
    }
    else {  
      XSetFillStyle(display, gc, FillStippled);
      XSetStipple(display, gc, grayStip);
      XDrawString(display, bp->win, gc, x1,y1, bp->str, strlen(bp->str));
      XSetFillStyle(display,gc,FillSolid);
    }
  }

}


SelBut(bp)
BSTRU *bp;
{

  XSetLineAttributes(display, gc, 2, LineSolid, CapButt, JoinMiter);
  XSetForeground(display, gc, Black);
  XDrawRectangle(display, bp->win, gc, bp->x-2, bp->y-2, bp->w+4, bp->h+4);
  XSetLineAttributes(display, gc, 1, LineSolid, CapButt, JoinMiter);

}

/***************************************************/
int Clickwin(but,num,x,y,check)
BSTRU  *but;
int x,y,num,check;
{
  BSTRU  *bp;
  int    bnum;

  for (bnum=0; bnum<num; bnum++) {
    bp = &but[bnum];
    if (bp->active != 2) if (VIERKANT(x, y, bp->x, bp->y, bp->w, bp->h)) break;
  }

  if (bnum<num) {   /* found one */
    if (check) {
	if (ChkBut(bp)) return (bnum);
    } else {
	return (bnum);
    }
  }

  return -1;
}

/**********************************************/
int ChkBut(bp)
BSTRU *bp;
{

  int          rval, inval;
#ifndef HASTIMER
  Window       rW, cW;
  int          x, y, rx, ry;
  unsigned int mask;
#endif

  if (bp->active != 1) return 0;   

  inval = bp->lit;
  bp->lit = !bp->lit;

  DrwBut(bp);  XFlush(display);
#ifdef HASTIMER
  Timer(120,0);  /* long enough for turn on to be visible */

#else
  while (XQueryPointer(display,bp->win,&rW,&cW,&rx,&ry,&x,&y,&mask)) {
    if (!(mask & Button1Mask)) break;    /* button released */

    if (bp->lit==inval && VIERKANT(x, y, bp->x, bp->y, bp->w, bp->h)) {
      bp->lit = !inval;  DrwBut(bp);  XFlush(display);
    }
    
    if (bp->lit!=inval && !VIERKANT(x, y, bp->x, bp->y, bp->w, bp->h)) {
      bp->lit = inval;  DrwBut(bp);  XFlush(display);
    }
  }
#endif

  rval = (bp->lit != inval);
  
  if (bp->lit ) 
    { bp->lit = 0;  DrwBut(bp);  XFlush(display); }

  return(rval);
}

#define EXPLSPACE 5
void DoExpl()
{
  Window win;
  int x,y,xt,yt;
  int wit,hit,bw,xp,retval,nlines,wittmp,ql;
  char *p, *q;
  BSTRU *bp;
  QBOXSTRU *qp;
  
  if ((!expldat.borq && expldat.barr == NULL) ||
      (expldat.borq && expldat.qarr == NULL)) return;

  if (expldat.winup != NULL) if (! *expldat.winup) return;

  expldat.active = 1;
  signal(SIGALRM,SIG_IGN);

  if (expldat.borq) {
	qp = &expldat.qarr[expldat.button];
	win = qp->win;
	x = qp->x; y = qp->y;
	p = qp->explstr;
	q = qp->explstr;
  } else {
	bp = &expldat.barr[expldat.button];
	win = bp->win;
	x = bp->x; y = bp->y;
	p = bp->explstr;
	q = bp->explstr;
  }

  XGetWindowAttributes(display, win, &xwa);

  nlines = 0;
  wit = 0;
  while ((p = strchr(q, '\n'))) {
     ql = (int) (p-q);
     wittmp = XTextWidth(mfinfo,q,ql) + 2*EXPLSPACE;
     if (wittmp > wit) wit = wittmp;
     p++;
     q = p;
     nlines++;
  }
  ql = strlen(q);
  wittmp = XTextWidth(mfinfo,q,ql) + 2*EXPLSPACE;
  if (wittmp > wit) wit = wittmp;
  nlines++;

  hit = EXPLSPACE + LINEHIGH*nlines + EXPLSPACE;
  xt = x-wit/2; yt = y-hit/2;
  if (x+wit > xwa.width) xt = xwa.width-wit; 
  if (xt < 0) xt = 0; 
  if (yt < 0) yt = 0; 
  
  XSelectInput(display, expldat.win, 
  ( ExposureMask | PointerMotionMask | VisibilityChangeMask ));
  
  XMoveResizeWindow(display, expldat.win, xt, yt, wit, hit);

  XMapRaised(display,expldat.win);

  XSync(display, False);

  XNextEvent(display, &event);

  XSetForeground(display, gc, colors[0]);

  nlines = 0;
  if (expldat.borq) {
	p = qp->explstr;
	q = qp->explstr;
  } else {
	p = bp->explstr;
	q = bp->explstr;
  }

  while ((p = strchr(q, '\n'))) {
		ql = (int) (p-q);
	        XDrawString(display, expldat.win, gc, 
			EXPLSPACE, CHIGH+nlines*LINEHIGH+EXPLSPACE, q, ql);
		p++;
		q = p;
		nlines++;
  }
  ql = strlen(q);
  XDrawString(display, expldat.win, gc, 
		EXPLSPACE, CHIGH+nlines*LINEHIGH+EXPLSPACE, q, ql);

  XFlush(display);

  XMaskEvent(display, PointerMotionMask | ButtonPressMask, &event);


  XUnmapWindow(display,expldat.win);
  XSync(display, False);
  expldat.active = 0;
  expldat.barr = NULL;
  expldat.qarr = NULL;
  expldat.win = -1;
}

int StringWidth(str)
char *str;
{
  return(XTextWidth(mfinfo, str, strlen(str)));
}


butje(bwin,x,y,w,h,r,bgcol,sh_ind,iopt,pix,pw,ph,rec)
Window bwin;
int x,y,w,h,r,bgcol,sh_ind,iopt;
Pixmap pix;
int pw,ph,rec;
{
  int i,x1,y1;
  int dark,light,medium;
  XPoint butb[10], butc[10], buta[5];

  if (DEBUG) fprintf(stderr,"butje in\n");

  if (bwin == (Window) NULL) return;

  buta[0].x = x+r;        buta[0].y = y+r;
  buta[1].x = x+r;        buta[1].y = y+h-r;
  buta[2].x = x+w-r;      buta[2].y = y+h-r;
  buta[3].x = x+w-r;      buta[3].y = y+r;
  buta[4].x = buta[0].x;  buta[4].y = buta[0].y;


  butb[0].x = x;            butb[0].y = y+h;
  butb[1].x = buta[1].x;    butb[1].y = buta[1].y;
  butb[2].x = buta[2].x;    butb[2].y = buta[2].y;
  butb[3].x = buta[3].x;    butb[3].y = buta[3].y;
  butb[4].x = x+w;          butb[4].y = y;
  butb[5].x = x+w;          butb[5].y = y+h;
  butb[6].x = x;            butb[6].y = y+h;

  butc[0].x = x;            butc[0].y = y+h;
  butc[1].x = buta[1].x;    butc[1].y = buta[1].y;
  butc[2].x = buta[0].x;    butc[2].y = buta[0].y;
  butc[3].x = buta[3].x;    butc[3].y = buta[3].y;
  butc[4].x = x+w;          butc[4].y = y;
  butc[5].x = x;            butc[5].y = y;
  butc[6].x = x;            butc[6].y = y+h;


  if (monoscr || colcells <= 32) {
    XSetForeground(display, gc, White);
    XFillRectangle(display, bwin, gc, x, y, w, h);
    XSetForeground(display, gc, Black);
    XDrawRectangle(display, bwin, gc, x, y, w, h);

    XSetForeground(display, gc, Black);
    XSetFillStyle(display, gc, FillStippled);
    XSetStipple(display, gc, hlfgrey);
    if (!iopt) XFillPolygon(display, bwin, gc, butc, 7, Nonconvex, CoordModeOrigin);
    else XFillPolygon(display, bwin, gc, butb, 7, Nonconvex, CoordModeOrigin);
    XSetFillStyle(display,gc,FillSolid);

    XSetForeground(display, gc, Black);
    XDrawLines(display, bwin, gc, buta, 5, CoordModeOrigin);  

    XDrawLine(display, bwin, gc, x+1,   y+1,  buta[0].x,buta[0].y);
    XDrawLine(display, bwin, gc, x+1,   y+h-1,buta[1].x,buta[1].y);
    XDrawLine(display, bwin, gc, x+w-1, y+h-1,buta[2].x,buta[2].y);
    XDrawLine(display, bwin, gc, x+w-1, y+1,  buta[3].x,buta[3].y);

  }
    
  else {  
    if (sh_ind >= 0) {
	dark   = shcolors[sh_ind]+DARK;
	light  = shcolors[sh_ind]+LIGHT;
	medium = shcolors[sh_ind]+MEDIUM;
    }
    else {
	dark   = 15-(sh_ind+1)*10+3;
	light  = 15-(sh_ind+1)*10+10;
	medium = 15-(sh_ind+1)*10+7;
    }

    XSetForeground(display, gc, colors[medium] );
    XFillRectangle(display, bwin, gc, x+1, y+1, w-1, h-1);

    if (!iopt) XSetForeground(display, gc, colors[dark]);
    else XSetForeground(display, gc, colors[light]);
    for (i=1; i<=r; i++) {
      XDrawLine(display, bwin, gc, x+i, y+i, x+w, y+i);
      XDrawLine(display, bwin, gc, x+i, y+i, x+i, y+h);
    }

    if (!iopt) XSetForeground(display, gc, colors[light]);
    else XSetForeground(display, gc, colors[dark]);
    for (i=1; i<=r; i++) {
      XDrawLine(display, bwin, gc, x+i, y+h-i, x+w, y+h-i);
      XDrawLine(display, bwin, gc, x+w-i, y+h, x+w-i, y+i);
    }

    if (rec) {
        XSetLineAttributes(display, gc, ABS(rec), LineSolid, CapButt, JoinMiter);
	if (rec > 0) XSetForeground(display, gc, Black);
	else {  if (bgcol == -1) XSetForeground(display, gc, White);
		else XSetForeground(display, gc, colors[bgcol]);
	}
	XDrawRectangle(display, bwin, gc, x, y, w, h);
        XSetLineAttributes(display, gc, 1, LineSolid, CapButt, JoinMiter);
    }

  }
    

  XSetForeground(display, gc, Black);

  if (pix != None) {                 
    x1 = x+(1+w-pw)/2;
    y1 = y+(1+h-ph)/2;

    if (monoscr || colcells <= 32) XSetBackground(display, gc, White);
    else XSetBackground(display, gc, colors[medium]);
    XCopyPlane(display, pix, bwin, gc, 0,0,pw,ph, x1,y1, 1);
    XSetBackground(display, gc, White);
  }

  if (DEBUG) fprintf(stderr,"butje out\n");

}


/***************************************************/
CreatewinC(geom)
char *geom;
{


  if (DEBUG) fprintf(stderr,"CreatewinC in\n");

  winC = CreateWindow("Molden Control",geom,WINCWIDE, WINCHIGH, infobg, infofg,(Window)0);

  subC = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],winC);

  DefBut(&dbut[BPSI],   winC, PLOFFX+BOFFX, PLOFFY+24            , 60, BUTTH, 
	   "Orbital", infobg, CNTCOL);
  dbut[BPSI].explstr = "Select orbital to display\nFor open shell:\nselect alpha or beta orbitals";
  DefBut(&dbut[BHOMO],  winC, PLOFFX+BOFFX, PLOFFY+24+BUTTN  , 60, BUTTH, 
	   "Homo", infobg, CNTCOL);
  dbut[BHOMO].explstr = "Highest Occupied Molecular Orbital\nis displayed";
  DefBut(&dbut[BLUMO],  winC, PLOFFX+BOFFX, PLOFFY+24+BUTTN*2, 60, BUTTH, 
	   "Lumo", infobg, CNTCOL);
  dbut[BLUMO].explstr = "Lowest Unoccupied Molecular Orbital\nis displayed";
  DefBut(&dbut[BNDEN],  winC, PLOFFX+BOFFX, PLOFFY+24+BUTTN*3, 60, BUTTH, 
	   "Density", infobg, CNTCOL);
  dbut[BNDEN].explstr = "Display electron density";
  DefBut(&dbut[BLAPL],  winC, PLOFFX+BOFFX+65, PLOFFY+24+BUTTN*3, 60, BUTTH, 
	   "Laplac.", infobg, CNTCOL);
  dbut[BLAPL].explstr = "Display Laplacian of\nelectron density";
  DefBut(&dbut[BBONDS], winC, PLOFFX+BOFFX, PLOFFY+24+BUTTN*4, 60, BUTTH, 
	   "Bonds", infobg, CNTCOL);
  dbut[BBONDS].explstr = "Display Difference Density:\nMolecular minus Atomic";
  DefBut(&dbut[BORI],   winC, PLOFFX+BOFFX+65,PLOFFY+36+BUTTN*4,TOGGWH, TOGGWH, 
	   " ", infobg, CNTCOL);
  dbut[BORI].explstr = "Use oriented atomic density in\ncalculation of Difference Density:\nMolecular minus Atomic";
  DefBut(&dbut[BATOM],  winC, PLOFFX+BOFFX, PLOFFY+24+BUTTN*5, 60, BUTTH, 
	   "Atomic", infobg, CNTCOL);
  dbut[BATOM].explstr = "Display Difference Density:\nMolecular minus Atomic\nOnly contributions where \nAO1,AO2 are on the same atom";
  DefBut(&dbut[BOVRLP], winC, PLOFFX+BOFFX, PLOFFY+24+BUTTN*6, 60, BUTTH, 
	   "Overlap", infobg, CNTCOL);
  dbut[BOVRLP].explstr = "Display Difference Density:\nMolecular minus Atomic\nOnly overlap contributions only:\nAO1,AO2 not on the same atom";
  DefBut(&dbut[BELPOT], winC, PLOFFX+BOFFX, PLOFFY+24+BUTTN*7, 60, BUTTH, 
	   "Elec. Pot", infobg, CNTCOL);
  dbut[BELPOT].explstr = "Calculate Electrostatic Potential";

  DefBut(&dbut[BCOMM],  winC, MSOFFX+BOFFX, MSOFFY+24+BUTTN*0, 70, BUTTH, 
	   "PlotPlane", infobg, CNTCOL);
  dbut[BCOMM].explstr = "commands that define the plotplane\nfor euclid plots\nand the grid size\n(also for space plots)";
  DefBut(&dbut[BMAXMIN],winC, MSOFFX+BOFFX, MSOFFY+24+BUTTN*1, 70, BUTTH, 
	   "Maxi/Mini", infobg, CNTCOL);
  dbut[BMAXMIN].explstr = "show the maxima and minima\nfor euclid plots";
  DefBut(&dbut[BPOST],  winC, MSOFFX+BOFFX, MSOFFY+24+BUTTN*2, 70, BUTTH, 
	   "Postscript", infobg, CNTCOL);
  dbut[BPOST].explstr = "write a postcript file\nof current plot";
  DefBut(&dbut[BMOLMOD],winC, MSOFFX+BOFFX, MSOFFY+24+BUTTN*3, 70, BUTTH, 
	   "Mol. Mode", infobg, CNTCOL);
  dbut[BMOLMOD].explstr = "switch back to the molecular mode";

  DefBut(&dbut[BEUCL],  winC, PMOFFX+30, PMOFFY+26, 60, BUTTH-2, 
	   "Euclid", infobg, CNTCOL);
  dbut[BEUCL].explstr = "2D contour plot of orbital/density\nin a plane";
  DefBut(&dbut[B3D],    winC, PMOFFX+15, PMOFFY+26+(BUTTH+2)*1, 40, BUTTH-2, 
	   "3D", infobg, CNTCOL);
  dbut[B3D].explstr = "3D plot of orbital/density\nin a plane";
  DefBut(&dbut[B3DX],   winC, PMOFFX+65, PMOFFY+26+(BUTTH+2)*1, 40, BUTTH-2, 
	   "3D-X", infobg, CNTCOL);
  dbut[B3DX].explstr = "3D plot of orbital/density\nin a plane:\nXwindows rendering";
  DefBut(&dbut[BSPACE], winC, PMOFFX+5, PMOFFY+26+(BUTTH+2)*2, 50, BUTTH-2, 
	   "Space", infobg, CNTCOL);
  dbut[BSPACE].explstr = "iso-surface of orbital/density\ncalculated in a 3D grid";
  DefBut(&dbut[BVRML2], winC, PMOFFX+63, PMOFFY+26+(BUTTH+2)*2, 24, 24, 
	   "VRML", infobg, CNTCOL);
  dbut[BVRML2].explstr = "write a Virtual Reality Modeling Language\nrepresentation of the current plot";
  DefBut(&dbut[BSRF2],  winC, PMOFFX+93, PMOFFY+26+(BUTTH+2)*2, 24, 24, 
	   "SRF", infobg, CNTCOL);
  dbut[BSRF2].explstr = "convert space plot so it can be\ndisplayed in molecular mode";

  DefBut(&dbut[BINCRS], winC, D3OFFX+BOFFX, D3OFFY+24+BUTTN*0, 80, BUTTH, 
	   "Incr. Scale", infobg, CNTCOL);
  dbut[BINCRS].explstr = "increase the heigth of the 3D plot.";
  DefBut(&dbut[BDECRS], winC, D3OFFX+BOFFX, D3OFFY+24+BUTTN*1, 80, BUTTH, 
	   "Decr. Scale", infobg, CNTCOL);
  dbut[BDECRS].explstr = "decrease the heigth of the 3D plot.";
  DefBut(&dbut[BCONT],  winC, D3OFFX+BOFFX, D3OFFY+24+BUTTN*2, TOGGWH, TOGGWH, 
	   " ", infobg, CNTCOL);
  dbut[BCONT].explstr = "toggle contours on/off in the 3D plot.";
  DefBut(&dbut[BMOL],   winC, D3OFFX+BOFFX, D3OFFY+24+BUTTN*3, TOGGWH, TOGGWH, 
	   " ", infobg, CNTCOL);
  dbut[BMOL].explstr = "toggle molecule on/off in the 3D plot.";

  DefBut(&dbut[BSTEP],  winC, CNOFFX+BOFFX, CNOFFY+24+BUTTN*0, 60, BUTTH, 
	   "Step", infobg, CNTCOL);
  dbut[BSTEP].explstr = "function value increment between\nconsequtive contour lines ";
  DefBut(&dbut[BCUT],   winC, CNOFFX+BOFFX, CNOFFY+24+BUTTN*1, 60, BUTTH, 
	   "Cut", infobg, CNTCOL);
  dbut[BCUT].explstr = "contours above cutoff are not shown";

  DefBut(&dbut[BFILL],  winC, SPOFFX+BOFFX, SPOFFY+24, TOGGWH, TOGGWH, 
	   " ", infobg, CNTCOL);

  DefBut(&dbut[BWRBAS], winC, BSOFFX+BOFFX, BSOFFY+24+BUTTN*0, 70, BUTTH, 
	   "Write Grid", infobg, CNTCOL);
  dbut[BWRBAS].explstr = "write 2D/3D grid as\ngridfile/3dgrifile";
  DefBut(&dbut[BRDBAS], winC, BSOFFX+BOFFX, BSOFFY+24+BUTTN*1, 70, BUTTH, 
	   "Read Grid", infobg, CNTCOL);
  dbut[BRDBAS].explstr = "read 2D/3D grid as\ngridfile/3dgrifile";

  DefBut(&dbut[BCUBE],  winC, QOFFX+BOFFX, QOFFY+3, 70, BUTTH, 
	   "Rd/Wr Cube", infobg, CNTCOL);
  dbut[BCUBE].explstr = "read/write Gaussian cube file (3D grid)";

  DefBut(&dbut[BQUIT],  winC, QOFFX+BOFFX+80, QOFFY+1, 22, 22, 
	   "Quit", infobg, CNTCOL);
  dbut[BQUIT].explstr = "exit molden";

#ifdef DOGL
  DefBut(&dbut[BOGL],  winC, PMOFFX+93, PMOFFY+21, 24, 24, 
	   "Ogl", infobg, CNTCOL);
  dbut[BOGL].explstr = "switch between Xwindows (primitive)\nand OpenGL (quality) rendering";
#endif

  dbut[BVRML2].pix = VRMLPix;
  dbut[BVRML2].pw  = vrml_width;
  dbut[BVRML2].ph  = vrml_height;

  dbut[BSRF2].pix = SurfPix;
  dbut[BSRF2].pw  = surf_width;
  dbut[BSRF2].ph  = surf_height;

  dbut[BQUIT].pix = SkullPix;
  dbut[BQUIT].pw  = skull_width;
  dbut[BQUIT].ph  = skull_height;

#ifdef DOGL
  dbut[BOGL].pix = OGLPix;
  dbut[BOGL].pw  = ogl_width;
  dbut[BOGL].ph  = ogl_height;

  if (*ifdogl) TogDown(&dbut[BOGL]);
  else TogUp(&dbut[BOGL]);
#endif

  if (DEBUG) fprintf(stderr,"CreatewinC out\n");
}
  

CreatewinMC(geom)
char *geom;
{


  if (DEBUG) fprintf(stderr,"CreatewinMC in\n");

  winMC = CreateWindow("Molden Control",geom,WINMCWIDE, WINMCHIGH, infobg, infofg,(Window)0);

  subMC = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],winMC);

  DefBut(&cbut[BFIRST], winMC, POFFX+BOFFX , POFFY+24         , 60, BUTTH, 
	   "First", infobg, CNTCOL);
  cbut[BFIRST].explstr = "When multiple structures available:\nMD trajectory, Geometry optimisation etc.\nGo to the first structure";

  DefBut(&cbut[BNEXT] , winMC, POFFX+BOFFX-5 , POFFY+24+BUTTN   , 35, BUTTH, 
	   "Next", infobg, CNTCOL);
  cbut[BNEXT].explstr = "When multiple structures available:\nMD trajectory, Geometry optimisation etc.\nGo to the next structure";

  DefBut(&cbut[BPREV] , winMC, POFFX+BOFFX+33 , POFFY+24+BUTTN   , 33, BUTTH, 
	   "Prev", infobg, CNTCOL);
  cbut[BPREV].explstr = "When multiple structures available:\nMD trajectory, Geometry optimisation etc.\nGo to the previous structure";

  DefBut(&cbut[BMOVIE], winMC, POFFX+BOFFX , POFFY+24+BUTTN*2 , 60, BUTTH, 
	   "Movie", infobg, CNTCOL);
  cbut[BMOVIE].explstr = "When multiple structures available:\nMD trajectory, Geometry optimisation etc.\nDisplay all structures as a movie";

  DefBut(&cbut[BMOLF], winMC,  POFFX+BOFFX+63,  POFFY+22, 24, 24, 
	   " ", infobg, CNTCOL);
  cbut[BMOLF].explstr = "Multiple outputs available in\nMolden format file\nClick two select output";

  DefBut(&cbut[BHOUR], winMC,  POFFX+BOFFX+70 , POFFY+24+BUTTN , 20, 25, 
	   " ", infobg, CNTCOL);
  cbut[BHOUR].explstr = "Set Minimum time\nbetween Movie frames";


  DefBut(&cbut[BSOLID], winMC, DMOFFX+BOFFX, DMOFFY+24        , TOGGWH, TOGGWH, 
	   " ", infobg, CNTCOL);
  cbut[BSOLID].explstr = "Toggle between stick and\nSolid drawing modes";

  DefBut(&cbut[BATCOL], winMC, DMOFFX+BOFFX, DMOFFY+24+BUTTN  , TOGGWH, TOGGWH, 
	   " ", infobg, CNTCOL);
  TogDown(&cbut[BATCOL]); 
  cbut[BATCOL].explstr = "Color by Atom or\nSubstructure (residue)";

  DefBut(&cbut[BSHADE], winMC, DMOFFX+BOFFX, DMOFFY+24+BUTTN*2, TOGGWH, TOGGWH, 
	   " ", infobg, CNTCOL);
  cbut[BSHADE].explstr = "Apply depth shading";

  DefBut(&cbut[BPERSP], winMC, DMOFFX+BOFFX, DMOFFY+24+BUTTN*3, TOGGWH, TOGGWH, 
	   " ", infobg, CNTCOL);
  cbut[BPERSP].explstr = "Toggle Perspective or\nOrthographic projection";

  DefBut(&cbut[BLABEL], winMC, DMOFFX+BOFFX, DMOFFY+24+BUTTN*4, TOGGWH, TOGGWH, 
	   " ", infobg, CNTCOL);
  DefBut(&cbut[BBACKB], winMC, DMOFFX+BOFFX, DMOFFY+24+BUTTN*5, TOGGWH, TOGGWH, 
	   "", infobg, CNTCOL);
  cbut[BBACKB].explstr = "Switch All Atom vs Backbone Atoms Only\nOnly for Protein Structures\nIn Solid mode,\nbackbone is drawn in cartoon style";

  DefBut(&cbut[BZOOMIN],  winMC, XOFFX+10, XOFFY+20+9, 30, 23, 
	   "In", infobg, CNTCOL);
  cbut[BZOOMIN].explstr = "Translate structure\nalong Z-axis. Alternative:\nCtrl+left mouse button+drag";

  DefBut(&cbut[BZOOMOUT], winMC, XOFFX+10, XOFFY+20+9+BUTTN, 30, 23, 
	   "Out", infobg, CNTCOL);
  cbut[BZOOMOUT].explstr = "Translate structure\nalong Z-axis. Alternative:\nCtrl+left mouse button+drag";

  DefBut(&cbut[BDENMOD], winMC, MOFFX+BOFFX, MOFFY+24     , 80, BUTTH, 
	   "Dens. Mode", infobg, CNTCOL);
  cbut[BDENMOD].explstr = "Switch to Density/Orbital mode";

  DefBut(&cbut[BREADF],  winMC, MOFFX+BOFFX-5, MOFFY+24+BUTTN*1, 40, BUTTH, 
	   "Read", infobg, CNTCOL);
  cbut[BREADF].explstr = "Read new structure from file";

  DefBut(&cbut[BWRITF],  winMC, MOFFX+BOFFX+45, MOFFY+24+BUTTN*1, 45, BUTTH, 
	   "Write", infobg, CNTCOL);
  cbut[BWRITF].explstr = "Write current structure to file";

  DefBut(&cbut[BZMAT],   winMC, MOFFX+BOFFX, MOFFY+24+BUTTN*2, 80, BUTTH, 
	   "ZMAT Editor", infobg, CNTCOL);
  cbut[BZMAT].explstr = "Edit internal coordinates of structure\nEdit Phi,Psi,Chi (Proteins Only)\nAnimate internal coordinates\nSubmit Gaussian/Gamess/Mopac jobs";
  DefBut(&cbut[BPOSTT],  winMC, MOFFX+BOFFX, MOFFY+24+BUTTN*3, 80, BUTTH, 
	   "PostScript", infobg, CNTCOL);

  DefBut(&cbut[BAUTH],   winMC, MIOFFX+6, MIOFFY+MICONY, 24, 24, 
	   "Auth", infobg, CNTCOL);
  cbut[BAUTH].explstr = "Apply force field\nOptimise with Amber/GAFF/Tinker\nSet atom properties:\nStickColor, Residue, Charge";

  DefBut(&cbut[BGIF],    winMC, MIOFFX+6, MIOFFY+MICONY+5+BUTTN, 24, 24, 
	   "Foto", infobg, CNTCOL);
  cbut[BGIF].explstr = "picture of each screen update.\nstick mode: GIF";

  DefBut(&cbut[BPAL],    winMC, MIOFFX+6, MIOFFY+MICONY+(5+BUTTN)*2, 24, 24, 
	   "Palette", infobg, CNTCOL);
  cbut[BPAL].explstr = "Change/Set Colors\nElement Properties\nSet Depth Shading";

  DefBut(&cbut[BCELL],   winMC, MIOFFX+6, MIOFFY+MICONY+(5+BUTTN)*3, 24, 24, 
	   "Cell", infobg, CNTCOL);
  cbut[BCELL].explstr = "Display/Create/Edit\nCrystal Structures";

  DefBut(&cbut[BORIG],   winMC, MIOFFX+6, MIOFFY+MICONY+(5+BUTTN)*4, 24, 24, 
	   "Origin", infobg, CNTCOL);
  cbut[BORIG].explstr = "Click on an atom\nto set new origin";

  DefBut(&cbut[BSURF],   winMC, MIOFFX+6, MIOFFY+MICONY+(5+BUTTN)*5, 24, 24, 
	   "Surface", infobg, CNTCOL);
  cbut[BSURF].explstr = "Create Surfaces,\nCalculate Charges,\nMultipoles,Dipole";

  DefBut(&cbut[BVRML],   winMC, MIOFFX+6, MIOFFY+MICONY+(5+BUTTN)*6, 24, 24, 
	   "VRML", infobg, CNTCOL);
  cbut[BVRML].explstr = "Virtual Reality Modeling Language,\nPovray, OpenGl helper program";

  DefBut(&cbut[BHYD],    winMC, MIOFFX+6, MIOFFY+MICONY+(5+BUTTN)*7, 24, 24, 
	   "Quit", infobg, CNTCOL);
  cbut[BHYD].explstr = "(Re)Calculate Hydrogen Bonds,\nSet Parameters Hydrogen Bonds,\n(Un)Display Hydrogens";

  DefBut(&cbut[BALIGN],  winMC, MIOFFX+6, MIOFFY+MICONY+(5+BUTTN)*8, 24, 24, 
	   "Align", infobg, CNTCOL);
  cbut[BALIGN].explstr = "Align two molecules,\nInteractive Docking";

  DefBut(&cbut[BQUITT],  winMC, MIOFFX+6, MIOFFY+MICONY+12+(5+BUTTN)*9, 24, 24, 
	   "Quit", infobg, CNTCOL);
  cbut[BQUITT].explstr = "Exit Molden";


  DefBut(&cbut[BDIST],  winMC, CLOFFX+BOFFX, CLOFFY+24        , 80, BUTTH, 
	   "Distance", infobg, CNTCOL);
  cbut[BDIST].explstr = "Calculate interatomic distance\nClick on two atoms";

  DefBut(&cbut[BANGLE], winMC, CLOFFX+BOFFX, CLOFFY+24+BUTTN*1, 80, BUTTH, 
	   "Angle", infobg, CNTCOL);
  cbut[BANGLE].explstr = "Calculate angle\nClick on three atoms";

  DefBut(&cbut[BDIHED], winMC, CLOFFX+BOFFX, CLOFFY+24+BUTTN*2, 80, BUTTH, 
	   "Dihedral", infobg, CNTCOL);
  cbut[BDIHED].explstr = "Calculate dihedral angle\nClick on four atoms";

  DefBut(&cbut[BCONV],  winMC, CVOFFX+BOFFX, CVOFFY+24        , 80, BUTTH, 
	   "SCF conv.", infobg, CNTCOL);
  cbut[BCONV].explstr = "Self Consistent Field convergence\nGamess/Gaussian/Molf Only";

  DefBut(&cbut[BGEOM],  winMC, CVOFFX+BOFFX, CVOFFY+24+BUTTN*1, 80, BUTTH, 
	   "Geom. conv.", infobg, CNTCOL);
  cbut[BGEOM].explstr = "Geometry convergence, for\nmultiple structures combined\nwith Energy/Step/Force info";

  DefBut(&cbut[BLEFT],  winMC, XOFFX+50   , XOFFY+5+BUTTN*1, 23, 23, 
	   "<", infobg, CNTCOL);
  cbut[BLEFT].explstr = "Translate structure\nalong X-axis. Alternative:\nShift+left mouse button+drag";

  DefBut(&cbut[BRIGHT], winMC, XOFFX+50+50, XOFFY+5+BUTTN*1, 23, 23, 
	   ">", infobg, CNTCOL);
  cbut[BRIGHT].explstr = "Translate structure\nalong X-axis. Alternative:\nShift+left mouse button+drag";

  DefBut(&cbut[BUP],    winMC, XOFFX+50+25, XOFFY+5        , 23, 23, 
	   "^", infobg, CNTCOL);
  cbut[BUP].explstr = "Translate structure\nalong Y-axis. Alternative:\nShift+left mouse button+drag";

  DefBut(&cbut[BDOWN],  winMC, XOFFX+50+25, XOFFY+5+BUTTN*2, 23, 23, 
	   "v", infobg, CNTCOL);
  cbut[BDOWN].explstr = "Translate structure\nalong Y-axis. Alternative:\nShift+left mouse button+drag";

  DefBut(&cbut[BPACE],  winMC, XOFFX+50+25, XOFFY+5+BUTTN*1, 23, 23, 
	   " ", infobg, CNTCOL);
  cbut[BPACE].explstr = "In old style rotation\nSet rotation increment:\nSmall,Medium or Large";

  DefBut(&cbut[BBALL],  winMC, XOFFX+50+65, XOFFY+5+BUTTN*2+7, 15, 15, 
	   " ", infobg, CNTCOL);
  cbut[BBALL].explstr = "Toggle: default rotation style/\nold style rotation";

  if ( colcells < 16 ) ActBut(&cbut[BSHADE],0);
  if (monoscr) ActBut(&cbut[BATCOL],0);
  
  cbut[BUP].pix = upPix;
  cbut[BUP].pw  = up_width;
  cbut[BUP].ph  = up_height;

  cbut[BDOWN].pix = downPix;
  cbut[BDOWN].pw  = down_width;
  cbut[BDOWN].ph  = down_height;

  cbut[BLEFT].pix = lPix;
  cbut[BLEFT].pw  = l_width;
  cbut[BLEFT].ph  = l_height;

  cbut[BRIGHT].pix = rPix;
  cbut[BRIGHT].pw  = r_width;
  cbut[BRIGHT].ph  = r_height;

  cbut[BBALL].pix = ballPix;
  cbut[BBALL].pw  = ball_width;
  cbut[BBALL].ph  = ball_height;

  cbut[BAUTH].pix = FFPix;
  cbut[BAUTH].pw  = ff_width;
  cbut[BAUTH].ph  = ff_height;

  cbut[BMOLF].pix = MLFPix;
  cbut[BMOLF].pw  = mlf_width;
  cbut[BMOLF].ph  = mlf_height;

/* Old, sigh
  cbut[BAUTH].pix = gPix;
  cbut[BAUTH].pw  = g_width;
  cbut[BAUTH].ph  = g_height;
*/

  cbut[BQUITT].pix = SkullPix;
  cbut[BQUITT].pw  = skull_width;
  cbut[BQUITT].ph  = skull_height;

  cbut[BHYD].pix = HPix;
  cbut[BHYD].pw  = hbit_width;
  cbut[BHYD].ph  = hbit_height;

  cbut[BORIG].pix = OrigPix;
  cbut[BORIG].pw  = orig_width;
  cbut[BORIG].ph  = orig_height;

  cbut[BSURF].pix = SurfPix;
  cbut[BSURF].pw  = surf_width;
  cbut[BSURF].ph  = surf_height;

  cbut[BVRML].pix = VRMLPix;
  cbut[BVRML].pw  = vrml_width;
  cbut[BVRML].ph  = vrml_height;

  cbut[BALIGN].pix = AlignPix;
  cbut[BALIGN].pw  = align_width;
  cbut[BALIGN].ph  = align_height;

  cbut[BCELL].pix = CellPix;
  cbut[BCELL].pw  = cell_width;
  cbut[BCELL].ph  = cell_height;

  cbut[BGIF].pix = FotoPix;
  cbut[BGIF].pw  = foto_width;
  cbut[BGIF].ph  = foto_height;

  cbut[BPAL].pix = ColPix;
  cbut[BPAL].pw  = palette_width;
  cbut[BPAL].ph  = palette_height;

  cbut[BHOUR].pix = HourPix;
  cbut[BHOUR].pw  = hourglass_width;
  cbut[BHOUR].ph  = hourglass_height;

  cbut[BPACE].pw  = pace_width;
  cbut[BPACE].ph  = pace_height;
  if (coarse==2) cbut[BPACE].pix = blastPix; 
  else if(coarse==1) cbut[BPACE].pix = fastPix;
  else cbut[BPACE].pix = slowPix;
  if (*ball) TogDown(&cbut[BBALL]);
  else TogUp(&cbut[BBALL]);
  if (*shade) TogDown(&cbut[BSHADE]);
  else TogUp(&cbut[BSHADE]);

  if (DEBUG) fprintf(stderr,"CreatewinMC out\n");
}

/***************************************************/
DirBox(hwin,vis)
Window  hwin;
int vis;
{
  if (vis) XMapRaised(display, hwin);
  else     XUnmapWindow(display, hwin);

}


/***************************************************/
RedrawwinC(x,y,w,h)
int x,y,w,h;
{
  int  i;
  XRectangle xr;

  if (DEBUG) fprintf(stderr,"RedrawwinC in\n");
  xr.x = x;  xr.y = y;  xr.width = w;  xr.height = h;
  XSetClipRectangles(display, gc, 0,0, &xr, 1, Unsorted);

  if (monoscr) {
	XSetFillStyle(display, gc, FillStippled);
	XSetStipple(display, gc, grayStip);
	XSetForeground(display, gc, infobg);
	XFillRectangle(display, winC, gc, PLOFFX, PLOFFY+22,120 ,198);
	XFillRectangle(display, winC, gc, MSOFFX, MSOFFY+22,120 ,102);
	XFillRectangle(display, winC, gc, PMOFFX, PMOFFY+22,120 ,73);
	XFillRectangle(display, winC, gc, D3OFFX, D3OFFY+22,120 ,52);
	XFillRectangle(display, winC, gc, CNOFFX, CNOFFY+22,120 ,50);
	XFillRectangle(display, winC, gc, BSOFFX, BSOFFY+22,120 ,50);
	XSetForeground(display, gc, infofg);
	XSetFillStyle(display, gc, FillSolid);}
  else {
	butje(winC,PLOFFX,PLOFFY,140,220,1,0,0,1,None,0,0,0);
	butje(winC,MSOFFX,MSOFFY,140,124,1,0,0,1,None,0,0,0);
	butje(winC,SPOFFX,SPOFFY,140,50,1,0,0,1,None,0,0,0);
	butje(winC,PMOFFX,PMOFFY,120,95,1,0,0,1,None,0,0,0);
	butje(winC,D3OFFX,D3OFFY,120,126,1,0,0,1,None,0,0,0);
	butje(winC,CNOFFX,CNOFFY,120,75,1,0,0,1,None,0,0,0);
	butje(winC,BSOFFX,BSOFFY,120,75,1,0,0,1,None,0,0,0);
	butje(winC,QOFFX,QOFFY,120,25,1,0,0,1,None,0,0,0);
  }


  for (i=0; i<NBUTTS; i++) DrwBut(&dbut[i]);

  ULineString(winC, "Plot Function:"  , PLOFFX+BOFFX, PLOFFY+15);
  ULineString(winC, "Miscellaneous:"  , MSOFFX+BOFFX, MSOFFY+15);
  ULineString(winC, "Plot Mode:"      , PMOFFX+30   , PMOFFY+15);
  ULineString(winC, "3D subcommands:" , D3OFFX+BOFFX, D3OFFY+15);
  ULineString(winC, "Contour subcomm.", CNOFFX+BOFFX, CNOFFY+15);
  ULineString(winC, "Space subcomm."  , SPOFFX+BOFFX, SPOFFY+15);
  ULineString(winC, "Basisset Differ.", BSOFFX+BOFFX, BSOFFY+15);
  ULineString(winC, "Status line:"    , S2OFFX+5 , S2OFFY);

  LineString(winC, "Orient"  , PLOFFX+BOFFX+88,PLOFFY+50+BUTTN*4);
  LineString(winC, "Fill"    , SPOFFX+BOFFX+28, SPOFFY+38);
  LineString(winC, "Contours", D3OFFX+BOFFX+28, D3OFFY+38+BUTTN*2);
  LineString(winC, "Molecule", D3OFFX+BOFFX+28, D3OFFY+38+BUTTN*3);

  XDrawRectangle(display, winC, gc, S2OFFX, S2OFFY+7,240 ,20);
  XDrawString(display,winC,gc,S2OFFX+5,S2OFFY+20,densstr,MINI(MAXSTRLMW,strlen(densstr)));

  XSetClipMask(display, gc, None);
  if (DEBUG) fprintf(stderr,"RedrawwinC out\n");
}


/***************************************************/
RedrawwinMC(x,y,w,h)
int x,y,w,h;
{
  int  i;

  if (DEBUG) fprintf(stderr,"RedrawwinMC in\n");

  if (monoscr) {
	XSetForeground(display, gc, infobg);
	XSetBackground(display, gc, infofg);
	XSetFillStyle(display, gc, FillOpaqueStippled);
	XSetStipple(display, gc, grayStip);
	XFillRectangle(display, winMC, gc, POFFX+5, POFFY+22 ,98 ,80);
	XFillRectangle(display, winMC, gc, MOFFX+5, MOFFY+22 ,98 ,95);
	if (!pdb) XFillRectangle(display, winMC, gc, FOFFX, 48,100 ,95);
	XFillRectangle(display, winMC, gc, CLOFFX, CLOFFY+22,100 ,72);
	XFillRectangle(display, winMC, gc, CVOFFX, CVOFFY+22,100 ,52);
	XSetFillStyle(display, gc, FillSolid);
	XSetForeground(display, gc, infofg);
	if (pdb) XFillRectangle(display, winMC, gc, FOFFX, FOFFY,100 ,146);
	else XFillRectangle(display, winMC, gc, FOFFX, FOFFY,110 ,44);
  }
  else {
	butje(winMC,POFFX,POFFY,108,101,1,0,0,1,None,0,0,0);
	butje(winMC,MOFFX,MOFFY,108,125,1,0,0,1,None,0,0,0);
	butje(winMC,DMOFFX,DMOFFY,108,176,1,0,0,1,None,0,0,0);

	butje(winMC,MIOFFX,MIOFFY,35,315,1,0,0,1,None,0,0,0);

	butje(winMC,FOFFX,FOFFY,107,146,1,0,0,1,None,0,0,0);
	butje(winMC,CLOFFX,CLOFFY,107,96,1,0,0,1,None,0,0,0);
	butje(winMC,CVOFFX,CVOFFY,107,75,1,0,0,1,None,0,0,0);

	butje(winMC,XOFFX,XOFFY,141,86,1,0,0,1,None,0,0,0);
  }



  for (i=0; i<NBUTTS2; i++) {
	if (! (i == BMOLF && ntits <= 1)) DrwBut(&cbut[i]);
  }

  ULineString(winMC, "Select Point:", POFFX+BOFFX , POFFY+15);
  ULineString(winMC, "Draw Mode:"   , DMOFFX+BOFFX , DMOFFY+15);
  ULineString(winMC, "Zoom:"        , XOFFX+10 , XOFFY+20);
  if (pdb) {
	ULineString(winMC, "Add to BackBone:", FOFFX+BOFFX, FOFFY+15);
	LineString(winMC, "SulfurBond",        FOFFX+BOFFX+28, FOFFY+38+BUTTN*3);
	LineString(winMC, "H-bonds",           FOFFX+BOFFX+28, FOFFY+38+BUTTN*4);
  }
  else {if (frfor) {
	ULineString(winMC, "Frequecies:", FOFFX+BOFFX , FOFFY+15);
	LineString(winMC, "Norm. Mode"         , FOFFX+BOFFX+20 , FOFFY+38);}
	else {
	ULineString(winMC, "Render Forces:", FOFFX+BOFFX , FOFFY+15);
	LineString(winMC, "Forces"         , FOFFX+BOFFX+28 , FOFFY+38);}
  }
  ULineString(winMC, "Calculate :"   , CLOFFX+BOFFX, CLOFFY+15);
  ULineString(winMC, "Miscellaneous:", MOFFX+BOFFX , MOFFY+15);
  ULineString(winMC, "Status line:"  , SOFFX+5  , SOFFY);
  ULineString(winMC, "Convergence:"  , CVOFFX+BOFFX, CVOFFY+15);

  LineString(winMC, "Solid",      DMOFFX+BOFFX+28, DMOFFY+38);
  LineString(winMC, "StickColor", DMOFFX+BOFFX+28, DMOFFY+38+BUTTN);
  LineString(winMC, "Shade",      DMOFFX+BOFFX+28, DMOFFY+38+BUTTN*2);
  LineString(winMC, "Perspect.",     DMOFFX+BOFFX+28, DMOFFY+38+BUTTN*3);
  LineString(winMC, "Label",      DMOFFX+BOFFX+28, DMOFFY+38+BUTTN*4);
  LineString(winMC, "BackBone",   DMOFFX+BOFFX+28, DMOFFY+38+BUTTN*5);

  XDrawRectangle(display, winMC, gc, SOFFX, SOFFY+7,240 ,20);
  XDrawString(display,winMC,gc,SOFFX+5,SOFFY+20,molwstr,MINI(MAXSTRLMW,strlen(molwstr)));

  if (DEBUG) fprintf(stderr,"RedrawwinMC out\n");
}

RedrawCOMMwin()
{
  int xboff,yboff,boff;

  xboff = 10; boff = 20; yboff = boff+30;
  XSetForeground(display, gc, infobg);
  PromptBox(&qboxes[QCOMM]); 

  butje(COMMwin,0,yboff-boff,QBOXWIDE,QBOXTX-boff-10,4,0,0,1,None,0,0,0);
  XDrawString(display,COMMwin,gc,xboff,yboff ,
  "The following commands are available:",37);
  XDrawString(display,COMMwin,gc,xboff,yboff+20 ,
  "Plane  = (atom1,atom2,atom3)  3 atoms define the plotplane             ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+30 ,
  "Rot    = (atom1,atom2,nnn.nn) rotate this plane  n.nn degrees around   ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+40 ,
  "                              the axis from atom1 and atom2, which must",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+50 ,
  "                              be one of the atoms used with plane      ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+60 ,
  "Center = atom1                coordinates of atom1 define plane center ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+70,
  "Center = (n.nn,n.nn,n.nn)     specify coordinates for plane center     ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+80,
  "Line   = atom1                vector; plane center - atom1 taken as    ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+90,
  "                              the outvector of the plotplane           ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+100,
  "Line   = (n.nn,n.nn,n.nn)     specify the outvector of the plotplane   ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+110,
  "Edge   = n.nn                 specify the size of the plotplane        ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+120,
  "Lift   = n.nn                 translate the center of the plotplane    ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+130,
  "                              along the outvector of the plane         ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+150,
  "Where atom[1-n] is an integer indicating the atoms number in the list  ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+170,
  "align                         center graph = center molecule           ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+180,
  "phase                         toggle the phase (sign) of the plot      ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+200,
  "nptsx  = n                    number of points in the x-direction      ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+210,
  "nptsy  = n                    number of points in the y-direction      ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+220,
  "nptsz  = n                    number of points in the z-direction      ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+230,
  "edx    = n.nn                 size of the plotplane in the x-direction ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+240,
  "edy    = n.nn                 size of the plotplane in the y-direction ",71);
  XDrawString(display,COMMwin,gc,xboff,yboff+250,
  "edz    = n.nn                 size of the plotplane in the z-direction ",71);
}

RedrawRESwin()
{
  int i;
  int xboff,yboff,boff;

  xboff = 10; boff = 20; yboff = boff+30;
  XSetForeground(display, gc, infobg);
  PromptBox(&qboxes[QRESI]); 

  butje(RESwin,0,yboff-boff,QBOXWIDE,QBOXTX-boff-10,4,0,0,1,None,0,0,0);
  XDrawString(display,RESwin,gc,xboff,yboff ,
  "The following commands are available:",37);
  XDrawString(display,RESwin,gc,xboff,yboff+20 ,
  "all [amino | nucl] [col]      display all residues                     ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+30 ,
  "clear [surf]                  clear all displayed residues             ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+40 ,
  "ala [col] [surf]              display all alanines                     ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+50 ,
  "                              Valid strings are:                       ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+60 ,
  "                              gly ala ser cys thr ile val met asp asn  ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+70,
  "                              leu lys glu gln pro arg his phe tyr trp  ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+80,
  "pos [col] [surf]              positively charged residues: lys arg his ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+90,
  "neg [col] [surf]              negatively charged residues: asp glu     ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+100,
  "cha [col] [surf]              charged residues: pos + neg              ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+110,
  "pol [col] [surf]              polar residues: cha + ser thr asn gln    ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+120,
  "aro [col] [surf]              aromatic aminoacids: phe + tyr + trp     ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+130,
  "ali [col] [surf]              display all aliphatic aminoacids:        ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+140,
  "                              gly + ala + val + leu + ile + pro        ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+150,
  "(aikknx) [col] [surf]         display all aminoacids specified by one  ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+160,
  "                              letter code pattern (max. 20 residues)   ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+170,
  "hel [rod | ball] [incl] [col] helix      [display type] [+backbone]    ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+180,
  "bet [rod | ball] [incl] [col] beta sheet [display type] [+backbone]    ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+200,
  "All previous symbols can be combined, and negated by the use of: not   ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+220,
  "20-30[:ChainNr] [col] [surf]  display residues number 20 through 31    ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+230,
  "20-30[:ChainNr] [hel|bet|rnd] set secondary structure of res. 20 to 30 ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+240,
  "neigh[=r] [surf]              display all neighbours at distance r Angs",71);
  XDrawString(display,RESwin,gc,xboff,yboff+250,
  "suron [mapped [local|global]] surface drawing mode ON, [map potential] ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+260,
  "suroff                        switches off surface drawing mode        ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+270,
  "all surf                      all currently displayed atoms as surface ",71);
  XDrawString(display,RESwin,gc,xboff,yboff+280,
  "[col]                         color select,if omitted def. per amin.a  ",71);
}

void fwincall(char *str)
{
	getfiles(str);
	RedrawFwin();
}

RedrawFwin()
{
  int i;

  XSetForeground(display, gc, infobg);
  strncpy(qboxes[QREADF].str,lastdir,MAXSTRLEN);
  PromptBox(&qboxes[QREADF]); 

  RedrawList(&flist);
  RedrawList(&dirlist);

  for (i=0; i<NBUTTR; i++) DrwBut(&rbut[i]);

  ULineString(Fwin, "Files", 325, 55);
  ULineString(Fwin, "Directories", 325, 265);
  LineString(Fwin, "Replace", 350, 85);
  LineString(Fwin, "Add", 350, 110);

}

ULineString(hwin,str,x,y)
Window hwin;
char *str;
int x,y;
{
  XDrawString(display, hwin, gc, x, y, str, strlen(str));
  XDrawLine(display, hwin, gc, x, y+DESCENT-1,
            x+StringWidth(str), y+DESCENT-1);
}

LineString(hwin,str,x,y)
Window hwin;
char *str;
int x,y;
{
  XDrawString(display, hwin, gc, x, y, str, strlen(str));
}


createauthor()
{
      winau = CreateWindow("Author",DEFAUTHGEOM,
              gijsface_width,gijsface_height, infofg, infobg,(Window)0);
      XSelectInput(display, winau, ExposureMask | 
              ButtonPressMask | KeyPressMask);
      gijs  = XCreateBitmapFromData(display, winau,
              gijsface_bits, gijsface_width, gijsface_height);
      XMapWindow(display, winau);
}

createconv()
{
      wincnv = CreateWindow("SCF Convergence",DEFCNVGEOM,
              CNVWIDE,CNVHIGH, infobg, infofg,(Window)0);
      XSelectInput(display, wincnv, ExposureMask | 
              ButtonPressMask | PointerMotionMask);
      XMapWindow(display, wincnv);
}

createfr()
{

   FrBox = CreateWindow("Molden Frequency Select","-80-80",QBOXWIDE,310,
	infobg,infofg,(Window)0);
   XSelectInput(display, FrBox, ExposureMask | KeyPressMask | 
	ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask);

   if (*ihasi < 0)
	DefList(&frlist,FrBox,DIRX,DIRY,DIRW,DIRH,"  Nr.     Frequency    (cm-1)",
	NFLS,frsym,freq,NULL,nfreq);
   else
      	DefList(&frlist,FrBox,DIRX,DIRY,DIRW,DIRH,"  Nr.     Frequency    (cm-1)",
	NFLS,NULL,freq,NULL,nfreq);

   qboxstr(&qboxes[QNSCAL],&FrBox,1,0,-1,DEFQX,270, 170,QBOXHIGH,0,
	"Scale Factor ? ","1.0", 0,3, 2000, dummyproc);

   qboxes[QNSCAL].qflt = frmul;
   sprintf(qboxes[QNSCAL].str,"%f", *frmul);
   qboxes[QNSCAL].explstr = "Scale amplitude atomic movements";
   XMapWindow(display,FrBox);
}

createspec()
{
      int i;

      if (!*ihasi) return;

      winspec = CreateWindow("Spectrum",DEFCNVGEOM,
              SPECWIDE,SPECHIGH+SPBHIGH, infobg, infofg,(Window)0);
      XSelectInput(display, winspec, ExposureMask | 
		ButtonPressMask | ButtonReleaseMask | PointerMotionMask | 
		StructureNotifyMask | KeyPressMask | 
		EnterWindowMask | LeaveWindowMask); 
      subSPEC = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],winspec);
      XMapWindow(display, winspec);
      spint = frint;
      min_freq = 0;
      max_freq = (int) (freq[*nfreq-1]*freq_scale);
      i = max_freq / 500;
      max_freq = (i+1)*500;
      calc_spectrum();

      spec_mx = spec_mn = out_spec[0];
      for (i=1; i < n_freqs; i++) {
        if (out_spec[i] > spec_mx) {
    	   spec_mx = out_spec[i];
        }
        if (out_spec[i] < spec_mn) {
    	   spec_mn = out_spec[i];
        }
      }


      DefBut(&spbut[0], winspec, 80, SPECHIGH + BUTTN, 100, 23, "Lorentzian", 
	infobg, ZMBCOL);
      spbut[0].str = pktyp[lorentzian];
      spbut[0].explstr = "Peak enveloppe: Lorentzian, Gaussian";

      DefBut(&spbut[1], winspec, 80, SPECHIGH, 100, 23, "Infra Red", 
	infobg, ZMBCOL);
      spbut[1].str = sptyp[spmode];
      spbut[1].explstr = "Type of spectrum: Infrared, Raman\nSome QM programs calculate both intensities";

      DefBut(&spbut[2], winspec, SPECWIDE-85, SPECHIGH + 2*BUTTN, 75, 23, 
	"Close", infobg, ZMBCOL);
      spbut[2].explstr = "Close window";

      DefBut(&spbut[3], winspec, SPECWIDE-85, SPECHIGH, 75, 23, 
	"Postscript", infobg, ZMBCOL);
      spbut[3].explstr = "Export spectrum as Postscript file";

      DefBut(&spbut[4], winspec, SPECWIDE-85, SPECHIGH + BUTTN,75, 23, 
	"to Xmgr", infobg, ZMBCOL);
      spbut[4].explstr = "Export spectrum as input file for Xmgr";

      qboxstr(&qboxes[QHW],&winspec,1,0,190,200,SPECHIGH,
	150,QBOXHIGH-5,2,"Half-Width"," ",10,QREAL,2000,updcallb);
      sprintf(qboxes[QHW].str,"%-4.1f",hwhm);
      qboxes[QHW].dflt = &hwhm;
      qboxes[QHW].explstr = "Half-Width of peak\nInfluences peak width";

      qboxstr(&qboxes[QSSCAL],&winspec,0,0,190,200,SPECHIGH+10+BUTTN,
	150,QBOXHIGH-5,2,"Scale Fac."," ",10,QREAL,2000,updcallb);
      sprintf(qboxes[QSSCAL].str,"%-4.2f",freq_scale);
      qboxes[QSSCAL].dflt = &freq_scale;
      qboxes[QSSCAL].explstr = "Apply frequency scale factor";

      qboxstr(&qboxes[QMINF],&winspec,0,0,190,350,SPECHIGH,
	150,QBOXHIGH-5,2,"Min. Freq."," ",10,QREAL,2000,updcallb);
      sprintf(qboxes[QMINF].str,"%d",min_freq);
      qboxes[QMINF].iflt = &min_freq;
      qboxes[QMINF].explstr = "Lowest frequency displayed\nSpecify displayed frequency range";

      qboxstr(&qboxes[QMAXF],&winspec,0,0,190,350,SPECHIGH+10+BUTTN,
	150,QBOXHIGH-5,2,"Max. Freq."," ",10,QREAL,2000,updcallb);
      sprintf(qboxes[QMAXF].str,"%d",max_freq);
      qboxes[QMAXF].iflt = &max_freq;
      qboxes[QMAXF].explstr = "Highest frequency displayed\nSpecify displayed frequency range";

      qboxstr(&qboxes[QIMAX],&winspec,0,0,190,350,SPECHIGH+15+2*BUTTN,
	150,QBOXHIGH-5,2,"Max. Ints."," ",10,QREAL,2000,updcallb);
      sprintf(qboxes[QIMAX].str,"%-4.2f",spec_mx);
      qboxes[QIMAX].dflt = &spec_mx;
      qboxes[QIMAX].explstr = "Highest frequency displayed\nSpecify displayed frequency range";
      qboxes[QIMAX].explstr = "Apply intensity scale factor\nInstrumental in comparing spectra";

      specup = 1;
}

creategeom()
{

      gwi = CNVWIDE*2; ghi = CNVHIGH*2;
      if (!*geopntr.idmxav && !*geopntr.idrmav) gwi = CNVWIDE;
      if (!*geopntr.ifmxav && !*geopntr.ifrmav) ghi = CNVHIGH;

      wingeo = CreateWindow("Geom. Convergence",DEFCNV2GEOM,
              gwi,ghi, infobg, infofg,(Window)0);
      XSelectInput(display, wingeo, ExposureMask | 
              ButtonPressMask | PointerMotionMask | StructureNotifyMask);
      XMapWindow(display, wingeo);
}

createscore()
{
      winsco = CreateWindow("Docking Score",DEFCNVGEOM,
              CNVWIDE,CNVHIGH+140, infobg, infofg,(Window)0);
      XSelectInput(display, winsco, ExposureMask | 
              ButtonPressMask | PointerMotionMask);
      XMapWindow(display, winsco);
      scoup = 1;

      DefBut(&scbut[0], winsco, 10, CNVHIGH + 10, 75, 23, 
	"Save Pose", infobg, ZMBCOL);

      DefBut(&scbut[1], winsco, 90, CNVHIGH + 10, 75, 23, 
	"Write Poses", infobg, ZMBCOL);

      DefBut(&scbut[2], winsco, 170, CNVHIGH + 10, 50, 23, 
	"AtomInf", infobg, ZMBCOL);

      DefBut(&scbut[3], winsco, CNVWIDE-60, CNVHIGH + 10, 50, 23, 
	"Close", infobg, ZMBCOL);

      DefBut(&scbut[4], winsco, 10, CNVHIGH + 40, 15, 15, 
	" ", infobg, ZMBCOL);

      DefBut(&scbut[5], winsco, 10, CNVHIGH + 60, 15, 15, 
	" ", infobg, ZMBCOL);

      if (*ipmfm) {
	  TogDown(&scbut[4]);
      } else {
	  TogUp(&scbut[4]);
      }

      if (*ipmfh) {
	  TogDown(&scbut[5]);
      } else {
	  TogUp(&scbut[5]);
      }
}

createpmf()
{
      winpmf = CreateWindow("PMF Score",DEFPMFGEOM,
              325,CNVHIGH+40, infobg, infofg,(Window)0);
      XSelectInput(display, winpmf, ExposureMask | 
              ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | 
		LeaveWindowMask);
      XMapWindow(display, winpmf);
      pmfup = 1;

      DefBut(&pbut[0], winpmf, 10, CNVHIGH + 10, 75, 23, 
	"Close", infobg, ZMBCOL);
/*
      DefList(&pmflistmn,winpmf,DIRX,DIRY,DIRW,80,
	"Top Negative Interactions",5,NULL,NULL,pmfmn,npmfmx);

      DefList(&pmflistmx,winpmf,DIRX,160,DIRW,80,
	"Top Positive Interactions",5,NULL,NULL,pmfmx,npmfmx);
*/
      DefList(&pmflistmn,winpmf,DIRX,DIRY,DIRW,80,
	NULL,5,NULL,NULL,pmfmn,npmfmx);

      DefList(&pmflistmx,winpmf,DIRX,160,DIRW,80,
	NULL,5,NULL,NULL,pmfmx,npmfmx);

}

#if defined(VMS) || defined(UNDERSC)
crsco()
#else
#ifdef CRAY
CRSCO()
#else
crsco_()
#endif
#endif
{
   createscore();
   if (ZMEup) UnMapZME();
}

#if defined(VMS) || defined(UNDERSC)
cpmf()
#else
#ifdef CRAY
CPMF()
#else
cpmf_()
#endif
#endif
{
   if (pmfup) drwpmf();
   else createpmf();
}

#if defined(VMS) || defined(UNDERSC)
upsco()
#else
#ifdef CRAY
UPSCO()
#else
upsco_()
#endif
#endif
{

   if (scoup) {
	drwsco();
   } else {
	createscore();
   }

}

#if defined(VMS) || defined(UNDERSC)
molstr(str, nstr, iwin)
#else
#ifdef CRAY
MOLSTR(str, nstr, iwin)
#else
molstr_(str, nstr, iwin)
#endif
#endif

#ifdef VMS
struct dsc$descriptor_s *str;
#else
#ifdef CRAY
_fcd str;
#else
char *str;
#endif
#endif
int *nstr;
int *iwin;
{
int i;
int ns;
int dobell;

       if(DEBUG)fprintf(stderr,"molstr in%d\n",*iwin);

       dobell = 0;

       ns = *nstr;
       if (*nstr > MAXSTRLMW ) ns = MAXSTRLMW;
       for (i=0; i<MAXSTRLMW; i++)
            {if (! *iwin) molwstr[i] = ' ';
             else densstr[i] = ' ';}
       if (! *iwin) strcp(str,molwstr,ns);
       else strcp(str,densstr,ns);

       if(DEBUG && *iwin)fprintf(stderr,"molstr in %d %s\n",*iwin,densstr);
       if(DEBUG && !*iwin)fprintf(stderr,"molstr in %d %s\n",*iwin,molwstr);
       for (i=0; i<ns; i++)
       {
           if (! *iwin && molwstr[i] == '!') dobell = 1;
           if ( *iwin && densstr[i] == '!') dobell = 1;
       }

       StatusStr(*iwin,dobell);

       if(DEBUG)fprintf(stderr,"molstr out\n");
}

StatusStr(iwin,dobell)
int iwin;
int dobell;
{

       if (dobell && *ibell) XBell(display,0);

       if (! iwin && !DowinMC) {
          XSetForeground(display, gc, infofg);
          XFillRectangle(display, winMC, gc, SOFFX, SOFFY+7,240 ,20);
          XSetForeground(display, gc, infobg);
          XDrawRectangle(display, winMC, gc, SOFFX, SOFFY+7,240 ,20);
          XDrawString(display,winMC,gc,SOFFX+5,SOFFY+20,molwstr,MINI(MAXSTRLMW,strlen(molwstr))); 
       }

       if ( iwin && !DowinC) {
          XSetForeground(display, gc, infofg);
          XFillRectangle(display, winC, gc, S2OFFX, S2OFFY+7,240 ,20);
          XSetForeground(display, gc, infobg);
          XDrawRectangle(display, winC, gc, S2OFFX, S2OFFY+7,240 ,20);
          XDrawString(display,winC,gc,S2OFFX+5,S2OFFY+20,densstr,MINI(MAXSTRLMW,strlen(densstr))); 
       }
       XFlush(display);
}

#if defined(VMS) || defined(UNDERSC)
errzme(str, nstr, icard, ivar)
#else
#ifdef CRAY
ERRZME(str, nstr, icard, ivar)
#else
errzme_(str, nstr, icard, ivar)
#endif
#endif

#ifdef VMS
struct dsc$descriptor_s *str;
#else
#ifdef CRAY
_fcd str;
#else
char *str;
#endif
#endif
int *nstr;
int *icard;
int *ivar;
{
int i;
int ns;

	if (DEBUG) fprintf(stderr,"errzme in\n");

	if (!ZMEup) return;

	ns = *nstr;
	if (*nstr > MAXZMEERR ) ns = MAXZMEERR;
	for (i=0; i<MAXZMEERR; i++) ZMEerr[i] = ' ';
	strcp(str,ZMEerr,ns);

	for (i=0; i<ns; i++) if (ZMEerr[i] == '!') 
	   if (*ibell) XBell(display,0);

	XFlush(display);
	for (i=0; i<*xyz.iatoms; i++) xyz.iaton[i] = 1;
	DeActZME();
	xyz.iaton[zmptr.imap[*icard-1]-1] = 3;
	update_sel = 1;
	if (ABS(*ivar) > 0) {
		if (*ivar < 0) ActOnErr(*icard-1,4+ABS(*ivar)-1,ZMEerr);
		else ActOnErr(*icard-1,*ivar,ZMEerr);
	}
	else ActOnErr(*icard-1,0,ZMEerr);

	if (DEBUG) fprintf(stderr,"errzme out\n");

	return(1);

}

#if defined(VMS) || defined(UNDERSC)
drwstr(xvl,yvl,strvl,sl)
#else
#ifdef CRAY
DRWSTR(xvl,yvl,strvl,sl)
#else
drwstr_(xvl,yvl,strvl,sl)
#endif
#endif

int *xvl;
int *yvl;
int *sl;
#ifdef VMS
struct dsc$descriptor_s *strvl;
#else
#ifdef CRAY
_fcd strvl;
#else
char *strvl;
#endif
#endif
{
  if (monoscr) XSetBackground(display, gc, BlackPixel(display,screen));
#ifdef VMS
  if (monoscr) XDrawImageString(display, molcur, gc, *yvl, *xvl, strvl->dsc$a_pointer, *sl);
  else {
#ifdef DOGL
     if (has_opengl && *fancy) {
	if (StarNet) {
	   XDrawString(display, win, gc, *yvl, *xvl, strvl->dsc$a_pointer, *sl);
	} else {
	   strvl[*sl] = '\0';
	   printString(*yvl,*xvl,0,strvl->dsc$a_pointer);
	}
     } else
#endif
        XDrawString(display, molcur, gc, *yvl, *xvl, strvl->dsc$a_pointer, *sl);
  }
#else
#ifdef CRAY
  if (monoscr) XDrawImageString(display, molcur, gc, *yvl, *xvl, _fcdtocp(strvl), *sl);
  else {
#ifdef DOGL
     if (has_opengl && *fancy) {
	if (StarNet) {
	   XDrawString(display, win, gc, *yvl, *xvl, _fcdtocp(strvl), *sl);
	} else {
	   strvl[*sl] = '\0';
	   printString(*yvl,*xvl,0,_fcdtocp(strvl));
     } else
#endif
	XDrawString(display, molcur, gc, *yvl, *xvl, _fcdtocp(strvl), *sl);
  }
#else
  if (monoscr) XDrawImageString(display, molcur, gc, *yvl, *xvl, strvl, *sl);
  else {
#ifdef DOGL
     if (has_opengl && *fancy) {
	if (StarNet) {
	   XDrawString(display, win, gc, *yvl, *xvl, strvl, *sl);
	} else {
	   strvl[*sl] = '\0';
	   printString(*yvl,*xvl,0,strvl);
	}
     } else
#endif
	XDrawString(display, molcur, gc, *yvl, *xvl, strvl, *sl);
  }
#endif
#endif

}


#if defined(VMS) || defined(UNDERSC)
drwqstr(xvl,yvl,ian,q)
#else
#ifdef CRAY
DRWQSTR(xvl,yvl,ian,q)
#else
drwqstr_(xvl,yvl,ian,q)
#endif
#endif

int *xvl;
int *yvl;
int *ian;
double *q;
{
  sprintf(pchgtmp,"%s %7.4f  ",elements[*ian],*q);
  if (monoscr) XSetBackground(display, gc, BlackPixel(display,screen));
  if (monoscr) XDrawImageString(display, molcur, gc, *yvl, *xvl, pchgtmp, 10);
  else {
#ifdef DOGL
     if (has_opengl && *fancy) {
	if (StarNet) {
	   XDrawString(display, win, gc, *yvl, *xvl, pchgtmp, 10);
	} else {
	   pchgtmp[10] = '\0';
	   printString(*yvl,*xvl,0,pchgtmp);
	}
     } else
#endif
	XDrawString(display, molcur, gc, *yvl, *xvl, pchgtmp, 10);
  }

}

#ifndef VMS   
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <dirent.h>
#else
#include <stat.h>
#include <ctype.h>
#include <errno.h>
#include <rmsdef.h>

struct dirent {
    char	d_name[100];		/* File name		*/
    int         d_namlen;
    int		vms_verscount;		/* Number of versions	*/
    int		vms_versions[20];	/* Version numbers	*/
};

typedef struct _dirdesc {
    long			context;
    int				vms_wantversions;
    char			*pattern;
    struct dirent		entry;
    struct dsc$descriptor_s	pat;
} DIR;


extern DIR		*opendir();
extern struct dirent	*readdir();
extern void             closedir();
#endif


#if defined(__convex__) && defined (__STDC__)
#define S_IFMT  _S_IFMT
#define S_IFDIR _S_IFDIR
#endif



static int dosort(s1,s2)
char **s1, **s2;
{
    return (strcmp((*s1), (*s2)));
}

int isdir(dirname)
char* dirname;
{
  struct stat st;
  int i,j, ftype;

  st.st_mode = 0;
  stat(dirname, &st);
  ftype = st.st_mode & S_IFMT;  
  if ((st.st_mode & S_IFMT) == S_IFDIR) {
     return(1);
  } else {
     return(0);
  }
}

getfiles(dirname)
char* dirname;
{
  DIR           *dir;
  int            i,j, ftype;
  int            idstat,ifstat;
  struct stat    st;
  struct dirent *dp;
  char tmpfname[MAXFILELEN];

  if (dirname[strlen(dirname)-1] != '/') strcat(dirname,"/");
  strcpy(lastdir,dirname);

  for (i=0; i<nfiles; i++) free(files[i]);
  nfiles = 0;
  lpnt = 0;

  for (i=0; i<ndirs; i++) free(dirs[i]);
  ndirs = 0;

  dir = opendir(dirname);
  if (!dir) {
    ndirs = 1;
    dirs[0] = (char *) malloc(6);
    strcpy(dirs[0], "..");
    return;
  }

  idstat=0; ifstat=0;
  i=0; j=0;
  while ( (dp = readdir(dir)) != NULL) {

	strcpy(tmpfname,dirname);
	strcat(tmpfname,dp->d_name);
        st.st_mode = 0;
        stat(tmpfname, &st);
	ftype = st.st_mode & S_IFMT;  
        if (ftype == S_IFDIR) {
	   if (j >= MAXDIRS) {
		idstat = 1;
	   } else {
		dirs[j] = (char *) malloc(strlen(dp->d_name) + 3);
		if (!dirs[j]) fprintf(stderr,"getfiles: malloc error\n");
		strcpy(dirs[j], dp->d_name); j++;
	   }
	} else {
	   if (i >= MAXNAMES) {
		ifstat = 1;
	   } else {
		files[i] = (char *) malloc(strlen(dp->d_name) + 3);
		if (!files[i]) fprintf(stderr,"getfiles: malloc error\n");
		strcpy(files[i], dp->d_name); i++;
	   }
	}

  }

  closedir(dir);

  if (idstat) {
      fprintf(stderr,
	"too many directories in directory only showing first %d.\n",MAXDIRS);
  }

  if (ifstat) {
      fprintf(stderr,
	"too many files in directory only showing first %d.\n",MAXNAMES);
  }

  nfiles = i;
  flist.lpnt = 0;
  flist.select = 0;

  qsort((char *) files, nfiles, sizeof(char *), dosort);

  ndirs = j;
  dirlist.lpnt = 0;
  dirlist.select = 0;

  if (ndirs == 0) {
    ndirs = 1;
    dirs[j] = (char *) malloc(6);
    strcpy(dirs[j], "..");
  } else {
    qsort((char *) dirs, ndirs, sizeof(char *), dosort);
  }

}

                                                                                
#ifdef VMS


DIR *
opendir(name)
    char	*name;
{
    DIR		*dd;

    /* Get memory for the handle, and the pattern. */
    if ((dd = (DIR *)malloc(sizeof *dd)) == NULL) {
	errno = ENOMEM;
	return NULL;
    }
    
    if (strcmp(".",name) == 0) name = "";
    
    dd->pattern = malloc((unsigned int)(strlen(name) + sizeof "*.*" + 1));
    if (dd->pattern == NULL) {
	free((char *)dd);
	errno = ENOMEM;
	return NULL;
    }

    /* Fill in the fields; mainly playing with the descriptor. */
    (void)sprintf(dd->pattern, "%s*.*", name);
    dd->context = 0;
    dd->vms_wantversions = 0;
    dd->pat.dsc$a_pointer = dd->pattern;
    dd->pat.dsc$w_length = strlen(dd->pattern);
    dd->pat.dsc$b_dtype = DSC$K_DTYPE_T;
    dd->pat.dsc$b_class = DSC$K_CLASS_S;

    return dd;
}


struct dirent *
readdir(dd)
    DIR				*dd;
{
    struct dsc$descriptor_s	res;
    char			*p;
    char			buff[sizeof dd->entry.d_name];
    int				i;

    /* Set up result descriptor, and get next file. */
    res.dsc$a_pointer = buff;
    res.dsc$w_length = sizeof buff - 2;
    res.dsc$b_dtype = DSC$K_DTYPE_T;
    res.dsc$b_class = DSC$K_CLASS_S;
    if (lib$find_file(&dd->pat, &res, &dd->context) == RMS$_NMF
     || dd->context == 0L)
	/* None left... */
	return NULL;

    /* Force the buffer to end with a NUL. */
    buff[sizeof buff - 1] = '\0';
    for (p = buff; !isspace(*p); p++)
	;
    *p = '\0';

    /* Skip any directory component and just copy the name. */
    if (p = strchr(buff, ']'))
	(void)strcpy(dd->entry.d_name, p + 1);
    else
	(void)strcpy(dd->entry.d_name, buff);

    /* Clobber the version. */
    if (p = strchr(dd->entry.d_name, ';'))
	*p = '\0';

    dd->entry.d_namlen = strlen(dd->entry.d_name);

    dd->entry.vms_verscount = 0;
    return &dd->entry;
}

void
closedir(dd)
    DIR         *dd;
{
    free(dd->pattern);
    free((char *)dd);
}
#endif /* end VMS */

actde(inactid,inactf,iwin)

int iwin;
int inactid;
int inactf;
{
     int i;
     int inact;
     int inaf;

     if (DEBUG) fprintf(stderr,"actde in\n");


     inact = inactid;
     inaf  = inactf;


     if ( iwin == 1 ) {
	 denmode = 1;
         for ( i = 0; i < NBUTTS; i++ ) ActBut(&dbut[i],1);
         if ( inact == 1 ) {
               ActBut(&dbut[BELPOT],0);
               ActBut(&dbut[BORI],0);
               ActBut(&dbut[BATOM],0);
               ActBut(&dbut[BOVRLP],0);
         }

     }
     else {
	 denmode = 0;
         pdb = 0;
	 frfor = 0;
	 ZMEAA = 0;
         if (inaf >= 10) {pdb = 1;inaf = inaf - 10;linmax = 3;}
	 if (inaf == 2) {
	    frfor = 1;
	    if (FRup) RedrawList(&frlist);
            if (*ihasi) {
	        if (specup) drwspec();
	    } else {
	        if (specup) {
		   XDestroyWindow(display,winspec);
		   specup = 0;
		}
	    }
	    if (*ihasi && specup) drwspec();
	 } else {
	    if (FRup) {
		RedrawList(&frlist);
		XDestroyWindow(display,FrBox);
		FRup = 0;
	    }
	    if (specup) {
		XDestroyWindow(display,winspec);
		specup = 0;
	    }
	 }
         if (pdb == 1) {
            if (!addfile) {
		backb = 0;
                hbon = 0;
	    }
            DefBut(&cbut[BFORC],  winMC, FOFFX+10, FOFFY+24, 80, BUTTH,
                     "Res.Comm.", infobg, CNTCOL);
	    cbut[BFORC].explstr = "Residue command window (protein only)\nIn combination with backbone display\nSwitch on/off residues";

            DefBut(&cbut[BINCRF], winMC, FOFFX+10, FOFFY+24+BUTTN*1, 80, BUTTH,
                     "Residue", infobg, CNTCOL);
	    cbut[BINCRF].explstr = "Switch on/off residues, by\nclicking on the backbone";

            DefBut(&cbut[BDECRF], winMC, FOFFX+10, FOFFY+24+BUTTN*2, 80, BUTTH,
                     "HetAtm", infobg, CNTCOL);
	    cbut[BDECRF].explstr = "Switch on/off NON amino acids:\nHETATM records in the PDB\nSwitch on/off secundary structure\ncartoons";

            DefBut(&cbut[BUNSC],  winMC, FOFFX+10, FOFFY+24+BUTTN*3, 
		TOGGWH, TOGGWH, " ", infobg, CNTCOL);
	    cbut[BUNSC].explstr = "Toggle display cysteine bridges";

            DefBut(&cbut[BHBOND], winMC, FOFFX+10, FOFFY+24+BUTTN*4, TOGGWH, TOGGWH,
                     " ", infobg, CNTCOL);
	    cbut[BHBOND].explstr = "Toggle display hydrogen bonds\n of secundary structure";

            if (!addfile) {
		TogUp(&cbut[BBACKB]);
		TogUp(&cbut[BATCOL]);
		TogUp(&cbut[BFORC]);
		TogUp(&cbut[BUNSC]);
		TogUp(&cbut[BHBOND]);
	    }
         }
         else {
	    DefBut(&cbut[BFORC],  winMC, FOFFX+10, FOFFY+24,
			TOGGWH, TOGGWH, " ", infobg, CNTCOL);
	    cbut[BFORC].explstr = "Switch on/off display of forces\nGaussian/Games/Molf only";
	    if (frfor) cbut[BFORC].explstr = 
		"Normal Mode/Frequency analysis";

            DefBut(&cbut[BINCRF], winMC, FOFFX+10, FOFFY+24+BUTTN*1, 80, BUTTH,
                     "Incr. Scale", infobg, CNTCOL);
	    cbut[BINCRF].explstr = "Increase scale of forces";

            DefBut(&cbut[BDECRF], winMC, FOFFX+10, FOFFY+24+BUTTN*2, 80, BUTTH,
                     "Decr. Scale", infobg, CNTCOL);
	    cbut[BDECRF].explstr = "Decrease scale of forces";

            DefBut(&cbut[BUNSC],  winMC, FOFFX+10, FOFFY+24+BUTTN*3, 80, BUTTH,
                     "Unscale", infobg, CNTCOL);
	    cbut[BUNSC].explstr = "no scaling of forces";

            DefBut(&cbut[BHBOND], winMC, FOFFX+10, FOFFY+24+BUTTN*4, 80, BUTTH,
                     "", infobg, CNTCOL);
         }
         for ( i = 0; i < NBUTTS2; i++ ) ActBut(&cbut[i],1);


         if (pdb) {
            if (!addfile) {
		ActBut(&cbut[BFORC],0);
		ActBut(&cbut[BINCRF],0);
		ActBut(&cbut[BDECRF],0);
		ActBut(&cbut[BUNSC],0);
		ActBut(&cbut[BHBOND],0);
	    }
         }
         if ( inact >= 4 ) {
            ActBut(&cbut[BDENMOD],0);
            denm = 0;
            inact = inact - 4;
         }
         else denm = 1;

         if ( inact >= 2 ) {
            ActBut(&cbut[BCONV],0);
            inact = inact - 2;
         }
         if ( inact == 1 ) {
            ActBut(&cbut[BFIRST],0);
            ActBut(&cbut[BNEXT],0);
            ActBut(&cbut[BPREV],0);
            ActBut(&cbut[BMOVIE],0);
            ActBut(&cbut[BGEOM],0);
         }
         if ( inaf >= 1 && !pdb ) {
            ActBut(&cbut[BFORC],0);
            ActBut(&cbut[BINCRF],0);
            ActBut(&cbut[BDECRF],0);
            ActBut(&cbut[BUNSC],0);
            ActBut(&cbut[BHBOND],0);
         }
         if ( inaf == 2 && !pdb ) {
		ActBut(&cbut[BFORC],1);
		TogUp(&cbut[BFORC]);
	 }
         if (!pdb) ActBut(&cbut[BBACKB],0);
         if (! *imol) {
            ActBut(&cbut[BMOLF],-1);
	 } else {
            ActBut(&cbut[BMOLF],1);
	 }
     }

     if (iwin) RedrawwinC(0,0,WINCWIDE,WINCHIGH);
     else      RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
     ATMsel = 0;
     if (ATMup) {
	UpdateATM();
	RedrawATM();
     }
     if (CPup) {
	UpdateCP();
	RedrawCP();
     }
     if (CTup) {
	RedrawCT();
     }

     if (pdb && ZMEup) {
	if (DoPDB()) i = 1;
     }
     if (DEBUG) fprintf(stderr,"actde out\n");
}


#if defined(VMS) || defined(UNDERSC)
hetnum(idum)
#else
#ifdef CRAY
HETNUM(idum)
#else
hetnum_(idum)
#endif
#endif
int *idum;
{
   *idum =  NHetAtm;
}

#if defined(VMS) || defined(UNDERSC)
chkmol2(iok)
#else
#ifdef CRAY
CHKMOL2(iok)
#else
chkmol2_(iok)
#endif
#endif
int *iok;
{
#if defined(VMS) || defined(UNDERSC)
   chkmld(iok,
#else
#ifdef CRAY
   CHKMLD(iok,
#else
   chkmld_(iok,
#endif
#endif
	xyz.ianz,xyz.ityp);

}

#if defined(VMS) || defined(UNDERSC)
parsfn(str, nstr, iopt)
#else
#ifdef CRAY
PARSFN(str, nstr, iopt)
#else
parsfn_(str, nstr, iopt)
#endif
#endif

#ifdef VMS
struct dsc$descriptor_s *str;
#else
#ifdef CRAY
_fcd str;
#else
char *str;
#endif
#endif
int *nstr;
int *iopt;
{
       int j;
       char **strarr;
       int *nstrings;
       int room;

       switch(*iopt) {
       case 0: 
	  strarr = files;
	  nstrings = &nfiles;
	  room = *nstr + 3;
	  break;
       case 1: 
	  strarr = HetAtm;
	  nstrings = &NHetAtm;
	  if (NHetAtm >= MXHETATM) return;
	  room = *nstr + 1;
	  break;
       case 2: 
	  strarr = &VRMLFname;
          j = 0;
	  nstrings = &j;
	  room = *nstr + 1;
	  break;
       case 3: 
	  strarr = ColNam;
	  nstrings = &NColNam;
	  room = *nstr + 1;
	  break;
       case 4: 
	  strarr = mm3;
	  nstrings = &Nmm3;
	  room = *nstr + 1;
	  break;
       case 5: 
	  strarr = chmtnk;
	  nstrings = &Nchmtnk;
	  room = *nstr + 1;
	  break;
       case 6: 
	  strarr = mol2;
	  nstrings = &Nmol2;
	  room = *nstr + 1;
	  break;
       case 7: 
	  strarr = chmsf;
	  nstrings = &Nchmsf;
	  room = *nstr + 1;
	  break;
       case 8: 
	  strarr = ambstr;
	  nstrings = &Nambstr;
	  room = *nstr + 1;
	  break;
       case 9: 
	  strarr = &GEOMstr;
          j = 0;
	  nstrings = &j;
	  room = *nstr + 1;
	  GEOMset = 1;
	  break;
       case 10: 
	  strarr = spacegr;
	  nstrings = &Nspgr;
	  room = *nstr + 1;
	  break;
       case 11: 
	  strarr = achain;
	  nstrings = &ncal;
	  room = *nstr + 1;
	  break;
       case 12: 
	  strarr = frsym;
	  nstrings = &nfr;
	  room = *nstr + 1;
	  break;
       case 13: 
	  strarr = mlftit;
	  nstrings = &ntits;
	  room = *nstr + 1;
	  break;
       case 14: 
	  strarr = gmx;
	  nstrings = &Ngmx;
	  room = *nstr + 1;
	  break;
       case 15: 
	  strarr = gmx2;
	  nstrings = &Ngmx2;
	  room = *nstr + 1;
	  break;
       case 16: 
	  strarr = g43;
	  nstrings = &Ng43;
	  room = *nstr + 1;
	  break;
       case 17: 
	  strarr = amostr;
	  nstrings = &Namostr;
	  room = *nstr + 1;
	  break;
       case 18: 
	  strarr = grostr;
	  nstrings = &Ngrostr;
	  room = *nstr + 1;
	  break;
       case 19: 
	  strarr = gffext;
	  nstrings = &Ngffext;
	  room = *nstr + 1;
	  break;
       case 20: 
	  strarr = exepath;
	  nstrings = &Nexepath;
	  room = *nstr + 1;
	  break;
       }

       strarr[*nstrings] = (char *) malloc(room);
       if (!strarr[*nstrings]) fprintf(stderr,"getfiles: malloc error\n");
       strcp(str,strarr[*nstrings],*nstr);
#ifndef CRAY
       strarr[*nstrings][*nstr] = '\0';
#endif
       (*nstrings)++;

/* postprocess some strings */

       if (*iopt == 20) {
	  char *p;
	  
	  if ((p = strrchr(exepath[0], '/'))) {
		p++; *p = '\0';
	  } else {
		p = exepath[0];
		*p = '\0';
	  }
       }
}

#if defined(VMS) || defined(UNDERSC)
parstr(str, iopt)
#else
#ifdef CRAY
PARSTR(str, iopt)
#else
parstr_(str, iopt)
#endif
#endif

#ifdef VMS
struct dsc$descriptor_s *str;
#else
#ifdef CRAY
_fcd str;
#else
char *str;
#endif
#endif
int *iopt;
{
       switch(*iopt) {
       case 0: 
	  glin1 = str;
	  break;
       case 1: 
	  glin2 = str;
	  break;
       case 2: 
	  gtitl = str;
	  break;
       case 3: 
	  jname = str;
	  break;
       case 4: 
	  qname = str;
	  break;
       case 5: 
	  ename = str;
	  break;
       case 6: 
	  tnkjn = str;
	  break;
       case 7: 
	  vfile = str;
	  break;
       case 8: 
	  mfile = str;
	  break;
       case 9: 
	  oglfile = str;
	  break;
       case 10: 
	  povfile = str;
	  break;
       }
}

cpstr(ostr,str,nlen)
char *ostr;
#ifdef VMS
struct dsc$descriptor_s *str;
#else
#ifdef CRAY
_fcd str;
#else
char *str;
#endif
#endif
int nlen;
{
  int i;
  int n;

  if (nlen) {
	n = MINI(strlen(ostr),nlen);
  } else {
	n = strlen(ostr);
  }

#ifdef VMS
                for (i=0; i<n; i++)
                      {str->dsc$a_pointer[i] = ostr[i];}
#else
#ifdef CRAY
                strncpy(_fcdtocp(str),ostr,n);
#else
                for (i=0; i<nlen; i++) str[i] = '\0';
                strncpy(str,ostr,n);
#endif
#endif
}

strcp(str,ostr,nlen)
#ifdef VMS
struct dsc$descriptor_s *str;
#else
#ifdef CRAY
_fcd str;
#else
char *str;
#endif
#endif
char *ostr;
int nlen;
{
  int i;

#ifdef VMS
                for (i=0; i<nlen; i++)
                      ostr[i] = str->dsc$a_pointer[i];
#else
#ifdef CRAY
                strncpy(ostr,_fcdtocp(str),nlen);
#else
                for (i=0; i<nlen; i++) ostr[i] = '\0';
                strncpy(ostr,str,nlen);
#endif
#endif
}

send_expose()
{
   XExposeEvent expe;

   expe.type = Expose;
   expe.send_event = True;
   expe.display = display;
   expe.window = win;
   expe.x = 0;
   expe.y = 0;
   expe.count = 0;
   expe.width = width; expe.height = height;
   XSendEvent(display, win, True, ExposureMask, (XEvent *) &expe);
   XFlush(display);
}

static int pdone;

static void handle_child()
{
/*  fprintf(stderr,"handle_child %d\n",tnkpid);*/
  pdone = 1;
  if (tnkloop) send_expose();
}

static int tdone;

static void handle_alarm()
{
  tdone = 1;
}

static void handle_explalarm()
{
   XCrossingEvent expe;
   Window win;

   expe.type = EnterNotify;
   expe.send_event = True;
   expe.display = display;
   if (expldat.borq) {
	win = expldat.qarr[expldat.button].win;
   } else {
	win = expldat.barr[expldat.button].win;
   }
   expe.window = win;
   expe.subwindow = expldat.win;
   if (!expldat.active) {
	XSendEvent(display, win, 
		False, EnterWindowMask, (XEvent *) &expe);
	XFlush(display);
   }
}

static int escopt = 0;

static void handle_tnk()
{
   int phlp,iret;
   char cmdcyc[MAXCMD];
   struct stat st;

   sprintf(cmdcyc,"%s.%03d",cmdstr,cycle);
   phlp = pdone;
   fndfile = 1;
   st.st_mode = 0;
   if (!stat(cmdcyc, &st)) {
	/*fprintf(stderr,"Found file %s\n",cmdcyc);*/
#if defined(VMS) || defined(UNDERSC)
       	tnkpnt(&cycle,&iret);
#else
#ifdef CRAY
       	TNKPNT(&cycle,&iret);
#else
       	tnkpnt_(&cycle,&iret);
#endif
#endif
        if (delcyclefile) unlink(cmdcyc);
	if (iret) {
	   tnkupd = 1;
	   if (tnkloop) send_expose();
	}
	cycle++;
	
   } else {
	if (phlp == pdone) {
	   fndfile = 0;
	   if (tnkloop) send_expose();
	}
	/*fprintf(stderr,"NOT Found file %s\n",cmdcyc);*/
   }
#ifdef HASTIMER
/*   delayt();*/
   Timer(100,1);
#else
   sleep(1);
#endif
}

static void handle_tnkesc()
{
   int ist,phlp,iret,cyclo;
   char cmdcyc[MAXCMD];
   char cmdtmp[MAXCMD];
   struct stat st;

   sprintf(cmdcyc,"%s.%03d",cmdstr,cycle);
   sprintf(cmdtmp,"%s.tmp",cmdstr);
   phlp = pdone;
   fndfile = 1;
   st.st_mode = 0;
   cyclo = cycle;
   while (!stat(cmdcyc, &st)) {
	/*fprintf(stderr,"esc Found file %s\n",cmdcyc);*/
	cyclo = cycle;
	if (delcyclefile) {
	   ist = rename(cmdcyc,cmdtmp);
	   if (rename(cmdcyc,cmdtmp)) {
	      unlink(cmdcyc);
	   }
	} else {
	   strcpy(cmdtmp,cmdcyc);
	}
	cycle++;
        sprintf(cmdcyc,"%s.%03d",cmdstr,cycle);
   }

   if ( (access(cmdtmp,F_OK) == 0 && !isdir(cmdtmp)) ) {

	if (delcyclefile) cyclo = -1;
#if defined(VMS) || defined(UNDERSC)
	tnkpnt(&cyclo,&iret);
#else
#ifdef CRAY
	TNKPNT(&cyclo,&iret);
#else
	tnkpnt_(&cyclo,&iret);
#endif
#endif
        if (delcyclefile) unlink(cmdtmp);

	if (iret) {
	   tnkupd = 1;
	   if (tnkloop) send_expose();
	}

   } else {

	if (phlp == pdone) {
	   fndfile = 0;
	   if (tnkloop) send_expose();
	}
   }

#ifdef HASTIMER
   Timer(100,1);
#endif
}

doamb(jobstr)
char *jobstr;
{
   char cmdfil[MAXCMD];
   char cmdopt[MAXCMD];
   char cmdtmp[MAXCMD] = "ambfor ";
   char **argv;
   char *ambfor = "ambfor";
   char *spntr;
   char gtolstr[20];
   char iterstr[20];
   FILE *out;

   strcpy(cmdtmp,DOSpath(jobstr));
   strcat(cmdtmp,"_opt.xyz");
   if ( (access(cmdtmp,F_OK) == 0 && !isdir(cmdtmp)) ) {
	strcpy(cmdopt,cmdtmp);
	strcat(cmdopt,".old");
	if (rename(cmdtmp,cmdopt)) {
	   fprintf(stderr,"error renaming existing file %s\n",cmdopt);
	}
   }

   strcpy(cmdtmp,DOSpath(jobstr));
   strcat(cmdtmp,".tmp");
   if ( (access(cmdtmp,F_OK) == 0 && !isdir(cmdtmp)) ) {
	unlink(cmdtmp);
   }

   sprintf(gtolstr,"%f",*currgrd);
   sprintf(iterstr,"%d",*tnkit);
   sprintf(cmdfil,"%sambfor",exepath[0]);

   if (! (access(cmdfil,F_OK) == 0 && !isdir(cmdfil))) {
	sprintf(cmdfil,"%sambfor/ambfor",exepath[0]);
	if (!access(cmdfil,F_OK) == 0) {
	   sprintf(cmdfil,"ambfor");
	}
   }

   strcpy(cmdtmp,cmdfil);
   strcat(cmdtmp," ");

   if (tnk_single) {
	strcat(cmdtmp,"-n -s ");
   } else {
	if (*tnkbg) {
	   strcat(cmdtmp,"-n ");
	} else {
	   strcat(cmdtmp,"-m ");
	}

	if (*arch) {
	   strcat(cmdtmp," -a ");
	}
   }

   strcat(cmdtmp,DOSpath(jobstr));

   if (tnk_single) {
	system(cmdtmp);
	strcpy(cmdtmp,DOSpath(jobstr));
	strcat(cmdtmp,".log");
	out = fopen(cmdtmp,"r");
	if (out != NULL) {
	   while (fgets(cmdfil,MAXCMD,out) != NULL) {
		if (strstr(cmdfil,"Estat") != NULL) {
		   spntr = cmdfil + 6;
		   sscanf(spntr,"%lf",&newen);
/*
		   fprintf(stderr,"newen %lf\n",newen);
*/
		}
	   }
	   fclose(out);
	}
   } else {
     if (*tnkbg) {
	if (*arch) {
	   if (execlp(cmdfil,"ambfor","-n","-a","-g",gtolstr,"-c",iterstr,
			DOSpath(jobstr),NULL) == -1) {
		system(cmdtmp);
	   }
	} else {
	   if (execlp(cmdfil,"ambfor","-n","-g",gtolstr,"-c",iterstr,
			DOSpath(jobstr),NULL) == -1) {
		system(cmdtmp);
	   }
	}
     } else {
	if (*arch) {
	   if (execlp(cmdfil,"ambfor","-m","-a","-g",gtolstr,"-c",iterstr,
			DOSpath(jobstr),NULL) == -1) {
		system(cmdtmp);
	   }
	} else {
	   if (execlp(cmdfil,"ambfor","-m","-g",gtolstr,"-c",iterstr,
		DOSpath(jobstr),NULL) == -1) {
		system(cmdtmp);
	   }
	}
     }
   }
}

#if defined(VMS) || defined(UNDERSC)
exstr(str,nstr,iopt)
#else
#ifdef CRAY
EXSTR(str,nstr,iopt)
#else
exstr_(str,nstr,iopt)
#endif
#endif

#ifdef VMS
struct dsc$descriptor_s *str;
#else
#ifdef CRAY
_fcd str;
#else
char *str;
#endif
#endif
int *nstr;
int *iopt;

{
	int pid,i,ns;
	char cmdfil[MAXCMD];
	int ptmp,ctmp;

	delcyclefile = 0;
        ns = *nstr;
        if (*nstr > MAXCMD ) ns = MAXCMD;
        for (i=0; i<MAXCMD; i++) cmdstr[i] = ' ';
	strcp(str,cmdstr,ns);
	cmdstr[ns] = '\0';

	switch(*iopt) {
	case 0:
	  system(cmdstr);
	  break;
	case 4:
	case 1:
	  pid = fork();
	  switch(pid) {
	  case -1:
		fprintf(stderr,"Couldnt Fork\n");
		break;
	  case 0:	/*child */
                if (*iopt == 1) {
		   execlp(cmdstr," ",(char *)0);
		} else {
		   doamb(cmdstr);
		}
		exit(0);
		break;
	  default:	/*parent*/
		return;
		break;
	  }
	  break;

	case 3:
	case 2:

	  signal(SIGCHLD,handle_child);
	  tnkpid = fork();

	  switch(tnkpid) {
	  case -1:
		fprintf(stderr,"Couldnt Fork\n");
		break;
	  case 0:	/*child */
		tnkpid = getpid();
#ifndef VMS 
		setpgid(tnkpid,tnkpid);
#endif
	  	signal(SIGCHLD,SIG_DFL);
	  	signal(SIGALRM,SIG_DFL);

                if (*iopt == 2) {

		   sprintf(cmdfil,"./%s.run",cmdstr);
		   execlp(cmdfil," ",(char *)0);

		} else if (*iopt == 3) {

		   doamb(cmdstr);
		}
		exit(0);
		break;
	  default:	/*parent*/
	  	pdone = 0;
	  	cycle = 1;
		fndfile = 1;
		escopt = 0;
#ifdef HASTIMER
		hold = 0;
		holdt = 0; holdp = 0;
		update_model = 0;
		if (*iopt == 3) delcyclefile = 1;
	  	signal(SIGCHLD,handle_child);
   		Timer(100,1);
	/*	delayt();*/
#endif
/* 
pdone = 1 means child is done or killed by users
fndfile = 1 means there is still a cycle file wich need to be read in
          and updated
The follwing while loop ends if pdone = 1 and fndfile = 0
*/

		while (!(pdone && !fndfile)) {
#ifdef HASTIMER
/* update the on screen structure  (just once)
   and the loop for holding a move direction
*/
		   if (hold || tnkupd) {
			 while (1){
			   XSync(display, False);
			   if (XCheckMaskEvent(display,
				ButtonReleaseMask, &event)) {
				hold = 0;
				holdt = 0; holdp = 0;
				moving = 0;
				break;
			   }
			   if (tnkupd && (*fancy && has_opengl)) update_model = 1;
			   doclr();
#if defined(VMS) || defined(UNDERSC)
			   mktrn(&holdt,&holdp);
			   qupd();
#else
#ifdef CRAY
			   MKTRN(&holdt,&holdp);
			   QUPD();
#else
			   mktrn_(&holdt,&holdp);
			   qupd_();
#endif
#endif
			   if (tnkupd) {
				tnkupd = 0;
				update_model = 0;
				if (!hold) break;
			   }

			 }
		   }
       		   XFlush(display);
		   tnkloop = 1;
		   XNextEvent(display, &event);
		   tnkloop = 0;
		   switch (event.type) {
			case KeyPress:
				{
				   XKeyEvent *key_event = (XKeyEvent *) &event;
				   char buf[10]; KeySym ks; XComposeStatus status;
				   int stlen,istat;
				   stlen = XLookupString(key_event,buf,10,
							&ks,&status);
				   if (key_event->window == win || 
				       key_event->window == winMC) {
				       if (ks==XK_Escape) {
					  if (!pdone) kill(-tnkpid,SIGKILL);
					  escopt = 1; pdone = 1;
					  *iopt = -1;
					  /*fndfile = 0;*/
					  break;
				       }
				   }

				}
				break;
			case ButtonPress:
				if (event.xbutton.window == win) {
				   if (event.xbutton.button == 3) OnTop();
				   else {
				      if (*ball) {
					moving = 1;
					startx = event.xbutton.x;
					starty = event.xbutton.y;
					btype = 0;
					if (event.xbutton.state & ShiftMask) 
						btype = 1;
					if (event.xbutton.state & ControlMask) 
						btype = 2;
					if ((event.xbutton.state & ControlMask) 
					 && (event.xbutton.state & ShiftMask)) 
						btype = 3;
					if (*fancy && has_opengl) 
					    moused(event.xbutton.button,
						   event.xbutton.state, 
						   event.xbutton.x, 
						   event.xbutton.y);
					} else {
					    rotat(event.xbutton.x,
						  event.xbutton.y);
					}
				   }
				} else if (event.xbutton.window == winMC) {
				   i = Clickwin(cbut,NBUTTS2,event.xbutton.x, 
					event.xbutton.y,1);
				   switch (i) {
					case BQUITT:
						kill(-tnkpid,SIGKILL);
						/*fndfile = 0;*/
						pdone = 1;
						*iopt = -1;
						break;
					case BZOOMIN:
						hold = 1; 
						holdt = 290; holdp = -1;
						break;
					case BZOOMOUT:
						hold = 1; 
						holdt = 290; holdp = 1;
						break;
					case BLEFT:    
						hold = 1; 
						holdt = 420; holdp = 0;
						break;
					case BRIGHT:    
						hold = 1; 
						holdt = 430; holdp = 0;
						break;
					case BUP:    
						hold = 1; 
						holdt = 440; holdp = 0;
						break;
					case BDOWN:    
						hold = 1; 
						holdt = 450; holdp = 0;
						break;
					case BSOLID:
						tnkupd = 1;
						TogBut(&cbut[BSOLID]);
						if (*fancy) {
						    *fancy = 0;
						    *ifogl = 0;
						}
						else {
						    *fancy = 1;
						    if (has_opengl) *ifogl = 1;
						}
						break;
					case BATCOL:
						tnkupd = 1;
						TogBut(&cbut[BATCOL]);
						if (*atcol) *atcol = 0;
						else *atcol = 1;
						break;
					case BSHADE:
						tnkupd = 1;
						TogBut(&cbut[BSHADE]);
						if (*shade) *shade = 0;
						else if (colcells >= 256) *shade = 1;
						break;
					case BPERSP:
						tnkupd = 1;
						TogBut(&cbut[BPERSP]);
						if (*persp) *persp = 0;
						else *persp = 1;
						break;
					default: 
						break;
				   }
				}
				break;
			case ButtonRelease:
				if (!(*fancy  && has_opengl) 
					&& event.xbutton.window == win) {
				   moving = 0;
				   gmoving = 0;
				}

				if (event.xbutton.window == win && 
				   (event.xbutton.button == 1 || 
				    event.xbutton.button == 2) && 
				    !ZoomSelection ) moving = 0;

				if ((*fancy  && has_opengl) && 
					event.xbutton.window == win) {
				   mouseu(event.xbutton.button,
					  event.xbutton.state, 
					  event.xbutton.x, event.xbutton.y);
				   dispsf();
				}
				break;
			case MotionNotify:
				motion_screen(&ctmp,&ptmp);
				break;
			case Expose:
				if (event.xexpose.window == win) {
				   if (*fancy && has_opengl) {
					dispsf();
				   } else {
					if (molback == molcur) 
					   XCopyArea(display,molcur,win,gc,
						0,0,width,height,0,0);
				   }
				}
				if (event.xexpose.window == ZMEwin) 
					RedrawZME();
				if (event.xexpose.window == winMC)
					RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
				if (event.xexpose.window == SEQwin) RedrawSEQ();
              			if (event.xexpose.window == ATMwin) RedrawATM();
				break;
			default: break;
		   }
#else
/* not hastimer */
                   handle_tnk();
#endif
		   if (tnkupd) {
		        update_model = 1;
			doclr();
#if defined(VMS) || defined(UNDERSC)
			mktrn(&holdt,&holdp);
			qupd();
#else
#ifdef CRAY
			MKTRN(&holdt,&holdp);
			QUPD();
#else
			mktrn_(&holdt,&holdp);
			qupd_();
#endif
#endif
		   }

		}
		/*fprintf(stderr,"End of process %d\n",tnkpid);*/
	  	signal(SIGCHLD,SIG_IGN);
	  	signal(SIGALRM,SIG_IGN);
		handle = 0;
		break;
	  }
	  break;
	}
}

int typchk()
{
   int i,j;

   j = 0;
   for ( i = 0; i < *xyz.iatoms; i++ ) 
	   if (xyz.ianz[i] < 99 && xyz.ityp[i] == 0) {
		fprintf(stderr,"AtomNr. %d untyped\n",i+1);
		j++;
	   }

   return(j);

}

int typit(ff)
int ff;
{
   int iretval,retype;
   char mess[64];

   iretval = 0;
   retype = 0; 

   if (*fftyp != ff) {
	*fftyp = ff;
	retype = 1;
   } else {
	if (typchk()) retype = 1;
   }
   
   if (retype) {
#if defined(VMS) || defined(UNDERSC)
	dotyp(ichx);
#else
#ifdef CRAY
	DOTYP(ichx);
#else
	dotyp_(ichx);
#endif
#endif
	iretval = typchk();

	if (ATMup) {
	   UpdateATM();
	   XMapRaised(display,ATMwin);
	   RedrawATM();
	}
	sprintf(mess,"(Re)typing %s",ForceFields[*fftyp]);
	if (DoCan(event.xbutton.x_root,event.xbutton.y_root,mess,0)) {}
   }
   return(iretval);
}

#define NUMCOL 15

static int PopUpNum, PopUpEntryH, PopUpHeight, PopUpWidth, PopUpChunk, PopUpCLow;
static int PopUpMaxNum = 20;

int DoPopUp(ParentWin,x,y,List,iopt,icent)
Window ParentWin;
int *iopt;
LSSTRU *List;
int x,y,icent;
{
  int done, inew, iold, ifrst, i, wit, wi, xt, ioptt;

  ioptt = *iopt;

  if (List == NULL) {
	PopUpNum = NUMCOL;
	PopUpEntryH = 14;
	PopUpWidth = 100;
  } else {
	PopUpChunk = -1;
	PopUpNum = List->nents;
	if (PopUpNum > PopUpMaxNum) {
	   PopUpChunk = 0;
	   PopUpCLow = PopUpChunk*PopUpMaxNum;
	   PopUpNum = PopUpMaxNum;
	   if ((PopUpChunk+1)*PopUpMaxNum > List->nents) PopUpNum = List->nents - PopUpCLow;
	} else {
	   PopUpCLow = 0;
	}
	PopUpEntryH = LINEHIGH;
	wi = 0;
	for (i=0; i<PopUpNum; i++) {
	    wit = XTextWidth(mfinfo,List->list[i],strlen(List->list[i]));
	    if (wit > wi) wi = wit;
	}
	PopUpWidth = wi + 2*SPACING;
  }

  PopUpHeight = PopUpNum*PopUpEntryH;
  if (PopUpChunk != -1) PopUpHeight = (PopUpNum+1)*PopUpEntryH;
  
  if (!PopUpHeight || !PopUpWidth) return;

  PopUp = CreateWindow("Molden Color Box",DEFQBOXGEOM,PopUpWidth,PopUpHeight,
                            colors[0],colors[190],ParentWin);

  XSelectInput(display, PopUp, 
  ( ExposureMask | ButtonPressMask | PointerMotionMask | VisibilityChangeMask));
  
  xt = x;
  if (icent) {
	xt = x - PopUpWidth/2;
	if (xt < 0) xt = 0;
  }
  XMoveResizeWindow(display, PopUp, xt, y, PopUpWidth, PopUpHeight);

  XSetFunction(display, gc, GXcopy);
  XSetPlaneMask(display, gc, colors[0] ^ colors[190]);
  XSetForeground(display, gc, colors[0]);
  XSetBackground(display, gc, colors[190]);

  XMapRaised(display,PopUp);

  XWindowEvent(display, PopUp, VisibilityChangeMask, &event);

  XFlush(display);

  iold = -1;
  ifrst = 1;
  done = 0;
  while (!done) {

    if (XPending(display)>0) {
      XNextEvent(display, &event);
      
      switch (event.type) {
      case Expose: {

	if (event.xexpose.window == PopUp) 
            RedrawPopUp(List);
      }
      break;

      case ButtonPress: {
        if (event.xbutton.window == PopUp) {
           *iopt = (event.xbutton.y*PopUpNum) / PopUpHeight;
           if (PopUpChunk != -1) *iopt = (event.xbutton.y*(PopUpNum+1)) / PopUpHeight;
	   if (PopUpChunk != -1) {
		if (*iopt == PopUpNum) {
		    PopUpChunk = PopUpChunk + 1;
		    if (PopUpChunk*PopUpMaxNum > List->nents) PopUpChunk = 0;
		    PopUpCLow = PopUpChunk*PopUpMaxNum;
		    PopUpNum = PopUpMaxNum;
		    if ((PopUpChunk+1)*PopUpMaxNum > List->nents) 
			PopUpNum = List->nents - PopUpCLow;
		    iold = -1;
		    RedrawPopUp(List);
		} else {
		    *iopt = *iopt + PopUpChunk*PopUpMaxNum;
		    done = 1;
		}
	   } else {
		done = 1;
	   }
        } else {
           done = 1;
           *iopt = ioptt;
	   XSetFunction(display, gc, GXcopy);
	   XSetPlaneMask(display, gc, (unsigned long) ~0L);
	   XDestroyWindow(display,PopUp);
	   return -1;
	}
      }
      break;

      case MotionNotify: {
        if (event.xmotion.window == PopUp) {
           inew = (event.xmotion.y*PopUpNum) / PopUpHeight;
	   if (PopUpChunk != -1) inew = (event.xmotion.y*(PopUpNum+1)) / PopUpHeight;
           if (inew != iold) {
		if (List == NULL) {
		    XSetForeground(display, gc, colors[1+iold]);
		    XDrawRectangle(display, PopUp, gc, 0,
		     (iold * PopUpHeight)/PopUpNum, PopUpWidth,PopUpEntryH);
		    XSetForeground(display, gc, colors[0]);
		    XDrawRectangle(display, PopUp, gc, 0,
		    (inew * PopUpHeight)/PopUpNum, PopUpWidth,PopUpEntryH);
		} else {
		    XSetFunction(display, gc, GXinvert);
		    XSetPlaneMask(display, gc, colors[190] ^ colors[0]);
		    if (!ifrst) {
		        XFillRectangle(display, PopUp, gc, 0,
		         iold * PopUpEntryH, PopUpWidth,PopUpEntryH);
		    } else ifrst = 0;
		    XFillRectangle(display, PopUp, gc, 0,
		     inew * PopUpEntryH, PopUpWidth,PopUpEntryH);
		    XSetFunction(display, gc, GXcopy);
		    XSetPlaneMask(display, gc, (unsigned long) ~0L);
		}
		iold = inew;
           }
        }
      }
      break;

      default: break;

      } /* end switch */
     }/* end if XPending*/
   } /*end while */

   XDestroyWindow(display,PopUp);
   return 0;
}

RedrawPopUp(List)
LSSTRU *List;
{
      int i;


  if (List == NULL) {
      XSetFunction(display, gc, GXcopy);
      XSetPlaneMask(display, gc, (unsigned long) ~0L);
      for (i=0; i < PopUpNum; i++) {
          XSetForeground(display, gc, colors[i+1]);
          XFillRectangle(display, PopUp, gc, 0,
               (i * PopUpHeight)/PopUpNum, PopUpWidth,PopUpEntryH);
      }
  }
  else {
      XSetFunction(display, gc, GXcopy);
      XSetPlaneMask(display, gc, colors[0] ^ colors[190]);
      for (i=0; i < PopUpNum; i++) {
          XSetForeground(display, gc, colors[190]);
          XFillRectangle(display, PopUp, gc, 0,
		         i * PopUpEntryH, PopUpWidth,PopUpEntryH);
          XSetForeground(display, gc, colors[0]);
	  LineString(PopUp,List->list[i+PopUpCLow],SPACING,ASCENT + i*PopUpEntryH);
      }
      if (PopUpChunk != -1) {
          XSetForeground(display, gc, colors[190]);
          XFillRectangle(display, PopUp, gc, 0,
		         PopUpNum * PopUpEntryH, PopUpWidth,PopUpEntryH);
          XSetForeground(display, gc, colors[0]);
	  LineString(PopUp,"More ...",SPACING,ASCENT + PopUpNum*PopUpEntryH);
      }
  }
}

#define POPSPACE 8
int DoCan(x,y,strval,docan)
int x,y;
char *strval;
int docan;
{
  int done,wit,hit,bw,xp,retval,nb,nlines,wittmp,ql;
  char wgeom[64];
  char *p, *q;

  retval = 0;
  nb = 1;
  if (docan) nb = 2;

  nlines = 0;
  p = strval;
  q = strval;
  wit = 0;
  while ((p = strchr(q, '\n'))) {
     ql = (int) (p-q);
     wittmp = XTextWidth(mfinfo,q,ql) + 2*POPSPACE;
     if (wittmp > wit) wit = wittmp;
     p++;
     q = p;
     nlines++;
  }
  ql = strlen(q);
  wittmp = XTextWidth(mfinfo,q,ql) + 2*POPSPACE;
  if (wittmp > wit) wit = wittmp;
  nlines++;

  hit = POPSPACE + LINEHIGH*nlines + POPSPACE + BUTTH + POPSPACE;
  

  sprintf(wgeom,"+%d+%d",x-wit/2,y-hit/2);

  PopOk = CreateWindow("Molden OK Box",wgeom,wit,hit,
                            infobg,colors[190],(Window)0);

  XSelectInput(display, PopOk, 
  ( ExposureMask | ButtonPressMask | VisibilityChangeMask ));
  
  XMoveResizeWindow(display, PopOk, x-wit/2, y-hit/2, wit, hit);

  XMapRaised(display,PopOk);

  XWindowEvent(display, PopOk, VisibilityChangeMask, &event);

  XFlush(display);

  if (docan) {
	bw = (wit - 4*POPSPACE) / 2;
	DefBut(&obut[0],  PopOk, POPSPACE, nlines*LINEHIGH + 2*POPSPACE, 
		bw, BUTTH, "OK", infobg, 0);
	DefBut(&obut[1],  PopOk, bw + 3*POPSPACE, nlines*LINEHIGH + 2*POPSPACE, 
		bw, BUTTH, "Cancel", infobg, 0);
  } else {
	bw = 40;
	xp = wit / 2 - bw / 2;
	DefBut(&obut[0],  PopOk, xp, nlines*LINEHIGH + 2*POPSPACE, 
		bw, BUTTH, "OK", infobg, 0);
  }

  done = 0;
  while (!done) {

    if (XPending(display)>0) {
      XNextEvent(display, &event);
      
      switch (event.type) {
      case Expose: {

	if (event.xexpose.window == PopOk) {
	   nlines = 0;
	   p = strval;
	   q = strval;
	   while ((p = strchr(q, '\n'))) {
		ql = (int) (p-q);
	        XDrawString(display, PopOk, gc, 
			POPSPACE, CHIGH+nlines*LINEHIGH+POPSPACE, q, ql);
		p++;
		q = p;
		nlines++;
	   }
	   ql = strlen(q);
	   XDrawString(display, PopOk, gc, 
			POPSPACE, CHIGH+nlines*LINEHIGH+POPSPACE, q, ql);
	   DrwBut(&obut[0]);
	   if (docan) DrwBut(&obut[1]);
	}
	if (event.xexpose.window == win) {
	   if (molback == molcur)
                    XCopyArea(display,molcur,win,gc,0,0,width,height,0,0);
	}
      }
      break;

      case ButtonPress: {
        if (event.xbutton.window == PopOk) {
	   if (Clickwin(obut,nb,event.xbutton.x, event.xbutton.y,1) == 1) 
		retval = 1;
           done = 1;
	} else {
	   DirBox(PopOk,1);
        }
      }
      break;

      default: break;

      } /* end switch */
     }/* end if XPending*/
   } /*end while */

   XDestroyWindow(display,PopOk);
   XSync(display, False);
   return(retval);
}

#if defined(VMS) || defined(UNDERSC)
confrm(iop,istat)
#else
#ifdef CRAY
CONFRM(iop,istat)
#else
confrm_(iop,istat)
#endif
#endif

int *iop;
int *istat;
{
   char statstr[200];

   if (!xison) return;

   switch (*iop) {
	case 0: 
		strcpy(statstr,"Setup completed, click OK to optimise");
		break;
	case 1: 
		strcpy(statstr,"Found mutiple structure XDATCAR file, \n click OK to use this in conjuction with POSCAR/CONTCAR file");
		break;
   }

   *istat = 1;
   if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
	statstr,1)) {
	*istat = 0;
   }
   if (*iop == 0) RedrawZME();
}

#if defined(VMS) || defined(UNDERSC)
plsph3(xori,yori,diameter,ia,ioffs,icfac)
#else
#ifdef CRAY
PLSPH3(xori,yori,diameter,ia,ioffs,icfac)
#else
plsph3_(xori,yori,diameter,ia,ioffs,icfac)
#endif
#endif

int *xori;
int *yori;
int *diameter;
int *ia;
int *ioffs;
int *icfac;
{
  int xc,yc,xce,yce;
  int thetad,coli,oldcol;
  double tcos,tsin;
  unsigned int wi,hi,wold,wtmp,whlf;

/*
   xori,yori = x,y of center of sphere
   diameter  = diameter of sphere
   ia        = flag for green circle around sphere (z-mat)
   ioffs     = offset in color array for atom color
   icfac     = range of shades possible
*/

  xc = *xori - *diameter/2;
  yc = *yori - *diameter/2;
  xce = *xori + *diameter/2;
  yce = *yori + *diameter/2;

  if (xce < 0 && yce < 0) return;
  if (xc > (int) width && yc > (int) height) return;

  oldcol = -1; wold = 30000;
  for ( thetad=90; thetad > 0; thetad-- ) {
     tcos = Tcos[thetad];  tsin = Tsin[thetad];
     wi = (unsigned int) (*diameter * tsin + 0.5);
     coli = (int)( *ioffs + tcos * (*icfac) + 0.5);
     if (coli != oldcol) {

        if (wold < 30000) {
           whlf = (wold + wi) / 2;
           XSetForeground(display, gc, colors[coli]);
           XSetBackground(display, gc, colors[oldcol]);
           XSetFillStyle(display,gc,FillOpaqueStippled);

           wtmp = (wold + whlf) / 2;
           xc = *xori - wtmp / 2;
           yc = *yori - wtmp / 2;
           XSetStipple(display,gc,qwgrey);
           XFillArc(display, molcur, gc, xc,yc, wtmp, wtmp, 0,360*64);

           xc = *xori - whlf / 2;
           yc = *yori - whlf / 2;
           XSetStipple(display,gc,stipple);
           XFillArc(display, molcur, gc, xc,yc, whlf, whlf, 0,360*64);

           wtmp = (wi + whlf) / 2;
           xc = *xori - wtmp / 2;
           yc = *yori - wtmp / 2;
           XSetStipple(display,gc,tqwgrey);
           XFillArc(display, molcur, gc, xc,yc, wtmp, wtmp, 0,360*64);

           XSetFillStyle(display,gc,FillSolid);
        }

        xc = *xori - wi / 2;
        yc = *yori - wi / 2;
        XSetBackground(display, gc, BlackPixel(display,screen));
        XSetForeground(display, gc, colors[coli]);
        XFillArc(display, molcur, gc, xc,yc, wi, wi, 0,360*64);

        oldcol = coli; wold = wi;
     }
  }

/* if atoms select for Z-matrix, draw green circle around it */

  xc = *xori - *diameter / 2;
  yc = *yori - *diameter / 2;
  
  if (*ia >= 2 && (ZMEup || ATMup) ) {
     wi = (unsigned int) *diameter;
     hi = wi;
     XSetForeground(display, gc, colors[rimcols[*ia]]);
     XDrawArc(display, molcur, gc, xc,yc, wi, hi, 0,360*64);
  }
}

#if defined(VMS) || defined(UNDERSC)
plrod3(xori,yori,diameter1,diameter2,diameter3,rodlen,ioffs,icfac,cosa,sina)
#else
#ifdef CRAY
PLROD3(xori,yori,diameter1,diameter2,diameter3,rodlen,ioffs,icfac,cosa,sina)
#else
plrod3_(xori,yori,diameter1,diameter2,diameter3,rodlen,ioffs,icfac,cosa,sina)
#endif
#endif

int *xori;
int *yori;
int *diameter1;
int *diameter2;
int *diameter3;
int *rodlen;
int *icfac;
int *ioffs;
float *cosa;
float *sina;
{
  int xc,yc;
  int thetad,coli,oldcol;
  double x,y,x1,y1,x2,y2,x3,y3;
  double tcos,tsin;
  unsigned int wi1,wi2,wi3,wold1,wtmp1,whlf1,wold3,wtmp3,whlf3;
  float Cosa,Sina;
  int rodl;
  int is;

/*
   xori,yori = x,y of center of sphere
   diameter  = diameter of sphere
   ia        = flag for green circle around sphere (z-mat)
   ioffs     = offset in color array for atom color
   icfac     = range of shades possible
*/

  is = 0;
  x1 = (double) *xori; y1 = (double) *yori;
  x = (double) 0; y = (double) -*rodlen;
  x2 = *xori + (*cosa*x - *sina*y);
  y2 = *yori + (*sina*x + *cosa*y);
  x3 = (x1 + x2) / 2.0;
  y3 = (y1 + y2) / 2.0;

  if ((x1 >= 0 && x1 <= (double) width) && 
	(y1 >= 0 && y1 <= (double) height)) is++;
  if ((x2 >= 0 && x2 <= (double) width) && 
	(y2 >= 0 && y2 <= (double) height)) is++;
  if ((x3 >= 0 && x3 <= (double) width) && 
	(y3 >= 0 && y3 <= (double) height)) is++;

  if (!is) return;

  Cosa = *cosa; Sina = *sina ; rodl = *rodlen;
  xc = *xori; yc = *yori;
  oldcol = -1; wold1 = 30000;
  for ( thetad=90; thetad > 0; thetad-- ) {
     tcos = Tcos[thetad];  tsin = Tsin[thetad];
     wi1 = (unsigned int) (*diameter1 * tsin + 0.5);
     wi2 = (unsigned int) (*diameter2 + 0.5);
     wi3 = (unsigned int) (*diameter3 * tsin + 0.5);
     coli = (int)( *ioffs + tcos * (*icfac) + 0.5);
     if (coli != oldcol) {

        if (wold1 < 30000) {
           whlf1 = (wold1 + wi1) / 2;
           whlf3 = (wold3 + wi3) / 2;
           XSetForeground(display, gc, colors[coli]);
           XSetBackground(display, gc, colors[oldcol]);
           XSetFillStyle(display,gc,FillOpaqueStippled);

           wtmp1 = (wold1 + whlf1) / 2;
           wtmp3 = (wold3 + whlf3) / 2;
           XSetStipple(display,gc,qwgrey);
	   plrod(xc,yc,wtmp1,wi2,wtmp3,rodl,Cosa,Sina);

           XSetStipple(display,gc,stipple);
	   plrod(xc,yc,whlf1,wi2,whlf3,rodl,Cosa,Sina);

           wtmp1 = (wi1 + whlf1) / 2;
           wtmp3 = (wi3 + whlf3) / 2;
           XSetStipple(display,gc,tqwgrey);
	   plrod(xc,yc,wtmp1,wi2,wtmp3,rodl,Cosa,Sina);

           XSetFillStyle(display,gc,FillSolid);
        }

        XSetBackground(display, gc, BlackPixel(display,screen));
        XSetForeground(display, gc, colors[coli]);
	plrod(xc,yc,wi1,wi2,wi3,rodl,Cosa,Sina);

        oldcol = coli; wold1 = wi1; wold3 = wi3; 
     }
  }
}


plellps(xori,yori,rada,radb,alpha)
int xori;
int yori; 
int rada; 
int radb; 
float alpha; 
{
	int beta;
	double x,y;
	XPoint points[400];
	int npoints;
	double C,S;
/*
   xori,yori = x,y of center of ellips
   rada      = first axis radius
   radb      = second axis radius
   alpha     = rotation angle of ellips

   Let beta run from 0 to 360 degrees:

   x = rada*cos(beta)
   y = radb*sin(beta)

   Then rotation over alpha degrees and translation

   X = xori + (cos(alpha)*x - sin(alpha)*y)
   Y = yori + (sin(alpha)*x + cos(alpha)*y)
*/
	C = cos(alpha);
	S = sin(alpha);
	for (beta=0; beta <= 360; beta++)
	{
		x = rada*Tcos[beta];
		y = radb*Tsin[beta];
		points[beta].x = xori + (C*x - S*y);
		points[beta].y = yori + (S*x + C*y);
	}
	npoints = 361;
	XFillPolygon(display,molcur,gc,points,npoints,Convex,CoordModeOrigin);
}

plrod(xori,yori,rada,radb,radc,rodl,cosa,sina)
int xori;
int yori; 
int rada; 
int radb; 
int radc; 
int rodl;
float cosa,sina; 
{
	int beta;
	double x,y;
	XPoint points[400];
	int npoints;
	int binc;
/*
   xori,yori = x,y of center of ellips on top of rod
   rada      = first axis radius
   radb      = second axis up radius
   radc      = second axis down radius
   rodl      = rod length
   alpha     = rotation angle of rod

   Let beta run from 0 to 360 degrees:

   x = rada*cos(beta)
   y = radb*sin(beta)

   Then rotation over alpha degrees and translation

   X = xori + (cos(alpha)*x - sin(alpha)*y)
   Y = yori + (sin(alpha)*x + cos(alpha)*y)
*/
	npoints = 0;

	if (rada) {
		binc = 180/rada; if (!binc) binc = 1;
	}
	else binc = 1;
	x = radc; y = -rodl;
	points[0].x = xori + (cosa*x - sina*y);
	points[0].y = yori + (sina*x + cosa*y);
	for (beta=0; beta <= 180; beta = beta + binc)
	{
		npoints++;
		x = rada*Tcos[beta];
		y = radb*Tsin[beta];
		points[npoints].x = xori + (cosa*x - sina*y);
		points[npoints].y = yori + (sina*x + cosa*y);
	}
	npoints++;
	x = -radc; y = -rodl;
	points[npoints].x = xori + (cosa*x - sina*y);
	points[npoints].y = yori + (sina*x + cosa*y);
	npoints++;
	XFillPolygon(display,molcur,gc,points,npoints,Convex,CoordModeOrigin);
}

#if defined(VMS) || defined(UNDERSC)
plrodx(xori,yori,rada,radb,radc,rodlen,ioffs,cosa,sina)
#else
#ifdef CRAY
PLRODX(xori,yori,rada,radb,radc,rodlen,ioffs,cosa,sina)
#else
plrodx_(xori,yori,rada,radb,radc,rodlen,ioffs,cosa,sina)
#endif
#endif

int *xori;
int *yori;
int *rada;
int *radb;
int *radc;
int *rodlen;
int *ioffs;
float *cosa;
float *sina;
{
  int rodl;
  int beta;
  int is;
  double x,y,x1,y1,x2,y2,x3,y3;
  XPoint points[400];
  int npoints;
  int binc;

/*
   xori,yori = x,y of center of sphere
   diameter  = diameter of sphere
   ia        = flag for green circle around sphere (z-mat)
   ioffs     = offset in color array for atom color
*/

  rodl = *rodlen;

  XSetForeground(display, gc, colors[*ioffs]);

  npoints = 0;

  if (*rada) {
	binc = 180/(*rada); if (!binc) binc = 1;
  }
  else binc = 1;

  is = 0;
  x1 = (double) *xori; y1 = (double) *yori;
  x = (double) 0; y = (double) -rodl;
  x2 = *xori + (*cosa*x - *sina*y);
  y2 = *yori + (*sina*x + *cosa*y);
  x3 = (x1 + x2) / 2.0;
  y3 = (y1 + y2) / 2.0;

  if ((x1 >= 0 && x1 <= (double) width) && 
	(y1 >= 0 && y1 <= (double) height)) is++;
  if ((x2 >= 0 && x2 <= (double) width) && 
	(y2 >= 0 && y2 <= (double) height)) is++;
  if ((x3 >= 0 && x3 <= (double) width) && 
	(y3 >= 0 && y3 <= (double) height)) is++;

  if (!is) return;

  x = *radc; y = -rodl;
  points[0].x = *xori + (*cosa*x - *sina*y);
  points[0].y = *yori + (*sina*x + *cosa*y);
  for (beta=0; beta <= 180; beta = beta + binc)
  {
	npoints++;
	x = *rada*Tcos[beta];
	y = *radb*Tsin[beta];
	points[npoints].x = *xori + (*cosa*x - *sina*y);
	points[npoints].y = *yori + (*sina*x + *cosa*y);
  }
  npoints++;
  x = -(*radc); y = -rodl;
  points[npoints].x = *xori + (*cosa*x - *sina*y);
  points[npoints].y = *yori + (*sina*x + *cosa*y);
  npoints++;
  XFillPolygon(display,molcur,gc,points,npoints,Convex,CoordModeOrigin);

  XSetBackground(display, gc, BlackPixel(display,screen));
  XSetFillStyle(display,gc,FillOpaqueStippled);
  XSetStipple(display,gc,stipple);

  npoints = 0;
  if (*cosa < 0) { 
    x = *radc; y = -rodl;
    points[0].x = *xori + (*cosa*x - *sina*y);
    points[0].y = *yori + (*sina*x + *cosa*y);
    for (beta=0; beta <= 90; beta = beta + binc)
    {
	   npoints++;
	   x = *rada*Tcos[beta];
	   y = *radb*Tsin[beta];
	   points[npoints].x = *xori + (*cosa*x - *sina*y);
	   points[npoints].y = *yori + (*sina*x + *cosa*y);
    }
    npoints++;
    x = 0; y = -rodl;
    points[npoints].x = *xori + (*cosa*x - *sina*y);
    points[npoints].y = *yori + (*sina*x + *cosa*y);
    npoints++;
    XFillPolygon(display,molcur,gc,points,npoints,Convex,CoordModeOrigin);
  }
  else {
    x = -(*radc); y = -rodl;
    points[0].x = *xori + (*cosa*x - *sina*y);
    points[0].y = *yori + (*sina*x + *cosa*y);
    for (beta=180; beta >= 90; beta = beta - binc)
    {
	   npoints++;
	   x = *rada*Tcos[beta];
	   y = *radb*Tsin[beta];
	   points[npoints].x = *xori + (*cosa*x - *sina*y);
	   points[npoints].y = *yori + (*sina*x + *cosa*y);
    }
    npoints++;
    x = 0; y = -rodl;
    points[npoints].x = *xori + (*cosa*x - *sina*y);
    points[npoints].y = *yori + (*sina*x + *cosa*y);
    npoints++;
    XFillPolygon(display,molcur,gc,points,npoints,Convex,CoordModeOrigin);
  }
  XSetFillStyle(display,gc,FillSolid);

  npoints = 0;
  x = (*radc)/2; y = -rodl;
  points[0].x = *xori + (*cosa*x - *sina*y);
  points[0].y = *yori + (*sina*x + *cosa*y);
  for (beta=0; beta <= 180; beta = beta + binc)
  {
	npoints++;
	x = (*rada)*Tcos[beta]/2;
	y = *radb*Tsin[beta];
	points[npoints].x = *xori + (*cosa*x - *sina*y);
	points[npoints].y = *yori + (*sina*x + *cosa*y);
  }
  npoints++;
  x = -(*radc)/2; y = -rodl;
  points[npoints].x = *xori + (*cosa*x - *sina*y);
  points[npoints].y = *yori + (*sina*x + *cosa*y);
  npoints++;
  XFillPolygon(display,molcur,gc,points,npoints,Convex,CoordModeOrigin);
}

#ifdef HASTIMER
#include <sys/time.h>


Timer(msec,timopt)   /* waits for 'n' milliseconds */
 int  msec;
 int timopt;
{
#ifdef VMS
  float ftime;
  ftime = msec / 1000.0;
  lib$wait(&ftime);

#else

  long usec;
  struct itimerval it;

  if (handle == 1 && timopt == 0) return;
  if (msec <= 0) return;
  usec = (long) msec * 1000;

  memset(&it, 0, sizeof(it));
  if (usec>=1000000L) {  
    it.it_value.tv_sec = usec / 1000000L;
    usec %= 1000000L;
  }

  it.it_value.tv_usec = usec;
  tdone = 0;
  handle = timopt;
  if (timopt == 2) {
     signal(SIGALRM,handle_explalarm);
  } else if (timopt == 1) {
     if (!escopt) {
	signal(SIGALRM,handle_tnk);
     } else {
	signal(SIGALRM,handle_tnkesc);
     }
  } else signal(SIGALRM,handle_alarm);
  setitimer(ITIMER_REAL, &it, NULL);
  if (!timopt) pause();
#endif 
}
#endif

#if defined(VMS) || defined(UNDERSC)
parptr(nptr, fptr, ffptr, nitem)
#else
#ifdef CRAY
PARPTR(nptr, fptr, ffptr, nitem)
#else
parptr_(nptr, fptr, ffptr, nitem)
#endif
#endif

int *nptr;
float *fptr;
float *ffptr;
int *nitem;
{

    switch(*nptr) {
    case 1: freq = fptr; nfreq = nitem;break;
    case 2: dorb.eiga = fptr; dorb.focc = (double *) ffptr; dorb.ncols = nitem;
	    break;
    case 3: geo1ptr = (GEO1STRU *) fptr; 
	    geopntr.fmaxt = &geo1ptr->fmaxt;
	    geopntr.frmst = &geo1ptr->frmst;
	    geopntr.dmaxt = &geo1ptr->dmaxt;
	    geopntr.drmst = &geo1ptr->drmst;
	    geopntr.fgmin = &geo1ptr->fgmin;
	    geopntr.fgmax = &geo1ptr->fgmax;
	    geopntr.dgmin = &geo1ptr->dgmin;
	    geopntr.dgmax = &geo1ptr->dgmax;
	    geopntr.enmax = &geo1ptr->enmax;
	    geopntr.enmin = &geo1ptr->enmin;
	    geopntr.ngeoms = &geo1ptr->ngeoms;
	    geopntr.nepnts = &geo1ptr->nepnts;
	    geopntr.gcvav = &geo1ptr->gcvav;
	    geopntr.ifmxav = &geo1ptr->ifmxav;
	    geopntr.ifrmav = &geo1ptr->ifrmav;
	    geopntr.idmxav = &geo1ptr->idmxav;
	    geopntr.idrmav = &geo1ptr->idrmav;
	    geopntr.ieav = &geo1ptr->ieav;
	    geopntr.mxpnt = &geo1ptr->mxpnt;
	    geopntr.mxorg = geo1ptr->mxpnt;
	    break;
    case 151: geo2ptr = (GEO2STRU *) fptr; 
	    geopntr.formax = geo2ptr->formax;
	    geopntr.forrms = geo2ptr->forrms;
	    geopntr.dismax = geo2ptr->dismax;
	    geopntr.disrms = geo2ptr->disrms;
	    geopntr.epoints = geo2ptr->epoints;
	    geopntr.isav = geo2ptr->isav;
	    break;
    case 4: cnvptr = (CNVSTRU *) fptr; break;
    case 5: ipnt = nitem; break;
    case 6: zmatptr = (ZMATSTRU *) fptr; 
	    zmptr.bl = zmatptr->bl;
	    zmptr.ibl = zmatptr->ibl;
	    zmptr.alph = zmatptr->alph;
	    zmptr.ialph = zmatptr->ialph;
	    zmptr.bet = zmatptr->bet;
	    zmptr.ibet = zmatptr->ibet;
	    zmptr.imap = zmatptr->imap;
	    zmptr.ianz = zmatptr->ianz;
	    zmptr.iz = (int *) zmatptr->iz;
	    break;
    case 7: atomptr = (ATOMSTRU *) fptr; 
	    xyz.coo = (double *) atomptr->coo;
	    xyz.rzp = (double *) atomptr->rzp;
	    xyz.ianz = (int *) atomptr->ianz;
	    xyz.iaton = (int *) atomptr->iaton;
	    xyz.iatclr = (int *) atomptr->iatclr;
	    xyz.iresid = (int *) atomptr->iresid;
	    xyz.ixp = (int *) atomptr->ixp;
	    xyz.iyp = (int *) atomptr->iyp;
	    xyz.iconn = (int *) atomptr->iconn;
	    break;
    case 8: scalptr = (SCALSTRU *) fptr; break;
    case 9: zmptr.nz = nitem; break;
    case 10: dorb.eigb = fptr; dorb.focb = (double *) ffptr; dorb.ncolb = nitem;
	     break;
    case 11: iuhf = nitem; break;
    case 12: ixp = nitem; break;
    case 13: iyp = nitem; break;
    case 14: iaton = nitem; break;
    case 15: iatoms = nitem; 
	     xyz.iatoms = nitem;
	     xyz.mxorg = NUMAT;
	     break;
    case 16: DoFreq = 0; break;
    case 129: DoFreq = 1; break;
    case 17: ichx = nitem; break;
    case 18: esp = (double *) fptr; break;
    case 19: doesp = nitem; break;
    case 20: plevel = (double *) fptr; nplev = *nitem; break;
    case 21: ipcol = nitem; break;
    case 22: iqon = nitem; break;
    case 23: ihasq = nitem; break;
    case 24: icolps = nitem; break;
    case 25: ivtwo = nitem; break;
    case 26: ixyz = nitem; break;
    case 27: iixyz = nitem; break;
    case 28: iwropt = nitem; break;
    case 29: itotc = nitem; break;
    case 30: imult = nitem; break;
    case 31: ibatch = nitem; break;
    case 32: ito = nitem; break;
    case 33: imo = nitem; break;
    case 34: ibo = nitem; break;
    case 35: ihs = nitem; break;
    case 36: itm = nitem; break;
    case 37: espvdw = (double *) fptr; break;
    case 38: ispd = nitem; break;
    case 39: ibgcol = nitem; break;
    case 40: cellconstants = (CELLSTRU *) fptr; break;
    case 41: jring = nitem; break;
    case 42: isimpl = nitem; break;
    case 43: surface = (SRFSTRU *) fptr; break;
    case 44: ivdwpl = nitem;break;
    case 45: natoms = nitem; break;
    case 46: dospa = nitem; break;
    case 47: qat = (double *) fptr; 
	     xyz.qat = qat;
	     break;
    case 48: fftyp = nitem; break;
    case 49: ityp = (short int *) nitem; 
	     xyz.ityp = ityp;
	     break;
    case 50: ipdbt = (short int *) nitem; 
	     xyz.ipdbt = ipdbt;
	     break;
    case 51: calfptr = (CALFSTRU *) fptr; break;
    case 52: isal = nitem; break;
    case 53: fancy = nitem; break;
    case 54: atcol = nitem; break;
    case 55: shade = nitem; break;
    case 56: persp = nitem; break;
    case 57: tnkprg = nitem; break;
    case 58: currgrd = (double *) fptr; break;
    case 59: tnkbg = nitem; break;
    case 60: arch = nitem; break;
    case 61: archfrq = nitem; break;
    case 62: tnkit = nitem; break;
    case 63: iqopt = nitem; break;
    case 64: icalc = nitem; break;
    case 65: ipdbon = nitem; break;
    case 66: cubetyp = nitem; break;
    case 67: natc = nitem; break;
    case 68: frmul = fptr; break;
    case 69: ibell = nitem; break;
    case 70: natorg = nitem; break;
    case 71: zmptr.ihaszm = nitem; break;
    case 72: zmptr.mxzat = nitem; break;
    case 73: tstoc = (TSTOCSTRU *) fptr;
	     stoc.cstoc = (double *) tstoc->cstoc;
	     stoc.czstoc = (double *) tstoc->czstoc;
	     stoc.astoc = tstoc->astoc;
	     stoc.bstoc = tstoc->bstoc;
	     stoc.ianstc = tstoc->ianstc;
	     break; 
    case 74: torb = (TORBSTRU *) fptr;
	     orb.qd = (double *) torb->qd;
	     orb.pd = torb->pd;
	     orb.gd = (double *) torb->gd;
	     orb.hd = (double *) torb->hd;
	     break; 
    case 75: dorb.vectrs = (double *) fptr; dorb.vectrb = (double *) ffptr;
	     break; 
    case 76: dorb.nocc = nitem; break;
    case 77: dorb.nocb = nitem; break;
    case 78: dorb.p = (double *) fptr; dorb.paa = (double *) ffptr;
	     break; 
    case 79: dorb.istos = nitem; break;
    case 80: dorb.stoalfa = fptr; dorb.stobnorm = ffptr;
	     dorb.naorbs = nitem; break;
    case 81: dorb.averag = (double *) fptr; break;
    case 82: dorb.mxorb = nitem; break;
    case 83: sgrd.denn = (double *) fptr; 
	     sgrd.pmnn = (double *) ffptr;
	     sgrd.mx3d = nitem;
	     break;
    case 84: sgrd.dens = (double *) fptr; 
	     sgrd.denst = (double *) ffptr;
	     sgrd.mx3d2 = nitem;
	     break;
    case 85: sgrd.edx = (double *) fptr; 
	     sgrd.edy = (double *) ffptr;
	     sgrd.iedlog = nitem;
	     break;
    case 86: sgrd.rz = (double *) fptr; 
	     sgrd.bucket = (double *) ffptr;
	     sgrd.ix = nitem;
	     break;
    case 87: sgrd.iy = nitem; break;
    case 88: sgrd.mx3d = nitem; sgrd.mxorg = *nitem; break;
    case 89: sgrd.mx3d2 = nitem; break;
    case 90: irtcel = nitem; break;
    case 91: idelx = nitem; break;
    case 92: uscl = (double *) fptr; break;
    case 93: ball = nitem; break;
    case 94: picmax = nitem; break;
    case 95: cellpnt = (CELLSTRUC *) nitem; break;
    case 96: igztyp = nitem; break;
    case 97: igtfil = nitem; break;
    case 98: mgrd.fmap = (double *) fptr; 
	     mgrd.mx3d = nitem; mgrd.mxorg = *nitem;
	     break;
    case 99: mapit = nitem; break;
    case 100: ipsi = nitem; break;
    case 101: mapval = (double *) fptr; break;
    case 102: imapopt = nitem; break;
    case 103: iwxyz = nitem; break;
    case 104: icopth = nitem; break;
    case 105: icoptm = nitem; break;
    case 106: icoptl = nitem; break;
    case 107: ispopth = nitem; break;
    case 108: ispoptm = nitem; break;
    case 109: ispoptl = nitem; break;
    case 110: ipdbwh = nitem; break;
    case 111: irsnr = nitem; break;
    case 112: frint = (double *) fptr; ramint = (double *) ffptr; 
		ihasi = nitem; break;
    case 113: ideltm = nitem; break;
    case 114: imol = nitem; break;
    case 115: ewin = (double *) fptr; break;
    case 116: npmfs = nitem; break;
    case 117: pmfmn = (double *) fptr; pmfmx = (double *) ffptr; 
		npmfmx = nitem; break;
    case 118: ipmfmn = nitem; break;
    case 119: ipmfmx = nitem; break;
    case 120: pmflga = (double *) fptr; break;
    case 121: ialtyp = nitem; break;
    case 122: iscst = nitem; break;
    case 123: ipmfm = nitem; break;
    case 124: levcol = nitem; break;
    case 125: ipmfh = nitem; break;
    case 126: ipart = nitem; break;
    case 127: imn = nitem; break;
    case 128: imx = nitem; break;
    case 130: rotptr = (ROTSTRU *) fptr; break;
    case 131: posptr = (POSSTRU *) fptr; break;
    case 132: logo = nitem; break;
    case 133: nscnd = nitem; break;
    case 134: dolabs = nitem; break;
    case 135: fcptr = (FCSTRU *) fptr; break;
    case 136: forces_yes_no = nitem; break;
    case 137: ifogl = nitem; break;
    case 138: itsrf = nitem; break;
    case 139: iams = nitem; break;
    case 140: srfmap = nitem; break;
    case 141: srfloc = nitem; break;
    case 142: XYZ = (XYZSTRU *) fptr; break;
    case 143: NAT = nitem; break;
    case 144: comsrfptr = (COMSRFSTRU *) fptr; break;
    case 145: scle = (double *) fptr; break;
    case 146: nps1 = nitem; break;
    case 147: nps2 = nitem; break;
    case 148: ifdogl = nitem; break;
    case 149: isurf = nitem; 
	      xyz.isurf = isurf;
	      break;
    case 150: mapcol = (RGB *) fptr; valcol = (double *) ffptr; break;
/* already declared above
    case 151: (GEO2STRU *) fptr; break;
*/
    case 152: ishoh = nitem; break;
    case 153: pmfrot = (PMFROTSTRU *) fptr; break;
    case 154: adjuss = (double *) fptr; break;
    case 155: calfpptr = (CALFPSTRU *) fptr; break;
    case 156: iocnt = nitem; break;
    case 157: monptr = (MONSTRU *) fptr; break;
    case 158: xyz.mxnat = nitem; break;
    case 159: xyz.lwrit = nitem; break;
    case 160: xyz.lring = nitem; break;
    case 161: xyz.inat = nitem; break;
    case 162: ibgclo = nitem; break;
    case 163: qdpptr = (CHGDIP *) fptr; break;
    case 164: ibgmod = nitem; break;
    case 165: rng1 = (double *) fptr; rng2 = (double *) ffptr; break;
    case 166: vlcnt = (double *) fptr; break;
    case 167: ihets = nitem; break;
    case 168: scndcol = nitem; break;
    case 169: idcur = nitem; break;
    case 170: idoh = nitem; break;
    case 171: hbpars = (HBSTRU *) fptr; break;
    case 172: itot = nitem; break;
    case 173: do3d = nitem; break;
    case 174: ambchg = nitem; break;
    }
}

drwcnv()
{
      int nents;

      if (cnvptr->icvav2) 
	  nents = MAXI(cnvptr->jend1,cnvptr->jend2);
      else nents = cnvptr->jend1;

      if (cnvptr->icvav1) 
      drwgra(&scfEfirst,-5,wincnv,CNVWIDE,CNVHIGH,NULL,cnvptr->convg1,cnvptr->jstrt1,cnvptr->jend1,nents,cnvptr->cnvmax,cnvptr->cnvmin,0.0e0,5,1,"Iterations","Energy","First Point",0,1,0,0);
      if (cnvptr->icvav2) 
      drwgra(&scfElast,10,wincnv,CNVWIDE,CNVHIGH,NULL,cnvptr->convg2,cnvptr->jstrt2,cnvptr->jend2,nents,cnvptr->cnvmax,cnvptr->cnvmin,0.0e0,6,1,"Iterations","Energy","Last Point",1,0,0,0);
      XSetLineAttributes(display, gc, 1, LineSolid, CapButt, JoinMiter);
}

drwspec()
{
      int i,j,ifr;
      double intensity, frq, center, rel_offset;
      double (*lineshape)(double);
      double fminus,scx,scy,x1,y1;


      if (out_spec == NULL) return;

      drwgra(&spect,-5,winspec,SPECWIDE,SPECHIGH,NULL,out_spec,1,n_freqs,n_freqs,spec_mx,spec_mn,0.0e0,5,1,"Frequency","Intensity","",0,1,0,1);
      XSetLineAttributes(display, gc, 1, LineSolid, CapButt, JoinMiter);

      if (lorentzian) {
	lineshape = lorentz;
      } else {
	lineshape = gauss;
      }

      spect.npts = 0;
      scx = 1.0*n_freqs;
      scy = spec_mx - spec_mn;
      fminus = spec_mn - 0.05*scy;
      scy = 1.05*scy;
      ifr = 1;

      for (i=0; i < *nfreq; i++) {
	intensity = 0.0;
	frq = ((double) freq[i])*freq_scale;
	for (j=0; j < *nfreq; j++) {
	   center = ((double) freq[j])*freq_scale ;
	   rel_offset = (frq - center) / hwhm;
	   intensity += spint[j] * lineshape(rel_offset);
	}
        
	x1 = ((((double) freq[i])*freq_scale - min_freq)/freq_step)/scx;
 	y1 = (intensity-fminus)/scy;
	if (spect.npts < MAXFRPNT) {
		glpnt(SPECWIDE,SPECHIGH,x1,y1,
		&spect.x[spect.npts],&spect.y[spect.npts],ifr);
		spect.index[spect.npts] = i;
	}
	spect.npts++;

      }

      spect.fpts = (double *) freq;

      for (i=0; i<NSBUTTS; i++) DrwBut(&spbut[i]);
      for (i=0; i<5; i++) {
	PromptBox(&qboxes[QHW+i]);
      }

      ULineString(winspec,"Spectrum:",CNVBORD, SPECHIGH+15);
      ULineString(winspec,"Lineshape:",CNVBORD, SPECHIGH+BUTTN+15);

}

drwsco()
{
   int i;
   int PEH,PH,PW,NE,MW,jx,jy;

   scomin = 1.e10;
   scomax = -1.e10;

   for (i=0; i<*npmfs; i++) {
	if (ewin[i] > scomax) scomax = ewin[i];
	if (ewin[i] < scomin) scomin = ewin[i];
   }
   scomax = 1.2e0*(scomax - scomin) + scomin;

   if (*npmfs && ! (scomax == scomin)) {
      drwgra(&docksco,-5,winsco,CNVWIDE,CNVHIGH,NULL,ewin,1,*npmfs,*npmfs,scomax,scomin,0.0e0,5,1,"Orientations","Score",NULL,0,1,0,0);
      XSetLineAttributes(display, gc, 1, LineSolid, CapButt, JoinMiter);
   }
   for (i=0; i<NSCBUTTS; i++) DrwBut(&scbut[i]);

   LineString(winsco, "Ligand Color Mode", 30, CNVHIGH+54);
   LineString(winsco, "Include Hydrogens", 30, CNVHIGH+74);

   NE = 4;
   PEH = 20;
   PW = 70;
   PH = NE*PEH;
   MW = 10;

   jx = CNVWIDE-PW-10;
   jy = CNVHIGH+45;

   if (! *ipmfm) {
	XSetForeground(display, gc, White);
	XFillRectangle(display, winsco, gc, jx-10,jy-10, PW+20,4*PEH+20);
	XSetForeground(display, gc, Black);
	return;
   }

   for (i=0; i < NE; i++) {
	XSetForeground(display, gc, colors[levcol[i]]);
	XFillRectangle(display, winsco, gc, jx,jy+(i * PH)/NE, PW,PEH);
   }

   XSetForeground(display, gc, Black);

   sprintf(stemp, "PMFmax");
   XDrawString(display,winsco,gc,jx+15,jy+4,
           stemp,strlen(stemp));
   sprintf(stemp, "PMFavg");
   XDrawString(display,winsco,gc,jx+15,jy+4+(2*PH)/NE,
           stemp,strlen(stemp));
   sprintf(stemp, "PMFmin");
   XDrawString(display,winsco,gc,jx+15,jy+4+(4*PH)/NE,
           stemp,strlen(stemp));

}

int ButtonsSCO(i)
int i;
{
   double tpmf;

   switch(i) {
   case 0:
#if defined(VMS) || defined(UNDERSC)
	alnsav();
#else
#ifdef CRAY
	ALNSAV();
#else
	alnsav_();
#endif
#endif
	break;
   case 1:
#if defined(VMS) || defined(UNDERSC)
	alnwrt();
#else
#ifdef CRAY
	ALNWRT();
#else
	alnwrt_();
#endif
#endif
	break;
   case 2:
	bflag = 1; bretval = 561;
	strcpy(molwstr,"Click on atom to analyze score !");
	StatusStr(0,1);
	XDefineCursor(display,win,AtomCursor);
	break;
   case 3:
	XDestroyWindow(display,winsco);scoup = 0;
	break;
   case 4:
	if (*ipmfm) {
	   *ipmfm = 0;
	} else {
	   *ipmfm = 1;
	}
	TogBut(&scbut[4]);
#if defined(VMS) || defined(UNDERSC)
	totpmf(&tpmf);
	qupd();
#else
#ifdef CRAY
	TOTPMF(&tpmf);
	QUPD();
#else
	totpmf_(&tpmf);
	qupd_();
#endif
#endif
	drwsco();

	break;
   case 5:
	if (*ipmfh) {
	   *ipmfh = 0;
	} else {
	   *ipmfh = 1;
	}
	TogBut(&scbut[5]);
#if defined(VMS) || defined(UNDERSC)
	totpmf(&tpmf);
	qupd();
#else
#ifdef CRAY
	TOTPMF(&tpmf);
	QUPD();
#else
	totpmf_(&tpmf);
	qupd_();
#endif
#endif
	drwsco();

	break;
   }
   return(0);
}

drwpmf()
{
   int i;

   butje(winpmf,0,0,325,CNVHIGH+40,2,0,2,1,None,0,0,0);
   for (i=0; i<NPBUTTS; i++) DrwBut(&pbut[i]);
   RedrawList(&pmflistmx);
   RedrawList(&pmflistmn);
   ULineString(winpmf, "Top Negative Interactions", SBOXOFFX, 25);
   ULineString(winpmf, "Top Positive Interactions", SBOXOFFX, 25+120);
   sprintf(stemp, "Total Score Atom  : %8.3f",*pmflga);
   LineString(winpmf, stemp, SBOXOFFX, 25+120+120);
   sprintf(stemp, "Total Score Ligand: %8.3f",ewin[*npmfs-1]);
   LineString(winpmf, stemp, SBOXOFFX, 25+120+140);

}

int ButtonsPMF(i)
int i;
{

   switch(i) {
   case 0:
	XDestroyWindow(display,winpmf);pmfup = 0;
	break;
   }
   return(0);
}

#if defined(VMS) || defined(UNDERSC)
drwgeo()
#else
#ifdef CRAY
DRWGEO()
#else
drwgeo_()
#endif
#endif
{
      int nitems;

      if (!*geopntr.gcvav || !geoup) return;

      nhframes = 1;
      if (*geopntr.ifmxav || *geopntr.ifrmav) nhframes = 2;
      nwframes = 1;
      if (*geopntr.idmxav || *geopntr.idrmav) nwframes = 2;

      if (*geopntr.ieav) {
	   nitems = *geopntr.nepnts;
	   if (nitems > *geopntr.mxpnt) nitems = *geopntr.mxpnt;
	   drwgra(&geoE,-5,wingeo,CNVWIDE,CNVHIGH,geopntr.isav,
	   geopntr.epoints,0,0,nitems,*geopntr.enmax,*geopntr.enmin,
	   0.0e0,9,1,"Point","Energy",NULL,0,1,1,0);
      }

      nitems = *geopntr.ngeoms;
      if (nitems > *geopntr.mxpnt) nitems = *geopntr.mxpnt;

      if (*geopntr.ifmxav)
	   drwgra(&geoFmax,-5,wingeo,CNVWIDE,CNVHIGH,geopntr.isav,
	   geopntr.formax,0,0,nitems,*geopntr.fgmax,*geopntr.fgmin,
	   *geopntr.fmaxt,5,2,"Point","Force","Max. Force",0,1,0,0);

      if (*geopntr.ifrmav) 
	   drwgra(&geoFrms,10,wingeo,CNVWIDE,CNVHIGH,geopntr.isav,
	   geopntr.forrms,0,0,nitems,*geopntr.fgmax,*geopntr.fgmin,
	   *geopntr.frmst,6,2,"Point","Force","Aver. Force",1,0,0,0);

      if (*geopntr.idmxav)
	   drwgra(&geoSmax,-5,wingeo,CNVWIDE,CNVHIGH,geopntr.isav,
	   geopntr.dismax,0,0,nitems,*geopntr.dgmax,*geopntr.dgmin,
	   *geopntr.dmaxt,1,3,"Point","Step","Max. Step",0,1,0,0);

      if (*geopntr.idrmav)
	   drwgra(&geoSrms,10,wingeo,CNVWIDE,CNVHIGH,geopntr.isav,
           geopntr.disrms,0,0,nitems,*geopntr.dgmax,*geopntr.dgmin,
	   *geopntr.drmst,11,3,"Point","Step","Aver. Step",1,0,0,0);

      XSetLineAttributes(display, gc, 1, LineSolid, CapButt, JoinMiter);


}

drwgra(tabptr,yelev,gwin,wide,high,isav,fpts,jbeg,jend,nents,fmax,fmin,flim,icol,ifr,xstr,ystr,labstr,isdash,init,notsav,ityp)
FRSTRU *tabptr;
int yelev;
Window gwin;
int wide,high;
int *isav;
double *fpts;
int jbeg,jend;
int nents;
double fmax,fmin,flim;
int icol;
int ifr;
char *xstr;
char *ystr;
char *labstr;
int isdash;
int init;
int notsav;
int ityp;
{
      int i,j,xt,yt,qlen;
      int ifrx,ifry;
      int dum0,dum1,itel,tick;
      double frq,fminus,scx,scy,x1,y1,x2,y2;
      char *tmpptr;

      tabptr->current = -1;
      tabptr->win = gwin;
      tabptr->fpts = fpts;
      tabptr->npts = 0;
      tabptr->yelev = yelev;
      tabptr->color = icol;
      tabptr->wide = wide;
      tabptr->high = high;

      dum0 = 0;
      dum1 = 1;

      tmpptr = ystr;

      ifrx = 0;
      ifry = 0;
      if (ifr == 3 || ifr == 4) ifrx = 1;
      if (ifr == 2 || ifr == 4) ifry = 1;

      scx = 1.0*nents;
      scy = fmax - fmin;
      fminus = fmin - 0.05*scy;
      scy = 1.05*scy;

      if (init) {
         XSetLineAttributes(display,gc,2,LineSolid,CapButt,JoinMiter);
	 butje(gwin,CNVBORD+tabptr->wide*ifrx,CNVBORD+tabptr->high*ifry,
	   tabptr->wide-2*CNVBORD,tabptr->high-2*CNVBORD,3,0,0,0,NULL,0,0,0);
         XSetForeground(display, gc, BlackPixel(display,screen));
         XDrawString(display,gwin,gc,(tabptr->wide-CNVBORD-100)+tabptr->wide*ifrx,(tabptr->high-CNVBORD-10)+tabptr->high*ifry,xstr,strlen(xstr));
         for (i=0; i < strlen(ystr); i++,tmpptr++)
             XDrawString(display,gwin,gc,CNVBORD+13+tabptr->wide*ifrx,CNVBORD+40+tabptr->high*ifry+i*10,tmpptr,1);

         XSetForeground(display, gc, BlackPixel(display,screen));

         x1 = 0.0;
         y1 = 0.0;
         x2 = 1.0;
         y2 = 0.0;
         drwgl(gwin,tabptr->wide,tabptr->high,x1,y1,x2,y2,dum0,dum0,ifr,isdash);
         x2 = 0.0;
         y2 = 1.0;
         drwgl(gwin,tabptr->wide,tabptr->high,x1,y1,x2,y2,dum0,dum0,ifr,isdash);

         tick = 5;
         if (nents > 50) tick = 10;
         if (nents > 500) tick = 100;
         if (nents > 1000) tick = 500;

	 if (ityp) {
	    i = min_freq / tick;
	    if (i < 0) i = 0;
	    for (frq=tick*i; frq <= max_freq; frq = frq + tick) {
               if (frq >= 0 && frq <= nents) {
		  x1 = ((frq - min_freq)/freq_step)/scx;
		  y1 = 0.0;
		  x2 = x1;
		  y2 = -0.02;
		  drwgl(gwin,tabptr->wide,tabptr->high,x1,y1,x2,y2,dum0,dum0,
		    ifr,isdash);
		  glpnt(tabptr->wide,tabptr->high,x1,-0.05,&xt,&yt,ifr);
		  sprintf(stemp,"%d",(int) frq);
		  qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
		  if (specps) {
			fprintf(spout,"%d %d m 4 0 (%s) ashow\n",
			  600*(xt-qlen/2)/SPECWIDE,-300*yt/SPECHIGH,stemp);
		  } else {
			XDrawString(display,gwin,gc,xt-qlen/2,yt,stemp,
			  strlen(stemp));
		  }
               }
	    }
	 } else {
	    for (i=0; i<=nents; i = i + tick) {
               if (i >= 0 && i <= nents) {
		  x1 = i/scx;
		  y1 = 0.0;
		  x2 = i/scx;
		  y2 = -0.02;
		  drwgl(gwin,tabptr->wide,tabptr->high,x1,y1,x2,y2,dum0,dum0,
		    ifr,isdash);
		  glpnt(tabptr->wide,tabptr->high,x1,-0.05,&xt,&yt,ifr);
		  sprintf(stemp,"%d",i);
		  qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
		  XDrawString(display,gwin,gc,xt-qlen/2,yt,stemp,strlen(stemp));
               }
	    }
	 }
      }

      if (labstr != NULL) {
         if (! monoscr) XSetForeground(display, gc, colors[icol]);
         else { 
             XSetForeground(display, gc, BlackPixel(display,screen));
             if (isdash) 
                  XSetLineAttributes(display,gc,2,LineOnOffDash,CapButt,JoinMiter);
	     else XSetLineAttributes(display,gc,2,LineSolid,CapButt,JoinMiter);
             XDrawLine(display,gwin,gc,(tabptr->wide-CNVBORD-250)+tabptr->wide*ifrx,CNVBORD+40+isdash*20+tabptr->high*ifry,(tabptr->wide-CNVBORD-250)+tabptr->wide*ifrx,CNVBORD+40+isdash*20+tabptr->high*ifry);
         }

         XSetLineAttributes(display,gc,2,LineSolid,CapButt,JoinMiter);
         XDrawString(display,gwin,gc,(tabptr->wide-CNVBORD-100)+tabptr->wide*ifrx,CNVBORD+40+isdash*20+tabptr->high*ifry,labstr,strlen(labstr));
      }

      if (scy == 0.0) return;

      if (isav != NULL) {
	 itel = -1;
         for (i=1; i <= nents-1; i++) {
            if (isav[i-1] == 1 || notsav) {
	       if (i == *ipnt) itel = tabptr->npts;
               x1 = i/scx;
               y1 = (fpts[i-1]-fminus)/scy;
	       tabptr->index[tabptr->npts] = i-1;
	       glpnt(tabptr->wide,tabptr->high,x1,y1,
		 &tabptr->x[tabptr->npts],&tabptr->y[tabptr->npts],ifr);
	       tabptr->npts++;
               for (j=i+1; j <= nents; j++) {
                 if (isav[j-1] == 1 || notsav) {
                    x2 = j/scx;
                    y2 = (fpts[j-1]-fminus)/scy;
                    drwgl(gwin,tabptr->wide,tabptr->high,x1,y1,x2,y2,
			icol,dum1,ifr,isdash);
		    if (j == nents) {
	       		if (j == *ipnt) itel = tabptr->npts;
			tabptr->index[tabptr->npts] = nents-1;
			glpnt(tabptr->wide,tabptr->high,x2,y2,
			 &tabptr->x[tabptr->npts],&tabptr->y[tabptr->npts],ifr);
			tabptr->npts++;
		    }
                    break;
                 }
               }
            }
         }
	 if (itel >= 0) {
	    XSetForeground(display,gc,colors[15]);
	    XDrawArc(display, gwin, gc, tabptr->x[itel]-10,tabptr->y[itel]-10, 20, 20, 0,360*64);
	 }
      }
      else {
/*
   Leave out first Energy point because the jump is to big, all detail
   of the rest of the curve would be lost
*/
         for (i=jbeg; i <= jend; i++) {
               x1 = (i)/scx;
               y1 = (fpts[i-1]-fminus)/scy;
               x2 = (i+1)/scx;
               y2 = (fpts[i]-fminus)/scy;
	       if (ityp) {
		  if (i <= jend-1) drwgl(gwin,tabptr->wide,tabptr->high,
		                   x1,y1,x2,y2,icol,dum0,ifr,isdash);
	       } else {
		  if (i <= jend-1) drwgl(gwin,tabptr->wide,tabptr->high,
		                   x1,y1,x2,y2,icol,dum1,ifr,isdash);
	                           tabptr->index[tabptr->npts] = i-1;
		  glpnt(tabptr->wide,tabptr->high,x1,y1,
		    &tabptr->x[tabptr->npts],&tabptr->y[tabptr->npts],ifr);
		  tabptr->npts++;
	       }
         }
      }

      if (flim > 0.0) {
         x1 = 0.0;
         y1 = (flim-fminus)/scy;
         x2 = 0.2;
         y2 = y1;
         drwgl(gwin,tabptr->wide,tabptr->high,x1,y1,x2,y2,icol,dum0,ifr,isdash);
      }

}

drwgl(gwin,wide,high,x1,y1,x2,y2,icol,icross,iframe,isdash)
Window gwin;
double x1;
double y1;
double x2;
double y2;
int wide,high;
int icol;
int icross;
int iframe;
int isdash;
{
  int x1t,x2t,y1t,y2t;

  glpnt(wide,high,x1,y1,&x1t,&y1t,iframe);
  glpnt(wide,high,x2,y2,&x2t,&y2t,iframe);

  if (monoscr) XSetForeground(display, gc, colors[0]);
  else XSetForeground(display,gc,colors[icol]);
  if (monoscr && icol) {
   if (isdash) XSetLineAttributes(display, gc, 2, LineOnOffDash, CapButt, JoinMiter);
  }
  if (specps) {
     fprintf(spout,"newpath\n");
     fprintf(spout,"%d %d m %d %d l\n",600*x1t/SPECWIDE,-300*y1t/SPECHIGH,
	600*x2t/SPECWIDE,-300*y2t/SPECHIGH);
     fprintf(spout,"stroke\n");
  } else {
     XDrawLine(display,gwin,gc,x1t,y1t,x2t,y2t);
  }

  if (icross == 1) {
     XDrawLine(display,gwin,gc,x1t-2,y1t-2,x1t+2,y1t+2);
     XDrawLine(display,gwin,gc,x1t-2,y1t+2,x1t+2,y1t-2);
     XDrawLine(display,gwin,gc,x2t-2,y2t-2,x2t+2,y2t+2);
     XDrawLine(display,gwin,gc,x2t-2,y2t+2,x2t+2,y2t-2);
  }
  if (monoscr && icol) {
   XSetLineAttributes(display, gc, 2, LineSolid, CapButt, JoinMiter);
  }
}

glpnt(wide,high,x,y,xr,yr,iframe)
int wide,high;
double x;
double y;
int *xr;
int *yr;
int iframe;
{
  int ifrx,ifry;

  ifrx = 0;
  ifry = 1;
  if (iframe == 3 || iframe == 4) ifrx = 1;
  if (iframe == 2 || iframe == 4) ifry = 2;

  *xr = x*(wide-2*CNVOFFX-2*CNVBORD) + CNVOFFX + CNVBORD + wide*ifrx;
  *yr = high*ifry - (y*(high-2*CNVOFFY-2*CNVBORD) + 1.4*CNVOFFY + CNVBORD);

}

parse_motion(tabptr)
FRSTRU *tabptr;
{
  int qlen,nopnt = 1;

  if (tabptr->npts <= 0) return;

  XSetLineAttributes(display, gc, 2, LineSolid, CapButt, JoinMiter);
  nopnt = FindSel(NULL,tabptr->x,tabptr->y,tabptr->npts,
	event.xmotion.x,event.xmotion.y,GLTOL);

  if (tabptr->current != nopnt) {
     if (tabptr->current != -1) {
        XSetForeground(display, gc, colors[190]);
        XSetFunction(display, gc, GXxor);
	if (tabptr->fpts == (double *) freq) {
	   sprintf(stemp,"%f",freq_scale*freq[tabptr->index[tabptr->current]]);
	} else {
	   sprintf(stemp,"%f",tabptr->fpts[tabptr->index[tabptr->current]]);
	}
        qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
        XDrawString(display,tabptr->win,gc,tabptr->x[tabptr->current]-qlen,
   	  tabptr->y[tabptr->current]+tabptr->yelev,stemp,strlen(stemp));
        XSetFunction(display, gc, GXcopy);
        XSetForeground(display, gc, colors[tabptr->color]);
        XDrawLine(display,tabptr->win,gc,tabptr->x[tabptr->current]-2,
   	  tabptr->y[tabptr->current]-2,tabptr->x[tabptr->current]+2,
   	  tabptr->y[tabptr->current]+2);
        XDrawLine(display,tabptr->win,gc,tabptr->x[tabptr->current]-2,
	  tabptr->y[tabptr->current]+2,tabptr->x[tabptr->current]+2,
	  tabptr->y[tabptr->current]-2);
     }
     if (nopnt != -1) {
        XSetForeground(display, gc, colors[190]);
        XSetFunction(display, gc, GXxor);
	if (tabptr->fpts == (double *) freq) {
           sprintf(stemp,"%f",freq_scale*freq[tabptr->index[nopnt]]);
	} else {
           sprintf(stemp,"%f",tabptr->fpts[tabptr->index[nopnt]]);
	}
        qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
        XDrawString(display,tabptr->win,gc,tabptr->x[nopnt]-qlen,
   	  tabptr->y[nopnt]+tabptr->yelev,stemp,strlen(stemp));
        XSetFunction(display, gc, GXcopy);
        XSetForeground(display, gc, BlackPixel(display, screen));
        XDrawLine(display,tabptr->win,gc,tabptr->x[nopnt]-2,tabptr->y[nopnt]-2,
   	  tabptr->x[nopnt]+2,tabptr->y[nopnt]+2);
        XDrawLine(display,tabptr->win,gc,tabptr->x[nopnt]-2,tabptr->y[nopnt]+2,
	  tabptr->x[nopnt]+2,tabptr->y[nopnt]-2);
     }
  }
  tabptr->current = nopnt;
  XSetLineAttributes(display, gc, 1, LineSolid, CapButt, JoinMiter);
}

parse_label(Ca,l,ix,iy)
int Ca;
int l;
int *ix;
int *iy;
{
      int x,y;

/* only visible atoms have non-zero ixp and iyp values */

      if ((Ca >= 0 && Ca != rsold) || (Ca <= -4 && Ca != rsold) || 
		(Ca == RESUND && rsold != RESUND)) {

	 if ( !(*fancy && has_opengl && !StarNet) ) {
           if (rsold != RESUND)
	       XCopyArea(display,bckwin,win,gc,0,0,BckW,BckH,bckx,bcky);
	 }

	 strcpy(atemp,"               ");

	 if ( ( (Ca >= 0 && Ca != rsold) || (Ca <= -4 && Ca != rsold) ) 
		&& Ca != RESUND) {

           
	   if (Ca >= 0) l = calfptr->icalf[Ca][0]-1;
	   x = iy[l];
	   y = ix[l];
           
	   if (Ca >= 0) {
		sprintf(atemp,"%3s %3d ",AminoAcids[calfptr->iamino[Ca]-1],
					 irsnr[Ca]);
	   } else {
		sprintf(atemp,"%3s     ",HetAtm[abs(Ca)]);
	   }
	   atemp[9] = '\0';

	   if (*fancy && has_opengl && !StarNet) {
#ifdef DOGL
	      dispsf();
	      printString(x,y,1,atemp);
#endif
	   } else {
	      foreground_pixel = colors[15];
	      XSetForeground(display, gc, foreground_pixel);
	      XCopyArea(display,win,bckwin,gc,x,y-20,BckW,BckH,0,0);
	      XDrawString(display, win, gc, x, y, atemp, 8);
	   }


	   bckx = x; bcky = y-20;
	 } else if (Ca == RESUND && rsold != RESUND) {
#ifdef DOGL
	   if (*fancy && has_opengl && !StarNet) dispsf();
#endif
	 }
	 rsold = Ca;
      }
}

parse_labelp(Ca,l,ix,iy)
int Ca;
int l;
int *ix;
int *iy;
{
      int x,y;

      if ( (Ca >= 0 && Ca != rsold && !(*fancy && has_opengl)) 
	|| (Ca <= -4 && Ca != rsold) || 
	   (Ca == RESUND && rsold != RESUND)) {

	 if ( !(*fancy && has_opengl && !StarNet) ) {
           if (rsold != RESUND)
	       XCopyArea(display,bckwin,win,gc,0,0,BckW,BckH,bckx,bcky);
	 }

	 strcpy(atemp,"        ");
	 if ( ( (Ca >= 0 && Ca != rsold) || (Ca <= -4 && Ca != rsold) ) 
		&& Ca != RESUND) {

	   if (Ca >= 0) {
            /*this gives a wrong position for res label */
		x = calfpptr->icyp[Ca];
		y = calfpptr->icxp[Ca];
	   } else {
		x = iy[l];
		y = ix[l]-20;
	   }

	   if (Ca >= 0) {
		sprintf(atemp,"%3s %3d ",AminoAcids[calfptr->iamino[Ca]-1],
					 irsnr[Ca]);
	   } else {
		sprintf(atemp,"%3s     ",HetAtm[abs(Ca)]);
		sprintf(atemp,"%3s     ",HetAtm[abs(Ca+1)]);
	   }

	   if (*fancy && has_opengl && !StarNet) {
#ifdef DOGL
	      dispsf();
	      printString(x,y,1,atemp);
#endif
	   } else {
	      foreground_pixel = colors[15];
	      XSetForeground(display, gc, foreground_pixel);
	      XCopyArea(display,win,bckwin,gc,x,y-20,BckW,BckH,0,0);
	      XDrawString(display, win, gc, x, y, atemp, 8);
	   }


	   bckx = x; bcky = y-20;
	 } else if (Ca == RESUND && rsold != RESUND) {
#ifdef DOGL
	   if (*fancy && has_opengl && !StarNet) dispsf();
#endif
	 }
	 rsold = Ca;
      }
}

int FindSel(onoff,x,y,num_items,cursorx,cursory,mindiff)
int *onoff;
int *x;
int *y;
int num_items;
int cursorx,cursory;
int mindiff;
{
    int i,irt,dx,dy,dsqr,dsq_min,found,oke;

    found = -1;
    dsq_min = mindiff*mindiff;
    for ( i = 0; i < num_items; i++ ) {
      oke = 0;
      if (onoff == NULL) oke = 1;
      else if (onoff[i] >= 1) oke = 1;
      if (oke) {
	  dx = ABS(cursorx - x[i]);
	  dy = ABS(cursory - y[i]);
	  dsqr = dx*dx + dy*dy;
          if (dx < mindiff && dy < mindiff && dsqr < dsq_min ) {
		dsq_min = dsqr;
		found = i;
          }
      }
    }
/* below is to accomodate to find a Calfa, because when in the upper loop it
   find Calfa it is from the secondary structure visualsation because these
   always come last in the atom array, so actually not the real Calfa is found
   but the visualisation Calfa (ianz = 100)
*/
    if ((found == -1 || (found != -1 && xyz.ianz[found] == 100 )) && *ipdbon && onoff != NULL) {
	irt = FindCa(onoff,x,y,cursorx,cursory,mindiff);
	if (irt != -1) irt = calfptr->icalf[irt][0]-1; 
	return(irt);
    } else return (found);
}

int FindCa(onoff,x,y,cursorx,cursory,mindiff)
int *onoff;
int *x;
int *y;
int cursorx,cursory;
int mindiff;
{
    int i,j,l,dx,dy,dsqr,dsq_min,dsq_minz,found,oke;
    double dz, dzmin;

    found = -1;
    dsq_min = mindiff*mindiff;
    dsq_minz = mindiff*mindiff;
    if (has_opengl && *fancy) {
	dzmin = 1000000;
    } else {
	dzmin = -1000000;
    }
    for ( i = 0; i < calfptr->ncalf; i++ ) {
     for ( j = 0; j < 4; j++ ) {
      l = calfptr->icalf[i][j]-1;
      oke = 0;
      if (onoff == NULL) oke = 1;
      else if (onoff[l] >= 1) oke = 1;
      if (1) {
	  dx = ABS(cursorx - x[l]);
	  dy = ABS(cursory - y[l]);
	  dz = xyz.rzp[l];
	  dsqr = dx*dx + dy*dy;
          if (dx < mindiff && dy < mindiff && dsqr < dsq_min) {
	     if (has_opengl && *fancy) {
		if (dz < dzmin) {
	 	  dzmin = dz;
		  found = i;
		}
	     } else {
		if (dz > dzmin) {
	 	  dzmin = dz;
		  found = i;
		}
	     }
          }
      }
     }
    }
    return (found);
}

int FindCaP(cursorx,cursory,mindiff)
int cursorx,cursory;
int mindiff;
{
    int i,dx,dy,dsqr,dsq_min,found;

    found = -1;
    dsq_min = mindiff*mindiff;
    for ( i = 0; i < calfptr->ncalf; i++ ) {
	dx = ABS(cursorx - calfpptr->icyp[i]);
	dy = ABS(cursory - calfpptr->icxp[i]);
	dsqr = dx*dx + dy*dy;
        if (dx < mindiff && dy < mindiff && dsqr < dsq_min) {
	  found = i;
        }
    }
    return (found);
}

#if defined(VMS) || defined(UNDERSC)
labnr(isup)
#else
#ifdef CRAY
LABNR(isup)
#else
labnr_(isup)
#endif
#endif

int *isup;
{
    if (ZMEup&&*zmptr.ihaszm) *isup = 1;
    else *isup = 0;
}

InitZME()
{
   int i;
   
   ZMEup = 1;

   ZME_window_pos = 0;
   ZMEmode = 0;
   ZMEsel = 0;

   ZMEanW  = XTextWidth(mfinfo,"  ",2)+3*QBOXFR+2*QBOXBORD;
   ZMEconW = XTextWidth(mfinfo,"   ",3)+3*QBOXFR+2*QBOXBORD;
   ZMEbutW = XTextWidth(mfinfo,"   ",3)+2*QBOXBORD+3;
   ZMEvarW = XTextWidth(mfinfo,"------------",11)+3*QBOXFR+2*QBOXBORD;
   ZMEvarWs = XTextWidth(mfinfo,"--------",8)+3*QBOXFR+2*QBOXBORD;
   ZMEiz4W = XTextWidth(mfinfo,"-",1)+3*QBOXFR+2*QBOXBORD;
   ZMEiz   = ZMEanW+ZMETab2+ZMEvarW+ZMETab3;
   ZMEizs  = ZMEvarWs;
   ZMEZWIDE = ZMEBord + ZMETab1 + 3*ZMEiz + ZMEiz4W + ZMEBord;

   XMapWindow(display,ZMEwin);


   DefBut(&ZMEbut[ZMECANC], ZMEwin, ZMEZOffx+ZMEZWIDE+ZMESCR-30, 5, 
	50, 23, "Close", infobg, ZMBCOL);
   ZMEbut[ZMECANC].explstr = "Close the Z-Matrix window";

   DefBut(&ZMEbut[ZMEARR1], ZMEwin, ZMEZOffx+ZMEZWIDE+ZMESCR, ZMEZOffy , 
	23, 23, " ", infobg, 0);
   DefBut(&ZMEbut[ZMEARR2], ZMEwin, ZMEZOffx+ZMEZWIDE+ZMESCR, 
	ZMEZOffy+ZME_window_high*ZMEQHIGH+ZMEBord-22, 23, 23, " ", infobg, 0);
 
   DefBut(&ZMEbut[ZMEAPPL], ZMEwin, ZMEZOffx, ZMEButOffy, 
	ZMEBW2, 23, "Apply Changes to current Z-Mat", infobg, ZMBCOL);
   ZMEbut[ZMEAPPL].explstr = "Update on screen structure by applying the current Z-matrix\nHitting Enter/Return in the variable fields has the same effect";

   DefBut(&ZMEbut[ZMECAN1], ZMEwin, ZMEZOffx, ZMEButOffy+ZMEBWIDE, 
	ZMEBW2, 23, "Cancel Non-Applied Changes", infobg, ZMBCOL);
   ZMEbut[ZMECAN1].explstr = "Restore values of the Z-matrix the last time it was applied";

   DefBut(&ZMEbut[ZMEDEL], ZMEwin, ZMEZOffx, ZMEButOffy+2*ZMEBWIDE, 
	ZMEBW4, 23, "Delete Line", infobg, ZMBCOL);
   ZMEbut[ZMEDEL].explstr = "Delete a line from Z-matrix ==\nDelete an atom/dummy from the structure:\nLines can ONLY be removed when no other lines\nuse it as reference.\nIf there are references, remove those first";

   DefBut(&ZMEbut[ZMEADD], ZMEwin, 2*ZMEZOffx+ZMEBW4, ZMEButOffy+2*ZMEBWIDE, 
	ZMEBW4, 23, "Add Line", infobg, ZMBCOL);
   ZMEbut[ZMEADD].explstr = "Add line to Z-matrix ==\nAdd an atom/dummy to your structure";

   DefBut(&ZMEbut[ZMEFRG], ZMEwin, ZMEZOffx, ZMEButOffy+3*ZMEBWIDE, 
	ZMEBW2, 23, "Substitute atom by Fragment", infobg, ZMBCOL);
   ZMEbut[ZMEFRG].explstr = "Substitute active atom/line\nby the fragment you select";

   DefBut(&ZMEbut[ZMENEW], ZMEwin, ZMEZOffx, ZMEButOffy+4*ZMEBWIDE, 
	ZMEBW4, 23, "New Z-mat", infobg, ZMBCOL);
   ZMEbut[ZMENEW].explstr = "Clear Z-Matrix.\nSame as start with empty structure";
   DefBut(&ZMEbut[ZMEMAP], ZMEwin, 2*ZMEZOffx+ZMEBW4, ZMEButOffy+4*ZMEBWIDE, 
	ZMEBW4, 23, "MapXYZ/Optimise", infobg, ZMBCOL);
   ZMEbut[ZMEMAP].explstr = "Convert a structure from file to the current Z-matrix.\nUseful if the optimised structure is only available as XYZ.\nBut you need it as Z-matrix\nAlso interfaces to external optimisers are available";
	
   DefBut(&ZMEbut[ZMECVAR], ZMEwin, ZMEZOffx+ZMEWINW/2, ZMEButOffy, 
	ZMEBW2, 23, "Set Status All Variables", infobg, ZMBCOL);
   ZMEbut[ZMECVAR].explstr = "Treat all bond distances, bond angles and dihedral angles\neither as variable or constant.\nIndividual variables can be set by cicking\nwith the second mouse button in the variable field";

   DefBut(&ZMEbut[ZMEORD],  ZMEwin, ZMEZOffx+ZMEWINW/2, ZMEButOffy+2*ZMEBWIDE,
	ZMEBW2, 23, "Reorder Z-matrix", infobg, ZMBCOL);
   ZMEbut[ZMEORD].explstr = "Reorder the Z-matrix by clicking on screen atoms\nin the order you want the Z-matrix to be\nYou can abort the specification after any number of clicked atoms\nMolden will supply the remaining ones";

   DefBut(&ZMEbut[ZMESEL], ZMEwin, ZMEZOffx+ZMEWINW/2, ZMEButOffy+3*ZMEBWIDE, 
	ZMEBW4, 23, "Select by pointer", infobg, ZMBCOL);
   ZMEbut[ZMESEL].explstr = "Select a substructure of on screen atoms of which a Z-matrix will be generated\nSelecting: click first mouse button,\ndrag while keeping the mouse button pressed.\nUse in combination with DeSelect and Apply Selection";

   DefBut(&ZMEbut[ZMEUSEL],ZMEwin, 2*ZMEZOffx+ZMEWINW/2+ZMEBW4, 
	ZMEButOffy+3*ZMEBWIDE, ZMEBW4, 23, "DeSelect", infobg,ZMBCOL);
   ZMEbut[ZMEUSEL].explstr = "Deselect on screen atoms of which a Z-matrix will be generated\nSelecting: click first mouse button,\ndrag while keeping the mouse button pressed.\nUse in combination with Select by pointer and Apply Selection";

   DefBut(&ZMEbut[ZMESELA],ZMEwin, ZMEZOffx+ZMEWINW/2, ZMEButOffy+4*ZMEBWIDE, 
	ZMEBW2, 23, "Apply Selection", infobg, ZMBCOL);
   ZMEbut[ZMESELA].explstr = "Generate Z-matrix of selected on screen atoms.\nUse in combination with Select by pointer and DeSelect";

   DefBut(&ZMEbut[ZMEGAM], ZMEwin, ZMEZOffx+75,ZMEWOffy+ZMEWBOFF , 23, 23, 
        	   " ", infobg, ZMBCOL);
   ZMEbut[ZMEGAM].explstr = "In combination with the Write Z-Matrix button:\nWrite the Z-matrix in Gamess format.\nIn combination with the Submit Job button\nSubmit a Gamess job";

   DefBut(&ZMEbut[ZMEGAU], ZMEwin, ZMEZOffx+175,ZMEWOffy+ZMEWBOFF, 23, 23, 
        	   " ", infobg, ZMBCOL);
   ZMEbut[ZMEGAU].explstr = "In combination with the Write Z-Matrix button:\nWrite the Z-matrix in Gaussian format.\nIn combination with the Submit Job button\nSubmit a Gaussian job";

   DefBut(&ZMEbut[ZMEMOP], ZMEwin, ZMEZOffx+275,ZMEWOffy+ZMEWBOFF, 23, 23, 
        	   " ", infobg, ZMBCOL);
   ZMEbut[ZMEMOP].explstr = "In combination with the Write Z-Matrix button:\nWrite the Z-matrix in MOPAC format.\nIn combination with the Submit Job button\nSubmit a MOPAC job";

   DefBut(&ZMEbut[ZMECAR], ZMEwin, ZMEZOffx+375,ZMEWOffy+ZMEWBOFF, 23, 23, 
        	   " ", infobg, ZMBCOL);
   DefBut(&ZMEbut[ZMEWRT], ZMEwin, ZMEZOffx,ZMEWOffy+10, ZMEBW2, 23, 
        	   "Write Z-Matrix", infobg, ZMBCOL);
   ZMEbut[ZMEWRT].explstr = "Write the current Z-Matrix\nIn combination with the format buttons";

   DefBut(&ZMEbut[ZMESUB], ZMEwin, ZMEZOffx+ZMEWINW/2,ZMEWOffy+10, 
		ZMEBW2, 23, "Submit Job", infobg, ZMBCOL);
   ZMEbut[ZMESUB].explstr = "Submit a Gaussian/Gamess/MOPAC job\nIn combination with the format buttons";

   DefBut(&ZMEBbut[ZMESIN], ZMEwin, ZMEZOffx+145,ZMEButOffy , 23, 23, 
        	   " ", infobg, ZMBCOL);
   ZMEBbut[ZMESIN].explstr = "Select bond distance and bond angle for a single bond";

   DefBut(&ZMEBbut[ZMEDBL], ZMEwin, ZMEZOffx+145,ZMEButOffy+ZMEBWIDE, 23, 23, 
        	   " ", infobg, ZMBCOL);
   ZMEBbut[ZMEDBL].explstr = "Select bond distance and bond angle for a double bond";

   DefBut(&ZMEBbut[ZMETRI], ZMEwin, ZMEZOffx+145,ZMEButOffy+2*ZMEBWIDE, 23, 23, 
        	   " ", infobg, ZMBCOL);
   ZMEBbut[ZMETRI].explstr = "Select bond distance and bond angle for a triple bond";

   DefBut(&ZMEswitch[0], ZMEwin, ZMEZOffx+ZMEZWIDE+ZMESCR-110,
	ZMEZOffy-ZMEFRBord+ZMEZHIGH-TOGGWH-1, TOGGWH, TOGGWH, " ", infobg, ZMBCOL);

   DefBut(&ZMEswitch[1], ZMEwin, ZMEZOffx+ZMEZWIDE+ZMESCR-55,
	5, 23, 23, " ", infobg, ZMBCOL);

   ZMEswitch[1].pix = BigPix;
   ZMEswitch[1].pw  = bigsmall_width;
   ZMEswitch[1].ph  = bigsmall_height;

   DefBut(&ZMEbut[ZMEUS], ZMEwin, ZMEZOffx+105,ZMEWOffy+ZMEWBOFF+18 , 15, 15, 
        	   " ", infobg, ZMBCOL);
   ZMEbut[ZMEUS].explstr = "Switch between Gamess-UK and Gamess-US format";

   ActBut(&ZMEbut[ZMEopt],-1);
   TogDown(&ZMEbut[ZMEopt]);
   ActBut(&ZMEBbut[ZMEmul],-1);
   TogDown(&ZMEBbut[ZMEmul]);
   if (ZMEAA) {
	TogUp(&ZMEswitch[0]);
   } else {
	TogDown(&ZMEswitch[0]);
   }
   if (ZMEbig) {
	TogUp(&ZMEswitch[1]);
   } else {
	TogDown(&ZMEswitch[1]);
   }
   if (SUBup) TogDown(&ZMEbut[ZMESUB]);
   ZMEbut[ZMEARR1].pix = upPix;
   ZMEbut[ZMEARR1].pw  = up_width;
   ZMEbut[ZMEARR1].ph  = up_height;
 
   ZMEbut[ZMEARR2].pix = downPix;
   ZMEbut[ZMEARR2].pw  = down_width;
   ZMEbut[ZMEARR2].ph  = down_height;

   qboxstr(&qboxes[QBZMAT],&ZMEwin,0,0,190,ZMEZOffx,ZMEWOffy+40,
      ZMEZWIDE,QBOXHIGH,2,"File name ? ",NULL,0,0,470,dummyproc);

   qboxstr(&EXPbox[0],&ZMEwin,0,0,190,ZMEZOffx+225,ZMEZOffy-ZMEFRBord+
	   ZMEZHIGH-TOGGWH,130,QBOXHIGH-9,2,"Expr.",NULL,10,0,2000,dummyproc);
   if (ZMEAA) EXPbox[0].fake = 0;
   else EXPbox[0].fake = 1;

   for (i=0; i < TABBUTN; i++) {
	if (i==TABBUTN-1)
   	DefBut(&TabBut[i],ZMEwin, ZMEZOffx+ZMEBord+TabPos[i][1]*(ZMETABH+1), ZMEZOffy+ZMEBord+TabPos[i][0]*(ZMETABH+1), ZMETABH, ZMETABH, 
        	   elements[99], infobg, -scalptr->icol[98]);
	else
   	DefBut(&TabBut[i],ZMEwin, ZMEZOffx+ZMEBord+TabPos[i][1]*(ZMETABH+1), ZMEZOffy+ZMEBord+TabPos[i][0]*(ZMETABH+1), ZMETABH, ZMETABH, 
        	   elements[i+1], infobg, -scalptr->icol[i]);
   }

   SetQZME();

   DefScroll(&zscroll,ZMEwin,ZMEZOffx+ZMEZWIDE+ZMESCR,ZMEZOffy+22,22,
             ZME_window_high*ZMEQHIGH+ZMEBord-2*22,zmptr.nz,
	    &ZME_window_pos,ZME_window_high);

   strcpy(ZMEerr,"Use Mouse Button 2 to change the status of a variable");

   if (ZMEAA) make_aa();
}

UnMapZME()
{
	SwitchOffAnim();
	TogUp(&cbut[BZMAT]);
	ZMEup = 0;
	XUnmapWindow(display,ZMEwin);
	ZoomEnable = False; ZoomSelection = False;
	DeActZME(); 
	ActBut(&cbut[BDIST],1);
	ActBut(&cbut[BANGLE],1);
	ActBut(&cbut[BDIHED],1);
        if (backb) {ActBut(&cbut[BDECRF],1); ActBut(&cbut[BUNSC],1);}
        ActBut(&cbut[BREADF],1);
        if (denm) ActBut(&cbut[BDENMOD],1);
}

RedrawZME()
{
   int i,ZMEx,ZMEy;

   if (!ZMEup) return;

   ZMEy = 20;
   ZMEx = ZMEZOffx + ZMEBord + 5;
   XDrawString(display,ZMEwin,gc,ZMEx,ZMEy,"Atom",4);
   ZMEx = ZMEx + ZMETab1 + ZMEconW + ZMETab2;

   if (monoscr) {
       XSetFillStyle(display, gc, FillStippled);
       XSetStipple(display, gc, hlfgrey);
       XSetForeground(display, gc, infobg);
       XFillRectangle(display, ZMEwin, gc, 0, ZMEZOffy-ZMEFRBord, ZMEWINW, ZMEZHIGH+1);
       XSetFillStyle(display,gc,FillSolid);}
   else {
	butje(ZMEwin,0,0,ZMEWINW-1,ZMEZOffy-ZMEFRBord+1,1,0,0,1,None,0,0,0);
        XSetForeground(display, gc, infobg);
	butje(ZMEwin,0,ZMEZOffy-ZMEFRBord,ZMEWINW-1,ZMEZHIGH,1,0,0,1,None,0,0,0);
   }
   if (ZMEAA) {
	XDrawString(display,ZMEwin,gc,ZMEZOffx+ZMETab1+15+0*ZMEizs,45,"Phi",3);
	XDrawString(display,ZMEwin,gc,ZMEZOffx+ZMETab1+15+1*ZMEizs,45,"Psi",3);
	XDrawString(display,ZMEwin,gc,ZMEZOffx+ZMETab1+15+2*ZMEizs,45,"Chi1",4);
	XDrawString(display,ZMEwin,gc,ZMEZOffx+ZMETab1+15+3*ZMEizs,45,"Chi2",4);
	XDrawString(display,ZMEwin,gc,ZMEZOffx+ZMETab1+15+4*ZMEizs,45,"Chi3",4);
	XDrawString(display,ZMEwin,gc,ZMEZOffx+ZMETab1+15+5*ZMEizs,45,"Chi4",4);
   } else {
	XDrawString(display,ZMEwin,gc,ZMEx,ZMEy,"BondLength",10);
	XDrawString(display,ZMEwin,gc,ZMEx+ZMEiz,ZMEy,"BondAngle",9);
	XDrawString(display,ZMEwin,gc,ZMEx+2*ZMEiz,ZMEy,"DiHedral",8);
   }

   butje(ZMEwin,0,ZMEZOffy-ZMEFRBord+ZMEZHIGH-1,ZMEWINW/2+1,ZMEBHIGH,1,0,0,1,None,0,0,0);
   butje(ZMEwin,ZMEWINW/2,ZMEZOffy-ZMEFRBord+ZMEZHIGH-1,ZMEWINW/2,ZMEBHIGH,1,0,0,1,None,0,0,0);
   RedrawStatus();
   butje(ZMEwin,0,ZMEWOffy-3,ZMEWINW-1,ZMEWHIGH,1,0,0,1,None,0,0,0);

   butje(ZMEwin, ZMEZOffx+1, ZMEZOffy, ZMEZWIDE-1, ZME_window_high*ZMEQHIGH+ZMEBord+1,2,0,2,0,None,0,0,0);

   UpdateZME();

   if (ZMEsel || ZMEmode) {
   	for (i=0; i<3; i++) DrwBut(&ZMEBbut[i]);
	ULineString(ZMEwin, "Bond Length:", ZMEZOffx+3 ,ZMEButOffy+15);
	LineString(ZMEwin, "Single", ZMEZOffx+190  ,ZMEButOffy+15);
	LineString(ZMEwin, "Double", ZMEZOffx+190 ,ZMEButOffy+ZMEBWIDE+15);
	LineString(ZMEwin, "Triple", ZMEZOffx+190 ,ZMEButOffy+2*ZMEBWIDE+15);
	return;
   }

   if (pdb) LineString(ZMEwin, "Full Z-Mat", ZMEZOffx+ZMEZWIDE+ZMESCR-80,
	ZMEZOffy-ZMEFRBord+ZMEZHIGH-ZMETABA+16);

   RedrawScroll(&zscroll);
   for (i=0; i<ZMEBUTTS; i++) DrwBut(&ZMEbut[i]);
   if (pdb && ! *ialtyp) DrwBut(&ZMEswitch[0]);
   DrwBut(&ZMEswitch[1]);

   PromptBox(&qboxes[QBZMAT]);
   ULineString(ZMEwin, "New Z-mat from screen coordinates:", ZMEZOffx+ZMEWINW/2+5 ,ZMEButOffy+15+ZMEBWIDE);
   ULineString(ZMEwin, "Format:", ZMEZOffx ,ZMEWOffy+ZMEWBOFF+15);
   LineString(ZMEwin, "Gamess"           , ZMEZOffx+75+30 ,ZMEWOffy+ZMEWBOFF+15);
   LineString(ZMEwin, "US", ZMEZOffx+125 ,ZMEWOffy+ZMEWBOFF+30);
   LineString(ZMEwin, "Gaussian"         , ZMEZOffx+175+30 ,ZMEWOffy+ZMEWBOFF+15);
   LineString(ZMEwin, "Mopac"            , ZMEZOffx+275+30 ,ZMEWOffy+ZMEWBOFF+15);
   LineString(ZMEwin, "Cartesian"        , ZMEZOffx+375+30 ,ZMEWOffy+ZMEWBOFF+15);
}

RedrawStatus()
{

 if (!ZMEup) return;

 butje(ZMEwin,0,ZMEZOffy-ZMEFRBord+ZMEZHIGH+ZMEBHIGH-2,ZMEWINW-1,ZMESHIGH,1,0,0,1,None,0,0,0);
 butje(ZMEwin,ZMEZOffx,ZMEZOffy-ZMEFRBord+ZMEZHIGH+ZMEBHIGH+8,ZMEZWIDE,20,2,0,2,0,None,0,0,0);
 XSetForeground(display, gc, infobg);
 XDrawString(display,ZMEwin,gc,ZMEZOffx+5,ZMEZOffy-ZMEFRBord+ZMEZHIGH+ZMEBHIGH+22,ZMEerr,strlen(ZMEerr));
}

UpdateZME()
{
   int i,j,k;
   int ZMEx,ZMEy,ZMESx,ZMESy;
   int isvis,isaa;

   if (DEBUG) fprintf(stderr,"UpdateZME in\n");
   if (!ZMEup) return;

   if (ZMEmode) {
	strcpy(ZMEerr,"Select Atom");
	RedrawStatus();
	for (i=0; i<TABBUTN; i++) DrwBut(&TabBut[i]);
	return;
   }

   if (ZMEAA) {

	for (i=0; i<*zmptr.nz; i++) {
	   BETbox[i].x = 0;
	   BETbox[i].y = 0;
	}

	zscroll.wn = &calfptr->ncalf;

	if (ZME_window_pos > calfptr->ncalf-1-ZME_window_high) {
	    if (calfptr->ncalf-1-ZME_window_high >= 0) {
		ZME_window_pos = calfptr->ncalf-ZME_window_high;
            } else ZME_window_pos = 0;
	}


        ZMESy = ZMEZOffy-ZMEFRBord+ZMEZHIGH-ZMETABA; 
        j = 0;
	for (i=0; i<calfptr->ncalf; i++) {

	   isvis = (i >= ZME_window_pos && i < ZME_window_pos + ZME_window_high);
	   if (isvis) {
		ZMEx = ZMEZOffx + ZMEBord - 3;
		ZMEy = ZMEZOffy + ZMEBord + (i - ZME_window_pos)*ZMEQHIGH;
		ZMESx = ZMEZOffx + ZMETab1 + 5 + j*ZMETABA;
	   } else {
		ZMEx = 0;
		ZMEy = 0;
	   }

           isaa = (*aaptr[i].iamino <= 23);

           if (isvis) {
		DefBut(&ZMEAAbut[j], ZMEwin, ZMEx, ZMEy, ZMEbutW, ZMETABH+2, 
        	   AminoAcids[*aaptr[i].iamino-1], infobg, 
		   -calfptr->iamicl[*aaptr[i].iamino-1]);
		if (i == CurAmino) {
			ZMEAAbut[j].lastused = 1;
			ZMEAAbut[j].bg = 1;
		} else {
			ZMEAAbut[j].lastused = -1;
			ZMEAAbut[j].bg = 196;
		}
		DefBut(&ZMEAASbut[j], ZMEwin, ZMESx, ZMESy, ZMETABA, ZMETABA, 
        	   AAlet[*aaptr[i].iamino-1], infobg, 
		   -calfptr->iamicl[*aaptr[i].iamino-1]);
		ZMEx = ZMEZOffx + ZMETab1 + 5 ;
		j++;
	   }

	   if (isaa) {
		BETbox[aaptr[i].phi].x = ZMEx;
		BETbox[aaptr[i].phi].y = ZMEy;
		if (isvis) PromptBox(&BETbox[aaptr[i].phi]);

		if (isvis) ZMEx = ZMEZOffx + ZMETab1 + 5 + 1*ZMEizs;
		BETbox[aaptr[i].psi].x = ZMEx;
		BETbox[aaptr[i].psi].y = ZMEy;
		if (isvis) PromptBox(&BETbox[aaptr[i].psi]);

		if (isvis) ZMEx = ZMEZOffx + ZMETab1 + 5 + 2*ZMEizs;
		if (aaptr[i].chi1 > -1) {
		   BETbox[aaptr[i].chi1].x = ZMEx;
		   BETbox[aaptr[i].chi1].y = ZMEy;
		   if (isvis) PromptBox(&BETbox[aaptr[i].chi1]);
		} else {
		   if (isvis) PFake(ZMEwin,ZMEx,ZMEy,ZMEvarWs,ZMEQHIGH,196);
		}

		if (isvis) ZMEx = ZMEZOffx + ZMETab1 + 5 + 3*ZMEizs;
		if (aaptr[i].chi2 > -1) {
		   BETbox[aaptr[i].chi2].x = ZMEx;
		   BETbox[aaptr[i].chi2].y = ZMEy;
		   if (isvis) PromptBox(&BETbox[aaptr[i].chi2]);
		} else {
		   if (isvis) PFake(ZMEwin,ZMEx,ZMEy,ZMEvarWs,ZMEQHIGH,196);
		}

		if (isvis) ZMEx = ZMEZOffx + ZMETab1 + 5 + 4*ZMEizs;
		if (aaptr[i].chi3 > -1) {
		   BETbox[aaptr[i].chi3].x = ZMEx;
		   BETbox[aaptr[i].chi3].y = ZMEy;
		   if (isvis) PromptBox(&BETbox[aaptr[i].chi3]);
		} else {
		   if (isvis) PFake(ZMEwin,ZMEx,ZMEy,ZMEvarWs,ZMEQHIGH,196);
		}

		if (isvis) ZMEx = ZMEZOffx + ZMETab1 + 5 + 5*ZMEizs;
		if (aaptr[i].chi4 > -1) {
		   BETbox[aaptr[i].chi4].x = ZMEx;
		   BETbox[aaptr[i].chi4].y = ZMEy;
		   if (isvis) PromptBox(&BETbox[aaptr[i].chi4]);
		} else {
		   if (isvis) PFake(ZMEwin,ZMEx,ZMEy,ZMEvarWs,ZMEQHIGH,196);
		}

	   } else {

		if (isvis) {
		   for (k=0; k<6; k++) {
			ZMEx = ZMEZOffx + ZMETab1 + 5 + k*ZMEizs;
			PFake(ZMEwin,ZMEx,ZMEy,ZMEvarWs,ZMEQHIGH,196);
		   }
		}
	   }
	}

        for (i=0; i<ZME_window_high; i++) {
	   if (i<calfptr->ncalf) {
		DrwBut(&ZMEAAbut[i]);
		DrwBut(&ZMEAASbut[i]);
	   }
	}
	ZMEx = ZMEZOffx + ZMEBord - 3;
        ZMESx = ZMEZOffx + ZMETab1;
        XSetForeground(display, gc, colors[190]);
	XFillRectangle(display, ZMEwin, gc,
                                ZMEx, ZMESy+3, 30, ZMETABA-4);
	sprintf(ZMEups,"%-4d",ZME_window_pos+1);
        XSetForeground(display, gc, colors[0]);
	XDrawString(display,ZMEwin,gc,ZMEx+5,ZMESy+17,ZMEups,4);
        EXPbox[0].fake = 0;
	PromptBox(&EXPbox[0]);

	return;
   }

   zscroll.wn = zmptr.nz;

   if (ZME_window_pos > *zmptr.nz-1-ZME_window_high) {
	if (*zmptr.nz-1-ZME_window_high >= 0) {
	    ZME_window_pos = *zmptr.nz-ZME_window_high;
        } 
	else ZME_window_pos = 0;
   }

   for (i=0; i<*zmptr.nz; i++) {
	isvis = (i >= ZME_window_pos && i < ZME_window_pos + ZME_window_high);
	if (isvis) {
	   ZMEx = ZMEZOffx + ZMEBord;
	   ZMEy = ZMEZOffy + ZMEBord + (i - ZME_window_pos)*ZMEQHIGH;
	}
	else {
	   ZMEx = 0;
	   ZMEy = 0;
	}
	IANZbox[i].x = ZMEx;
	IANZbox[i].y = ZMEy;
	if (isvis) PromptBox(&IANZbox[i]);
	for (j=0; j<3; j++) {
		if (isvis) ZMEx = ZMEZOffx + ZMEBord + ZMETab1 + j*ZMEiz;
	   	IZbox[i*4+j].x = ZMEx;
	   	IZbox[i*4+j].y = ZMEy;
		if (isvis) PromptBox(&IZbox[i*4+j]);
		if (isvis) ZMEx = ZMEx + ZMEconW + ZMETab2;
		if (j == 0) {
	   	   BLbox[i].x = ZMEx;
	   	   BLbox[i].y = ZMEy;
		   if (isvis) PromptBox(&BLbox[i]);
		}
		else if (j == 1) {
	   	   ALPHbox[i].x = ZMEx;
	   	   ALPHbox[i].y = ZMEy;
		   if (isvis) PromptBox(&ALPHbox[i]);
		}
		else if (j == 2) {
	   	   BETbox[i].x = ZMEx;
	   	   BETbox[i].y = ZMEy;
		   if (isvis) PromptBox(&BETbox[i]);
		}
	}
	if (isvis) ZMEx = ZMEZOffx + ZMEBord + ZMETab1 + 3*ZMEiz;
	IZbox[i*4+3].x = ZMEx;
	IZbox[i*4+3].y = ZMEy;
	if (isvis) PromptBox(&IZbox[i*4+3]);
   }
   EXPbox[0].fake = 1;
   if (pdb) PFake(ZMEwin,ZMEZOffx+225,ZMEZOffy-ZMEFRBord+ZMEZHIGH-TOGGWH,130,
	QBOXHIGH-9, EXPbox[0].bgcol);
   if (DEBUG) fprintf(stderr,"UpdateZME out\n");
}

QPcol(qp,iop)
QBOXSTRU *qp;
{
    int icol;

    switch (iop) {
	case 0: icol = ZC_CONST; break;
	case 1: icol = ZC_VAR; break;
	default: icol = ZC_LINK;
    }
    qp->col = icol;
}

SetConst(iop)
int iop;
{
 int i,icol;

    switch (iop) {
	case 0: icol = ZC_CONST; break;
	case 1: icol = ZC_VAR; break;
	default: icol = ZC_LINK;
    }
    for (i=0; i<*zmptr.nz; i++) {
		zmptr.ibl[i] = iop; 
		BLbox[i].col = icol; 
		BLbox[i].changed = 1;
		zmptr.ialph[i] = iop; 
		ALPHbox[i].col = icol; 
		ALPHbox[i].changed = 1; 
		zmptr.ibet[i] = iop; 
		BETbox[i].col = icol; 
		BETbox[i].changed = 1; 
    }
   UpdateZME();
}

SetQZME()
{
   int i,j;
   int nvar,fake,zvw,zvwn;

   if (DEBUG) fprintf(stderr,"SetQZME in\n");

/*
   SetQZME updates on screen zmat information with the zmat-structure
*/

   if (!*zmptr.ihaszm) return;

   strcpy(ZMEerr," ");
   for (i=0; i<*zmptr.nz; i++) {
	   if (zmptr.ianz[i] >= 0 && zmptr.ianz[i] < 100) 
		sprintf(stemp,"%s",elements[zmptr.ianz[i]]);
	   else sprintf(stemp,"%s","?");

	   qboxstr(&IANZbox[i],&ZMEwin,0,0,196,0,0,ZMEanW,ZMEQHIGH,
		    ZC_DEF,NULL,stemp,2,0,0,dummyproc);
	   IANZbox[i].explstr = IANZstr;
	   nvar = 3; if (i <= 2) nvar = i;
	   for (j=0; j<3; j++) {
		fake = 1;
		if (j<nvar) fake = 0;
		sprintf(stemp,"%d",izz(i,j));
		qboxstr(&IZbox[i*4+j],&ZMEwin,0,fake,196,0,0,ZMEconW,ZMEQHIGH,
		     ZC_CONN,NULL,stemp,5,1,0,dummyproc);
		IZbox[i*4+j].explstr = IZstr;
		if (j == 0) {
	   	   sprintf(stemp,zmeblform[ZMEAA],zmptr.bl[i]);
	   	   qboxstr(&BLbox[i],&ZMEwin,0,fake,196,0,0,ZMEvarW,ZMEQHIGH,
		     ZC_DEF,NULL,stemp,11,2,0,dummyproc);
		   QPcol(&BLbox[i],zmptr.ibl[i]);
		   BLbox[i].explstr = BLstr;
		}
		else if (j == 1) {
	   	   sprintf(stemp,zmeform[ZMEAA],zmptr.alph[i]);
	   	   qboxstr(&ALPHbox[i],&ZMEwin,0,fake,196,0,0,ZMEvarW,ZMEQHIGH,
		     ZC_DEF,NULL,stemp,11,2,0,dummyproc);
		   QPcol(&ALPHbox[i],zmptr.ialph[i]);
		   ALPHbox[i].explstr = ALPHstr;
		}
		else if (j == 2) {
		   zvw = ZMEvarW; zvwn = 11;
                   if (ZMEAA) {
			zvw = ZMEvarWs;
			zvwn = 8;
		   }
	   	   sprintf(stemp,zmeform[ZMEAA],zmptr.bet[i]);
	   	   qboxstr(&BETbox[i],&ZMEwin,0,fake,196,0,0,zvw,ZMEQHIGH,
		     ZC_DEF,NULL,stemp,zvwn,3,0,dummyproc);
		   QPcol(&BETbox[i],zmptr.ibet[i]);
		   BETbox[i].explstr = BETstr;
		}
	   }
	   fake = 1;
	   if (i > 2) fake = 0;
	   sprintf(stemp,"%d",izz(i,3));
	   qboxstr(&IZbox[i*4+3],&ZMEwin,0,fake,196,0,0,ZMEiz4W,ZMEQHIGH,
	       ZC_CONN,NULL,stemp,1,1,0,dummyproc);
   }
   if (DEBUG) fprintf(stderr,"SetQZME out\n");
}


#if defined(VMS) || defined(UNDERSC)
upzme()
#else
#ifdef CRAY
UPZME()
#else
upzme_()
#endif
#endif
{
/* for the convenience of fortran */
	SetQZME();
	if (ZME_window_pos >= *zmptr.nz) ZME_window_pos = 0;
	if (*zmptr.nz < ZME_window_high) RedrawZME();
	else {
	   UpdateZME();
	   if (ZMEup) RedrawScroll(&zscroll);
	}
}

GetQZME()
{
   int i,j;
   int nvar,found;

   if (DEBUG) fprintf(stderr,"GetQZME in\n");

/*
Textual zmat to numeric
*/

   for (i=0; i<*zmptr.nz; i++) {

	   found = 0;
	   for (j=0; j<100; j++) {
		if (strcasecmp(IANZbox[i].str,elements[j]) == 0) {
		    found = 1;
		    zmptr.ianz[i] = j;
		}
	   }
	   if (strcasecmp(IANZbox[i].str,"XX") == 0) {
		found = 1;
		zmptr.ianz[i] = 99;
	   }
	   if (!found) {
		ActOnErr(i,0,"ZMAT NOT parsed: Unrecognised Atom Name !");
		return;
	   }

	   nvar = 3; if (i <= 2) nvar = i;
	   for (j=0; j<nvar; j++) {

		if (strlen(IZbox[i*4+j].str)) 
		    sscanf(IZbox[i*4+j].str,"%d",pizz(i,j));
		else {
		    ActOnErr(i,4+j,"ZMAT NOT parsed: Empty string !");
		    return;
		}

		switch (j) {
		case 0:

		    if (zmptr.ibl[i] > 1) {
			zmptr.bl[i] = zmptr.bl[zmptr.ibl[i] - 1];
			strcpy(BLbox[i].str,BLbox[zmptr.ibl[i] - 1].str);
		    } else {
			if (BLbox[i].changed) {
	   		    if (strlen(BLbox[i].str)) 
				sscanf(BLbox[i].str,"%lf",&zmptr.bl[i]);
			    else {
				ActOnErr(i,1,"ZMAT NOT parsed: Empty string !");
				return;
			    }
			    BLbox[i].changed = 0;
			}
		    }
		    break;
		case 1:

		    if (zmptr.ialph[i] > 1) {
			zmptr.alph[i] = zmptr.alph[zmptr.ialph[i] - 1];
			strcpy(ALPHbox[i].str,ALPHbox[zmptr.ialph[i] - 1].str);
		    } else {
			if (ALPHbox[i].changed) {
	   		    if (strlen(ALPHbox[i].str)) 
				sscanf(ALPHbox[i].str,"%lf",&zmptr.alph[i]);
			    else {
				ActOnErr(i,2,"ZMAT NOT parsed: Empty string !");
				return;
			    }
			    ALPHbox[i].changed = 0;
			}
		    }
		    break;
		case 2:
		    if (ABS(zmptr.ibet[i]) > 1) {
			if (zmptr.ibet[i] > 0) {
			    zmptr.bet[i] = zmptr.bet[zmptr.ibet[i] - 1];
			    strcpy(BETbox[i].str,BETbox[zmptr.ibet[i] - 1].str);
			} else {
			    zmptr.bet[i] = -zmptr.bet[ABS(zmptr.ibet[i]) - 1];
			    sprintf(stemp,"%f",zmptr.bet[i]);
			    strcpy(BETbox[i].str,stemp);
			}
		    } else {
			if (BETbox[i].changed) {
	   		    if (strlen(BETbox[i].str)) 
				sscanf(BETbox[i].str,"%lf",&zmptr.bet[i]);
			    else {
				ActOnErr(i,3,"ZMAT NOT parsed: Empty string !");
				return;
			    }
			    BETbox[i].changed = 0;
			}
		    }
		    break;
		}
	   }
	   if (i > 2) {
		sscanf(IZbox[i*4+3].str,"%d",pizz(i,3));
	   }
   }
   if (DEBUG) fprintf(stderr,"GetQZME out\n");
}

ActOnErr(zline,boxnum,errstr)
int zline;
int boxnum;
char *errstr;
{
    if (zline >= 0) {
	ZME_window_pos = zline;
	IANZbox[zline].col = ZC_AT1;
	switch(boxnum) {
	case 0: IANZbox[zline].active = 1; break;
	case 1: BLbox[zline].active = 1; break;
	case 2: ALPHbox[zline].active = 1; break;
	case 3: BETbox[zline].active = 1; break;
	case 4: IZbox[zline*4].active = 1; break;
	case 5: IZbox[zline*4+1].active = 1; break;
	case 6: IZbox[zline*4+2].active = 1; break;
	case 7: IZbox[zline*4+3].active = 1; break;
	}
	UpdateZME();
	RedrawScroll(&zscroll);
    }
    strcpy(ZMEerr,errstr);
    RedrawStatus();
}

int MapAtom(jxyz)
int jxyz;
{
int j;

    for (j=0; j<*zmptr.nz; j++) {
	if (jxyz == zmptr.imap[j]) {
	    return j;
	}
    }
    return (-1);

}

float CalcBL(mult,atomnr1,atomnr2)
int atomnr1;
int atomnr2;
int mult;
{
  int iptr1,iptr2;
  float BL;

    iptr1 = FindInd(atomnr1,DisAtoms,NUMDIS);
    iptr2 = FindInd(atomnr2,DisAtoms,NUMDIS);

    if (iptr1 > -1 && iptr2 > -1) {
	switch (mult) {
	case 0: BL = SingleDis[iptr1][iptr2]; break;
	case 1: BL = DoubleDis[iptr1][iptr2]; break;
	case 2: BL = TripleDis[iptr1][iptr2]; break;
	}
	strcpy(ZMEerr,"Bondlength from literature");
    }
    else {
	BL = (scalptr->vdwr[atomnr1-1] + scalptr->vdwr[atomnr2-1])*0.98;
	strcpy(ZMEerr,"Bondlength estimated from Van der Waals Radii");
    }
    return BL;

}

FirstLine()
{

	*zmptr.nz = 1;
	xyz.ianz[0] = zmptr.ianz[0];
	zmptr.imap[0] = 1;
	*xyz.iatoms = 1;
	xyz.coo[0] = 0.0;
	xyz.coo[1] = 0.0;
	xyz.coo[2] = 0.0;
	xyz.iconn[0] = 0;
	xyz.iaton[0] = 1;
	scalptr->scali = 3.5;
	scalptr->scal = 2.5*scalptr->scali;
	ZME_window_pos = 0;
#if defined(VMS) || defined(UNDERSC)
	setrot();
#else
#ifdef CRAY
	SETROT();
#else
	setrot_();
#endif
#endif
	update_sel = 1;
}

int GetRes(atomnr,iph,Asel)
int atomnr;
short int *iph;
int Asel;
{
  int irt,irtt;
  short int ipt;

  *iph = 0; irt = NHETRES;

  if (*ipdbon && !*ialtyp) {

#if defined(VMS) || defined(UNDERSC)
	numhed(&irt,xyz.iresid);
#else
#ifdef CRAY
	NUMHED(&irt,xyz.iresid);
#else
	numhed_(&irt,xyz.iresid);
#endif
#endif
	irt++;
	irt = -irt;

	irtt = xyz.iresid[Asel];

	if (irtt > 0) {

/* attach to residue atom */

		if (atomnr == 1) {

		/* attach H to residue atom */

		   ipt = xyz.ipdbt[Asel];
		   switch (calfptr->iamino[irtt-1]) {
		   case 9:
		   /* asparate */
			switch (ipt) {
			case 29:
			   *iph = 22;
			   irt = irtt;
			   break;
			case 30:
			   *iph = 25;
			   irt = irtt;
			   break;
			}
			break;
		   case 13:
		   /* glutamate */
			switch (ipt) {
			case 34:
			   *iph = 31;
			   irt = irtt;
			   break;
			case 35:
			   *iph = 34;
			   irt = irtt;
			   break;
			}
			break;
		   case 17:
		   /* histidine */
			switch (ipt) {
			case 20:
			   *iph = 22;
			   irt = irtt;
			   break;
			case 24:
			   *iph = 34;
			   irt = irtt;
			   break;
			}
			break;
		   }
		}

	} else {

/* attach to NON residue atom */

		irt = irtt;
	}
	if (irt != irtt) {
	   NHetAtm == ABS(irt)+1;
	   calfptr->ihet[ABS(irt)] = 1;
	   HetAtm[ABS(irt)] = "NewRes";
	}
  }

  return(irt);
}

AddLine(atomnr,activate,Asel,dist,covang,dihang,multip)
int *Asel;
float *dist;
float *covang;
float *dihang;
int atomnr;
int activate;
int multip;
{
  int i,j,fake,nvar,ioke,irt,irtt,row;
  int iptr1,iptr3,izptr;
  int hit,nhits;
  float angle[2],angtmp,dis,dihtmp;
  short int ipt,iph;

/*
  AddLine receives an atom to be connected to 3 atoms defined by asel
  and parses new zmat
*/

  iph = 0;
  ioke =1;
  if (*zmptr.nz >= *zmptr.mxzat - 1) {
	ioke = 0;
	if (AllocZMat(*xyz.mxnat)) ioke = 1;
  }
  if (!ioke) return;

  if (!mapchk()) map_prop();

  izptr = *zmptr.nz;

  if (Asel != NULL) {
	irt = GetRes(atomnr,&iph,Asel[0]);
  } else {
	irt = NHETRES;
  }

  if (iph) {
	int imxt,imnt,ipartt;

	imxt = *imx; imnt = *imn; ipartt = *ipart;
	FindZRange(irt);
	row = *imx;
	*imx = imxt; *imn = imnt; *ipart = ipartt;
	InsertEmptyLines(0,row,1,0,0,NULL);
	izptr = row;
  }

  if (ZMEup) {

	qboxstr(&IANZbox[izptr],&ZMEwin,0,0,196,0,0,ZMEanW,ZMEQHIGH,
		    ZC_DEF,NULL,elements[atomnr],2,0,0,dummyproc);
	zmptr.ianz[izptr] = atomnr;
	if (activate) {
	    IANZbox[izptr].col = ZC_AT1;
	    IANZbox[izptr].active = 1;
	}

	nvar = 3; if (izptr <= 2) nvar = izptr;
	for (j=0; j<3; j++) {
	    fake = 1;
	    if (j<nvar) fake = 0;
	    qboxstr(&IZbox[izptr*4+j],&ZMEwin,0,fake,196,0,0,
		ZMEconW,ZMEQHIGH,ZC_CONN,NULL,NULL,3,1,0,dummyproc);
	    switch (j) {
	    case 0: qboxstr(&BLbox[izptr],&ZMEwin,0,fake,196,0,0,
			ZMEvarW,ZMEQHIGH,ZC_DEF,NULL,NULL,11,2,0,dummyproc);
		    break;
	    case 1: qboxstr(&ALPHbox[izptr],&ZMEwin,0,fake,196,0,0,
			ZMEvarW,ZMEQHIGH,ZC_DEF,NULL,NULL,11,2,0,dummyproc);
		    break;
	    case 2: qboxstr(&BETbox[izptr],&ZMEwin,0,fake,196,0,0,
			ZMEvarW,ZMEQHIGH,ZC_DEF,NULL,NULL,11,3,0,dummyproc);
		    break;
	    }
	}
	fake = 1;
	if (izptr > 2) fake = 0;
	qboxstr(&IZbox[izptr*4+3],&ZMEwin,0,fake,196,0,0,ZMEiz4W,ZMEQHIGH,
	       ZC_CONN,NULL,"0",1,1,0,dummyproc);

	if (!nvar) {
	    GetQZME();
	    FirstLine();
	    return;
	}
/*
	connectivity
*/
	for (i = 0; i <3; i++) {
	    if (Asel[i] != -1) {
		sizz(izptr,i, Asel[i] + 1);
	    }
	    sprintf(stemp,"%d",izz(izptr,i));
	    strcpy(IZbox[izptr*4+i].str,stemp);
	    IZbox[izptr*4+i].changed = 1;
	}

/*
	Bondlength
*/
	if (dist == NULL) {
	    dis = CalcBL(multip,zmptr.ianz[izptr],zmptr.ianz[Asel[0]]);
	} else dis = *dist;

	sprintf(BLbox[izptr].str,"%f",dis);
	zmptr.bl[izptr] = (double) dis;
	BLbox[izptr].changed = 1;

/*
	BondAngle
*/
	angtmp = 109.471;
	if (covang == NULL) {
	    if (izz(Asel[1],0)-1 == Asel[0] &&
		izz(Asel[1],1)-1 == Asel[2] && izptr > 2) {
		if (ABS(zmptr.alph[Asel[1]]-120.0) <=
		    ABS(zmptr.alph[Asel[1]]-109.471)) angtmp = 120.0;
	    } else {
		for (i=0; i<izptr; i++) {
		    if (izz(i,0)-1 == Asel[0] &&
			izz(i,1)-1 == Asel[1] && izptr > 2) {
			if (ABS(zmptr.alph[i]-120.0) <=
			   ABS(zmptr.alph[i]-109.471)) angtmp = 120.0;
		    }
		}
	    }
	    switch (multip) {
	    case 0: break;
	    case 1: angtmp = 120.0; break;
	    case 2: angtmp = 179.0; break;
	    }
	}
	else angtmp = *covang;

	sprintf(ALPHbox[izptr].str,"%f",angtmp);
	zmptr.alph[izptr] = (double) angtmp;
	ALPHbox[izptr].changed = 1;

/*
	DihedralAngle
*/
	if (dihang == NULL) {
	    nhits = 0;
	    for (j=0; j<izptr; j++) {
		hit = 1;
		for (i = 0; i <3; i++) {
		    if (izz(izptr,i) != izz(j,i)) {
			hit = 0;
		    }
		}
		if (hit) {
		    if (nhits < 2) angle[nhits] = zmptr.bet[j];
		    nhits++;
		}
	    }

	    switch (nhits) {
	    case 0: iptr3 = izz(izptr,2);
		    if (izz(izptr,0) == izz(iptr3,0) &&
			izz(izptr,1) == izz(iptr3,1)) {
			if (angtmp == 120.0) dihtmp = 180.0;
			else dihtmp = 120.0;
		    } else dihtmp = 180.0;
		    break;
	    case 1: angtmp = angle[0]+120.0;
		    if (angtmp >= 360.0) angtmp = angtmp - 360.0;
		    dihtmp = angtmp;
		    break;
	    default:
	    case 2: angtmp = (angle[0] + angle[1])/2 + 180.0;
		    if (angtmp >= 360.0) angtmp = angtmp - 360.0;
		    dihtmp = angtmp;
		    break;
	    }
	}
	else dihtmp = *dihang;

	sprintf(BETbox[izptr].str,"%f",dihtmp);
	zmptr.bet[izptr] = (double) dihtmp;
	BETbox[izptr].changed = 1;

        zmptr.ibl[izptr] = 1;
        zmptr.ialph[izptr] = 1;
        zmptr.ibet[izptr] = 1;
        zmptr.imap[izptr] = izptr+1;

        iptr1 = izptr;
	if (*ialtyp) iptr1 = iptr1 + *iscst;
        
	xyz.ipdbt[iptr1] = iph;
	xyz.iresid[iptr1] = irt;
	xyz.ityp[iptr1] = 0;
	xyz.iaton[iptr1] = 1;
	xyz.iatclr[iptr1] = 1;

	(*zmptr.nz)++;
	update_sel = 1;
	SetQZME();
  }
}

int SelZME(asel)
int *asel;
{
  int selMap[3];
  int i;
  float b,a,d;

/*
  SelZME receives an atom to be connected to 3 atoms defined by asel
  and parses new zmat
*/

  if (ZMEup && ZMEsel) {
	for (i = 0; i <3; i++) {
	    selMap[i] = MapAtom(asel[i]);
	}

	if (ZMEatom == 99) {
	   b = 1.0; a = 90.0; d = 180.0;
	   AddLine(ZMEatom,1,selMap,&b,&a,&d,ZMEmul);
	}
	else AddLine(ZMEatom,1,selMap,NULL,NULL,NULL,ZMEmul);

	ActBut(&cbut[BDIST],1);
	ActBut(&cbut[BANGLE],1);
	ActBut(&cbut[BDIHED],1);
	ZMEsel = 0;
	ZME_window_pos = *zmptr.nz-ZME_window_high;
	if (ZME_window_pos < 0) ZME_window_pos = 0;
	RedrawStatus();
	RedrawZME();
	*Sinct = 530;
	return(1);
  }
  return(0);
}

int GetRow(update)
int update;
{
    int type,row,column;

    activeZME(&type,&row,&column);
    if (type == -1 || row < 0) {
	if (type == -1 && update) {
	    strcpy(ZMEerr,"FRAGMENT NOT ADDED: no atom selected");
	}
	row = -1;
	if (update) RedrawStatus();
    } 
    return row;
}

AddXH3(atnr,update) 
int atnr;
int update;
{
    int row,iptr1,irt,rest;
    int selMap[3];
    int isfirst;
    short int iph;

    isfirst = 0;
    if (!*zmptr.nz) isfirst = 1;
    
    row = GetRow(1);
    if (row == -1) {
	if (isfirst) {
           AddLine(1,0,selMap,NULL,NULL,NULL,0);
           *zmptr.nz = 1;
	   row = 0;
	} else {
	   return;
	}
    }

    irt = NHETRES;
    rest = zmptr.imap[row]-1;
    if (rest >= 0) irt = GetRes(atnr,&iph,rest);

    sizz(1,1,0);
    sizz(1,2,0);
    sizz(1,3,0);
    sizz(2,2,0);
    sizz(2,3,0);
    zmptr.alph[1] = 0.0;
    zmptr.bet[1] = 0.0;
    zmptr.bet[2] = 0.0;

    *zmptr.ihaszm = 1;

    switch(atnr) {
    case 6: strcpy(IANZbox[row].str,"C");break;
    case 7: strcpy(IANZbox[row].str,"N");break;
    }
    IANZbox[row].changed = 1;

    iptr1 = row;
    if (*ialtyp) iptr1 = iptr1 + *iscst;

    xyz.ipdbt[iptr1] = 0;
    xyz.ityp[iptr1] = 0;
    xyz.iresid[iptr1] = irt;
    xyz.iatclr[iptr1] = 1;
    xyz.iaton[iptr1] = 1;
    update_sel = 1;

    if (*zmptr.nz >1) {
	sprintf(BLbox[row].str,"%f",
	    CalcBL(0,atnr,zmptr.ianz[izz(row,0)-1]));
	BLbox[row].changed = 1;
    }
    if (!isfirst) {
	GetQZME();
	DeActZME();
    }

    selMap[0] = row;
    if (row == 0) {
	selMap[1] = 1;
	selMap[2] = 2;
    } else if (row == 1) {
	selMap[1] = 0;
	selMap[2] = 2;
    } else {
	selMap[1] = izz(row,0)-1;
	selMap[2] = izz(row,1)-1;
    }
    AddLine(1,0,selMap,NULL,NULL,NULL,0);

    selMap[2] = *zmptr.nz-1;

    switch(atnr) {
    case 6:	AddLine(1,0,selMap,NULL,NULL,NULL,0);
	        if (*zmptr.nz == 3) selMap[2] = *zmptr.nz-1;
    		AddLine(1,1,selMap,NULL,NULL,NULL,0);
		break;
    case 7:	AddLine(1,1,selMap,NULL,NULL,NULL,0);
		break;
    }

    if (update) {
	ZME_window_pos = *zmptr.nz-ZME_window_high;
	if (ZME_window_pos < 0) ZME_window_pos = 0;

	RedrawZME();
	*Sinct = 530;
    }

}

#if defined(VMS) || defined(UNDERSC)
cnvfrg(fraglen)
#else
#ifdef CRAY
CNVFRG(fraglen)
#else
cnvfrg_(fraglen)
#endif
#endif
int *fraglen;
{
    ZLINESTRU *frag;
    int frglen;
    int i,j,offset;

    frglen = *fraglen;

    frglen = *zmptr.nz - frglen;
    *zmptr.nz = *zmptr.nz - frglen;

    if (!frglen) return;

    frag = (ZLINESTRU *) malloc((sizeof *frag)*frglen);

    for (i=0; i < frglen; i++) {
	offset = *zmptr.nz + i;
	frag[i].ianz = zmptr.ianz[offset];
	for (j=0; j < 3; j++) {
            frag[i].iz[j] = izz(offset,j);
	}
	frag[i].iz[3] = izz(offset,3);
	frag[i].bl = zmptr.bl[offset];
	frag[i].alph = zmptr.alph[offset];
	frag[i].bet = zmptr.bet[offset];
    }
    AddFrag(frag,frglen,109.471,180.0,-1,1,1);
}

scrfrg(ScrewNotTrans,nfrg)
int ScrewNotTrans;
int nfrg;
{
    ZLINESTRU *frag;
    int frglen;
    int i,j,offset,offhlp,xprev,xxprev;
    int scangle,iscangle;
    double *arr;

    if ((arr = (double *) malloc((sizeof *arr)*(*zmptr.mxzat))) == NULL) 
	return;

    for (j=0; j<*zmptr.nz; j++) {
	if (zmptr.imap[j] > 0) {
	   arr[j] = xyz.qat[zmptr.imap[j]-1];
	} else {
	   arr[j] = 0.0;
	}
    }
    for (j=0; j<*zmptr.nz; j++) xyz.qat[j] = arr[j];

    if (ScrewNotTrans) {
	scangle = 180.0;
    } else {
	scangle = 0.0;
    }

    frglen = *zmptr.nz;
    *zmptr.nz = 0;

    if (!frglen) return;

    frag = (ZLINESTRU *) malloc((sizeof *frag)*frglen);


    for (i=0; i < frglen; i++) {
	offset = *zmptr.nz + i;
	frag[i].ianz = zmptr.ianz[offset];
	for (j=0; j < 3; j++) {
            frag[i].iz[j] = izz(offset,j);
	}
	frag[i].iz[3] = izz(offset,3);
	frag[i].bl = zmptr.bl[offset];
	frag[i].alph = zmptr.alph[offset];
	frag[i].bet = zmptr.bet[offset];
    }
    *zmptr.nz = 0;
    CopyFrag(SCREW,2,-1);
    CopyFrag(frag,frglen,-1);

    sizz(2,0,2);
    sizz(2,1,1);
    sizz(2,2,0);
    zmptr.bl[2] = 1.08;
    if (!ScrewNotTrans) zmptr.ibl[2] = 0;
    zmptr.alph[2] = 90.0;
    zmptr.ialph[2] = 0;
    zmptr.bet[2] = 0.0;

    sizz(3,1,2);
    sizz(3,2,1);
    zmptr.alph[3] = 120.0;
    zmptr.bet[3] = 120.0;
    
    sizz(4,2,2);
    zmptr.bet[4] = 120.0;

    for (j=0; j < *zmptr.nz; j++) xyz.iatclr[j] = 12;

    xyz.qat[0] = 0.0;
    xyz.qat[1] = 0.0;
    for (j=frglen-1; j >= 0; j--) {
	xyz.iresid[j+2] = 1;
	xyz.qat[j+2] = xyz.qat[j];
    }

    xxprev = 1;
    xprev = 2;

    for (i=0; i < nfrg; i++) {

	offset = *zmptr.nz;
	offhlp = offset;
	*zmptr.nz = *zmptr.nz + 1;
	zmptr.ianz[offset] = 99;
	sizz(offset,0,xprev);
	sizz(offset,1,xprev + 1);
	sizz(offset,2,xxprev);
	zmptr.bl[offset] = zmptr.bl[1];
	zmptr.ibl[offset] = 2;
	zmptr.alph[offset] = 90.0;
	zmptr.ialph[offset] = 0;
	zmptr.bet[offset] = 180.0;
	zmptr.ibet[offset] = 0;
        xyz.qat[offset] = 0.0;

	offset++;

	CopyFrag(frag,frglen,3);

	sizz(offset,0,offset);
	sizz(offset,1,xprev);
	sizz(offset,2,xprev + 1);
	zmptr.bl[offset] = zmptr.bl[2];
	zmptr.ibl[offset] = 3;
	zmptr.alph[offset] = 90.0;
	zmptr.ialph[offset] = 0;
	zmptr.bet[offset] = scangle;
	if (i == 0) {
	   zmptr.ibet[offset] = 0;
	   iscangle = offset + 1;
	} else {
	   zmptr.ibet[offset] = iscangle;
	}
   
	offset++;

	sizz(offset,1,offset - 1);
	sizz(offset,2,xprev);
	zmptr.alph[offset] = zmptr.alph[3];
	zmptr.ialph[offset] = 4;
	zmptr.bet[offset] = zmptr.bet[3];
	zmptr.ibet[offset] = 4;
    
	offset++;
	sizz(offset,2,offset - 2);
	zmptr.bet[offset] = zmptr.bet[4];
	zmptr.ibet[offset] = 5;

	xxprev = xprev;
	xprev = 2 + (1+frglen)*(i+1);

	for (j=offhlp; j < *zmptr.nz; j++) xyz.iatclr[j] = i + 1;

	for (j=frglen-1; j >= 0 ; j--) {
	   xyz.iresid[j+offhlp+1] = i+1;
	   xyz.qat[j+offhlp+1] =arr[j];
	}
    }

    for (j=0; j < *zmptr.nz; j++) xyz.iaton[j] = 1;
    update_sel = 1;

    DeActZME(); 

    *zmptr.ihaszm = 1;

    SetQZME(); 

    ZME_window_pos = 0;

    if (*zmptr.nz < ZME_window_high) RedrawZME();
    else UpdateZME();

#if defined(VMS) || defined(UNDERSC)
    dumzm(xyz.coo,xyz.ianz,xyz.iatoms);
    doconn();docent();doclr();qupd();
#else
#ifdef CRAY
    DUMZM(xyz.coo,xyz.ianz,xyz.iatoms);
    DOCONN();DOCENT();doclr();QUPD();
#else
    dumzm_(xyz.coo,xyz.ianz,xyz.iatoms);
    doconn_();docent_();doclr();qupd_();
#endif
#endif

    free(arr);
}

SetPDBArray(pdbt,frglen,value,offset)
int *pdbt;
int frglen;
int value;
int offset;
{
    int i,j;

    for (i=0; i<frglen; i++) {
	j = offset+i;
	if (j < *xyz.mxnat) pdbt[j] = value;
    }
}

CopyPDBTyp(pdbt,fragpdb,frglen,offset)
short int *pdbt;
short int *fragpdb;
int frglen;
int offset;
{
    int i,j;

    for (i=0; i<frglen; i++) {
	j = offset+i;
	if (j < *xyz.mxnat) pdbt[j] = fragpdb[i];
    }
}

int AddAmino(iamin,addrow,aphi,apsi,omega,chi1,chi2,chi3,chi4,iconf,update,iadd)
int iamin;
int *addrow;
double aphi;
double apsi;
double *omega;
double *chi1;
double *chi2;
double *chi3;
double *chi4;
int iconf;
int update;
int iadd;
{
    int frglen;
    int i,isfirst,row,iret;
    int co,ca,nn,nz,amiami,sidechainstart;

    nz = *zmptr.nz;

    iret = 1;
    if (nz > *zmptr.mxzat-28) {
	iret = 0;
	if (AllocZMat(*xyz.mxnat)) iret = 1;
    }
    if (!iret) {
	if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
	     "No more room to add residues !",0)) { i = 0;}
	return(iret);
    }

    amiami = 0;
    isfirst = 0;
    if (!*zmptr.nz) isfirst = 1;

/* Check if O is the right oxygen of the two connected to the C-terminus */

    co = ca = nn = -1;

    if (*addrow == -1) row = GetRow(0);
    else row = *addrow;
    if (!isfirst && row == -1) row = LastAmino;

    if (isfirst) {
	FirstLine();
	row = 0;
	nz = 1;
    } else {
	if (row == -1) {
	    row = GetRow(1); return(iret);
	} else {
	    if (zmptr.ianz[row] == 8) {
		if (zmptr.ianz[izz(row,0)-1] == 6) {
		   co = izz(row,0)-1;
		   if (izz(row,2) == row) {
			if (zmptr.ianz[row-1] == 8) {
			    row--;
			    if (update) {
				DeActZME();
				IANZbox[row].active = 1;
			    }
			}
		   }
		   nn = row;
		   if (zmptr.ianz[izz(co,0)-1] == 6)
			ca = izz(co,0)-1;
		}
	    }
	}
    }
    if (ca != -1 && co != -1 && nn != -1) amiami = 1;

    if (!pdb) {
	calfptr->nchain = 1;
	calfptr->ianf[0] = 1;
	pdb = 1;
	*ipdbon = 1;
	hbon = 0;
	ActBut(&cbut[BBACKB],1);
	cbut[BFORC].str = "Res.Comm.";
	cbut[BINCRF].str = "Residue";
	cbut[BDECRF].str = "HetAtm";
	cbut[BUNSC].str = " ";
	cbut[BHBOND].str = " ";
	cbut[BFORC].w = 80;
	cbut[BINCRF].w = 80;
	cbut[BDECRF].w = 80;
	cbut[BUNSC].w = TOGGWH;
	cbut[BHBOND].w = TOGGWH;
	NHetAtm = 4;
	HetAtm[0] = "Helix";
	HetAtm[1] = "Beta";
	HetAtm[2] = "RNA/DNA";
	HetAtm[3] = "HET";
    } else if (!amiami && iadd) {
	calfptr->ianf[calfptr->nchain] = calfptr->ncalf+1;
	calfptr->nchain++;
    }
    calfptr->issdon = 0;

    calfptr->reson[calfptr->ncalf] = 0;
    calfptr->iamino[calfptr->ncalf] = iamin + 1;
    calfptr->icalf[calfptr->ncalf][0] = nz+1;
    if (isfirst) calfptr->icalf[calfptr->ncalf][1] = 1;
    else calfptr->icalf[calfptr->ncalf][1] = nn+1;
    calfptr->icalf[calfptr->ncalf][2] = nz+2;
    calfptr->icalf[calfptr->ncalf][3] = nz+5;
    isal[calfptr->ncalf] = iconf;
    irsnr[calfptr->ncalf] = calfptr->ncalf+1;
    if (calfptr->ncalf-1 > 0)
	strcpy(achain[calfptr->ncalf],achain[calfptr->ncalf-1]);
    calfptr->ncalf++;
    if (iadd) calfptr->islu[calfptr->nchain-1] = calfptr->ncalf;

    frglen = 6;
    if (iamin == 14) frglen = 5;
    MoveFrag(BACK,AMINO,frglen,0);
    CopyPDBTyp(xyz.ipdbt,BACK_TYP,frglen-1,nz);
    if (isfirst) {
	xyz.ipdbt[0] = 1;
	xyz.iresid[0] = calfptr->ncalf;
	xyz.iatclr[0] = 12;
    } else {
	xyz.ipdbt[row] = 1;
	xyz.iresid[row] = calfptr->ncalf;
	xyz.iatclr[row] = 12;
    }

    MoveFrag(aminozmt[iamin].zmat,AMINO,aminozmt[iamin].zlines,frglen);
    CopyPDBTyp(xyz.ipdbt,aminozmt[iamin].ipdbt,aminozmt[iamin].zlines,
		nz+frglen-1);
    frglen = frglen + aminozmt[iamin].zlines;

    if (isfirst) {
	MoveFrag(BACKHS,AMINO,2,frglen);
	CopyPDBTyp(xyz.ipdbt,BACKHS_TYP,2,nz+frglen-1);
	frglen = frglen + 2;
    }
    AddFrag(AMINO,frglen,109.471,180.0,row,0,0);
    SetPDBArray(xyz.iresid,frglen-1,calfptr->ncalf,nz);
    SetPDBArray(xyz.iatclr,frglen-1,12,nz);

    if (isfirst) {
	zmptr.bet[nz+2] = apsi;
    } else if (amiami) {
	if (iamin != 14) {
	    sizz(nz+4,2,co + 1);
	    zmptr.bet[nz+4] = 180.0;
	}
	zmptr.bl[nn] = 1.340;
	zmptr.alph[nn] = 112.7;
	sizz(nz,1,co + 1);
	sizz(nz,2,ca + 1);
	zmptr.alph[nz] = 121.0;
	if (omega != NULL) zmptr.bet[nz] = *omega;
	else zmptr.bet[nz] = 180.0;
	sizz(nz+1,2,co + 1);
	zmptr.bet[nz+1] = aphi;
	zmptr.bet[nz+2] = apsi;
    }

    sidechainstart = nz+5;
    if (iamin == 14) sidechainstart = nz+4;
    if (chi1 != NULL && aminozmt[iamin].chis[0] != -1) 
	zmptr.bet[sidechainstart-1+aminozmt[iamin].chis[0]] = *chi1;
    if (chi2 != NULL && aminozmt[iamin].chis[1] != -1) 
	zmptr.bet[sidechainstart-1+aminozmt[iamin].chis[1]] = *chi2;
    if (chi3 != NULL && aminozmt[iamin].chis[2] != -1) 
	zmptr.bet[sidechainstart-1+aminozmt[iamin].chis[2]] = *chi3;
    if (chi4 != NULL && aminozmt[iamin].chis[3] != -1) 
	zmptr.bet[sidechainstart-1+aminozmt[iamin].chis[3]] = *chi4;
    
    if (update) {
	SetQZME();
	DeActZME();
	if (isfirst) IANZbox[3].active = 1;
	else IANZbox[nz+2].active = 1;
	if (ZMEAA) {
	   make_aa();
	   ZME_window_pos = calfptr->ncalf-ZME_window_high;
	   if (ZME_window_pos < 0) ZME_window_pos = 0;
	} else {
	   ZME_window_pos = *zmptr.nz-ZME_window_high;
	   if (ZME_window_pos < 0) ZME_window_pos = 0;
	}
	RedrawZME();
	*Sinct = 530;
    }

    *addrow = nz+2;
    LastAmino = *addrow;

    return(iret);

}
    
#define ALPHA 0
#define BETA 1
#define TURN 2

AddSequence(sequence,seq_len,sec_struc)
int *sequence;
int seq_len;
int sec_struc;
{
    int i;
    int addrow,update;
    double phit;

    addrow = -1;

    for (i=0; i < seq_len; i++) {
	phit = phi_angle;
	update = 0;
	if (i == seq_len - 1) update = 1;
	if (sequence[i] == 14) phit = -70.0;
	if (!AddAmino(sequence[i],&addrow,
	   phit,psi_angle,NULL,NULL,NULL,NULL,NULL,iconform,update,1)) break;
        calfptr->reson[calfptr->ncalf-1] = 1;
    }

}

InsertEmptyLines(ires,row,nlines,seq_len,nprot,iprot)
int ires;
int row;
int nlines;
int seq_len;
int nprot;
int *iprot;
{
/*
ires   = residue
row    = zmat line from which lines will be added/inserted
nlines = number of lines inserted
seq_len = number of amino acids inserted
*/

  int i,j,k,l,kcon,prot,ab,noab;

    for (j=*zmptr.nz-1; j >= row; j--) {
	zmptr.bl[j+nlines] = zmptr.bl[j];
	zmptr.alph[j+nlines] = zmptr.alph[j];
	zmptr.bet[j+nlines] = zmptr.bet[j];
	zmptr.ianz[j+nlines] = zmptr.ianz[j];
	zmptr.imap[j+nlines] = zmptr.imap[j] + nlines;
	for (k=0; k < 4; k++) {
	   prot = 0;
	   for (l=0; l < nprot; l++) {
		if ((izz(j,k) == iprot[l]) && xyz.iresid[j] <= 0) prot = 1;
	   }
	   if (izz(j,k) < row+1 || prot)
		sizz(j+nlines,k,izz(j,k));
	   else
		sizz(j+nlines,k,izz(j,k) + nlines);
	}
	if (ABS(zmptr.ibl[j]) < row+1) 
	   zmptr.ibl[j+nlines] = zmptr.ibl[j];
	else zmptr.ibl[j+nlines] = zmptr.ibl[j]-SIGN(zmptr.ibl[j]);

	if (ABS(zmptr.ialph[j]) < row+1)
	   zmptr.ialph[j+nlines] = zmptr.ialph[j];
	else zmptr.ialph[j+nlines] = zmptr.ialph[j]-SIGN(zmptr.ialph[j]);

	if (ABS(zmptr.ibet[j]) < row+1) 
	   zmptr.ibet[j+nlines] = zmptr.ibet[j];
	else zmptr.ibet[j+nlines] = zmptr.ibet[j]-SIGN(zmptr.ibet[j]);
    }

    for (j=*xyz.iatoms-1; j >= row; j--) {
	xyz.iatclr[j+nlines] = xyz.iatclr[j];
	if (xyz.iresid[j] >= ires) {
	   xyz.iresid[j+nlines] = xyz.iresid[j] + seq_len;
        } else {
	   xyz.iresid[j+nlines] = xyz.iresid[j];
	}
	xyz.iaton[j+nlines] = xyz.iaton[j];
	xyz.ianz[j+nlines] = xyz.ianz[j];
	stoc.ianstc[j+nlines] = xyz.ianz[j];
	xyz.ipdbt[j+nlines] = xyz.ipdbt[j];
	xyz.ityp[j+nlines] = xyz.ityp[j];
	if (*ihasq) xyz.qat[j+nlines] = xyz.qat[j];
	for (k=0; k < 3; k++) {
	   xyz.coo[(j+nlines)*3+k] = xyz.coo[j*3+k];
	   stoc.cstoc[(j+nlines)*3+k] = xyz.coo[j*3+k];
	   stoc.czstoc[(j+nlines)*3+k] = xyz.coo[j*3+k];
	}
	kcon = 0;
	for (k=0; k < xyz.iconn[j*(MXCON+1)]; k++) {
	   noab = xyz.iconn[j*(MXCON+1)+k+1];
	   ab = ABS(noab);
	   prot = 0;
	   for (l=0; l < nprot; l++) {
		if ((ab == iprot[l]) && xyz.iresid[j] <= 0) prot = 1;
	   }
	   if (ab > row && !prot) {
		if (noab > 0) {
		   xyz.iconn[(j+nlines)*(MXCON+1)+kcon+1] = noab + nlines;
		} else {
		   xyz.iconn[(j+nlines)*(MXCON+1)+kcon+1] = noab - nlines;
		}
		kcon++;
	   } else {
		xyz.iconn[(j+nlines)*(MXCON+1)+kcon+1] = noab;
		kcon++;
	   }
	}
	xyz.iconn[(j+nlines)*(MXCON+1)] = kcon;
    }

}

int InsertSequence(sequence,seq_len,sec_struc,ires,nprot,iprot)
int *sequence;
int seq_len;
int sec_struc;
int ires;
int nprot;
int *iprot;
{
    int i,j,k,l, nzold, nlines,nlinesn,row,nc,nch,iaf,isl;
    int addrow,update;
    int ica,in,inn,icop,icap;
    double phit;


/* ires schuift op, dus insertie voor ires */

    addrow = -1;

    nc = calfptr->ncalf;
    nch = 0; iaf = 1; isl = nc;
    for (i=0; i < calfptr->nchain; i++) {
        if (ires >= calfptr->ianf[i] && ires < calfptr->islu[i]) {
	   nch = i;
	   iaf = calfptr->ianf[i];
	   isl = calfptr->islu[i];
	}
    }
    if (ires >= calfptr->islu[calfptr->nchain - 1]) {
	nch = calfptr->nchain - 1;
	isl = calfptr->islu[nch];
    }
    nzold = *zmptr.nz;

    nlines = 0;
    for (i=0; i < seq_len; i++) {
	nlines = nlines + aminozmt[sequence[i]].zlines + 5;
	if (sequence[i] == 14) nlines--;
    }

    DeActZME();
    if (ires <= nc ) {
	row = calfptr->icalf[ires-1][0] - 1;
	addrow = izz(row,0) - 1;
	zmptr.ianz[addrow] = 8;
    } else {
	row = -1;
	ica = calfptr->icalf[ires-2][0] - 1;
	for (i=ica; i < *zmptr.nz; i++) {
	    if (xyz.iresid[i] != ires-1) {
		row = i; break;
	    }
	}
	if (row == -1) row = *zmptr.nz;
	addrow = ica + 2;
    }

    InsertEmptyLines(ires,row,nlines,seq_len,nprot,iprot);

    for (j=calfptr->ncalf-1; j >= 0; j--) {
	for (k=0; k < 4; k++) {
	   if (calfptr->icalf[j][k]-1 >= row) 
		calfptr->icalf[j+seq_len][k] = calfptr->icalf[j][k] + nlines;
	} 
	if (j >= ires-1) {
	   calfptr->iamino[j+seq_len] = calfptr->iamino[j];
	   calfptr->reson[j+seq_len] = calfptr->reson[j];
	   isal[j+seq_len] = isal[j];
	   irsnr[j+seq_len] = irsnr[j]+seq_len;
	   strcpy(achain[j+seq_len],achain[j]);
	}
    }

    *zmptr.nz = row;
    calfptr->ncalf = ires - 1;

    update = 0;
    for (i=0; i < seq_len; i++) {
	phit = phi_angle;
	if (sequence[i] == 14) phit = -70.0;
	if (!AddAmino(sequence[i],&addrow,
	   phit,psi_angle,NULL,NULL,NULL,NULL,NULL,iconform,update,0)) break;
        calfptr->reson[calfptr->ncalf-1] = 1;
    }

/* Connect last of inserted residue to next residue, except when this
   was actually an add, insert at last residue, for the benefit of
   replace last residue (=del+ins) */

    if (ires-1 != nc) {

	ica = calfptr->icalf[ires-1+seq_len][0] - 1;
	icap = calfptr->icalf[ires-2+seq_len][0];
	icop = icap + 1;
	in = icap + 2;
	zmptr.ianz[in-1] = 7;
	xyz.ipdbt[in-1] = 1;
	xyz.iresid[in-1] = ires+seq_len;
	calfptr->icalf[ires-1+seq_len][1] = in;

	inn = izz(ica,0);

	sizz(ica,0,in);
	sizz(ica,1,icop);
	sizz(ica,2,icap);

	sizz(ica+1,1,in);
	sizz(ica+1,2,icop);

	sizz(ica+2,2,in);

/* The general situation, the forth atom after Calfa is H attached to N */

	if (zmptr.ianz[ica+4] == 1 && zmptr.ianz[ica+3] == 8) {
	   sizz(ica+4,0,in);
	   sizz(ica+4,2,icop);
	}

/* When res after insert is the last res, the third atom after Calfa in not N but H */
	if (zmptr.ianz[ica+3] == 1) {
	   sizz(ica+3,0,in);
	   sizz(ica+3,2,icop);
	}

/* if res after insert is proline, this is not actually a check for proline,
   this should deal with the Cbeta, why isnt this picked up later with check for inn ? */

	if (zmptr.ianz[ica+3] == 8 && zmptr.ianz[ica+4] == 6) {
/* regular pro */
	   sizz(ica+4,0,ica+1);
	   sizz(ica+4,2,in);
	} else if (zmptr.ianz[ica+2] == 8 && zmptr.ianz[ica+3] == 6) {
/* end pro */
	   sizz(ica+3,0,ica+1);
	   sizz(ica+3,2,in);
	}


	xyz.iatclr[in-1] = xyz.iatclr[ica];

    }
    if (ires == 1) {
	zmptr.alph[ica] = 121.0;
	zmptr.bet[ica] = 180.0;
	zmptr.bet[ica+1] = phi_angle;
	zmptr.bet[ica+4] = 180.0;
    }

/* search for more lines which where defines with respect to backbone
   N of residue ires+1; inn */

/* and Beware oflast residue */

    if (ires-1 != nc) {
      nlinesn = aminozmt[calfptr->iamino[ires-1+seq_len]-1].zlines + 5;
      if (calfptr->iamino[ires-1+seq_len]-1 == 14) nlinesn--;
	for (i=ica; i < nzold + nlines; i++) {
	     for (k=0; k < 3; k++) {
	        if (izz(i,k) == inn) sizz(i,k,in);
	     }
	}
    }


    *zmptr.nz = nzold + nlines;
    calfptr->ncalf = nc + seq_len;

    for (i=0; i < calfptr->nchain; i++) {
        if (i == nch) {
	   calfptr->islu[i] = isl + seq_len;
	} else {
           if (ires <= calfptr->islu[i]) 
		calfptr->islu[i] = calfptr->islu[i] + seq_len;
           if (ires < calfptr->ianf[i]) 
		calfptr->ianf[i] = calfptr->ianf[i] + seq_len;
	}
    }

    calfptr->issdon = 0;

    SetQZME();
    DeActZME();

    if (ZMEAA) {
	if (ZME_window_pos > calfptr->ncalf-1-ZME_window_high) {
	   if (calfptr->ncalf-1-ZME_window_high >= 0) {
	    ZME_window_pos = calfptr->ncalf-ZME_window_high;
           } 
	   else ZME_window_pos = 0;
	}
    } else {
	if (ZME_window_pos > *zmptr.nz-1-ZME_window_high) {
	   if (*zmptr.nz-1-ZME_window_high >= 0) {
	    ZME_window_pos = *zmptr.nz-ZME_window_high;
           } 
	   else ZME_window_pos = 0;
	}
    }
    if (ZME_window_pos < 0) ZME_window_pos = 0;
    if (ZMEAA) make_aa();
    RedrawZME();
    *Sinct = 530;
    update_sel = 1;
    return(nlines);

}


#define MXPROTHET 100
ReplaceSequence(sequence,seq_len,sec_struc,ires)
int *sequence;
int seq_len;
int sec_struc;
int ires;
{
   int ica0,ica,ica2,ict1,i,k,l,n,ilst1,ilst2,ilst2am,ilst2nl,ktyp;
   int ina, ico,icap;
   double ph,ps,omeg,ph2;
   int nprot;
   int iprot[3];
   double bl1[5],alph1[5],bet1[5];
   double bl2[3],alph2[3];
   double bl3[1],alph3[1];
   double refa1[3],refa2[3],refa3[3];
   int prothet[MXPROTHET][5],nprothet;
   int ndellin,ninslin,nefflin;

/* ica2 blijkt vrij nutteloos te zijn doch helemaal weg kan hij niet */

   ica0 = calfptr->icalf[ires-1][1] - 1;
   ica = calfptr->icalf[ires-1][0] - 1;
   ica2 = -1;

   if (ires == 1) {
	ina = calfptr->icalf[ires-1][1] - 1;
	ico = calfptr->icalf[ires-1][2] - 1;
   	icap = calfptr->icalf[ires][0] - 1;
	ph2 = zmptr.bet[icap+1];
	for (i=0; i < 3; i++) {
	   refa1[i] = stoc.czstoc[ina*3+i];
	   refa2[i] = stoc.czstoc[ica*3+i];
	   refa3[i] = stoc.czstoc[ico*3+i];
	}
   }

   if (ires >= calfptr->ncalf) {
	for (i=ica; i < *zmptr.nz; i++) {
	    if (xyz.iresid[i] != ires) {
		ica2 = i; break;
	    }
	}
	if (ica2 == -1) ica2 = *zmptr.nz - 1;

   } else {
	ica2 = calfptr->icalf[ires][0] - 1;
   }
   ilst2am = calfptr->iamino[ires] - 1;
   ilst2nl = aminozmt[ilst2am].zlines + 5;
   if (ilst2am == 14) ilst2nl--;

   ph = phi_angle;
   ps = psi_angle;

   if (seq_len == 1) {
	phi_angle = zmptr.bet[ica+1];

/* if list2: psi_angle != zmptr.bet[ica+2]; */
	psi_angle = zmptr.bet[ica+2];

	omeg = zmptr.bet[ica];
	for (i=0; i < 4; i++) {
           bl1[i] = zmptr.bl[ica+i];
           alph1[i] = zmptr.alph[ica+i];
           bet1[i] = zmptr.bet[ica+i];
	}
	if (zmptr.ianz[ica+2] == 7) {
	   ilst1 = 0;
	} else if (zmptr.ianz[ica+2] == 8) {
	   ilst1 = 1;
	}

/* 
   check for chain break after to be replaced residue:
   then the atom just before Calfa is an N 
   (mind you zmatlines number 0 - nz-1, atom references in
   zmat run from 1 - iatoms, so:

   izz(ica2,0) == ica2 instead of izz(ica2,0) == ica2-1
*/

	ilst2 = 0;
	if (izz(ica2,0) == ica2) {
	   ilst2 = 1;
	   ica2 = ica2 - 1;
	   psi_angle = zmptr.bet[ica2];
	}

	for (i=0; i < 3; i++) {
           bl2[i] = zmptr.bl[ica2+i];
           alph2[i] = zmptr.alph[ica2+i];
	}
	bl3[0] = zmptr.bl[ica0];
	alph3[0] = zmptr.alph[ica0];
   }


   ict1 = calfptr->icalf[ires-1][0];

   nprot = 3;
   iprot[0] = ica+1;
   iprot[1] = izz(ica,0);
   iprot[2] = ica+2;

   nprothet = 0; ndellin = 0; ninslin = 0;
   for (i=ica; i < *zmptr.nz; i++) {
	ktyp = 0;
	if (xyz.iresid[i] <= 0) ktyp = 1;
	if ((xyz.iresid[i] == ires) && (xyz.ianz[i] == 1) &&
	   (i > ica2) ) ktyp = 2;
	if (ktyp) {
	   for (k=0; k < 5; k++) prothet[nprothet][k] = -1;
	   for (k=0; k < 3; k++) {
		for (l=0; l < nprot; l++) {
		   if (izz(i,k) == iprot[l] && nprothet < MXPROTHET) {
			prothet[nprothet][k+1] = iprot[l];
			prothet[nprothet][0] = i;
			prothet[nprothet][4] = ktyp;
		   }
		}
	   }
	   if (prothet[nprothet][0] != -1) nprothet++;
	}
   }

   ndellin = DelAmino(ires);

   if (ires-1 == calfptr->ncalf) {
	calfptr->icalf[ires-1][0] = ict1;
   }


   ninslin = InsertSequence(sequence,seq_len,iconform,ires,0,NULL);

   if (seq_len == 1) {
	if (sequence[0] == 14) zmptr.bet[ica+1] = phi_angle;
	if (ilst2) {
	   zmptr.bet[ica+2] = psi_angle;
	   zmptr.bet[ica+3] = bet1[2];
	}
	if (ires == 1) {
	   icap = calfptr->icalf[1][0] - 1;
	   zmptr.bet[ica+2] = psi_angle;
	   zmptr.bet[icap+1] = ph2;
	}
	phi_angle = ph;
	psi_angle = ps;

	n = 4;

/* if last res replaced (or actually last before chain break)
   if replaced by a a proline ica + 3 was H(-N) and then becomes a Cbeta */
/* NOG DOEN: als een PRO vervangen wordt door een PRO dan eigenlijk wel
   weer n = 4 */

	if (ilst1 && sequence[0] == 14) n = 3;

	for (i=0; i < n; i++) {
           zmptr.bl[ica+i] = bl1[i];
           zmptr.alph[ica+i] = alph1[i];
	}

/* ilst2 = 1
   Als laatste RES voor chainbreak vervangen wordt dan veranderd de volgorde
   van:

   Calfa(res)    N    (res)    Coo  (res-1) Calfa(res-1)
   Coo  (res)    Calfa(res)    N    (res)   Coo  (res-1)
   Ooc  (res)    Coo  (res)    Calfa(res)   N    (res)
   .... H or Cbeta (ANY or PRO)

-> N    (res+1)  Coo  (res)    Calfa(res)   N    (res)
   Calfa(res+1)  N    (res+1)  Coo  (res)   Calfa(res)
   Coo  (res+1)  Calfa(res+1)  N    (res+1) Coo  (res)

   Naar:

   Calfa(res)    N    (res)    Coo  (res-1) Calfa(res-1)
   Coo  (res)    Calfa(res)    N    (res)   Coo  (res-1)
-> N    (res+1)  Coo  (res)    Calfa(res)   N    (res)
   Ooc  (res)    Coo  (res)    Calfa(res)   N    (res)
   .... H or Cbeta (ANY or PRO)

   Calfa(res+1)  N    (res+1)  Coo  (res)   Calfa(res)
   Coo  (res+1)  Calfa(res+1)  N    (res+1) Coo  (res)

*/

	if (ilst2) {
           zmptr.bl[ica+2] = bl2[0];
           zmptr.alph[ica+2] = alph2[0];
           zmptr.bl[ica+3] = bl1[3];
           zmptr.alph[ica+3] = alph1[3];
	}
	zmptr.bl[ica0] = bl3[0];
	zmptr.alph[ica0] = alph3[0];
	zmptr.bet[ica] = omeg;
   }

   nefflin = ninslin - ndellin;

   for (l=0; l < nprothet; l++) {
	i = prothet[l][0];
	for (k=0; k < 3; k++) {
	   if (prothet[l][1+k] != -1) {
		sizz(i+nefflin,k,prothet[l][1+k]);
	   }
	}
	if (prothet[l][4] == 2) xyz.iresid[i+nefflin] = ires;
   }

   if (ires == 1) {
	for (i=0; i < 3; i++) {
	   xyz.coo[i*3]   = refa1[i];
	   xyz.coo[i*3+1] = refa2[i];
	   xyz.coo[i*3+2] = refa3[i];
	}
   }

}

prtzmt(ibeg)
int ibeg;
{
   int i;

   fprintf(stderr,"Zmatrix\n");
   fprintf(stderr,"zmptr.nz %d\n",*zmptr.nz);
   for (i=ibeg; i < *zmptr.nz; i++) {
	fprintf(stderr,"zmt %d ianz %d iz0 %d iz1 %d iz2 %d\n",i,zmptr.ianz[i],izz(i,0),izz(i,1),izz(i,2));
	fprintf(stderr,"atm iresid %d ipdbt %d ityp %d iaton %d \n",xyz.iresid[i],xyz.ipdbt[i],xyz.ityp[i],xyz.iaton[i]);
   }
   fprintf(stderr,"Residues\n");
   for (i=0; i < calfptr->ncalf; i++) {
	fprintf(stderr,"calf %d iamino %d reson %d isal %d irsnr %d\n",i,calfptr->iamino[i],calfptr->reson[i],isal[i],irsnr[i]);
   }
   fprintf(stderr,"Residues icalf\n");
   for (i=0; i < calfptr->ncalf; i++) {
	fprintf(stderr,"calf %d icalf0 %d icalf1 %d icalf2 %d\n",i,calfptr->icalf[i][0],calfptr->icalf[i][1],calfptr->icalf[i][2]);
   }
   fprintf(stderr,"Chains %d\n",calfptr->nchain);
   for (i=0; i < calfptr->nchain; i++) {
	fprintf(stderr,"ch ianf %d islu %d\n",calfptr->ianf[i],calfptr->islu[i]);
   }
}

#if defined(VMS) || defined(UNDERSC)
readsq(ami,angs,namin)
#else
#ifdef CRAY
READSQ(ami,angs,namin)
#else
readsq_(ami,angs,namin)
#endif
#endif
int *ami;
double angs[][7];
int *namin;
{
    int i,j;
    int addrow,update;
    double phit,psit;
    double *omchi[5];


    addrow = -1;

    for (i=0; i < *namin; i++) {

	phit = -119.0;
	if (ami[i] == 14) phit = -70.0;
	psit = 113.0;
        if (angs[i][0] != -1) phit = angs[i][0];
        if (angs[i][1] != -1) psit = angs[i][1];

        for (j=0; j < 5; j++) {
	   if (angs[i][2+j] != -1) omchi[j] = &angs[i][2+j];
	   else omchi[j] = NULL;
	}

	update = 0;
	if (i == (*namin)-1) update = 1;
	if (!AddAmino(ami[i],&addrow,phit,psit,omchi[0],omchi[1],omchi[2],
		omchi[3],omchi[4],iconform,update,1)) break;
    }

    NSeq = 0;
    UpdateSeqStat();
}

CopyFrag(frag,frglen,linkoffset) 
ZLINESTRU *frag;
int frglen;
int linkoffset;
{
    int i,j,offset,variablestatus;

    for (i=0; i < frglen; i++) {
	offset = *zmptr.nz + i;
	if (linkoffset != -1) {
	   variablestatus = linkoffset + i;
	} else {
	   variablestatus = 1;
	}
	zmptr.ianz[offset] = frag[i].ianz;
	for (j=0; j < 3; j++) {
	    sizz(offset,j, frag[i].iz[j] + *zmptr.nz);
	}
	sizz(offset,3,0);
	zmptr.bl[offset] = frag[i].bl;
	zmptr.ibl[offset] = variablestatus;
	zmptr.alph[offset] = frag[i].alph;
	zmptr.ialph[offset] = variablestatus;
	zmptr.bet[offset] = frag[i].bet;
	zmptr.ibet[offset] = variablestatus;
    }
    *zmptr.nz = *zmptr.nz + frglen;
}

MoveFrag(frag,destiny,frglen,destoff) 
ZLINESTRU *frag;
ZLINESTRU *destiny;
int frglen;
int destoff;
{
    int i,j;

    for (i=0; i < frglen; i++) {
	destiny[destoff+i].ianz = frag[i].ianz;
	for (j=0; j < 3; j++) {
	    destiny[destoff+i].iz[j] = frag[i].iz[j];
	}
	destiny[destoff+i].bl = frag[i].bl;
	destiny[destoff+i].alph = frag[i].alph;
	destiny[destoff+i].bet = frag[i].bet;
    }
}

AddFrag(frag,fraglen,covang,dih,addrow,update,pdbt) 
ZLINESTRU *frag;
int fraglen;
double covang,dih;
int addrow;
int update;
int pdbt;
{
    int row,iptr1,irt,rest,atnr;
    int offset,i,j,isfirst;
    short int iph;

    isfirst = 0;
    if (!*zmptr.nz) isfirst = 1;

    if (DEBUG) {
	fprintf(stderr,"nz %d\n",*zmptr.nz);
	for (i=0; i < fraglen; i++) {
	    fprintf(stderr,"ianz %d\n",frag[i].ianz);
	    for (j=0; j < 4; j++) {
		fprintf(stderr,"iz[%d] %d\n",j,frag[i].iz[j]);
	    }
	fprintf(stderr,"bl %f\n",frag[i].bl);
	fprintf(stderr,"alph %f\n",frag[i].alph);
	fprintf(stderr,"bet %f\n",frag[i].bet);
	}
    }
    

    if (addrow == -1) {
        row = GetRow(1);
        if (row == -1) {
	   if (isfirst) {
		FirstLine();
		row = 0;
		*zmptr.nz = 1;
	   } else {
		return;
	   }
	}
    } else row = addrow;

    atnr = 6;
    irt = NHETRES;
    rest = zmptr.imap[row]-1;
    if (rest >= 0) irt = GetRes(atnr,&iph,rest);

    if (*zmptr.nz >1) {
	zmptr.ianz[row] = frag[0].ianz;
	zmptr.bl[row] = 
		CalcBL(0,frag[0].ianz,zmptr.ianz[izz(row,0)-1]);
	if (pdbt) {

	   iptr1 = row;
	   if (*ialtyp) iptr1 = iptr1 + *iscst;

	   xyz.ipdbt[iptr1] = 0;
	   xyz.ityp[iptr1] = 0;
	   xyz.iresid[iptr1] = irt;
	   xyz.iatclr[iptr1] = 1;
	   xyz.iaton[iptr1] = 1;
	}
    }

    if (*zmptr.nz == 1) {
	row = 0;
        zmptr.ianz[0] = frag[0].ianz;
    }

    for (i=1; i < fraglen; i++) {
	offset = *zmptr.nz + i - 1;
	zmptr.ianz[offset] = frag[i].ianz;
	for (j=0; j < 3; j++) {
	    if (frag[i].iz[j] == 1) {
		sizz(offset,j, row + 1);
	    } else {
		sizz(offset,j, frag[i].iz[j] + *zmptr.nz - 1);
	    }
	}
	sizz(offset,3, frag[i].iz[3]);
	zmptr.bl[offset] = frag[i].bl;
	zmptr.ibl[offset] = 1;
	zmptr.alph[offset] = frag[i].alph;
	zmptr.ialph[offset] = 1;
	zmptr.bet[offset] = frag[i].bet;
	zmptr.ibet[offset] = 1;
	zmptr.imap[offset] = offset+1;
	xyz.iatclr[offset] = 12;
	if (pdbt) {

	    iptr1 = offset;
	    if (*ialtyp) iptr1 = iptr1 + *iscst;

	    xyz.ipdbt[iptr1] = 0;
	    xyz.iresid[iptr1] = irt;
	    xyz.iatclr[iptr1] = 1;
	    xyz.ityp[iptr1] = 0;
	    xyz.iaton[iptr1] = 1;
	}
    }


    sizz(1,1,0);
    sizz(1,2,0);
    sizz(1,3,0);
    sizz(2,2,0);
    sizz(2,3,0);
    zmptr.alph[1] = 0.0;
    zmptr.bet[1] = 0.0;
    zmptr.bet[2] = 0.0;

    if (*zmptr.nz > 1) {
	offset = *zmptr.nz;
	if (row == 0) {
	    sizz(offset,1,2);
	    sizz(offset,2,3);
	} else if (row == 1) {
	    sizz(offset,1,1);
	    sizz(offset,2,3);
	} else {
	    sizz(offset,1,izz(row,0));
	    sizz(offset,2,izz(row,1));
	}
	zmptr.alph[offset] = covang;
	zmptr.bet[offset] = dih;
	offset++;
	if (row == 0) {
	    sizz(offset,2,2);
	} else if (row == 1) {
	    sizz(offset,2,1);
	} else {
	    sizz(offset,2,izz(row,0));
	}
	zmptr.bet[offset] = 180.0;
    }

    update_sel = 1;
    if (update) DeActZME(); 

    *zmptr.nz = *zmptr.nz + fraglen - 1;

    *zmptr.ihaszm = 1;

    if (update) {

	SetQZME(); 

	ZME_window_pos = *zmptr.nz-ZME_window_high;
	if (ZME_window_pos < 0) ZME_window_pos = 0;

	if (*zmptr.nz < ZME_window_high) RedrawZME();
	else UpdateZME();

	*Sinct = 530;
    }
}

AddCycloHexane() {

    AddXH3(6,0);
    (*zmptr.nz)--;
    DeActZME();
    IANZbox[*zmptr.nz-2].active = 1;
    AddXH3(6,0);
    DeActZME();
    IANZbox[*zmptr.nz-3].active = 1;
    AddXH3(6,0);
    strcpy(BETbox[*zmptr.nz-3].str,"60.0");
    BETbox[*zmptr.nz-3].changed = 1;
    GetQZME();
    DeActZME();
    IANZbox[*zmptr.nz-3].active = 1;
    AddXH3(6,0);
    strcpy(BETbox[*zmptr.nz-3].str,"300.0");
    BETbox[*zmptr.nz-3].changed = 1;
    DeActZME();
    GetQZME();
    IANZbox[*zmptr.nz-3].active = 1;
    AddXH3(6,0);
    strcpy(BETbox[*zmptr.nz-3].str,"60.0");
    BETbox[*zmptr.nz-3].changed = 1;
    GetQZME();
    DeActZME();
    IANZbox[*zmptr.nz-3].active = 1;
    AddXH3(6,0);
    strcpy(BETbox[*zmptr.nz-3].str,"60.0");
    BETbox[*zmptr.nz-3].changed = 1;
    DeActZME();
    GetQZME();
    (*zmptr.nz)--;

    ZME_window_pos = *zmptr.nz-ZME_window_high;
    if (ZME_window_pos < 0) ZME_window_pos = 0;

    RedrawZME();
    *Sinct = 530;

}

int ScreenZME(cursorx,cursory)
int cursorx;
int cursory;
{
 int i,j,k,n,ires;

/*

  ScreenZME light up atom closest to cursor, and light up corresponding
  atom in the zmatrix-editor

*/


 if (ZMEup) {

	i = FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
			cursorx,cursory,MINDIFF);

	if (i >= 0) {
    		update_sel = 1;
		for (j=0; j<*zmptr.nz; j++) {
			if (i == zmptr.imap[j]-1) {
				for (k=0; k<*xyz.iatoms; k++) 
				   if (xyz.iaton[k] >= 1) xyz.iaton[k] = 1;
				DeActZME();
				xyz.iaton[i] = 3;
                                if (ZMEAA) {
				   ires = xyz.iresid[i] - 1;
				   CurAmino = ires;
				   if (ires < 0) return(0);
				   ZME_window_pos =  ires;
				} else {
				   n = j/ZME_window_high;
				   ZME_window_pos =  n*ZME_window_high;
				   IANZbox[j].col = ZC_AT1;
				   IANZbox[j].active = 1;
				}
				UpdateZME();
				sprintf(ZMEerr, "Line %d Atom %d",i+1,zmptr.imap[i]);
				RedrawStatus();
				RedrawScroll(&zscroll);
				return(1);
			}
		}
	}
 }
 return(0);
}

int ScreenPDB(cursorx,cursory)
int cursorx;
int cursory;
{
 int iat,ires;

/*

  ScreenPDB light up atom closest to cursor, set CurAmino for later use in AmiCom

*/

   iat = -1; ires = -1;

   if (has_opengl) {
	if (*ipdbon) {
	   if (*fancy) {
                iat = FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
				cursorx,cursory,MINDIFF);
	   } else {
                iat = FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
				cursorx,cursory,MINDIFF);
                if (iat < 0) ires = FindCaP(cursorx,cursory,MINDIFF);
	   }
	}
   } else {
	if (*ipdbon) {
           iat = FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
			cursorx,cursory,MINDIFF);
	   if (iat < 0) ires = FindCaP(cursorx,cursory,MINDIFF);
	}
   }

   if ((iat >= 0 || ires >= 0) && *ipdbon) {
	if (iat >= 0) {
	   CurAmino = xyz.iresid[iat] - 1;
	} else if (ires >= 0) {
	   CurAmino = ires;
	}
	return(1);
   }

   return(0);
}

map_prop()
{
  int j,k;
  int *iarr;
  int *imarr;


/*
 Dont do property mapping when doing interactive docking
*/
  if (*ialtyp == 1) return;
  if (!*zmptr.ihaszm) return;

  if (*ihasq) maparr(NULL,xyz.qat,NULL,NULL,1);
  maparr(NULL,NULL,NULL,xyz.ityp,3);
  maparr(NULL,NULL,NULL,xyz.ipdbt,3);
  maparr(NULL,NULL,xyz.iatclr,NULL,2);
  maparr(NULL,NULL,xyz.iresid,NULL,2);

  if ((iarr = (int *) malloc((sizeof j)*(*zmptr.mxzat))) != NULL) {
    if ((imarr = (int *) malloc((sizeof j)*(*zmptr.mxzat))) != NULL) {
	rearrz(iarr);
	for (k=0; k<6; k++) {
	   for (j=0; j<calfptr->ncalf; j++)
		imarr[j] = calfptr->icalf[j][k];

	   for (j=0; j<calfptr->ncalf; j++) {
		if (imarr[j]-1 >= 0)
		   calfptr->icalf[j][k] = iarr[imarr[j]-1]+1;
	   }
	}
	free(imarr);

     }
     free(iarr);
  }
}

DelLine(row,nlines,nprot,iprot)
int row;
int nlines;
int nprot;
int *iprot;
{
  int j,k,l,rowmap,prot,kcon,noab,ab;

  DeActZME();
  rowmap = zmptr.imap[row];

   map_prop();

   for (j=row; j < *zmptr.nz-nlines; j++) {
	zmptr.bl[j] = zmptr.bl[j+nlines];
	zmptr.alph[j] = zmptr.alph[j+nlines];
	zmptr.bet[j] = zmptr.bet[j+nlines];
	zmptr.ianz[j] = zmptr.ianz[j+nlines];
	for (k=0; k < 4; k++) {
	   prot = 0;
	   for (l=0; l < nprot; l++) {
		if ((izz(j+nlines,k) == iprot[l]) && xyz.iresid[j+nlines] <= 0) prot = 1;
	   }
	   if ((izz(j+nlines,k) < row+1) || prot) 
		sizz(j,k,izz(j+nlines,k));
	   else sizz(j,k,izz(j+nlines,k)-nlines);
	}
	if (ABS(zmptr.ibl[j+nlines]) < row+1) 
	   zmptr.ibl[j] = zmptr.ibl[j+nlines];
	else zmptr.ibl[j] = zmptr.ibl[j+nlines]-SIGN(zmptr.ibl[j+nlines]);

	if (ABS(zmptr.ialph[j+nlines]) < row+1)
	   zmptr.ialph[j] = zmptr.ialph[j+nlines];
	else zmptr.ialph[j] = zmptr.ialph[j+nlines]-SIGN(zmptr.ialph[j+nlines]);

	if (ABS(zmptr.ibet[j+nlines]) < row+1) 
	   zmptr.ibet[j] = zmptr.ibet[j+nlines];
	else zmptr.ibet[j] = zmptr.ibet[j+nlines]-SIGN(zmptr.ibet[j+nlines]);

	xyz.iatclr[j]  = xyz.iatclr[j+nlines];
	xyz.iresid[j]  = xyz.iresid[j+nlines];
	xyz.iaton[j]   = xyz.iaton[j+nlines];
	xyz.ianz[j]    = xyz.ianz[j+nlines];
	stoc.ianstc[j] = xyz.ianz[j+nlines];
	xyz.ipdbt[j]   = xyz.ipdbt[j+nlines];
	xyz.ityp[j]    = xyz.ityp[j+nlines];
	if (*ihasq) xyz.qat[j] = xyz.qat[j+nlines];
	for (k=0; k < 3; k++) {
	   xyz.coo[j*3+k] = xyz.coo[(j+nlines)*3+k];
	   stoc.cstoc[j*3+k] = xyz.coo[(j+nlines)*3+k];
	   stoc.czstoc[j*3+k] = xyz.coo[(j+nlines)*3+k];
	}
	kcon = 0;
	for (k=0; k < xyz.iconn[(j+nlines)*(MXCON+1)]; k++) {
	   noab = xyz.iconn[(j+nlines)*(MXCON+1)+k+1];
	   ab = ABS(noab);
	   prot = 0;
	   for (l=0; l < nprot; l++) {
		if ((ab == iprot[l]) && xyz.iresid[j+nlines] <= 0) prot = 1;
	   }
	   if (ab > row && !prot) {
		if (noab > 0) {
		   xyz.iconn[j*(MXCON+1)+kcon+1] = noab - nlines;
		} else {
		   xyz.iconn[j*(MXCON+1)+kcon+1] = noab + nlines;
		}
		kcon++;
	   } else {
		xyz.iconn[j*(MXCON+1)+kcon+1] = noab;
		kcon++;
	   }
	}
	xyz.iconn[j*(MXCON+1)] = kcon;

   }

   for (j=0; j < *zmptr.nz; j++) {
	zmptr.imap[j] = j + 1;
   }


   for (j=0; j < calfptr->ncalf; j++) {
	for (k=0; k < 4; k++) 
	   if (calfptr->icalf[j][k] >= row) 
		calfptr->icalf[j][k] = calfptr->icalf[j][k] - nlines;
   }

   *zmptr.nz = *zmptr.nz - nlines;
   update_sel = 1;
}

int CheckCOO(ires)
int ires;
{
   int i,ica,icnt,iresult;

   ica = calfptr->icalf[ires-1][0] - 1;
   icnt = 0; iresult = 0;

/* Coo is always the next line after Calfa */

   for (i=0; i < xyz.iconn[(ica+1)*(MXCON+1)]; i++)
	if (xyz.ianz[xyz.iconn[(ica+1)*(MXCON+1)+1+i]-1] == 8) icnt++;
   if (icnt == 2) iresult = 1;

   return(iresult);
   
}

int CheckNH3(ires,icnn1,icnn2)
int ires;
int *icnn1;
int *icnn2;
{
   int i,k,ica,in,icnt,iatje;

   ica = calfptr->icalf[ires-1][0] - 1;
   in = izz(ica,0) - 1;
   icnt = 0; 
   for (i=0; i < xyz.iconn[in*(MXCON+1)]; i++)
	iatje = xyz.iconn[in*(MXCON+1)+1+i]-1;
	if (xyz.ianz[iatje] == 1) {
	   icnt++;
	   if (icnt == 2) {
		icnn1[0] = iatje;
		for (k=0; k<3; k++) {
		   icnn1[k+1] = izz(iatje,k);
		}
	   }
	   if (icnt == 3) {
		icnn2[0] = iatje;
		for (k=0; k<3; k++) {
		   icnn2[k+1] = izz(iatje,k);
		}
	   }
	}
   icnt--;

   return(icnt);
   
}

int DelAmino(ires)
int ires;
{
   int i,j,k,n,ica,ican,nlines,in,inn,icap,icop,iaminn,nlinesn;
   int iend,ibeg,nprot,isrend,isnh3;
   int iprot[3];
   int icnn1[4],icnn2[4];

   ica = calfptr->icalf[ires-1][0] - 1;

   iend = 0; ibeg = 0;

   for (i=0; i < calfptr->nchain; i++) {
	if (ires == calfptr->islu[i]) iend = i + 1;
	if (ires == calfptr->ianf[i]) ibeg = i + 1;
   }

   isrend = CheckCOO(ires);
   isnh3 = CheckNH3(ires,icnn1,icnn2);

   if (iend && isrend) {
	iaminn = calfptr->iamino[ires-1] - 1;
	nlines = aminozmt[iaminn].zlines + 5;
	if (iaminn == 14) nlines--;
	nlinesn = 0;
   } else {
	if (iend == calfptr->nchain) {
	   nlines = *zmptr.nz - ica;
	   for (i=ica; i < *zmptr.nz; i++) {
		if (xyz.iresid[i] != ires) {
		   nlines = i - ica; break;
		}
	   }
	   nlinesn = 0;
	} else {
	   ican = calfptr->icalf[ires][0] - 1;
	   nlines = ican - ica;
	   iaminn = calfptr->iamino[ires] - 1;
	   nlinesn = aminozmt[iaminn].zlines + 5;
	   if (iaminn == 14) nlinesn--;
	}
   }


   in = izz(ica,0);
   icop = izz(ica,1);
   icap = izz(ica,2);

   nprot = 3;
   iprot[0] = ica+1;
   iprot[1] = izz(ica,0);
   iprot[2] = ica+2;
   nprot = 0;

   DelLine(ica,nlines,0,NULL);

   inn = izz(ica,0);
   n = 0;

   if (! (iend && (isrend || iend == calfptr->nchain)) ) {
	sizz(ica,0,in);
	sizz(ica,1,icop);
	sizz(ica,2,icap);

	sizz(ica+1,1,in);
	sizz(ica+1,2,icop);

	n = 5;

	if (zmptr.ianz[ica+2] == 7) {

	   sizz(ica+2,2,in);
	   sizz(ica+4,0,in);
	   sizz(ica+4,2,icop);

	} else {

	   if (zmptr.ianz[ica+2] == 8) {

		if (zmptr.ianz[ica+3] == 1) {
		   sizz(ica+3,0,in);
		   sizz(ica+3,2,icop);
		   n = 4;
		}
		if (zmptr.ianz[ica+3] == 8) {
		   sizz(ica+2,2,in);
		   sizz(ica+4,0,in);
		   sizz(ica+4,2,icop);
		   n = 5;
		}
	
	   }
	}
   }

   if (ibeg) sizz(ica+4,2,ica + 2);

   if (iend && (isrend || iend == calfptr->nchain) ) {

/* 
   if this was the last residue, change the N to OXT
   BUT what if it was the last of this chain, and it goes on
   with an other chain. Then you have lost the N which belonged to
   the next residue !!!. You now have the first residue of a new chain
   WITHOUT an N
*/
	zmptr.ianz[in-1] = 8;
	xyz.iresid[in-1] = xyz.iresid[in-1] - 1;
	xyz.ipdbt[in-1] = 38;
   } else {
	xyz.iatclr[in-1] = xyz.iatclr[ica];
   }

/* search for more lines which where defines with respect to backbone
   N of residue ires+1; inn */

   if (! (iend && (isrend || iend == calfptr->nchain)) ) {
	for (i=ica+n; i < *zmptr.nz; i++) {
	   for (k=0; k < 3; k++) 
		if (izz(i,k) == inn) sizz(i,k,in);
	}
/* 
   In case of res after the deleted one is after a chain break, the N has
   three H's attached to it. Two of them are not located in the amino part of
   the zmatrix, but rather much further down. The have to be connected to
   the right atom again.
   DUBBEL OP zie boven !!!, alleen als grenzen i=ica; i < ica+nlinesn
   voegt dit iets toe
*/
	for (i=ica+nlinesn; i < *zmptr.nz; i++) {
	   if (izz(i,0) == inn) sizz(i,0,in);
	}
   }

   for (i=0; i < *zmptr.nz; i++) {
	if (xyz.iresid[i] > ires) 
	   xyz.iresid[i] = xyz.iresid[i] - 1;
   }

   for (j=ires-1; j < calfptr->ncalf; j++) {
	for (k=0; k < 4; k++) 
		calfptr->icalf[j][k] = calfptr->icalf[j+1][k];
	calfptr->iamino[j] = calfptr->iamino[j+1];
	calfptr->reson[j] = calfptr->reson[j+1];
	irsnr[j] = irsnr[j+1] - 1;
	isal[j] = isal[j+1];
	strcpy(achain[j],achain[j+1]);
   }

   calfptr->ncalf = calfptr->ncalf - 1;
   calfptr->issdon = 0;

   for (i=0; i < calfptr->nchain; i++) {
	if (ires <= calfptr->islu[i]) calfptr->islu[i] = calfptr->islu[i] - 1;
	if (ires < calfptr->ianf[i]) calfptr->ianf[i] = calfptr->ianf[i] - 1;
   }

   if (ZME_window_pos >= *zmptr.nz-1) ZME_window_pos = 0;
   SetQZME(); RedrawZME(); 

   return(nlines);
}

FindZRange(ires)
int ires;
{
   int ica,ica2,i;

   ica = calfptr->icalf[ires-1][0] - 1;
   ica2 = calfptr->icalf[ires][0] - 1;

   *imx = -1;
   for (i=ica; i < *zmptr.nz; i++) {
        if (xyz.iresid[i] != ires) {
            *imx = i; break;
        }
   }
   *imn = ica + 1;
   /*
   *imn = ica;
   */
   if (*imx == -1) *imx = *zmptr.nz;
   else *imx = *imx + 1;

   if (ires <= calfptr->ncalf-1) *imx = ica2;

   if (*imx > *imn) *ipart = 2;
}

FindZRangeFromBox(isel)
int isel;
{
   int ica,ires,iamino,sidechainstart,i;

   if (!*ipdbon || *ialtyp) return;
/*
 Dont do partial zmatrix update when doing interactive docking
*/

   ires = xyz.iresid[isel];

   if (ires < 0) {
	*imn = isel + 1;
	*imx = *zmptr.nz;

	if (*imx > *imn) *ipart = 1;
	return;
   }

   iamino = calfptr->iamino[ires-1];

   if (!(iamino > 0 && iamino <= 23)) return;

   ica = calfptr->icalf[ires-1][0] - 1;

   sidechainstart = ica+5;

   if (iamino == 15) {
	sidechainstart = ica+4;
	if (zmptr.ianz[ica+2] == 8) { 
		sidechainstart--; 
	}
   } else {
/* if start residue there might be an N missing at nz+2 */

	if (zmptr.ianz[ica+4] != 1 && zmptr.ianz[ica+3] == 1) 
		sidechainstart--; 
   }

   if (isel < sidechainstart) return;

   for (i=sidechainstart; i < *zmptr.nz; i++) {
        if (xyz.iresid[i] != ires) {
            *imx = i; break;
        }
   }
   *imn = sidechainstart + 1;
   *imx = *imx + 1;

   if (*imx > *imn) *ipart = 1;
}

int AmiCom(iopt,x,y)
int iopt;
int x;
int y;
{

  if (ZMEAA || (!ZMEup && *ipdbon) ) {
        int ires,i;

	ires = -1;

	if (iopt) {
	   ires = CurAmino + 1;
	   if (ires <= -4) {
		if (HetCom(x,y)) return(1);
	   }
	} else {
	   i = Clickwin(ZMEAAbut,ZME_window_high,x,y,1);
	   if (i>=0) {
		ires = ZME_window_pos+i+1;
		CurAmino = ires-1;
	   }
	}
	moving = gmoving = 0;
	if (ires > 0) {
	   LSSTRU List; int iamin, aminotyp;

	   aminotyp = calfptr->iamino[ires-1]-1;

#ifdef DOGL
	   List.list = AmiBOpt; List.nents = 14;

           if (calfptr->iamino[ires-1] > 23 || (!ZMEup && *ipdbon)) {
		List.nents = 5;
	   } else {
		if (ires == calfptr->ncalf) List.nents = 15;
	   }
#else
	   List.list = AmiBOpt; List.nents = 13;

           if (calfptr->iamino[ires-1] > 23 || (!ZMEup && *ipdbon)) {
		List.nents = 4;
	   } else {
		if (ires == calfptr->ncalf) List.nents = 14;
	   }
#endif
  
	   if (iopt) {
		if (DoPopUp(win,x,y,&List,&iamin,0) == -1) return 0;
	   } else {
		if (DoPopUp(ZMEwin,
			ZMEAAbut[i].x+5,ZMEAAbut[i].y+5,
			&List,&iamin,0) == -1) return 0;
	   }

#ifndef DOGL
	   if (iamin >= 4) iamin++;
#endif

	   switch (iamin) {
	   case 0:
#if defined(VMS) || defined(UNDERSC)
			actami(&ires,&ZERO,&ONE,&ZERO);
#else
#ifdef CRAY
			ACTAMI(&ires,&ZERO,&ONE,&ZERO);
#else
			actami_(&ires,&ZERO,&ONE,&ZERO);
#endif
#endif
			rsold = RESUND;
#ifdef DOGL
			ogres(ires,ONE,1);
#else
			return(1);
#endif
			break;
	   case 1:
#if defined(VMS) || defined(UNDERSC)
			actami(&ires,&ZERO,&ZERO,&ZERO);
#else
#ifdef CRAY
			ACTAMI(&ires,&ZERO,&ZERO,&ZERO);
#else
			actami_(&ires,&ZERO,&ZERO,&ZERO);
#endif
#endif
			rsold = RESUND;
#ifdef DOGL
			ogres(ires,ONE,1);
			return(1);
#else
			return(1);
#endif
			break;
	   case 2:
#if defined(VMS) || defined(UNDERSC)
			setorg(&calfptr->icalf[ires-1][0]);
#else
#ifdef CRAY
			SETORG(&calfptr->icalf[ires-1][0]);
#else
			setorg_(&calfptr->icalf[ires-1][0]);
#endif
#endif
			return(1);
			break;
	   case 3:
#if defined(VMS) || defined(UNDERSC)
			proxic(&calfptr->icalf[ires-1][0],&backb);
#else
#ifdef CRAY
			PROXIC(&calfptr->icalf[ires-1][0],&backb);
#else
			proxic_(&calfptr->icalf[ires-1][0],&backb);
#endif
#endif
			XMapRaised(display,DISTwin);
			RedrawDIST();
			return(1);
			break;
	   case 4:
			iams[ires-1] = 1;
#if defined(VMS) || defined(UNDERSC)
			initsrf();
#else
#ifdef CRAY
	 		INITSRF();
#else
			initsrf_();
#endif
#endif
		/*	return(1);*/
			break;
	   case 5:
#if defined(VMS) || defined(UNDERSC)
			curs(&ONE);
#else
#ifdef CRAY
	 		CURS(&ONE);
#else
			curs_(&ONE);
#endif
#endif
			idum1 = DelAmino(ires);
			make_aa();
			if (ZME_window_pos >= calfptr->ncalf) ZME_window_pos = 0;
			if (calfptr->ncalf < ZME_window_high) RedrawZME();
			else UpdateZME();
			RedrawScroll(&zscroll);
			*Sinct = 530;
			update_model = 1;
			return(1);
			break;
	   case 6:
			InsertAmino = ires;
			ReplaceAmino = 0;
			if (SEQup) {
			   XMapRaised(display,SEQwin);
			   RedrawSEQ();
			} else {
			   InitSEQ(event.xbutton.x_root,event.xbutton.y_root);
			}
			update_model = 1;
			break;
	   case 7:	{
			LSSTRU List; int inrs; int irsnrt;
			List.list = AminoAcids; List.nents = 20;

			if (iopt) {
			   if (DoPopUp(win,x,y,&List,&inrs,0) == -1) return 0;
			} else {
			   if (DoPopUp(ZMEwin,
				ZMEAAbut[i].x+5,ZMEAAbut[i].y+5,
				&List,&inrs,0) == -1) return 0;
			}
#if defined(VMS) || defined(UNDERSC)
			curs(&ONE);
#else
#ifdef CRAY
	 		CURS(&ONE);
#else
			curs_(&ONE);
#endif
#endif
			Sequence[0] = inrs;

    			irsnrt = irsnr[ires-1];
			ReplaceSequence(Sequence,1,0,ires);
    			irsnr[ires-1] = irsnrt;
			make_aa();
			SetQZME();
			if (ZME_window_pos >= calfptr->ncalf) ZME_window_pos = 0;
			if (calfptr->ncalf < ZME_window_high) RedrawZME();
			else UpdateZME();
			RedrawScroll(&zscroll);
			FindZRange(ires);

#if defined(VMS) || defined(UNDERSC)
			actami(&ires,&ZERO,&ONE,&ZERO);
#else
#ifdef CRAY
			ACTAMI(&ires,&ZERO,&ONE,&ZERO);
#else
			actami_(&ires,&ZERO,&ONE,&ZERO);
#endif
#endif
   			zmt2cor(ires,1);
			}
			break;
	   case 8:	  
			if (!AddCap(ires)) return(0);
			return(1);
			break;
	   case 9:	{  
			LSSTRU List; int inrs;
			List.list = Rotamers; 
			List.nents = aminozmt[aminotyp].nrots;

			if (iopt) {
			   if (DoPopUp(win,x,y,&List,&inrs,0) == -1) return 0;
			} else {
			   if (DoPopUp(ZMEwin,
				ZMEAAbut[i].x+5,ZMEAAbut[i].y+5,
				&List,&inrs,0) == -1) return 0;
			}
			if (aminozmt[aminotyp].chis[0] != -1) 
				zmptr.bet[aaptr[ires-1].chi1] = aminozmt[aminotyp].rots[inrs].rots[0];
			if (aminozmt[aminotyp].chis[1] != -1) 
				zmptr.bet[aaptr[ires-1].chi2] = aminozmt[aminotyp].rots[inrs].rots[1];
			if (aminozmt[aminotyp].chis[2] != -1) 
				zmptr.bet[aaptr[ires-1].chi3] = aminozmt[aminotyp].rots[inrs].rots[2];
			if (aminozmt[aminotyp].chis[3] != -1) 
				zmptr.bet[aaptr[ires-1].chi4] = aminozmt[aminotyp].rots[inrs].rots[3];
#if defined(VMS) || defined(UNDERSC)
			curs(&ONE);
#else
#ifdef CRAY
	 		CURS(&ONE);
#else
			curs_(&ONE);
#endif
#endif
			SetQZME();
			if (ZME_window_pos >= calfptr->ncalf) ZME_window_pos = 0;
			if (calfptr->ncalf < ZME_window_high) RedrawZME();
			else UpdateZME();
			RedrawScroll(&zscroll);
			FindZRange(ires);
   			zmt2cor(ires,0);
			}
			break;
	   case 10:	{  
			void scanrot(int,int);

			scanrot(ires,aminotyp);

			}
			break;
	   case 11:	{  
			void onerot(int);

			onerot(ires);

			}
			break;
	   case 12:	
			{int ikeus;
	   		List.list = RotLib; List.nents = 2;
			if (DoPopUp(win,x,y,&List,&ikeus,0) == -1) return 0;
			if (ikeus) aminozmt = aminozmtd;
			else aminozmt = aminozmtr;
			}
			break;
	   case 13:	
			initflx();
			for (i=0; i < *xyz.iatoms; i++) {
			   if (xyz.iresid[i] == ires) {
				xyz.iatclr[i] = 1;
			   }
			}
			pmfrot->idrs[pmfrot->ndrs] = ires;
			resrot[0].idrs[pmfrot->ndrs] = ires;
			pmfrot->ndrs++;
			resrot[0].ndrs = pmfrot->ndrs;
#ifdef DOGL
			ogres(ires,1,1);
#endif
			update_model = 0;
			break;
	   case 14:	
#if defined(VMS) || defined(UNDERSC)
			curs(&ONE);
#else
#ifdef CRAY
	 		CURS(&ONE);
#else
			curs_(&ONE);
#endif
#endif
			InsertAmino = -1;
			ReplaceAmino = 0;
			LastAmino = calfptr->icalf[ires-1][2];
			if (SEQup) {
			   XMapRaised(display,SEQwin);
			   RedrawSEQ();
			} else {
			   InitSEQ(event.xbutton.x_root,event.xbutton.y_root);
			}
			break;
	   }
	}
  }
  return(0);
}

int HetCom(x,y)
int x;
int y;
{

  if (ZMEAA || (!ZMEup && *ipdbon) ) {
        int ires,i,istat;
	double rdist;

        rdist = 5.0;


	ires = CurAmino + 1;

	moving = gmoving = 0;

	if (ires < 0) {
	   LSSTRU List; int iamin, aminotyp;

#ifdef DOGL
	   List.list = HetOpt; List.nents = 5;

#else
	   List.list = HetOpt; List.nents = 4;

#endif
  
	   if (DoPopUp(win,x,y,&List,&iamin,0) == -1) return 0;

	   switch (iamin) {
	   case 0:
			i = FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
			            x,y,MINDIFF);
			if (i != -1) {
			   i++;
#if defined(VMS) || defined(UNDERSC)
			setorg(&i);
#else
#ifdef CRAY
			SETORG(&i);
#else
			setorg_(&i);
#endif
#endif
			return(1);
			}
			break;
	   case 1:
			i = FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
			            x,y,MINDIFF);
			i++; 
#if defined(VMS) || defined(UNDERSC)
			proxic(&i,&backb);
#else
#ifdef CRAY
			PROXIC(&i,&backb);
#else
			proxic_(&i,&backb);
#endif
#endif
			XMapRaised(display,DISTwin);
			RedrawDIST();
			return(1);
			break;
	   case 2:
#if defined(VMS) || defined(UNDERSC)
			eem(&ONE,&ires,&istat);
#else
#ifdef CRAY
	 		EEM(&ONE,&ires,&istat);
#else
			eem_(&ONE,&ires,&istat);
#endif
#endif
		/*	return(1);*/
			break;
	   case 3:
			DelHet(ires);
			return(1);
			break;
	   case 4:
			if (ires < 0) {
			   ihets[ABS(ires)] = 1;
#if defined(VMS) || defined(UNDERSC)
			   initsrf();
#else
#ifdef CRAY
	 		   INITSRF();
#else
			   initsrf_();
#endif
#endif
			}
		/*	return(1);*/
			break;
	   }
	}
  }
  return(0);
}

int PressZME(butnr,x,y)
int butnr;
int x;
int y;
{
  int i,j,k,iptr;
  int nat,nattmp,nprev,nvar;
  int type,row,column,deloke;
  LSSTRU List;

  if (DEBUG) fprintf(stderr,"PressZME in\n");

if (ZMEmode) {
  i = Clickwin(TabBut,TABBUTN,x,y,1);
      if (i>=0) {
	DeActZME();
        if (i==TABBUTN-1) ZMEatom = 99;
	else ZMEatom = i+1;
	nvar = 3; if (*zmptr.nz <= 2) nvar = *zmptr.nz;
	ZMEmode = 0;
	if (nvar > 0) {
	    ZMEsel = 1;
	    aflag = nvar;anum = nvar;acnt = 0;
	    sprintf(stemp,
		"Select %d Atoms to define the connectivety of this Center"
		,nvar);
	    strcpy(ZMEerr,stemp);
	    XDefineCursor(display,win,AtomCursor);
	    ActBut(&cbut[BDIST],0);
	    ActBut(&cbut[BANGLE],0);
	    ActBut(&cbut[BDIHED],0);
	}
	else AddLine(ZMEatom,1,NULL,NULL,NULL,NULL,ZMEmul);
	RedrawZME();
	return(1);
      }
      i = Clickwin(&ZMEBbut[ZMESIN],3,x,y,1);

      if (i>=0) {
	  switch (i) {
	  case ZMESIN:	TogBut(&ZMEBbut[ZMEmul]);ActBut(&ZMEBbut[ZMEmul],1);
			ZMEmul = ZMESIN;
			TogBut(&ZMEBbut[ZMEmul]);ActBut(&ZMEBbut[ZMEmul],-1);
			break;
	  case ZMEDBL:	TogBut(&ZMEBbut[ZMEmul]);ActBut(&ZMEBbut[ZMEmul],1);
			ZMEmul = ZMEDBL;
			TogBut(&ZMEBbut[ZMEmul]);ActBut(&ZMEBbut[ZMEmul],-1);
			break;
	  case ZMETRI:	TogBut(&ZMEBbut[ZMEmul]);ActBut(&ZMEBbut[ZMEmul],1);
			ZMEmul = ZMETRI;
			TogBut(&ZMEBbut[ZMEmul]);ActBut(&ZMEBbut[ZMEmul],-1);
			break;
	  }
      }
      return(0);
}
else if (!Selecting && !ZMEsel) {

  if (butnr == 3) { 
	k = 0;
	if (QBoxPaste(ZMEwin,IANZbox,*zmptr.nz)) k = 1;;
	if (QBoxPaste(ZMEwin,BLbox,*zmptr.nz)) k = 1;;
	if (QBoxPaste(ZMEwin,ALPHbox,*zmptr.nz)) k = 1;;
	if (QBoxPaste(ZMEwin,BETbox,*zmptr.nz)) k = 1;;
	if (!k) OnTop();
	return(0);
  } else { 

     i = ClickBox(IANZbox,*zmptr.nz,x,y);
     if (i>=0) {
   	DeActZME();
	IANZbox[i].col = ZC_AT1;
	IANZbox[i].active = 1; UpdateZME();
	if (zmptr.imap[i]-1 >= 0) xyz.iaton[zmptr.imap[i]-1] = 3;
	sprintf(ZMEerr, "Line %d Atom %d",i+1,zmptr.imap[i]);
	RedrawStatus();
	update_model = 0;
	update_sel = 1;
	return(1);
     }
     i = ClickBox(BLbox,*zmptr.nz,x,y);
     if (i>=0) {
	ActVar(i,0,butnr);
	return(1);
     }
     i = ClickBox(ALPHbox,*zmptr.nz,x,y);
     if (i>=0) {
	ActVar(i,1,butnr);
	return(1);
     }
     i = ClickBox(BETbox,*zmptr.nz,x,y);
     if (i>=0) {
	ActVar(i,2,butnr);
	return(1);
     }
     for (i=0; i<*zmptr.nz; i++) {
	j = ClickBox(&IZbox[i*4],4,x,y);
	if (j>=0) {
		update_model = 0;
		DeActZME(); 
		iptr = izz(i,j)-1;
		if (iptr < *zmptr.nz && iptr >= 0) {
			IANZbox[iptr].col = ZC_AT2+j;
			xyz.iaton[zmptr.imap[iptr]-1] = 4+j;
		}
		IANZbox[i].col = ZC_AT1;
		IZbox[i*4+j].active = 1;
		UpdateZME();
		if (zmptr.imap[i]-1 >= 0) xyz.iaton[zmptr.imap[i]-1] = 3;
		update_sel = 1;
		return(1);
	}
     }
   }
}

if (ZMEsel) return(0);

  i = ClickBox(&qboxes[QBZMAT],1,x,y);
  if (i>=0) {
		DeActZME(); 
		UpdateZME();
		qboxes[QBZMAT].active = 1;
		EXPbox[0].active = 0;
		PromptBox(&qboxes[QBZMAT]);
		PromptBox(&EXPbox[0]);
  }

  i = ClickBox(&EXPbox[0],1,x,y);
  if (i>=0) {
		DeActZME(); 
		UpdateZME();
		EXPbox[0].active = 1;
		qboxes[QBZMAT].active = 0;
		PromptBox(&EXPbox[0]);
		PromptBox(&qboxes[QBZMAT]);
  }

  i = Clickwin(ZMEswitch,2,x,y,1);
  if (i>=0) {
     switch (i) {
     case 0:
	if (pdb && ! *ialtyp) {
	   if (ZMEAA) {
		ZMEAA = 0;
		TogDown(&ZMEswitch[0]);
		EXPbox[0].fake = 1;
	   } else {
		ZMEAA = 1;
		make_aa();
		TogUp(&ZMEswitch[0]);
		EXPbox[0].fake = 0;
	   }
	   DeActZME();
	   SetQZME();
	   RedrawZME();
	}
	break;
     case 1:
	size_hints.flags =  USSize;
	size_hints.width = ZMEWINW;
	if (!ZMEbig) {
	   size_hints.height = ZMEWINH;
	   ZMEbig = 1;
	} else {
	   size_hints.height = ZMEZOffy-ZMEFRBord+ZMEZHIGH+1;
	   ZMEbig = 0;
	}
	XSetNormalHints(display, ZMEwin, &size_hints);
	XResizeWindow(display, ZMEwin, ZMEWINW,size_hints.height);
	TogBut(&ZMEswitch[1]);
	DrwBut(&ZMEswitch[1]);
	break;
     }
  }

  if (AmiCom(0,x,y) == 1) {
	update_model = 0;
	return(1);
  }

  i = Clickwin(ZMEbut,ZMEBUTTS,x,y,1);

      if (i>=0) {
	  strcpy(ZMEerr," ");
	  RedrawStatus();
	  switch (i) {
	  case ZMEARR1: ScrollBut(i); break;
	  case ZMEARR2: ScrollBut(i); break;
          case ZMEAPPL:	if (!Selecting && !ZMEsel) {
			    DeActZME(); GetQZME(); UpdateZME(); 
		  	    map_prop();
			    for (j=0; j<MAXSURF; j++) SSon[j] = 0;
			    SSdone = 0;
			    *Sinct = 530; return(1); 
			}
			break;
          case ZMECAN1:	if (!Selecting && !ZMEsel) {
			    DeActZME(); SetQZME(); UpdateZME(); return(1); 
			}
			break;
          case ZMEFRG:	
			{int iret; 
			   iret = GetFrag(0,0,0);
			   if (iret != -1) return(iret);
			}
			break;
	  case ZMEADD:	if (!Selecting && !ZMEsel) {
			    ZMEmode = 1; RedrawZME(); return(0); 
			    calfptr->issdon = 0;
			}
			break;
	  case ZMEDEL:	if (Selecting || ZMEsel) break;
			activeZME(&type,&row,&column);
			deloke = 1;
			calfptr->issdon = 0;
			if (row < *zmptr.nz && row >= 0) {
				for (j=row+1; j < *zmptr.nz; j++) {
					for (k=0; k < 4; k++)
						if (izz(j,k) == row+1) 
							deloke = 0;
					if (deloke) {
					if (ABS(zmptr.ibl[j]) == row+1) 
						deloke = -1;
					if (ABS(zmptr.ialph[j]) == row+1) 
						deloke = -1;
					if (ABS(zmptr.ibet[j]) == row+1) 
						deloke = -1;
					}
				}
			} else {
				deloke = -2;
			}
			if (deloke == 1) {
				DelLine(row,1,0,NULL);
				if (ZME_window_pos >= *zmptr.nz-1) ZME_window_pos = 0;
				SetQZME(); RedrawZME(); *Sinct = 530; return(1);
			}
			else {
				if (deloke == -1) strcpy(ZMEerr,
					"LINE NOT DELETED: first remove all links to this line");
				else if (deloke == -2) strcpy(ZMEerr,
					"LINE NOT DELETED: no atom selected");
				else strcpy(ZMEerr,
					"LINE NOT DELETED: first remove all atoms connected to this line");
				if (*ibell) XBell(display,0);
				RedrawStatus();
			}
			break;
	  case ZMENEW:	if (!Selecting && !ZMEsel) {
			   *irtcel = 0;
			   *fftyp = 0;
			   pdb = 0;
			   *ipdbon = 0;
			   *icalc = 0;
			   *ichx = 0;
			   *natorg = 0;
			   DeActZME();
			   *xyz.iatoms = 0;
			   for (j=0; j < 3; j++)
			      for (k=0; k < 3; k++)
				xyz.coo[j*3+k] = 0.0;
			   *zmptr.nz = 0;
			   ZME_window_pos = 0;
			   *zmptr.ihaszm = 1;
			   *geopntr.ieav = 0;
			   calfptr->ncalf = 0;
			   backb = 0;
			   calfptr->nchain = 0;
			   LastAmino = -1;
			   calfptr->issdon = 0;
			   ZMEAA = 0;
          		   SetQZME(); RedrawZME();
			   if (ATMup) {
				UpdateATM();
				XMapRaised(display,ATMwin);
				RedrawATM();
			   }
			   send_expose();
			   empty_model();
			   return(1);
			}
			break;
	  case ZMEMAP:	if (!Selecting && !ZMEsel) {
			   int ff; List.list = mapopt; List.nents = 7;
			   if (DoPopUp(ZMEwin,
				ZMEbut[ZMEMAP].x+1,ZMEbut[ZMEMAP].y-BUTTH,
				&List,iixyz,0) == -1) break;
			   if (*iixyz >= 4) {
				switch(*iixyz) {
				case 4:
					ff = 5;
					break;
				case 5:
					ff = 6;
					break;
				case 6:
					if (! (*fftyp >= 1 && *fftyp <= 4) ) {
					   ff = 1;
					   if (pdb) ff = 2;
					} else {
					   ff = *fftyp;
					}
					break;
				default:
					break;
				}
				if (typit(ff)) {
				   if (DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
					"Found UnTyped Atoms !",0)) {}
				} else {
				   if (*iixyz == 6) {
					if (TNKup) {
					   XMapRaised(display,TNKwin);
					   RedrawTNK();
					} else {
					   InitTNK(event.xbutton.x_root,
						event.xbutton.y_root);
					}
				   } else {
					*Sinct = 151; return(1);
				   }
				}
			   } else {
			      qboxstr(&qboxes[QMXYZ],NULL,1,0,-1,DEFQX,DEFQY,
				   QBOXWIDE,QBOXHIGH, 0,"XYZ file ? ",NULL,
				   0,0,151,dummyproc);
			   }
			}
			break;
	  case ZMECANC:	
			UnMapZME();
			break;
	  case ZMECVAR:	 { int iop;
			   List.list = zmevarclr; List.nents = 2;
			   if (DoPopUp(ZMEwin,
				ZMEbut[ZMECVAR].x+1,ZMEbut[ZMECVAR].y+BUTTH,
				&List,&iop,0) == -1) break;
			   SetConst(iop);
			}
			break;
	  case ZMEGAM:	TogBut(&ZMEbut[ZMEopt]);ActBut(&ZMEbut[ZMEopt],1);
			ZMEopt = ZMEGAM;
			TogBut(&ZMEbut[ZMEopt]);ActBut(&ZMEbut[ZMEopt],-1);
			break;
	  case ZMEUS:
			if (*igztyp) {
			   TogBut(&ZMEbut[ZMEUS]);
			   *igztyp = 0;
			   strcpy(ZMEerr,"Switching to Gamess-UK style of Z-Matrix writing");
			} else {
			   TogDown(&ZMEbut[ZMEUS]);
			   *igztyp = 1;
			   strcpy(ZMEerr,"Switching to Gamess-US style of Z-Matrix writing");
			}
			RedrawStatus();
			break;
	  case ZMEGAU:	TogBut(&ZMEbut[ZMEopt]);ActBut(&ZMEbut[ZMEopt],1);
			ZMEopt = ZMEGAU;
			TogBut(&ZMEbut[ZMEopt]);ActBut(&ZMEbut[ZMEopt],-1);
			break;
	  case ZMEMOP:	TogBut(&ZMEbut[ZMEopt]);ActBut(&ZMEbut[ZMEopt],1);
			ZMEopt = ZMEMOP;
			TogBut(&ZMEbut[ZMEopt]);ActBut(&ZMEbut[ZMEopt],-1);
			break;
	  case ZMECAR:	{LSSTRU List;
			TogBut(&ZMEbut[ZMEopt]);ActBut(&ZMEbut[ZMEopt],1);
			ZMEopt = ZMECAR;
			TogBut(&ZMEbut[ZMEopt]);ActBut(&ZMEbut[ZMEopt],-1);
			List.list = xyzopt; List.nents = 5; /* List.nents = 4; */
			DoPopUp(ZMEwin,ZMEbut[ZMECAR].x+1,
					ZMEbut[ZMECAR].y-3*BUTTH,&List,ixyz,0);
			/* DoPopUp(ZMEwin,ZMEbut[ZMECAR].x+1,
					ZMEbut[ZMECAR].y-2*BUTTH,&List,ixyz,0); */
			}
			break;
	  case ZMESUB:
			if (TogBut(&ZMEbut[ZMESUB])) {
			   XDestroyWindow(display,SUBwin);
		   	   SUBup = 0;
			} else {
			   if ((ZMEopt == ZMEGAM) && *igztyp) {
		  	 	if (DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
					"Submit Gamess-US not available",0)) {
				}
				TogBut(&ZMEbut[ZMESUB]); 
			   } else {
				if (!CreateSUB(ZMEopt-ZMEGAM)) 
					TogBut(&ZMEbut[ZMESUB]);
			   }
			}
			break;
	  case ZMEWRT:
			*Sinct = qboxes[QBZMAT].qbinct;
			*iwropt = ZMEopt-ZMEGAM + 1;
			cpstr(qboxes[QBZMAT].str,Sstr,
				strlen(qboxes[QBZMAT].str));
			*Snstr = strlen(qboxes[QBZMAT].str);
			return(1);
			break;
	  case ZMEORD:
			if (!Selecting && !dflag && !cflag) {
			   if (!DoCan(event.xbutton.x_root,
				event.xbutton.y_root,
				"Use ESC to cancel\nUse CNTL to rotate",1)) {
				for (i = 0; i <*xyz.iatoms; i++) 
				   if (i < *xyz.mxnat) jring[i] = 0;
				Selecting = 1; ZMEsel = 1;
				dflag = 1;
				aflag = *xyz.iatoms; 
				anum = *xyz.iatoms; acnt = 0;
				XDefineCursor(display,win,AtomCursor);
				strcpy(ZMEerr,"Select Atoms in the order you want the Z-matrix created");
				RedrawStatus();
				DeActZME();
			   }
			}
			break;
	  case ZMESEL:
			strcpy(ZMEerr,selstr);
			RedrawStatus();
			DeActZME();
			Selecting = 1;
			ZoomEnable = True;Select = True;
			break;
	  case ZMEUSEL:
			strcpy(ZMEerr,dselstr);
			ZoomEnable = True;Select = False;
			break;
	  case ZMESELA:
			Selecting = 0;
			nat = 0;
			for ( i = 0; i < *xyz.iatoms; i++ ) 
				if (xyz.iaton[i] > 1) nat++;
			if (!nat) {
				strcpy(ZMEerr,"Invalid Selection: No atoms selected");
				if (*ibell) XBell(display,0);
				RedrawStatus();
				return(0);
			}
			if (nat > *zmptr.mxzat) {
			   strcpy(ZMEerr,"Invalid Selection: Too many atoms selected");
			   if (*ibell) XBell(display,0);
			   RedrawStatus();
			   for ( i = 0; i < *xyz.iatoms; i++ ) 
				if (xyz.iaton[i] >= 2) xyz.iaton[i] = 1;
			   update_sel = 1;
		  	   return(1);
			}
			else {
			   AGLAB:
			   nprev = -1;
			   nattmp = 0;
			   for ( i = 0; i < *xyz.iatoms; i++ ) {
				if (xyz.iaton[i] >= 2) {
			  	    nattmp++;
				    if (i != nprev+1) {
					for ( j = 0; j < *xyz.iatoms-i; j++ ) {
					    for (k=0; k < 3; k++)
						xyz.coo[(nprev+1+j)*3+k] = 
						   xyz.coo[(i+j)*3+k];
					    xyz.ianz[nprev+1+j] = xyz.ianz[i+j];
					    xyz.iaton[nprev+1+j] = xyz.iaton[i+j];
					    xyz.iatclr[nprev+1+j] = xyz.iatclr[i+j];
					    xyz.iresid[nprev+1+j] = xyz.iresid[i+j];
					    xyz.qat[nprev+1+j] = xyz.qat[i+j];
					    xyz.ipdbt[nprev+1+j] = xyz.ipdbt[i+j];
					    xyz.ityp[nprev+1+j] = xyz.ityp[i+j];
					}
					if (nattmp < nat) goto AGLAB;
				    }
				    nprev = i;
				}
			   }
		 	   *xyz.iatoms = nat;
			   *ichx = 0; cellpnt->iclon = 0;
			   *ipdbon = 0;
			   ZMEAA = 0;
			   ApplSel(1);
			   empty_model();
			   *Sinct = 530;
			   update_sel = 1;
			   return(1);
			}
			break;
          }
      }
  ScrollPage(NULL,&zscroll,x,y);

  if (DEBUG) fprintf(stderr,"PressZME out\n");
  return (0);
}

ApplSel(iop)
int iop;
{
int i,j;

   ZME_window_pos = 0;
   *doesp = 0;

   if (iop) {
#if defined(VMS) || defined(UNDERSC)
	docent();doconn();doscal();setxyv();
#else
#ifdef CRAY
	DOCENT();DOCONN();DOSCAL();SETXYV();
#else
	docent_();doconn_();doscal_();setxyv_();
#endif
#endif
   }



   j = 0;
#if defined(VMS) || defined(UNDERSC)
   intzmt(&j);
#else
#ifdef CRAY
   INTZMT(&j);
#else
   intzmt_(&j);
#endif
#endif

   if (*ihasq) maparr(NULL,xyz.qat,NULL,xyz.ityp,1);
   maparr(NULL,NULL,NULL,xyz.ityp,3);
   maparr(NULL,NULL,NULL,xyz.ipdbt,3);
   maparr(NULL,NULL,xyz.iatclr,NULL,2);
   maparr(NULL,NULL,xyz.iresid,NULL,2);

   for ( i = 0; i < *xyz.iatoms; i++ ) {
	if (xyz.iaton[i] >= 2) xyz.iaton[i] = 1;
   }
   update_sel = 1;
   SetQZME();
   RedrawZME();
}

maparr(flarr,dblarr,intarr,shintarr,iopt)
float *flarr;
double *dblarr;
int *intarr;
short int *shintarr;
int iopt;
{
   float *flarrt;
   double *dblarrt;
   int *intarrt;
   short int *shintarrt;
   int j;

   switch(iopt) {
   case 0:
	if ((flarrt = (float *) malloc((sizeof *flarrt)*(*zmptr.mxzat))) 
	   != NULL) {

	   for (j=0; j<*zmptr.nz; j++) {
	      if (zmptr.imap[j] > 0) {
		flarrt[j] = flarr[zmptr.imap[j]-1];
	      } else {
		flarrt[j] = 0.0;
	      }
	   }
	   for (j=0; j<*zmptr.nz; j++) flarr[j] = flarrt[j];
	   free(flarrt);
	}
	break;
   case 1:
	if ((dblarrt = (double *) malloc((sizeof *dblarrt)*(*zmptr.mxzat))) 
	   != NULL) {

	   for (j=0; j<*zmptr.nz; j++) {
	      if (zmptr.imap[j] > 0) {
		dblarrt[j] = dblarr[zmptr.imap[j]-1];
	      } else {
		dblarrt[j] = 0.0;
	      }
	   }
	   for (j=0; j<*zmptr.nz; j++) dblarr[j] = dblarrt[j];
	   free(dblarrt);
	}
	break;
   case 2:
	if ((intarrt = (int *) malloc((sizeof *intarrt)*(*zmptr.mxzat))) 
	   != NULL) {

	   for (j=0; j<*zmptr.nz; j++) {
	      if (zmptr.imap[j] > 0) {
		intarrt[j] = intarr[zmptr.imap[j]-1];
	      } else {
		intarrt[j] = 0;
	      }
	   }
	   for (j=0; j<*zmptr.nz; j++) intarr[j] = intarrt[j];
	   free(intarrt);
	}
	break;
   case 3:
	if ((shintarrt = (short int *) malloc((sizeof *shintarrt)*(*zmptr.mxzat))) 
	   != NULL) {

	   for (j=0; j<*zmptr.nz; j++) {
	      if (zmptr.imap[j] > 0) {
		shintarrt[j] = shintarr[zmptr.imap[j]-1];
	      } else {
		shintarrt[j] = 0;
	      }
	   }
	   for (j=0; j<*zmptr.nz; j++) shintarr[j] = shintarrt[j];
	   free(shintarrt);
	}
	break;
   default:
	break;
   }

}

ScrollBut(i)
int i;
{

    switch (i) {
    case ZMEARR1: 
#ifdef HASTIMER
        XSync(display, False);
	do {
		if (*zscroll.wn > ZME_window_high) 
		   if (ZME_window_pos) {
			ZME_window_pos--;
			RedrawScroll(&zscroll);
			UpdateZME();
			Timer(50,0);
		   }
		}
	while (!XCheckWindowEvent(display, ZMEwin, ButtonReleaseMask, &event));
#else
	if (*zscroll.wn > ZME_window_high) {
	   if (ZME_window_pos) {
		ZME_window_pos--;UpdateZME();
		RedrawScroll(&zscroll);
	   }
	}
#endif
	break;
    case ZMEARR2:	
#ifdef HASTIMER
        XSync(display, False);
        do {
       		if (*zscroll.wn > ZME_window_high) {
           		ZME_window_pos++; 
               		if (ZME_window_pos > *zscroll.wn-ZME_window_high) 
				ZME_window_pos = *zscroll.wn-ZME_window_high;
               		else {RedrawScroll(&zscroll); UpdateZME(); }
			Timer(50,0);
              	}
	 } while (!XCheckWindowEvent(display, ZMEwin, ButtonReleaseMask, &event));
#else
	if (*zscroll.wn > ZME_window_high) {
		ZME_window_pos++; 
		if (ZME_window_pos > *zscroll.wn-ZME_window_high) 
			ZME_window_pos = *zscroll.wn-ZME_window_high;
		UpdateZME();
		RedrawScroll(&zscroll);
	}
#endif
	break;
    }
}


int ScrollPage(lp,sc,x,y)
SCRSTRU *sc;
LISTSTRU *lp;
int x;
int y;
{
  int slidey,slideh,fnd,wposold;
  float ZMEScrRatio;
  XEvent xev;

  fnd = 0;

/* 
   divide number of elements in scroll window (wh) 
   by total number of elements (wn). Height of slider (slideh)
   with respect to height scroll bar (sc->h) has the same ratio
   wh : slideh = wn : sc->h
*/

  if (*sc->wn > 0) ZMEScrRatio = (sc->wh*1.0) / (*sc->wn);
  else ZMEScrRatio = 1.0;
  if (ZMEScrRatio > 1.0) ZMEScrRatio = 1.0;

  slideh = sc->h * ZMEScrRatio;
  if (slideh < 5) slideh = SCRMIN;

/* sc->wpos position of first element visible listbox in the element array.
  Height per elemnt =  h/wn , Hwpos = wpos*(h/wn)
*/

  if (*sc->wn > 0) ZMEScrRatio = (sc->h-slideh)*1.0 / (*sc->wn - sc->wh);
  else ZMEScrRatio = 0.0;
  slidey = *sc->wpos * ZMEScrRatio;

  if (VIERKANT(x, y, sc->x, sc->y, sc->w, sc->h)) {
	fnd = 2;
/*      clicked on slider */
  }
  if (VIERKANT(x, y, sc->x, sc->y, sc->w, slidey)) {
	*sc->wpos = *sc->wpos - sc->wh;
	fnd = 1;
/*      clicked above slider */
  }
  if (VIERKANT(x, y, sc->x, sc->y+slidey+slideh, sc->w, 
               sc->h-slideh-slidey)) {
	*sc->wpos = *sc->wpos + sc->wh;
	fnd = 1;
/*      clicked below slider */
  }
  if (VIERKANT(x, y, sc->x, slidey, sc->w, 
               slideh)) {
	fnd = 2;
/*      clicked below slider */
  }


  wposold = -1;
  while (fnd) {
	if (*sc->wpos > (*sc->wn) - 1 - sc->wh) {
	   if ((*sc->wn) - 1 - sc->wh >= 0) {
		*sc->wpos = (*sc->wn) - sc->wh;
	   }
	   else *sc->wpos = 0;
	}
	if (*sc->wpos < 0) *sc->wpos = 0;

        if (*sc->wpos != wposold) {
	   if (sc->win == ZMEwin) {
		UpdateZME();
		RedrawScroll(sc);
	   } else if (lp != NULL) {
		RedrawLBox(lp); RedrawScroll(&lp->scrbar);
	   } else {
		RedrawScroll(sc);
	   }
	   XSync(display,True);
	}
	wposold = *sc->wpos;

	if (fnd == 1) {
	   return(1);
	} else {
	   XNextEvent(display, &xev);
	   switch (xev.type) {
		case ButtonRelease:
		case LeaveNotify:
		   return(1);
		   break;
		case MotionNotify:
		   if (xev.xmotion.window == sc->win)  {
			*sc->wpos = *sc->wn * ((int) xev.xmotion.y - sc->y) 
				/ (int) (sc->h);
		   }
		   break;
	   }
	}
  } 

  return(0);

}

ActVar(isel,itype,butnr)
int isel;
int itype;
int butnr;
{
   int i,j,iptr,ierr;
   int *ii;

   i = isel;

   ierr = 0;

   if (butnr == 2) ierr = QBselect(i,itype);

   switch (itype) {
	case 0: ii = &zmptr.ibl[isel] ; break;
	case 1: ii = &zmptr.ialph[isel]; break;
	case 2: ii = &zmptr.ibet[isel]; break;
   }

   switch (ABS(*ii)) {
	case 0: strcpy(ZMEerr,"Constant"); break;
	case 1: strcpy(ZMEerr,"Variable"); break;
	default: i = ABS(*ii) - 1;
		 if (*ii < 0) {
			strcpy(ZMEerr,"Negative Linked Variable");
		 } else {
			strcpy(ZMEerr,"Linked Variable");
		 }
   }
   if (!ierr) RedrawStatus();

   DeActZME();
   for (j=0; j<itype+1; j++) {
	iptr = izz(i,j)-1;
	if (iptr < *zmptr.nz && iptr >= 0) {
		IANZbox[iptr].col = ZC_AT2+j;
		xyz.iaton[zmptr.imap[iptr]-1] = 4+j;
	}
   }
   IANZbox[i].col = ZC_AT1;

   switch (itype) {
   case 0:	BLbox[i].active = 1; break;
   case 1:	ALPHbox[i].active = 1; break;
   case 2:	BETbox[i].active = 1; break;
   }

   
   if (ZMEAA) {
	CurAmino = -1;
	for (j=0; j<ZME_window_high; j++) {
	   ZMEAAbut[j].lastused = -1;
	   ZMEAAbut[j].bg = 196;
	}
   }

   update_model = 0;
   update_sel = 1;
   UpdateZME();
   if (zmptr.imap[i]-1 >= 0) xyz.iaton[zmptr.imap[i]-1] = 3;

}

int QBselect(isel,itype)
int isel;
int itype;
{
    XEvent xev;
    int x,y,doit,ierr,ilnkerr,i,icol;
    LSSTRU List; int iop; int ltype;

    switch (itype) {
	case 0: x = BLbox[isel].x; y = BLbox[isel].y; break;
	case 1: x = ALPHbox[isel].x; y = ALPHbox[isel].y; break;
	case 2: x = BETbox[isel].x; y = BETbox[isel].y; break;
    }

    if (*ipdbon) 
	if (xyz.iresid[isel] > 0) update_res = xyz.iresid[isel];

    ierr = 0; ilnkerr = 0;
    List.list = zmevaropt; List.nents = 6;
    if (itype == 2) List.nents = 7;
    if (DoPopUp(ZMEwin,x+1,y+BUTTH,&List,&iop,0) == -1) return 0;

    if (iop == 4) {
	animptr.isel = isel;
	animptr.vdirection = 1;
	animptr.frame = 0;
	switch (itype) {
	    case 0: 
		animptr.variable = &zmptr.bl[isel]; 
		if (zmptr.ibl[isel] > 1) {
		   animptr.variable = &zmptr.bl[zmptr.ibl[isel] - 1];
		   animptr.isel = zmptr.ibl[isel] - 1;
		}
		break;
	    case 1: 
		animptr.variable = &zmptr.alph[isel]; 
		if (zmptr.ialph[isel] > 1) {
		   animptr.variable = &zmptr.alph[zmptr.ialph[isel] - 1];
		   animptr.isel = zmptr.ialph[isel] - 1;
		}
		break;
	    case 2: 
		animptr.variable = &zmptr.bet[isel]; 
		if (ABS(zmptr.ibet[isel]) > 1) {
		   animptr.variable = &zmptr.bet[ABS(zmptr.ibet[isel])-1];
		   animptr.isel = ABS(zmptr.ibet[isel])-1;
		}
		break;
	}
	animptr.varinit = *animptr.variable;
	animptr.vartype = itype;
	animptr.on = 1;
	FindZRangeFromBox(isel);
	if (*ipart) animptr.part = *ipart;
	if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
	"Click on Z-Matrix window to STOP the animation",0)) {
	}
	*Sinct = 530;
        return(0);
    }
    if (iop > 4) iop--;

    if (iop == 2 || iop == 3) {
	if (iop == 2) icol = ZC_MARK;
	if (iop == 3) {
	    switch (itype) {
	    case 0: iop = zmptr.ibl[isel]; break;
	    case 1: iop = zmptr.ialph[isel]; break;
	    case 2: iop = zmptr.ibet[isel]; break;
	    }
	    switch (iop) {
		case 0: icol = ZC_CONST; break;
		case 1: icol = ZC_VAR; break;
		default: icol = ZC_LINK;
	    }
	}
	switch (itype) {
	case 0: BLbox[isel].col = icol; break;
	case 1: ALPHbox[isel].col = icol; break;
	case 2: BETbox[isel].col = icol; break;
	}
	return(0);
    }

    if (iop > 3) {
      switch (itype) {
	case 0: strcpy(ZMEerr,"Click on a Z-matrix Bondlength"); break;
	case 1: strcpy(ZMEerr,"Click on a Z-matrix BondAngle"); break;
	case 2: strcpy(ZMEerr,"Click on a Z-matrix Dihedral"); break;
      }
      if (*ibell) XBell(display,0);
      RedrawStatus();
      ltype = 1;
      if (iop == 5) ltype = -1;
      doit = 1;
      while (doit) {
        XNextEvent(display, &xev);
        if (xev.xexpose.window == ZMEwin) {
	    switch (xev.type) {

		case Expose:	RedrawZME(); break;
		case ButtonPress:    
		    i = Clickwin(ZMEbut,ZMEBUTTS,xev.xbutton.x,xev.xbutton.y,1);

		    if (i>=0) {
			switch (i) {
			    case ZMEARR1: ScrollBut(i); break;
			    case ZMEARR2: ScrollBut(i); break;
			}
			break;
		    }
		    if (ScrollPage(NULL,&zscroll,xev.xbutton.x,xev.xbutton.y)) 
			break;
                    iop = 1;
		    switch (itype) {
			case 0: iop = 1+ClickBox(BLbox,*zmptr.nz,xev.xbutton.x,xev.xbutton.y); 
				if (ABS(zmptr.ibl[iop-1]) > 1) ilnkerr = 1;
				break;
			case 1: iop = 1+ClickBox(ALPHbox,*zmptr.nz,xev.xbutton.x,xev.xbutton.y); 
				if (ABS(zmptr.ialph[iop-1]) > 1) ilnkerr = 1;
				break;
			case 2: iop = 1+ClickBox(BETbox,*zmptr.nz,xev.xbutton.x,xev.xbutton.y); 
				if (ABS(zmptr.ibet[iop-1]) > 1) ilnkerr = 1;
				break;
		    }

		    if (!iop) {
			iop = 1;
			strcpy(ZMEerr,"No suitable variable chosen");
			ierr = 1;
		    }
		    if (iop > isel) {
			iop = 1;
			strcpy(ZMEerr,"ERROR: Link only to earlier defined variable");
			ierr = 1;
		    }
		    if (ilnkerr) {
			iop = 1;
			strcpy(ZMEerr,"ERROR: CAN Not link to a linked variable");
			ierr = 1;
		    }
		    if (ierr) {
			if (*ibell) XBell(display,0);
      			RedrawStatus();
		    }
		    iop = iop * ltype;
		    if (iop == -1) iop = 1;
		    doit = 0;
            }
	}
      }
    }
    switch (iop) {
	case 0: icol = ZC_CONST; break;
	case 1: icol = ZC_VAR; break;
	default: icol = ZC_LINK;
    }
    switch (itype) {
	case 0: 
		zmptr.ibl[isel] = iop; 
		BLbox[isel].col = icol; 
		BLbox[isel].changed = 1;
		break;
	case 1: 
		zmptr.ialph[isel] = iop; 
		ALPHbox[isel].col = icol; 
		ALPHbox[isel].changed = 1; 
		break;
	case 2: 
		zmptr.ibet[isel] = iop; 
		BETbox[isel].col = icol; 
		BETbox[isel].changed = 1; 
		break;
    }
    /*fprintf(stderr,"itype %d , %d\n",itype,iop);*/
    if (ABS(iop) > 1) {GetQZME();*Sinct = 530; }
    return (ierr);
}

SwitchOffAnim()
{
	if (!animptr.on) return;

	animptr.on = 0;
	if (animptr.part) *ipart = animptr.part;
	*animptr.variable = animptr.varinit;
	AnimLinks(animptr.varinit);
	anim();
	if (*ipdbon) presetp();
        update_res = -1;
	animptr.part = 0;
	XSync(display, False);
}

AnimLinks(vartmp)
double vartmp;
{
	int i;

	switch (animptr.vartype) {
	   case 0:
		sprintf(BLbox[animptr.isel].str,"%f",vartmp);
		PromptBox(&BLbox[animptr.isel]);
		break;
	   case 1:
		sprintf(ALPHbox[animptr.isel].str,"%f",vartmp);
		PromptBox(&ALPHbox[animptr.isel]);
		break;
	   case 2:
		sprintf(BETbox[animptr.isel].str,"%f",vartmp);
		PromptBox(&BETbox[animptr.isel]);
		break;
	}

	if (*ipart) return;

	for (i=0; i<*zmptr.nz; i++) {
	    switch (animptr.vartype) {
		case 0:
		   if (zmptr.ibl[i] > 1 && 
			zmptr.ibl[i] - 1 == animptr.isel)
			zmptr.bl[i] = vartmp;
		   break;
		case 1:
		   if (zmptr.ialph[i] > 1 &&
			zmptr.ialph[i] - 1 == animptr.isel)
			zmptr.alph[i] = vartmp;
		   break;
		case 2:
		   if (ABS(zmptr.ibet[i]) > 1 && 
			ABS(zmptr.ibet[i]) - 1 == animptr.isel) {
			if (zmptr.ibet[i] > 0) {
			   zmptr.bet[i] = vartmp;
			} else {
			   zmptr.bet[i] = -vartmp;
			}
		   }
		   break;
	    }
	}
}

DefScroll(sc,win,x,y,w,h,wn,wpos,wh)
SCRSTRU		*sc;
Window		win;
int		x,y;
unsigned int	w,h;
int		*wn;
int		*wpos;
int		wh;
{
  sc->win = win;
  sc->x = x;  sc->y = y;  sc->w = w;  sc->h = h;
  sc->wn = wn;
  sc->wpos = wpos;
  sc->wh = wh;
}


RedrawScroll(sc)
SCRSTRU		*sc;
{
  int slidey,slideh;
  float ZMEScrRatio;

  if (*sc->wn > 0) ZMEScrRatio = (sc->wh*1.0) / (*sc->wn);
  else ZMEScrRatio = 1.0;
  if (ZMEScrRatio > 1.0) ZMEScrRatio = 1.0;
  slideh = (int) sc->h * ZMEScrRatio;
  if (slideh < 5) slideh = SCRMIN;
  if (*sc->wn > 0) ZMEScrRatio = (*sc->wpos)*1.0 / (*sc->wn);
  else ZMEScrRatio = 0.0;
  slidey = (int) sc->h * ZMEScrRatio;
  if (sc->h - slidey < slideh) slidey = sc->h - slideh;

  butje(sc->win, sc->x, sc->y,        sc->w, sc->h ,3,0,0,0,None,0,0,0);
  butje(sc->win, sc->x, sc->y+slidey, sc->w, slideh,3,0,0,1,None,0,0,0);

}

DeActZME()
{
  int i,j,type,iptr;

  if (!ZMEup) return;

  if (qboxes[QBZMAT].active) {
	qboxes[QBZMAT].active = 0;
	PromptBox(&qboxes[QBZMAT]);
	return;
  }
  if (EXPbox[0].active) {
	EXPbox[0].active = 0;
	PromptBox(&EXPbox[0]);
	return;
  }
  activeZME(&type,&i,&j);
  switch(type) {
  case 0:
	IANZbox[i].col = ZC_DEF;
	IANZbox[i].active = 0;
	if (zmptr.imap[i]-1 >= 0)
		xyz.iaton[zmptr.imap[i]-1] = 1;
	break;
  case 1:
	iptr = izz(i,0)-1;
	if (iptr < *zmptr.nz && iptr >= 0) {
		IANZbox[iptr].col = ZC_DEF;
		xyz.iaton[zmptr.imap[iptr]-1] = 1;
	}
	IANZbox[i].col = ZC_DEF;
	BLbox[i].active = 0;
	if (zmptr.imap[i]-1 >= 0)
		xyz.iaton[zmptr.imap[i]-1] = 1;
	break;
  case 2:
	for (j=0; j<2; j++) {
		iptr = izz(i,j)-1;
		if (iptr < *zmptr.nz && iptr >= 0) {
			IANZbox[iptr].col = ZC_DEF;
			xyz.iaton[zmptr.imap[iptr]-1] = 1;
		}
	}
	IANZbox[i].col = ZC_DEF;
	ALPHbox[i].active = 0;
	if (zmptr.imap[i]-1 >= 0)
		xyz.iaton[zmptr.imap[i]-1] = 1;
	break;
  case 3:
	for (j=0; j<3; j++) {
		iptr = izz(i,j)-1;
		if (iptr < *zmptr.nz && iptr >= 0) {
			IANZbox[iptr].col = ZC_DEF;
			xyz.iaton[zmptr.imap[iptr]-1] = 1;
		}
	}
	IANZbox[i].col = ZC_DEF;
	BETbox[i].active = 0;
	if (zmptr.imap[i]-1 >= 0)
		xyz.iaton[zmptr.imap[i]-1] = 1;
	break;
  case 4:
	iptr = izz(i,j)-1;
	if (iptr < *zmptr.nz && iptr >= 0) {
		IANZbox[iptr].col = ZC_DEF;
		xyz.iaton[zmptr.imap[iptr]-1] = 1;
	}
	IANZbox[i].col = ZC_DEF;
	IZbox[i*4+j].active = 0;
	if (zmptr.imap[i]-1 >= 0)
		xyz.iaton[zmptr.imap[i]-1] = 1;
	break;
  }
  update_sel = 1;
}

UndoZME()
{
  int i,j,type;

  activeZME(&type,&i,&j);
  switch(type) {
  case 0:
        if (zmptr.ianz[i] >= 0 && zmptr.ianz[i] < 100)
             sprintf(stemp,"%s",elements[zmptr.ianz[i]]);
        else sprintf(stemp,"%s","?");
	strcpy(IANZbox[i].str,stemp);
	PromptBox(&IANZbox[i]);
	break;
  case 1:
	sprintf(stemp,"%f",zmptr.bl[i]);
	strcpy(BLbox[i].str,stemp);
	PromptBox(&BLbox[i]);
	break;
  case 2:
	sprintf(stemp,"%f",zmptr.alph[i]);
	strcpy(ALPHbox[i].str,stemp);
	PromptBox(&ALPHbox[i]);
	break;
  case 3:
	sprintf(stemp,"%f",zmptr.bet[i]);
	strcpy(BETbox[i].str,stemp);
	PromptBox(&BETbox[i]);
	break;
  case 4:
	sprintf(stemp,"%d",izz(i,j));
	strcpy(IZbox[i*4+j].str,stemp);
	PromptBox(&IZbox[i*4+j]);
	break;
  }
}


activeZME(type,row,column)
int *type;
int *row;
int *column;
{
  int i,j;

  *type = -1;
  *column = 0;
  for (i=0; i<*zmptr.nz; i++) {
	if (IANZbox[i].active) {
	   *type = 0; *row = i; 
	}
	if (BLbox[i].active) {
	   *type = 1; *row = i; 
	}
	if (ALPHbox[i].active) {
	   *type = 2; *row = i; 
	}
	if (BETbox[i].active) {
	   *type = 3; *row = i; 
	}
	for (j=0; j<4; j++) {
		if (IZbox[i*4+j].active) {
	   	   *type = 4; *row = i; *column = j;
		}
	}
  }
}

int FindInd(ival,iarr,idimens)
int ival;
int *iarr;
int idimens;
{
	int i;

	for (i=0; i<idimens; i++) 
		if (ival == iarr[i]) return(i);
	return(-1);
}

typedef unsigned char Byte;
#ifdef _LONGLONG
typedef unsigned int Card;
#else
typedef unsigned long Card;
#endif

static XImage *image;
static FILE *GIFFile;
static int LZWClrCode; 
static int LZWEOICode;
static short store1[4096];
static short store2[4096];
static short HashTable[256];
static Byte UsedColors[4096];
static int UsedCol[256];
static Byte Buffer[256];
static Byte MapPixel[256];
static Card BitBuffer;
static int BitBufLen;
static int ByteCount;
static int CodeSize;
static Byte pix2col[256],red[256],green[256],blue[256];

int CompressCMap()
{
    register int i,x,y, NumUsedColors;

    for (i=0; i<256; i++) {   
        MapPixel[colors[i]] = i;
        Buffer[i] = 0;
        UsedCol[i] = 5;
    }

    NumUsedColors = 0;

    for (x=0; x < width; x++) {
	for (y=0; y < height; y++) {
	    i = MapPixel[XGetPixel(image,x,y)];
	    if( !Buffer[i] )
	    {   UsedCol[NumUsedColors++] = i;
		Buffer[i] = NumUsedColors;
	    }
	}
    }

    for (i=0; i<256; i++)
        MapPixel[i] = Buffer[MapPixel[i]]-1;
    return (NumUsedColors);
}

int MapPixel24(pixval)
    unsigned long pixval;
{
    int i;

    for (i=255; i>=0; i--) {   
	if (pixval == colors[i]) return(i);
    }

    return(0);
}
    
int MapPixel24U(pixval,NumUsedColors)
    unsigned long pixval;
    int NumUsedColors;
{
    int i;

    for (i=0; i<NumUsedColors; i++) {   
	if (pixval == colors[UsedCol[i]]) return(i);
    }

    return(0);
}
    
int FakeCompress24()
{
    register int i,x,y, NumUsedColors;

    for (i=0; i<256; i++) {   
        Buffer[i] = 0;
        UsedCol[i] = 5;
    }

    NumUsedColors = 0;

    for (x=0; x < width; x++) {
	for (y=0; y < height; y++) {
	    i = MapPixel24(XGetPixel(image,x,y));
	    if( !Buffer[i] )
	    {   UsedCol[NumUsedColors++] = i;
		Buffer[i] = NumUsedColors;
	    }
	}
    }

    return (NumUsedColors);
}


void LZWwrite(code)
    int code;
{
    register int max;

    max = (code==LZWEOICode)? 0 : 7;
    BitBuffer |= ((Card)code<<BitBufLen);
    BitBufLen += CodeSize;

    while (BitBufLen > max) {    
         Buffer[ByteCount++]=BitBuffer;
         BitBuffer >>= 8;
         BitBufLen -= 8;

        if (ByteCount==255) {
	    fputc(0xff,GIFFile);
            fwrite((char*)Buffer,1,255,GIFFile);
            ByteCount = 0;
        }
    }
}

compress(BitsPerPixel,NumUsedColors,imag,do24)
    int BitsPerPixel;
    int NumUsedColors;
    int do24;
    Byte *imag;
{
    register int i,CurrentColor;
    register int Prefix,next,last,ilast;
    register unsigned long pixel;
    register short *prev;
    register int x,y;
    int istart;

    ByteCount=0; BitBuffer=0; BitBufLen=0;

    LZWClrCode = (1<<BitsPerPixel);
    LZWEOICode = LZWClrCode + 1;
    ilast = (LZWClrCode<<1) - LZWEOICode;
    BitsPerPixel++;

    for( i=0; i<NumUsedColors; i++ )
        HashTable[i]=0;
    CodeSize = BitsPerPixel;
    next = 1; last = ilast;

/* begin of compression */

    LZWwrite(LZWClrCode);

    istart = 0;
    Prefix = 0;
    prev = (short *)0; 

    for (y=0; y<height; y++) {   
        for (x=0; x<width; x++) {   
	    if (do24 == 2) {
		pixel = imag[(height-y+1)*width+x];
	    } else {
		pixel = XGetPixel(image,x,y);
	    }
	    if (!istart) {
		if (do24 == 2) Prefix = pix2col[pixel];
		else if (do24) Prefix = MapPixel24U(pixel,NumUsedColors);
		else Prefix = MapPixel[pixel];
                prev = HashTable+Prefix;
                istart = 1;
                continue;
            }

	    if (do24 == 2) CurrentColor = pix2col[pixel];
	    else if (do24) CurrentColor = MapPixel24U(pixel,NumUsedColors);
            else CurrentColor = MapPixel[pixel];

            while (*prev && (UsedColors[*prev] != (Byte)CurrentColor))
                prev = store1+*prev;

            if (*prev) {
		Prefix = *prev+LZWEOICode; prev = store2+*prev;
            } else {
		LZWwrite(Prefix);
                if (next==last) {
		    if (CodeSize==12) {
			LZWwrite(LZWClrCode);
                        Prefix = CurrentColor;  prev = HashTable+CurrentColor;
                        for( i=0; i<NumUsedColors; i++ )
                            HashTable[i] = 0;
                        CodeSize = BitsPerPixel;
                        next = 1; last = ilast;
                        continue;
                    }
                    last = (last<<1)+LZWEOICode;
                    CodeSize++;
                }
                *prev = next;
                store1[next] = 0; store2[next] = 0;
                UsedColors[next] = CurrentColor;
                prev = HashTable+CurrentColor; Prefix = CurrentColor;
                next++;
            }
        }
    }


    LZWwrite(Prefix);

/* end of compression */

    LZWwrite(LZWEOICode);

/* write last buffer */

    if (ByteCount) {
	fputc(ByteCount,GIFFile);
        fwrite((char*)Buffer,1,ByteCount,GIFFile);
    }

/* zero byte count terminates Raster Data stream */

    fputc(0x00,GIFFile);
}


ToGIF(win,filename)
    char *filename;
    Drawable win;
{
    int i,NumUsedColors,BitsPerPixel,do24;
    XColor exact_def;
    Byte *imag = NULL;

    GIFFile = fopen(filename,"w");
    if (!GIFFile) {
	fprintf(stderr,"Output Error: Unable to create GIF file %s\n",filename);
	return;
    }

    do24 = 0;
    if (DisplayPlanes(display, screen) > 8) do24 = 1;

    image = XGetImage(display,win,0,0,width,height,AllPlanes,ZPixmap);

    if (image == NULL) {
	fprintf(stderr,"Output Error: Unable to create GIF file\n");
	return;
    }

    if (do24) NumUsedColors = FakeCompress24();
    else NumUsedColors = CompressCMap();

    if (NumUsedColors<2) {
	XDestroyImage(image);
	return;
    }

    for (BitsPerPixel=0; BitsPerPixel<8; BitsPerPixel++)
        if( (1<<BitsPerPixel)>=NumUsedColors ) break;
    NumUsedColors = 1<<BitsPerPixel;

/* Signature */

    fwrite("GIF87a",1,6,GIFFile);

/* Screen descriptor */

    fputc(width&0xff,GIFFile);  fputc((width>>8)&0xff,GIFFile);
    fputc(height&0xff,GIFFile);  fputc((height>>8)&0xff,GIFFile);
    fputc(0xf0|(BitsPerPixel-1),GIFFile); 
    fputc(0x00,GIFFile); 
    fputc(0x00,GIFFile);

/* Global Colormap */



    for (i=0; i<NumUsedColors; i++) {   
	exact_def.pixel = colors[UsedCol[i]];
	XQueryColor(display,cmap,&exact_def);
        fputc((int)exact_def.red>>8,GIFFile);
        fputc((int)exact_def.green>>8,GIFFile);
        fputc((int)exact_def.blue>>8,GIFFile);
    }

/* Image Descriptor */

    fputc(',',GIFFile);
    fputc(0x00,GIFFile); fputc(0x00,GIFFile);
    fputc(0x00,GIFFile); fputc(0x00,GIFFile);
    fputc(width&0xff,GIFFile); fputc((width>>8)&0xff,GIFFile);
    fputc(height&0xff,GIFFile); fputc((height>>8)&0xff,GIFFile);
    fputc(0x00,GIFFile); fputc(BitsPerPixel,GIFFile);

/* Raster Data */

    compress(BitsPerPixel,NumUsedColors,imag,do24);

/* Gif Terminator */

    fputc(';',GIFFile);
    fclose(GIFFile);

    XDestroyImage(image);
    return;
}

#define RANGE(a,b,c) { if (a < b) a = b;  if (a > c) a = c; }
#define MAXCOL  256
#define BOX_DIM  128

typedef unsigned short histcell;
typedef unsigned short * histptr;
typedef unsigned short hist1d[32];
typedef hist1d hist2d[64];
typedef hist2d hist3d[32];
static hist2d * histogram;

typedef struct {
  int rmin, rmax;
  int gmin, gmax;
  int bmin, bmax;
  int volume;
  long colorcount;
} box;
typedef box * boxptr;

static short * fserrors;
static int * maxerr;
static unsigned char * clmap[3];
static int num_colors;

void initz(s, len)
     char   *s;
     size_t  len;
{
  for ( ; len>0; len--) *s++ = 0;
}

void inithis(rgbimg, npix)
Byte *rgbimg;
int   npix;
{
  histptr histp;

  initz((char *) histogram, sizeof(hist3d));

  while (npix-- > 0) {
    histp = & histogram[rgbimg[0]/8] [rgbimg[1]/4] [rgbimg[2]/8];
    if (++(*histp) <= 0)
      (*histp)--;
    rgbimg += 3;
  }
}

boxptr cbmax(boxlist, nbox)
boxptr boxlist;
int nbox;
{
  boxptr boxp, w = NULL;
  int i, maxc = 0;
  
  for (i = 0, boxp = boxlist; i < nbox; i++, boxp++) {
    if (boxp->colorcount > maxc && boxp->volume > 0) {
      w = boxp;
      maxc = boxp->colorcount;
    }
  }
  return w;
}


boxptr colmax(bl, nbox)
boxptr bl;
int nbox;
{
  boxptr boxp;
  int i;
  int maxv = 0;
  boxptr wh = NULL;
  
  for (i = 0, boxp = bl; i < nbox; i++, boxp++) {
    if (boxp->volume > maxv) {
      wh = boxp;
      maxv = boxp->volume;
    }
  }
  return wh;
}

/* based on jpeg library routine */

void boxupd(boxp)
boxptr boxp;
{
  histptr histp;
  int r,g,b;
  int rmin,rmax,gmin,gmax,bmin,bmax;
  int dr,dg,db;
  long ccount;
  
  rmin = boxp->rmin;  
  rmax = boxp->rmax;
  gmin = boxp->gmin;  
  gmax = boxp->gmax;
  bmin = boxp->bmin;  
  bmax = boxp->bmax;
  
  if (rmax > rmin)
    for (r = rmin; r <= rmax; r++)
      for (g = gmin; g <= gmax; g++) {
	histp = &histogram[r][g][bmin];
	for (b = bmin; b <= bmax; b++)
	  if (*histp++ != 0) {
	    boxp->rmin = rmin = r;
	    goto have_rmin;
	  }
      }
 have_rmin:
  if (rmax > rmin)
    for (r = rmax; r >= rmin; r--)
      for (g = gmin; g <= gmax; g++) {
	histp = &histogram[r][g][bmin];
	for (b = bmin; b <= bmax; b++)
	  if (*histp++ != 0) {
	    boxp->rmax = rmax = r;
	    goto have_rmax;
	  }
      }
 have_rmax:
  if (gmax > gmin)
    for (g = gmin; g <= gmax; g++)
      for (r = rmin; r <= rmax; r++) {
	histp = &histogram[r][g][bmin];
	for (b = bmin; b <= bmax; b++)
	  if (*histp++ != 0) {
	    boxp->gmin = gmin = g;
	    goto have_gmin;
	  }
      }
 have_gmin:
  if (gmax > gmin)
    for (g = gmax; g >= gmin; g--)
      for (r = rmin; r <= rmax; r++) {
	histp = &histogram[r][g][bmin];
	for (b = bmin; b <= bmax; b++)
	  if (*histp++ != 0) {
	    boxp->gmax = gmax = g;
	    goto have_gmax;
	  }
      }
 have_gmax:
  if (bmax > bmin)
    for (b = bmin; b <= bmax; b++)
      for (r = rmin; r <= rmax; r++) {
	histp = &histogram[r][gmin][b];
	for (g = gmin; g <= gmax; g++, histp += 32)
	  if (*histp != 0) {
	    boxp->bmin = bmin = b;
	    goto have_bmin;
	  }
      }
 have_bmin:
  if (bmax > bmin)
    for (b = bmax; b >= bmin; b--)
      for (r = rmin; r <= rmax; r++) {
	histp = &histogram[r][gmin][b];
	for (g = gmin; g <= gmax; g++, histp += 32)
	  if (*histp != 0) {
	    boxp->bmax = bmax = b;
	    goto have_bmax;
	  }
      }
 have_bmax:

  dr = (rmax - rmin) * 16;
  dg = (gmax - gmin) * 12;
  db = (bmax - bmin) *  8;
  boxp->volume = dr*dr + dg*dg + db*db;
  
  ccount = 0;
  for (r = rmin; r <= rmax; r++)
    for (g = gmin; g <= gmax; g++) {
      histp = &histogram[r][g][bmin];
      for (b = bmin; b <= bmax; b++, histp++)
	if (*histp != 0) {
	  ccount++;
	}
    }
  boxp->colorcount = ccount;
}

int setavg(bl, nbox, nc)
boxptr bl;
int nbox, nc;
{
  int n,dr,dg,db,cmax;
  boxptr b1,b2;

  while (nbox < nc) {

    if (nbox*2 <= nc) {
      b1 = cbmax(bl, nbox);
    } else {
      b1 = colmax(bl, nbox);
    }

    if (b1 == NULL) break;

    b2 = &bl[nbox];

    *b2 = *b1; /* copy box at b1 to box at b2 */

    dr = (b1->rmax - b1->rmin) * 16;
    dg = (b1->gmax - b1->gmin) * 12;
    db = (b1->bmax - b1->bmin) *  8;

    cmax = dg; n = 1;
    if (dr > cmax) { cmax = dr; n = 0; }
    if (db > cmax) n = 2;

    switch (n) {
    case 0:
      b1->rmax = AVG(b1->rmax,b1->rmin);
      b2->rmin = b1->rmax+1;
      break;
    case 1:
      b1->gmax = AVG(b1->gmax,b1->gmin);
      b2->gmin = b1->gmax+1;
      break;
    case 2:
      b1->bmax = AVG(b1->bmax,b1->bmin);
      b2->bmin = b1->bmax+1;
      break;
    }

    boxupd(b1);
    boxupd(b2);
    nbox++;
  }
  return nbox;
}


void setclr(boxp, ic)
boxptr boxp;
int ic;
{
  histptr histp;
  int r,g,b;
  int tel,tot,rtot,gtot,btot;
  
  tot = rtot = gtot = btot = 0;

  for (r = boxp->rmin; r <= boxp->rmax; r++)
    for (g = boxp->gmin; g <= boxp->gmax; g++) {
      histp = &histogram[r][g][boxp->bmin];
      for (b = boxp->bmin; b <= boxp->bmax; b++) {
	if ((tel = *histp++) != 0) {
	  tot += tel;
	  rtot += (r*8 + 4) * tel;
	  gtot += (g*4 + 2) * tel;
	  btot += (b*8 + 4) * tel;
	}
      }
    }
  
  clmap[0][ic] = (unsigned char) ((rtot + (tot/2)) / tot);
  clmap[1][ic] = (unsigned char) ((gtot + (tot/2)) / tot);
  clmap[2][ic] = (unsigned char) ((btot + (tot/2)) / tot);
}

#define AB2(a,b) ((a)*(a)*(b)*(b))

int appcols(rgbmin,cl)
int *rgbmin;
unsigned char *cl;
{
  int i,j, ct, ncolors;
  int dmaxje, dmin, dmax;
  int dmincl[MAXCOL];
  int rgbext[3][4], rgbfac[3], rgbmlt[3];

  rgbfac[0] = 24; rgbfac[1] = 28; rgbfac[2] = 24;
  rgbmlt[0] = 2; rgbmlt[1] = 3; rgbmlt[2] = 1;

  for (j = 0; j < 3; j++) {
     rgbext[j][0] = rgbmin[j];
     rgbext[j][1] = rgbmin[j] + rgbfac[j];
     rgbext[j][2] = (2*rgbmin[j] + rgbfac[j])/2;
     rgbext[j][3] = rgbmlt[j];
  }

  dmaxje = 0x7FFFFFFFL;

  for (i = 0; i < num_colors; i++) {

    dmin = dmax = 0;

    for (j = 0; j < 3; j++) {

	ct = clmap[j][i];

	if (ct < rgbext[j][0]) {

	   dmin += AB2(ct-rgbext[j][0],rgbext[j][3]);
	   dmax += AB2(ct-rgbext[j][1],rgbext[j][3]);

	} else if (ct > rgbext[j][1]) {

	   dmin += AB2(ct-rgbext[j][1],rgbext[j][3]);
	   dmax += AB2(ct-rgbext[j][0],rgbext[j][3]);

	} else {

	   if (ct <= rgbext[j][2]) {
		dmax += AB2(ct-rgbext[j][1],rgbext[j][3]);
	   } else {
		dmax += AB2(ct-rgbext[j][0],rgbext[j][3]);
	   }

	}
    }

    dmincl[i] = dmin;

    if (dmax < dmaxje) dmaxje = dmax;
  }

  ncolors = 0;
  for (i = 0; i < num_colors; i++) {
    if (dmincl[i] <= dmaxje)
      cl[ncolors++] = (unsigned char) i;
  }
  return ncolors;
}


void optcols(rgbmin, numcolors, cl, bc)
int *rgbmin;
int numcolors;
unsigned char *cl;
unsigned char *bc;
{
  int i, ir, ig, ib, ic;
  int * bptr;
  unsigned char * cptr;
  int drgb2, drgb2t, drgb2tt;
  int tr, tg, tb;
  int dr, dg, db;
  int optdrgb2[BOX_DIM];

  bptr = optdrgb2;

  for (i = BOX_DIM-1; i >= 0; i--)
    *bptr++ = 0x7FFFFFFFL;
  
  for (i = 0; i < numcolors; i++) {

    ic = cl[i];
    drgb2 = 0;

    dr = (rgbmin[0] - (int) clmap[0][ic]) * 2;
    drgb2 += dr*dr;
    dg = (rgbmin[1] - (int) clmap[1][ic]) * 3;
    drgb2 += dg*dg;
    db = (rgbmin[2] - (int) clmap[2][ic]) * 1;
    drgb2 += db*db;

    dr = dr*32 + 256;
    dg = dg*24 + 144;
    db = db*16 + 64;

    bptr = optdrgb2;
    cptr = bc;
    tr = dr;

    for (ir = 3; ir >= 0; ir--) {
      drgb2t = drgb2;
      tg = dg;

      for (ig = 7; ig >= 0; ig--) {
	drgb2tt = drgb2t;
	tb = db;

	for (ib = 3; ib >= 0; ib--) {
	  if (drgb2tt < *bptr) {
	    *bptr = drgb2tt;
	    *cptr = (unsigned char) ic;
	  }
	  drgb2tt += tb;
	  tb += 128;
	  bptr++;
	  cptr++;
	}
	drgb2t += tg;
	tg += 288;
      }
      drgb2 += tr;
      tr += 512;
    }
  }
}

void ininvcm(r,g,b)
int r,g,b;
{
  int rgbmin[3];
  int i, j, k;
  unsigned char * cptr;
  histptr ptr;
  unsigned char cl[MAXCOL], bc[BOX_DIM];
  int nc;

  r = r/4;
  g = g/8;
  b = b/4;

  rgbmin[0] = r*32 + 4;
  rgbmin[1] = g*32 + 2;
  rgbmin[2] = b*32 + 4;
  
  nc = appcols(rgbmin, cl);

  optcols(rgbmin, nc, cl, bc);

  r = r*4;
  g = g*8;
  b = b*4;

  cptr = bc;

  for (i = 0; i < 4; i++) 

    for (j = 0; j < 8; j++) {

      ptr = &histogram[r+i][g+j][b];

      for (k = 0; k < 4; k++) 
	*ptr++ = (unsigned short) (*cptr++ + 1);

    }

}

void map_pixels(rgbimg, width, height, imag, rtoggle)
Byte *rgbimg, *imag;
int   width, height;
int rtoggle;
{
  int cur[3],bel[3],bpr[3];
  short * errorptr;
  unsigned char *inptr,*outptr;
  histptr tmpptr;
  int j, dir, dir3;
  int row, col;

  for (row = 0; row < height; row++) {

    inptr  = &rgbimg[row*width * 3];
    outptr = &imag[row*width];

    if (rtoggle) {

      inptr += (width-1)*3;
      outptr += width-1;
      dir = -1;
      dir3 = -3;
      errorptr = fserrors + (width+1)*3;
      rtoggle = False;

    } else {

      dir = 1;
      dir3 = 3;
      errorptr = fserrors;
      rtoggle = True;

    }

    for (j = 0; j < 3; j++) {
	cur[j] = 0; bel[j] = 0; bpr[j] = 0;
    }

    for (col = width; col > 0; col--) {

      for (j = 0; j < 3; j++) {
	cur[j] = (cur[j] + errorptr[dir3+j] + 8)/16;
	cur[j] = maxerr[cur[j]];
	cur[j] += inptr[j];
	RANGE(cur[j], 0, 255);
      }

      tmpptr = &histogram[cur[0]/8][cur[1]/4][cur[2]/8];

      if (*tmpptr == 0)
	ininvcm(cur[0]/8, cur[1]/4, cur[2]/8);

      *outptr = (unsigned char) (*tmpptr - 1);
      for (j = 0; j < 3; j++) 
	   cur[j] -= (int) clmap[j][*tmpptr - 1];

      { int nxterr, dc;

	for (j = 0; j < 3; j++) {
	   nxterr = cur[j];
	   dc = cur[j] * 2;
	   cur[j] += dc;
	   errorptr[j] = (short) (bpr[j] + cur[j]);
	   cur[j] += dc;	
	   bpr[j] = bel[j] + cur[j];
	   bel[j] = nxterr;
	   cur[j] += dc;
	}

      }

      inptr += dir3;
      outptr += dir;
      errorptr += dir3;	
    }

    for (j = 0; j < 3; j++) 
	errorptr[j] = (short) bpr[j]; 
  }
}


void init_err()
{
  int i, j;

  maxerr = (int *) malloc((size_t) ((255*2+1) * sizeof(int)));
  if (!maxerr) return;

  maxerr += 255;

  j = 0;
  for (i = 0; i < 16; i++, j++) {
    maxerr[i] = j; maxerr[-i] = -j;
  }
  for (; i < 48; i++, j += (i&1) ? 0 : 1) {
    maxerr[i] = j; maxerr[-i] = -j;
  }
  for (; i <= 255; i++) {
    maxerr[i] = j; maxerr[-i] = -j;
  }
}

void pickcol(nc)
int nc;
{
  box bl[MAXCOL];
  int nbox;
  int i;

  nbox = 1;

  bl[0].rmin = bl[0].gmin = bl[0].bmin = 0;
  bl[0].rmax = bl[0].bmax = 31;
  bl[0].gmax = 63;

  boxupd(bl);

  nbox = setavg(bl, nbox, nc);

  for (i = 0; i < nbox; i++)
    setclr(&bl[i], i);

  num_colors = nbox;

}

int quant(rgbimg, width, height, imag, nc)
Byte *rgbimg, *imag;
int   width, height, nc;
{
  size_t fssize = (width + 2) * (3 * sizeof(short));

  if (maxerr == NULL) init_err();

  histogram = (hist2d *) malloc(sizeof(hist3d));
  fserrors = (short *) malloc(fssize);

  if (! maxerr || ! histogram || ! fserrors) {
    if (histogram) free(histogram);
    if (fserrors) free(fserrors);
    fprintf(stderr,"24->8 failed to allocate workspace\n");
    return 1;
  }

  inithis(rgbimg, width*height);

  pickcol(nc);

  initz((char *) histogram, sizeof(hist3d));
  initz((char *) fserrors, fssize);

  map_pixels(rgbimg, width, height, imag, False);

  free(histogram);
  free(fserrors);

  return 0;
}



#if defined(VMS) || defined(UNDERSC)
curs(on)
#else
#ifdef CRAY
CURS(on)
#else
curs_(on)
#endif
#endif
int *on;
{

   if (!xison) return;
   if (animptr.on) return;

   if (*on) {
	XDefineCursor(display, win, WaitCursor);
	XDefineCursor(display, winMC, WaitCursor);
	XDefineCursor(display, winC, WaitCursor);
	XDefineCursor(display, Fwin, WaitCursor);
	XDefineCursor(display, ZMEwin, WaitCursor);
	if (specup) XDefineCursor(display, winspec, WaitCursor);
	if (FRup) XDefineCursor(display, FrBox, WaitCursor);
	if (FLXup) XDefineCursor(display, FLXwin, WaitCursor);
   } else {
	XUndefineCursor(display, win);
	XUndefineCursor(display, winMC);
	XUndefineCursor(display, winC);
	XUndefineCursor(display, Fwin);
	XUndefineCursor(display, ZMEwin);
	if (specup) XUndefineCursor(display, winspec);
	if (FRup) XUndefineCursor(display, FrBox);
	if (FLXup) XUndefineCursor(display, FLXwin);
   }
   XSync(display, False);
}

#if defined(VMS) || defined(UNDERSC)
messg(istat)
#else
#ifdef CRAY
MESSG(istat)
#else
messg_(istat)
#endif
#endif
int *istat;
{
   char statstr[200];
   int x,y;

   if (!xison) return;

   switch (*istat) {
	case 0: 
		strcpy(statstr,"Optimisation complete");
		break;
	case 1: 
		strcpy(statstr,"Error Job");
		break;
	case 2: 
		strcpy(statstr,"Some Required Potential Energy\nParameters are Undefined\nSee the file jobname.log");
		break;
	case 3: 
		strcpy(statstr,"Incomplete Convergence");
		break;
	case 4: 
		strcpy(statstr,"Too many Parameters");
		break;
	case 5: 
		strcpy(statstr,"Job Aborted");
		break;
	case 6: 
		strcpy(statstr,"Job started");
		break;
	case 7: 
		strcpy(statstr,"WARNING: reading connectivity from file molden_connect");
		break;
	case 8: 
		strcpy(statstr,"ERROR: couldnt open mapfile");
		break;
	case 9: 
		strcpy(statstr,"ERROR: error reading mapfile");
		break;
	case 10: 
		strcpy(statstr,"ERROR: dimensions grid dont match first grid");
		break;
	case 11: 
		strcpy(statstr,"WARNING: current grid does not hold density !");
		break;
	case 12: 
		strcpy(statstr,"WARNING: could not open file !");
		break;
	case 13: 
		strcpy(statstr,"WARNING: Only Hetatm atoms may be selected !");
		break;
	case 14: 
		strcpy(statstr,"WARNING EEM: element missing parameters!");
		break;
	case 15: 
		strcpy(statstr,"WARNING Mol2: untyped atoms !");
		break;
	case 17: 
		strcpy(statstr,"WARNING Mol2: atom type inconsistancy, please retyp !");
		break;
	case 16: 
		sprintf(atemp,"Contour Value [%f - %f] ?",*rng1,*rng2);
		*vlcnt = (*rng1 + *rng2) / 2.0;
		sprintf(stemp,"%f",*vlcnt);
		qboxstr(&qboxes[QCNT],NULL,1,0,-1,DEFQX,DEFQY,
		   QBOXWIDE,QBOXHIGH, 0,atemp,stemp,
		   0,3,587,dummyproc);
		qboxes[QCNT].dflt = vlcnt;
		return;
		break;
	case 18: 
		strcpy(statstr,"Succesfully wrote file resrot");
		break;
	case 19: 
		strcpy(statstr,"Did not find file resrot");
		break;
	case 20: 
		strcpy(statstr,"Optimisation aborted");
		break;
	default:
		break;
   }

   x = event.xbutton.x_root; y = event.xbutton.y_root;
   if (x == 0 && y == 0) {
	x = DisplayWidth(display,screen) / 2;
	y = DisplayHeight(display,screen) / 2;
   }

   if (DoCan(x,y,statstr,0)) {}
}

MkDistWin(asel,opt,val)
int *asel;
int opt;
float val;
{
   int nval;

   if (monoscr || colcells <= 32) {
	XSetForeground(display, gc, colors[7]);
	XFillRectangle(display,distpix,gc,0,0,DBWIDE,DBHIGH-5);
	if (monoscr) XSetForeground(display, gc, colors[0]);
	else XSetForeground(display, gc, colors[6]);
	XDrawRectangle(display,distpix,gc,0,0,DBWIDE,DBHIGH-5);}
   else {
	XSetForeground(display, gc, colors[190]);
	XFillRectangle(display,distpix,gc,0,0,DBWIDE,DBHIGH);
	butje(distpix,0,0,DBWIDE,DBHIGH,3,0,0,1,None,0,0,0);
   }
   XSetForeground(display, gc, colors[0]);
/*
   if (monoscr) XSetForeground(display, gc, colors[0]);
   else  XSetForeground(display, gc, colors[9]);
*/

   switch(opt) {
   case 5:	sprintf(stemp,"Electrost. Pot. %#11.5f",val);
		nval = 27;break;
   case 4:	sprintf(stemp,"Dihedral %#8.3f Degrees",val);
		nval = 25;break;
   case 3:	sprintf(stemp,"Covalent Angle %#8.3f Degrees",val);
		nval = 31;break;
   case 2:	sprintf(stemp, "         %#11.5f a.u.",val);
		nval=25;
		XDrawString(display,distpix,gc,10,35,stemp,nval);
		sprintf(stemp, "Distance %#11.5f Angstrom",val*toangs);
		nval=29;
		aselkeep[0] = asel[0];
		aselkeep[1] = asel[1];
		break;
   default:	break;
   }
   XDrawString(display, distpix, gc, 10, 15, stemp, nval);

   if (opt == 2) {
	ActBut(&clbut[BMONI],1);
   } else {
	ActBut(&clbut[BMONI],0);
   }

   if (!distup) {
	XMapRaised(display,DISTwin);
	distup = 1;
   } else {
	XMapRaised(display,DISTwin);
	RedrawDIST();
   }

}

RedrawDIST()
{
 int i;

      XCopyArea(display,distpix,DISTwin,gc,0,0,DBWIDE,DBHIGH,0,0);
      for (i=0; i<NCLBUT; i++) DrwBut(&clbut[i]);
}

int ButtonsDIST(i)
int i;
{
 int j,iscon1,iscon2;


	switch (i) {
	case BCLOSE:
		distup = 0;
		signal(SIGALRM,SIG_IGN);
		XUnmapWindow(display,DISTwin);
		return(0);
		break;
	case BMONI:
#if defined(VMS) || defined(UNDERSC)
		setmon(aselkeep,&anum);
#else
#ifdef CRAY
		SETMON(aselkeep,&anum);
#else
		setmon_(aselkeep,&anum);
#endif
#endif
		if (has_opengl && *fancy) {
		   update_model = 0;
		   dispsf();
		} else {
		   update_model = 1;
		   return(1);
		}
		break;
	case BCLR:
#if defined(VMS) || defined(UNDERSC)
		clrmon();
#else
#ifdef CRAY
		CLRMON();
#else
		clrmon_();
#endif
#endif
		if (has_opengl && *fancy) {
		   update_model = 0;
		   dispsf();
		} else {
		   update_model = 1;
		   return(1);
		}
		break;
	case BCNTCT:
		if (!DoCan(event.xbutton.x_root,event.xbutton.y_root,
			   "Select Atom for close contact",1)) {
		   bflag = 1; bretval = 461;
		   XDefineCursor(display,win,AtomCursor);
		   return(0);
		}
		break;
	case BCONN:
		iscon1 = -1;
		iscon2 = -1;
		for (j=0; j<xyz.iconn[(aselkeep[0]-1)*(MXCON+1)]; j++) {
		   if (ABS(xyz.iconn[(aselkeep[0]-1)*(MXCON+1)+1+j]) == aselkeep[1]) 
			iscon1 = j;
       		}
		for (j=0; j<xyz.iconn[(aselkeep[1]-1)*(MXCON+1)]; j++) {
		   if (ABS(xyz.iconn[(aselkeep[1]-1)*(MXCON+1)+1+j]) == aselkeep[0]) 
			iscon2 = j;
       		}
		if (iscon1 != -1 || iscon2 != -1) {
		    if (iscon1 != -1) {
			for (j=iscon1; j<xyz.iconn[(aselkeep[0]-1)*(MXCON+1)]-1; j++) 
			   xyz.iconn[(aselkeep[0]-1)*(MXCON+1)+1+j] = 
				xyz.iconn[(aselkeep[0]-1)*(MXCON+1)+2+j];
			xyz.iconn[(aselkeep[0]-1)*(MXCON+1)] = 
				xyz.iconn[(aselkeep[0]-1)*(MXCON+1)] - 1;
		    }
		    if (iscon2 != -1) {
			for (j=iscon2; j<xyz.iconn[(aselkeep[1]-1)*(MXCON+1)]-1; j++) 
			   xyz.iconn[(aselkeep[1]-1)*(MXCON+1)+1+j] = 
				xyz.iconn[(aselkeep[1]-1)*(MXCON+1)+2+j];
			xyz.iconn[(aselkeep[1]-1)*(MXCON+1)] = 
				xyz.iconn[(aselkeep[1]-1)*(MXCON+1)] - 1;
		    }
		} else {
		   if (xyz.iconn[(aselkeep[0]-1)*(MXCON+1)] < MXCON) {
			xyz.iconn[(aselkeep[0]-1)*(MXCON+1)] = 
			   xyz.iconn[(aselkeep[0]-1)*(MXCON+1)] + 1;
			xyz.iconn[(aselkeep[0]-1)*(MXCON+1)+xyz.iconn[(aselkeep[0]-1)*(MXCON+1)]] =
			aselkeep[1];
		   }
		   if (xyz.iconn[(aselkeep[1]-1)*(MXCON+1)] < MXCON) {
			xyz.iconn[(aselkeep[1]-1)*(MXCON+1)] = 
			   xyz.iconn[(aselkeep[1]-1)*(MXCON+1)] + 1;
			xyz.iconn[(aselkeep[1]-1)*(MXCON+1)+xyz.iconn[(aselkeep[1]-1)*(MXCON+1)]] =
			aselkeep[0];
		   }
		}
		update_model = 1;
		return(1);
		break;
	}
}

int ChangeLevel(button12,cursorx,cursory)
int button12;
int cursorx;
int cursory;
{
 int i,j,jx,jy;
 int PEH,PH,PW,NE,MW;

 if (*doesp) {
    NE = nplev+1;
    if (*itsrf) NE = 5;
    PEH = 20;
    PW = 70;
    PH = NE*PEH;
    MW = 10;
    jx = width-70-20;
    jy = 20;
    if (VIERKANT(cursorx, cursory, jx-MW, jy-MW, PW+2*MW, PH+2*MW)) {

         if (button12 == 1) {
   	     qboxstr(&qboxes[QCSPACE],NULL,1,0,-1,DEFQX,DEFQY,QBOXWIDE,QBOXHIGH,
		     0,"Level Spacing ? ",NULL,0,3,590,dummyproc);
         } else {
	     if (!(has_opengl && *fancy && *itsrf)) {
		if (DoPopUp(win,cursorx-20,cursory,NULL,&j,0) == -1) return 0;
		i = (cursory - jy) / PEH;
		if (i > nplev) i = nplev;
		ipcol[i] = j + 1;
		*Sinct = 591;
	     }
	 }
	 update_model = 1;
         return(1);
    }

 }
 return(0);
}

int FindEsp(button12,cursorx,cursory)
int button12;
int cursorx;
int cursory;
{
 int i;

 update_model = 0;
 if (*itsrf) return(0);

 if (*doesp) {
	i = FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
			cursorx,cursory,MINDIFF);
	if (i >= 0) {
	    MkDistWin(xyz.iaton,5,esp[i]);
            return(1);
        } else {
	    if (ChangeLevel(button12,cursorx,cursory)) return(1);
	}

 }

 return(0);

}

PlotColIndex()
{
  int i,PEH,PH,PW,NE,MW,jx,jy;

  NE = nplev+1;
  if (*itsrf) NE = 5;
  PEH = 20;
  PW = 70;
  PH = NE*PEH;
  MW = 10;

  jx = width-PW-20;
  jy = 20;


  if (*itsrf) {
     if (has_opengl && *fancy) {
	butje(win,jx-MW,jy-MW,PW+2*MW,PH+2*MW,3,0,0,1,None,0,0,0);
	for (i=0; i < NE; i++) {
	   XSetForeground(display, gc, mappedcols[i]);
	   XFillRectangle(display, win, gc, jx,jy+(i * PH)/NE, PW,PEH);
	}
     }
  } else {
     if (has_opengl && *fancy) {
	butje(win,jx-MW,jy-MW,PW+2*MW,PH+2*MW,3,0,0,1,None,0,0,0);
	for (i=0; i < NE; i++) {
	   XSetForeground(display, gc, colors[ipcol[i]]);
	   XFillRectangle(display, win, gc, jx,jy+(i * PH)/NE, PW,PEH);
	}
     } else {
	butje(molcur,jx-MW,jy-MW,PW+2*MW,PH+2*MW,3,0,0,1,None,0,0,0);
	for (i=0; i < NE; i++) {
	   XSetForeground(display, gc, colors[ipcol[i]]);
	   XFillRectangle(display, molcur, gc, jx,jy+(i * PH)/NE, PW,PEH);
	}
     }
  }

  XSetForeground(display, gc, Black);
  if (*itsrf) {
     if (has_opengl && *fancy) {
	for (i=0; i < 5; i++) {
	   sprintf(stemp, "%#11.5f",valcol[i]);
	   XDrawString(display,win,gc,jx-10,jy+14+(i * PH)/NE,
	   	stemp,strlen(stemp));
	}
     }
  } else {
     for (i=0; i < NE-1; i++) {
	sprintf(stemp, "%#11.5f",plevel[i]);
	if (has_opengl && *fancy) 
	   XDrawString(display,win,gc,jx-10,jy+4+((i+1) * PH)/NE,
		stemp,strlen(stemp));
	else
	   XDrawString(display,molcur,gc,jx-10,jy+4+((i+1) * PH)/NE,
		stemp,strlen(stemp));
     }
  }
}

#if defined(VMS) || defined(UNDERSC)
butset(class,butnr,on)
#else
#ifdef CRAY
BUTSET(class,butnr,on)
#else
butset_(class,butnr,on)
#endif
#endif
int *class;
int *butnr;
int *on;
{
	if (!xison) return;

	switch(*class) {
	case 0: if (*on) TogUp(&dbut[*butnr]);
		else TogDown(&dbut[*butnr]);
		RedrawwinC(0,0,WINCWIDE,WINCHIGH);
		break;
	case 1: if (*on) TogUp(&cbut[*butnr]);
		else TogDown(&cbut[*butnr]);
	/*	RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);*/
		break;
	case 2: if (*on) TogUp(&ZMEbut[*butnr]);
		else TogDown(&ZMEbut[*butnr]);
		RedrawZME();
		break;
	}
}

OnTop()
{
int i;

	if (ZMEup) DirBox(ZMEwin,1);

	if (CHGup) DirBox(CHGwin,1);
	if (SRFup) DirBox(SRFwin,1);
	if (PARup) DirBox(PARwin,1);
	if (FLXup) DirBox(FLXwin,1);
	if (qbrfile) DirBox(Fwin,1);
	if (qbres) DirBox(RESwin,1);
	if (geoup) DirBox(wingeo,1);
	if (cnvup) DirBox(wincnv,1);
	if (distup) DirBox(DISTwin,1);
	if (ATMup) DirBox(ATMwin,1);
	if (COLup) DirBox(COLwin,1);
	if (SEQup) DirBox(SEQwin,1);
	if (TNKup) DirBox(TNKwin,1);
	if (ONIup) DirBox(ONIwin,1);
	if (specup) DirBox(winspec,1);
	if (scoup) DirBox(winsco,1);

	if (denmode) DirBox(winC,1);
	else DirBox(winMC,1);

	for (i=0; i<NQBOX; i++) 
		if (qboxes[i].pop && qboxes[i].active) 
			XMapRaised(display,qboxes[i].win);
}

InitCOL()
{
   int i;
   
   COLup = 1;

   COLwin = CreateWindow("Atom Property Editor","-0+0",COLWINW,COLWINHT,
	 		 infobg,infofg,(Window)0);
   XSelectInput(display, COLwin, 
	KeyPressMask | ExposureMask | ButtonPressMask | ButtonReleaseMask);
   XMapWindow(display,COLwin);


   DefBut(&colbut[0], COLwin, COLOffx, 5, 50, 23, "Close", infobg, 0);
   DefBut(&colbut[1], COLwin, COLOffx+225, 5, 120, 23, "Radius", infobg, 0);

   for (i=0; i < TABBUTN; i++) {
	if (i==TABBUTN-1)
	   DefBut(&AtmBut[i],COLwin, COLOffx+COLBord+TabPos[i][1]*(ZMETABH+1), 
		COLOffy+COLBord+TabPos[i][0]*(ZMETABH+1), ZMETABH, ZMETABH, 
        	   elements[99], infobg, -scalptr->icol[98]);
	else
	   DefBut(&AtmBut[i],COLwin, COLOffx+COLBord+TabPos[i][1]*(ZMETABH+1), 
		COLOffy+COLBord+TabPos[i][0]*(ZMETABH+1), ZMETABH, ZMETABH, 
        	   elements[i+1], infobg, -scalptr->icol[i]);
   }

   qboxstr(&qboxes[QRADI],&COLwin,1,0,190,COLOffx+345,5,
	120,38,2," "," ",SUBLEN2,QPOSREAL,2000,colcall);

   ipropopt = 0;
   colbut[1].str = propopts[ipropopt];
}

RedrawCOL()
{
   int i;

   if (!COLup) return;

   if (monoscr) {
	XSetFillStyle(display, gc, FillStippled);
	XSetStipple(display, gc, hlfgrey);
	XSetForeground(display, gc, infobg);
	XFillRectangle(display, COLwin, gc, 0, COLOffy-COLFRBord, 
		COLWINW, COLWINH+1);
	XSetFillStyle(display,gc,FillSolid);
   } else {
	butje(COLwin,0,0,COLWINW-1,COLOffy-COLFRBord+1,1,0,0,1,None,0,0,0);
        XSetForeground(display, gc, infobg);
	butje(COLwin,0,COLOffy-COLFRBord,COLWINW-1,COLWINH,
			1,0,0,1,None,0,0,0);
   }


   ULineString(COLwin, "Edit Property:",COLOffx+120, 20);

   for (i=0; i<NBUTSC; i++) DrwBut(&colbut[i]);

   if (ipropopt) PromptBox(&qboxes[QRADI]);

   butje(COLwin, COLOffx+1, COLOffy, COLWINIW, COLWINIH,2,0,2,0,None,0,0,0);
   for (i=0; i<TABBUTN; i++) DrwBut(&AtmBut[i]);

   if (propat == 98) SelBut(&AtmBut[TABBUTN-1]);
   else SelBut(&AtmBut[propat]);

}

RButtonsCOL(i)
int i;
{
    LSSTRU List;

    SetRadius();

    switch (i) {
    case 0: XDestroyWindow(display,COLwin);COLup = 0; break;
    case 1: List.list = propopts; List.nents = 4;
	    if (DoPopUp(COLwin,
			colbut[1].x+60,colbut[1].y+BUTTH,
			&List,&ipropopt,1) == -1) break;
	    colbut[1].str = propopts[ipropopt];
	    switch (ipropopt) {
	    case PVDWRAD:
		sprintf(qboxes[QRADI].str,"%f",scalptr->vdwr[propat]);
		break;
	    case PDISRAD:
		sprintf(qboxes[QRADI].str,"%f",scalptr->vrad[propat]*toangs);
		break;
	    case PESPRAD:
		sprintf(qboxes[QRADI].str,"%f",espvdw[propat]);
		break;
	    }
	    RedrawCOL();
 	    break;
    }
}

ButtonsCOL(i)
int i;
{
    int csel,updown;

    
    SetRadius();

    if (i==TABBUTN-1) propat = 98;
    else propat = i;

    switch (ipropopt) {
    case PATMCOL:
	updown = AtmBut[i].y+BUTTH;
	if (i > 85 || (i > 56 && i < 71) ) updown = updown - NUMCOL*14;
	if (DoPopUp(COLwin,AtmBut[i].x-8,updown,NULL,&csel,0) == -1) return;
	scalptr->icol[propat] = csel + 1;
	WriteRes();

	DefBut(&AtmBut[i],COLwin, 
		COLOffx+COLBord+TabPos[i][1]*(ZMETABH+1), 
		COLOffy+COLBord+TabPos[i][0]*(ZMETABH+1), 
		ZMETABH, ZMETABH, elements[propat+1], infobg, 
		-scalptr->icol[propat]);

	DrwBut(&AtmBut[i]);

	break;
    case PVDWRAD:
	sprintf(qboxes[QRADI].str,"%f",scalptr->vdwr[propat]);
	RedrawCOL();
#if defined(VMS) || defined(UNDERSC)
	doconn();
#else
#ifdef CRAY
	DOCONN();
#else
	doconn_();
#endif
#endif
	break;
    case PDISRAD:
	sprintf(qboxes[QRADI].str,"%f",scalptr->vrad[propat]*toangs);
	RedrawCOL();
	break;
    case PESPRAD:
	sprintf(qboxes[QRADI].str,"%f",espvdw[propat]);
	RedrawCOL();
	break;
    }

}

SetRadius()
{
     switch (ipropopt) {
     case PATMCOL: 
		break;
     case PVDWRAD: 
		scalptr->vdwr[propat] = atof(qboxes[QRADI].str);
		break;
     case PDISRAD: 
		scalptr->vrad[propat] = atof(qboxes[QRADI].str)/toangs;
		break;
     case PESPRAD:
		espvdw[propat] = atof(qboxes[QRADI].str);
		break;
     }

}

void colcall(char* str)
{
	SetRadius();
#if defined(VMS) || defined(UNDERSC)
	doconn();
#else
#ifdef CRAY
	DOCONN();
#else
	doconn_();
#endif
#endif
}

CreateCellPar()
{
  int i;

  if (CPup) {
	XMapRaised(display,CPwin);
	return;
  }

  CPup = 1;

  CPwin = CreateWindow("Edit Cell Parameters","-80-80",
			 CPBOXWIDE,CPBOXHIGH,infobg,infofg,(Window)0);
  XSelectInput(display, CPwin, 
	ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask);

  XMapWindow(display,CPwin);

  DefBut(&cpbut[BCPAPP], CPwin, 70, 5+8*(BUTTN+8), 50, 23,
	"Apply", infobg, -15);

  DefBut(&cpbut[BCPCAN], CPwin, 70+60, 5+8*(BUTTN+8), 50, 23,
	"Close", infobg, -15);

  for (i=0; i<8; i++) {
	qboxstr(&qboxes[QCPA+i],&CPwin,0,0,190,CPBOXOFFX,CPBOXOFFY+i*(BUTTN+5), 
		200,QBOXHIGH,2,cellpars[i],"10.0",9,2,2000,dummyproc);
  }
  qboxes[QCPSPGN].qbopt = 1;
  qboxes[QCPSPGS].qbopt = 0;
  qboxes[QCPSPGN].changed = 0;
  qboxes[QCPSPGS].changed = 0;
  UpdateCP();
}

UpdateCP()
{
 int i,j;
 double todeg;

 todeg = 45.0e0/atan(1.0e0);

 for (j=0; j<6; j++) {
	if (j<3) sprintf(qboxes[QCPA+j].str,"%-9.4f",
			cellconstants->cellc[j]);
	else if (j<6) sprintf(qboxes[QCPA+j].str,"%-9.3f",
			cellconstants->cellc[j]*todeg);
 }
 sprintf(qboxes[QCPSPGN].str,"%d",cellconstants->nspg);
 
 if (cellconstants->nspg != 0) {
   i = fndchr(spacegr[cellconstants->nspg - 1],' ');
   if (i == 0) i = 7;
   strncpy(qboxes[QCPSPGS].str,spacegr[cellconstants->nspg - 1],i);
   qboxes[QCPSPGS].str[i] = '\0';
 } else {
   strcpy(qboxes[QCPSPGS].str,"unknown");
 }

 if (cellconstants->nspg == 1 || cellconstants->nspg == 2) CPopt = 0;
 if ((cellconstants->nspg >= 3 && cellconstants->nspg <= 15) ||
	cellconstants->nspg == 231 ) CPopt = 1;
 if (cellconstants->nspg >= 16 && cellconstants->nspg <= 74) CPopt = 2;
 if ((cellconstants->nspg >= 75 && cellconstants->nspg <= 194) ||
       (cellconstants->nspg >= 232 && cellconstants->nspg <= 238)) CPopt = 3;
 if (cellconstants->nspg >= 195 && cellconstants->nspg <= 230) CPopt = 4;

}

RedrawCP()
{
  int i;

  butje(CPwin,0,0,CPBOXWIDE,CPBOXHIGH,4,0,0,1,None,0,0,0);
  for (i=0; i<NBUTCP; i++) DrwBut(&cpbut[i]);
  for (i=0; i<8; i++) PromptBox(&qboxes[QCPA+i]);
}

int ButtonsCP(x,y)
int x,y;
{
 int i,j;

 i = Clickwin(cpbut,NBUTCP,x,y,1);
 if (i>=0) {
	switch (i) {
	case BCPAPP:

	   for (j=0; j<6; j++) 
		cellconstants->cellc[j] = atof(qboxes[QCPA+j].str);

	   if (qboxes[QCPSPGN].changed) {

		cellconstants->nspg = atoi(qboxes[QCPSPGN].str);

	   } 

	   if (qboxes[QCPSPGS].changed) {
		int n, fnd;
		char spgtmp[] = "       ";

		n = strlen(qboxes[QCPSPGS].str);
		if (n > 7) n = 7;
		strncpy(spgtmp,qboxes[QCPSPGS].str,n);

		fnd = 0;
		for (i=0; i<MXSG; i++)
		   if (strcasecmp(spgtmp, spacegr[i]) == 0) {
			cellconstants->nspg = i + 1;
			fnd = 1;
		   }
		if (!fnd) {
		   strcpy(molwstr,"Unrecognized Spacegroup !");
		   StatusStr(0,1);
		}
	   }
	   qboxes[QCPSPGN].changed = 0;
	   qboxes[QCPSPGS].changed = 0;

#if defined(VMS) || defined(UNDERSC)
	   chgpar(xyz.ianz,xyz.coo);
#else
#ifdef CRAY
	   CHGPAR(xyz.ianz,xyz.coo);
#else
	   chgpar_(xyz.ianz,xyz.coo);
#endif
#endif
	   UpdateCP();
	   RedrawCP();
	   return(1);
	   break;

	case BCPCAN:
	   XDestroyWindow(display,CPwin);
	   CPup = 0;
	   break;
	default: break;
	}
 } else {
	i = ClickBox(&qboxes[QCPA],8,x,y);
	if (i>=0) {
		for (j=0; j<8; j++) qboxes[QCPA+j].active = 0;
		if (i == 6) qboxes[QCPSPGN].active = 1;
		if (i == 7) qboxes[QCPSPGS].active = 1;
		else if (CPact[CPopt][i]) qboxes[QCPA+i].active = 1;
		RedrawCP();
	}

 }

 return(0);

}

InitISO(x,y)
int x,y;
{
   char wgeom[64];
   
   ISOup = 1;

   sprintf(wgeom,"+%d+%d",x,y);

   ISOwin = CreateWindow("Isodensity Window",wgeom,ISOWINW,ISOWINH,
	 		 infobg,infofg,(Window)0);
   XSelectInput(display, ISOwin, 
	KeyPressMask | ExposureMask | ButtonPressMask | ButtonReleaseMask);
   XMapWindow(display,ISOwin);


   DefBut(&isobut[0], ISOwin, ISOWINW/2+15, 15+2*QBOXHIGH, 50, 23, "Number of Surfaces", infobg, ZMBCOL);
   isobut[0].str = ChainLength[surface->nvalc-1];
   DefBut(&isobut[1], ISOwin, ISOWINW/2-50/2, 250, 50, 23, "OK", infobg, ZMBCOL);

   qboxstr(&qboxes[QEDGE],&ISOwin,1,0,190,ISOOffx,15,
	200,QBOXHIGH,2,"Grid Size        "," ",SUBLEN2,QPOSREAL,2000,
	dummyproc);

   qboxstr(&qboxes[QNPTS],&ISOwin,0,0,190,ISOOffx,15+1*QBOXHIGH,
	200,QBOXHIGH,2,"Number of Points "," ",SUBLEN2,QPOSINT,2000,
	dummyproc);

   qboxstr(&qboxes[QVALC1],&ISOwin,0,0,190,ISOOffx,15+3*QBOXHIGH,
	200,QBOXHIGH,2,"Contour Value1   "," ",SUBLEN2,QPOSREAL,2000,
	dummyproc);

   qboxstr(&qboxes[QVALC2],&ISOwin,0,0,190,ISOOffx,15+4*QBOXHIGH,
	200,QBOXHIGH,2,"Contour Value2   "," ",SUBLEN2,QPOSREAL,2000,
	dummyproc);

   qboxstr(&qboxes[QVALC3],&ISOwin,0,0,190,ISOOffx,15+5*QBOXHIGH,
	200,QBOXHIGH,2,"Contour Value3   "," ",SUBLEN2,QPOSREAL,2000,
	dummyproc);

   sprintf(qboxes[QEDGE].str,"%f",surface->edge);
   sprintf(qboxes[QVALC1].str,"%f",surface->ctval[0]);
   sprintf(qboxes[QVALC2].str,"%f",surface->ctval[1]);
   sprintf(qboxes[QVALC3].str,"%f",surface->ctval[2]);
   sprintf(qboxes[QNPTS].str,"%d",surface->nspts);

}

RedrawISO()
{
  int i;

  butje(ISOwin,0,0,ISOWINW,ISOWINH,4,0,0,1,None,0,0,0);
  for (i=0; i<NBUTISO; i++) DrwBut(&isobut[i]);
  ULineString(ISOwin, "Number of Surfaces:",ISOOffx, 30+2*QBOXHIGH);
  PromptBox(&qboxes[QEDGE]);
  PromptBox(&qboxes[QVALC1]);
  PromptBox(&qboxes[QVALC2]);
  PromptBox(&qboxes[QVALC3]);
  PromptBox(&qboxes[QNPTS]);
}

int ButtonsISO(i)
int i;
{
  switch (i) {
  case 1:	
	surface->edge = atof(qboxes[QEDGE].str);
	surface->ctval[0] = atof(qboxes[QVALC1].str);
	surface->ctval[1] = atof(qboxes[QVALC2].str);
	surface->ctval[2] = atof(qboxes[QVALC3].str);
	surface->nspts = atoi(qboxes[QNPTS].str);
	XDestroyWindow(display,ISOwin);
	ISOup = 0;
	*Sinct = ISOt;
	return(1);
	break;
  case 0:	{
	LSSTRU List;
	List.list = ChainLength; List.nents = 3;
	if (DoPopUp(ISOwin,isobut[0].x+20,isobut[0].y,
		&List,&surface->nvalc,0) == -1) break;
	   surface->nvalc++;
	   isobut[0].str = ChainLength[surface->nvalc-1];
	   DrwBut(&isobut[0]);
	}
	break;
  }
  return(0);
}

InitATM(x,y)
int x,y;
{
   char wgeom[64];
   
   ATMup = 1;

   sprintf(wgeom,"+%d+%d",x,y);

   ATMwin = CreateWindow("Atom Attributes Window",wgeom,ATMWINW,ATMWINH,
	 		 infobg,infofg,(Window)0);
   subATM = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],ATMwin);
   XSelectInput(display, ATMwin, KeyPressMask | ExposureMask | ButtonPressMask 
	| ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask |
				PointerMotionMask | EnterWindowMask);
   XMapWindow(display,ATMwin);

   DefBut(&butATM[1],ATMwin, 100, 15, 100, 23, "Force Field", infobg, ZMBCOL);
   butATM[1].str = ForceFields[*fftyp];
   butATM[1].explstr = "Select a Force Field to type atoms with";

   DefBut(&butATM[2],ATMwin, 100, 15+BUTTN, 100, 23, "Total Charge", infobg, 
	ZMBCOL);
   butATM[2].str = copt[itcopt];
   butATM[2].explstr = "Select the total charge of the molecule";

   DefBut(&butATM[0], ATMwin, 150, 15+3*BUTTN, 70, 23, "AtomColor", infobg, 
	ZMBCOL);
   butATM[0].explstr = "Select substructure color of the atom.\nSelect atom: 2nd Mouse Button";

   DefBut(&butATM[3], ATMwin, ATMWINW/2-50/2, 315, 50, 23, "OK", infobg, ZMBCOL);
   butATM[3].explstr = "Close the window";

   DefBut(&butATM[4], ATMwin, 210, 15, 30, 23, "OPT", infobg, ZMBCOL);
   butATM[4].explstr = "Setup Tinker/AMBFOR optimisation\nAMBFOR is Molden\'s own optimiser\nfor AMBER/GAFF force fields\nGAFF is for small molecules";

   DefBut(&butATM[5], ATMwin, 210, 15+BUTTN, 30, 23, "E q", infobg, ZMBCOL);
   butATM[5].explstr = "Calculate van der Waals and \nElectrostatic energies between\n atoms with different residue numbers";

   qboxstr(&qboxes[QCHARG],&ATMwin,1,0,190,ATMOffx,35+4*BUTTN,
	110,QBOXHIGH,2,"Charge"," ",10,QREAL,2000,dummyproc);
   qboxes[QCHARG].explstr = "Partial charge of selected atom\nSelect atom: 2nd Mouse Button";

   qboxstr(&qboxes[QRSD],&ATMwin,0,0,190,ATMOffx+115,35+4*BUTTN,
	100,QBOXHIGH,2,"Residue"," ",4,QREAL,2000,dummyproc);
   qboxes[QRSD].explstr = "Rseidue number of selected atom\nSelect atom: 2nd Mouse Button";

   DefList(&fftlist,ATMwin,6,35+5*BUTTN+QBOXHIGH,ATMWINW-37,110,
	NULL,9,typs[1],NULL,NULL,Ntyps[1]);

   UpdateATM();

}

UpdateATM()
{
   int i;

   sprintf(qboxes[QCHARG].str,"%f",xyz.qat[ATMsel]);
   qboxes[QCHARG].dflt = &xyz.qat[ATMsel];
   sprintf(qboxes[QRSD].str,"%d",xyz.iresid[ATMsel]);
   qboxes[QRSD].iflt = &xyz.iresid[ATMsel];
   fftlist.list.ilst = ffptr[*fftyp];
   if (xyz.ityp[ATMsel] < 0) {
	fftlist.list.list = typsn[*fftyp];
	fftlist.list.nents = Ntypsn[*fftyp];
	fftlist.scrbar.wn = Ntypsn[*fftyp];
   } else {
	fftlist.list.list = typs[*fftyp]; 
	fftlist.list.nents = Ntyps[*fftyp];
	fftlist.scrbar.wn = Ntyps[*fftyp];
   }

   if (ffptr[*fftyp] == NULL) {
	fftlist.select = abs(xyz.ityp[ATMsel]) - 1;
   } else {
	fftlist.select = -1;
	for (i=0; i<*Ntyps[*fftyp]; i++)
	   if (abs(xyz.ityp[ATMsel]) - 1 == fftlist.list.ilst[i]) fftlist.select = i;
   }
   if (fftlist.select >= *fftlist.list.nents) fftlist.select = 0;
   if (fftlist.select == -1 && ffptr[*fftyp] != NULL 
	&& fftlist.list.ilst != NULL) {
	for (i=0; i<*Ntyps[*fftyp]; i++) {
	   if (xyz.ianz[ATMsel] == ffatnr[*fftyp][i]) {
		fftlist.lpnt = i;
		break;
	   }
	}
   } else {
	fftlist.lpnt = fftlist.select - 4;
   }
   if (fftlist.lpnt < 0) fftlist.lpnt = 0;
   if (fftlist.lpnt > *fftlist.list.nents - fftlist.mxents) 
	fftlist.lpnt = *fftlist.list.nents - fftlist.mxents;
   if (! *fftyp) {
	fftlist.select = 0;
	fftlist.lpnt = 0;
	*fftlist.scrbar.wpos = 0;
   }
   butATM[1].str = ForceFields[*fftyp];
}

RedrawATM()
{
  int i;
  char nrstr[80];
  char atstr[3];

  butje(ATMwin,0,0,ATMWINW,75,4,0,0,1,None,0,0,0);
  butje(ATMwin,0,75,ATMWINW,ATMWINH-75,4,0,0,1,None,0,0,0);
  LineString(ATMwin, "Force Field ",ATMOffx, 30);
  LineString(ATMwin, "Total Charge",ATMOffx, 30+BUTTN);
  strcpy(atstr,"  ");
  if (ATMsel >= 0 && ATMsel < *xyz.mxnat) {
     if (xyz.ianz[ATMsel] >= 0 && xyz.ianz[ATMsel] < MXEL)
	strcpy(atstr,elements[xyz.ianz[ATMsel]]);
	
  }
  sprintf(nrstr,"Atom: %s  Number: %d", atstr,ATMsel+1);
  LineString(ATMwin, nrstr,ATMOffx, 30+3*BUTTN);
  ULineString(ATMwin,"Atom Type",ATMOffx, 43+4*BUTTN+QBOXHIGH);
  for (i=0; i<NBUTATM; i++) DrwBut(&butATM[i]);
  PromptBox(&qboxes[QCHARG]);
  PromptBox(&qboxes[QRSD]);
  RedrawList(&fftlist);
}

int ButtonsATM(i)
int i;
{
  int ff,nuse;

  switch (i) {
  case 0:	{
	if (DoPopUp(ATMwin,butATM[0].x-8,butATM[0].y+BUTTH,
			NULL,&xyz.iatclr[ATMsel],0) == -1) break;
	   xyz.iatclr[ATMsel]++;
	   DrwBut(&butATM[0]);
	   *Sinct = 0;
	   return(1);
	}
	break;
  case 1:	{
	LSSTRU List;
	List.list = ForceFields; List.nents = 8;
	if (DoPopUp(ATMwin,butATM[1].x+20,butATM[1].y,
			&List,fftyp,0) == -1) break;
	   butATM[1].str = ForceFields[*fftyp];
	   DrwBut(&butATM[1]);
#if defined(VMS) || defined(UNDERSC)
	   dotyp(ichx);
#else
#ifdef CRAY
	   DOTYP(ichx);
#else
	   dotyp_(ichx);
#endif
#endif
	   Progs = TnkProgs;
	   nprogs = 5;
	   if (*fftyp == 7) {
		Progs = AmbProgs; 
		nprogs = 1;
		*tnkprg = 0;
	   }
           UpdateATM();
           RedrawATM();
	   return(1);
	}
	break;
  case 2:	{
	LSSTRU List; int totch;

	List.list = copt; List.nents = 7;
	if (DoPopUp(ATMwin,butATM[2].x+20,butATM[2].y,
		&List,&itcopt,0) == -1) break;
	   butATM[2].str = copt[itcopt];
	   DrwBut(&butATM[2]);
	   totch = itcopt -3;
#if defined(VMS) || defined(UNDERSC)
	   fixchg(&totch,xyz.qat);
#else
#ifdef CRAY
	   FIXCHG(&totch,xyz.qat);
#else
	   fixchg_(&totch,xyz.qat);
#endif
#endif
	   *ihasq = 1;
           UpdateATM();
           RedrawATM();
	   return(1);
	}
	break;
  case 3:
	XDestroyWindow(display,ATMwin);
	ATMup = 0;
	*Sinct = ATMt;
	return(1);
	break;
  case 4:
	if ( ! ((*fftyp >= 1 && *fftyp <= 4) || *fftyp == 7) ) {
	   if (DoCan(event.xbutton.x_root,
		event.xbutton.y_root,"No Tinker or AMBFOR Force Field Selected !",0)) {}
	} else {
	   if ( ! ((*fftyp >= 1 && *fftyp <= 4) || *fftyp == 7) ) {
		ff = 1;
		if (pdb) ff = 7;
	   } else {
		ff = *fftyp;
	   }
	   if (typit(ff)) {
		if (DoCan(event.xbutton.x_root,
		   event.xbutton.y_root,"Found UnTyped Atoms !",0)) {}
	   } else {
		*iixyz = 6;
		if (TNKup) {
		   XMapRaised(display,TNKwin);
		   RedrawTNK();
		} else {
		   InitTNK(event.xbutton.x_root,
			event.xbutton.y_root);
		}
	   }
	}
	break;
  case 5:
	*icalc = 1;
	fprintf(stderr,"\n - vdWaals only for H,C,N,O,S,Cl\n\
 - residue 0 is not considered in residue-residue electrostatics\n");
#if defined(VMS) || defined(UNDERSC)
	nuse = 0; calcij(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
	nuse = 2; calcij(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
	nuse = 3; calcij(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
	nuse = 4; calcij(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
#else
#ifdef CRAY
	nuse = 0; CALCIJ(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
	nuse = 2; CALCIJ(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
	nuse = 3; CALCIJ(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
	nuse = 4; CALCIJ(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
#else
	nuse = 0; calcij_(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
	nuse = 2; calcij_(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
	nuse = 3; calcij_(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
	nuse = 4; calcij_(&nuse,xyz.coo,xyz.ianz,xyz.iresid,xyz.iconn,xyz.qat);
#endif
#endif
	break;
  }
  return(0);
}

#define ROWLEN 10

InitSEQ(x,y)
int x,y;
{
   int i,row,col;
   char wgeom[64];
   
   SEQup = 1;

   sprintf(wgeom,"+%d+%d",x,y);

   SEQwin = CreateWindow("Build Sequence Window",wgeom,SEQWINW,SEQWINH,
	 		 infobg,infofg,(Window)0);
   XSelectInput(display, SEQwin, KeyPressMask | ExposureMask | ButtonPressMask 
	| ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask);
   XMapWindow(display,SEQwin);


   DefBut(&butSEQ[0], SEQwin, 100, SEQCONFY, 100, 23, "Alpha", infobg, ZMBCOL);
   butSEQ[0].str = Conformations[iconform];

   DefBut(&butSEQ[1], SEQwin, SEQOffx,      SEQBROWY, 75, 23, "Build", 
	infobg, ZMBCOL);

   DefBut(&butSEQ[2], SEQwin, SEQOffx+90,   SEQBROWY, 75, 23, "Undo", 
	infobg, ZMBCOL);

   DefBut(&butSEQ[4], SEQwin, SEQOffx+2*90, SEQBROWY, 75, 23, "Read", 
	infobg, ZMBCOL);

   DefBut(&butSEQ[3], SEQwin, SEQOffx+3*90, SEQBROWY, 75, 23, "Close", 
	infobg, ZMBCOL);

   for (i=0; i < NAminos; i++) {
      row = i / ROWLEN;
      col = i - row*ROWLEN;
      DefBut(&butSEQ[5+i], SEQwin, SEQOffx+col*40, SEQRESY+row*30, 35, 23, 
	AminoAcids[i], infobg, ZMBCOL);
   }

   qboxstr(&qboxes[QPHI],&SEQwin,1,0,190,210,SEQCONFY-5,
        100,QBOXHIGH,2,"PHI"," ",SUBLEN2,QREAL,2000,dummyproc);
   qboxstr(&qboxes[QPSI],&SEQwin,0,0,190,320,SEQCONFY-5,
        100,QBOXHIGH,2,"PSI"," ",SUBLEN2,QREAL,2000,dummyproc);

   phi_angle = phis[iconform];
   psi_angle = psis[iconform];
   sprintf(qboxes[QPHI].str,"%-9.3f",phi_angle);
   sprintf(qboxes[QPSI].str,"%-9.3f",psi_angle);
}

RedrawSEQ()
{
  int i;

  butje(SEQwin,0,0,SEQWINW,SEQWINH,4,0,0,1,None,0,0,0);

  LineString(SEQwin, "Residues:",SEQOffx, SEQRESY - 10);
  LineString(SEQwin, "Conformation:",SEQOffx, SEQCONFY+13);
  for (i=0; i<NBUTSEQ; i++) DrwBut(&butSEQ[i]);
  UpdateSeqStat();
  PromptBox(&qboxes[QPHI]);
  PromptBox(&qboxes[QPSI]);

}

UpdateSeqStat()
{
  int i;
  int il;

  il = NSeq-16;
  if (il < 0) il = 0;

  strcpy(SeqStat," ");
  for (i=il; i < NSeq; i++) {
	strcat(SeqStat,AminoAcids[Sequence[i]]);
	if (i < NSeq-1) strcat(SeqStat,"-");
  }

  butje(SEQwin,SEQOffx,SEQSTATY,SEQWINW-2*SEQOffx,30,2,0,2,0,None,0,0,0);
  LineString(SEQwin, SeqStat,SEQOffx, SEQSTATY+18);

}

int ButtonsSEQ(i)
int i;
{
  int residue, newSQ;

  switch (i) {
  case 0:	{
	LSSTRU List;
	List.list = Conformations; List.nents = 3;
	   if (DoPopUp(SEQwin,butSEQ[0].x+4,butSEQ[0].y+BUTTH-5,
		&List,&iconform,0) == -1) break;
	   butSEQ[0].str = Conformations[iconform];
	   phi_angle = phis[iconform];
	   psi_angle = psis[iconform];
	   sprintf(qboxes[QPHI].str,"%-9.3f",phi_angle);
	   sprintf(qboxes[QPSI].str,"%-9.3f",psi_angle);
	   PromptBox(&qboxes[QPHI]);
	   PromptBox(&qboxes[QPSI]);
	   DrwBut(&butSEQ[0]);
	}
	break;
  case 1:
	phi_angle = atof(qboxes[QPHI].str);
	psi_angle = atof(qboxes[QPSI].str);
	newSQ = LastAmino;
	if (InsertAmino != -1) {
	   if (ReplaceAmino) 
		ReplaceSequence(Sequence,NSeq,iconform,InsertAmino);
	   else
		idum1 = InsertSequence(Sequence,NSeq,iconform,InsertAmino,0,NULL);
	   InsertAmino = -1;
	   ReplaceAmino = 0;
	   NSeq = 0;
	   UpdateSeqStat();
	   XSync(display, False);
	   XDestroyWindow(display,SEQwin);
	   SEQup = 0;
	} else {
	   ReplaceAmino = 0;
	   AddSequence(Sequence,NSeq,iconform);
	   NSeq = 0;
	   UpdateSeqStat();
	}
	if (ZMEAA) { 
	   *Sinct = 530; 
	} else {
	   make_aa();
	   SetQZME();
/*
	   TogUp(&ZMEswitch[0]);
	   EXPbox[0].fake = 0;
*/
	   UpdateZME(); RedrawZME();
	}
	if (newSQ == -1) {
#if defined(VMS) || defined(UNDERSC)
	   dumzm(xyz.coo,xyz.ianz,xyz.iatoms);
	   conpdb();docent();doscal();setxyv();doclr();qupd();
#else
#ifdef CRAY
	   DUMZM(xyz.coo,xyz.ianz,xyz.iatoms);
	   CONPDB();DOCENT();DOSCAL();SETXYV();doclr();QUPD();
#else
   	   dumzm_(xyz.coo,xyz.ianz,xyz.iatoms);
	   conpdb_();docent_();doscal_();setxyv_();doclr();qupd_();
#endif
#endif
	}
	return(1);
	break;
  case 2:
	NSeq--;
	if (NSeq < 0) NSeq = 0;
	UpdateSeqStat();
	break;
  case 3:	
	XDestroyWindow(display,SEQwin);
	SEQup = 0;
	break;
  case 4:	
	if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
	   "Protein File, per line:\n\n\
3 letter amino acid code Phi Psi [Omega] [Chi1] [Chi2] [Chi3] [Chi4]\n\n\
The current Conformation will be assigned to it",0)) {}
	qboxstr(&qboxes[QPROT],NULL,1,0,-1, DEFQX,DEFQY,
	   QBOXWIDE,QBOXHIGH,0,"Protein Filename ? ",NULL,0,0,
	   640,dummyproc);
	break;
  default:
	residue = i - 5;
	if (residue >= 0 && residue < NAminos) {
	   if (NSeq < MAXSEQ-1) {
		Sequence[NSeq] = residue;
		NSeq++;
	   }
	}
	UpdateSeqStat();
	break;
  }
  return(0);
}

InitTNK(x,y)
int x,y;
{
   char wgeom[64];
   int xmax;
   
   TNKup = 1;

   Progs = TnkProgs;
   nprogs = 5;
   AddChrg = 0;

   if (*fftyp == 7) {
	Progs = AmbProgs; 
	nprogs = 1;
	AddChrg = 1;
	*tnkprg = 0;
   }

   xmax = DisplayWidth(display,screen) - TNKWINW;
   if (x > xmax) x = xmax;
   sprintf(wgeom,"+%d+%d",x,y);

   TNKwin = CreateWindow("Tinker/AMBFOR Preferences",wgeom,TNKWINW,TNKWINH,
	 		 infobg,infofg,(Window)0);
   XSelectInput(display, TNKwin, KeyPressMask | ExposureMask | ButtonPressMask 
	| ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask
		| PointerMotionMask | EnterWindowMask);
   subTNK = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],TNKwin);
   XMapWindow(display,TNKwin);


   DefBut(&butTNK[0], TNKwin, 100, TNKRESY, 80, 23, "minimize", infobg, ZMBCOL);
   butTNK[0].str = Progs[*tnkprg];
   butTNK[0].explstr = "Select program to optimise structure";

   DefBut(&butTNK[1], TNKwin, 100, TNKRESY+TNKBWIDE, 15, 15, " ", 
	infobg, ZMBCOL);
   butTNK[1].explstr = "Detach Job:\ndont wait for the job to finish";

   DefBut(&butTNK[2], TNKwin, 100, TNKRESY+2*TNKBWIDE, 15, 15, " ", 
	infobg, ZMBCOL);
   butTNK[2].explstr = "Archive Job:\ncreate archive file with multiple\nintermediate structures";

   DefBut(&butTNK[3], TNKwin, TNKOffx, TNKBROWY, 75, 23, "GO", 
	infobg, ZMBCOL);

   DefBut(&butTNK[4], TNKwin, TNKOffx+100, TNKBROWY, 75, 23, "Close", 
	infobg, ZMBCOL);

   DefBut(&butTNK[5], TNKwin, 100, TNKRESY+3*TNKBWIDE, 15, 15, " ", 
	infobg, ZMBCOL);
   butTNK[5].explstr = "Calculate partial charges";


   if (*tnkbg) {
	TogDown(&butTNK[1]);
   } else {
	TogUp(&butTNK[1]);
   }
 
   if (*arch) {
	TogDown(&butTNK[2]);
   } else {
	TogUp(&butTNK[2]);
   }
 
   if (AddChrg) {
	TogDown(&butTNK[5]);
   } else {
	TogUp(&butTNK[5]);
   }
 
   qboxstr(&qboxes[QGRD],&TNKwin,0,0,190,210,TNKRESY-5,
        200,QBOXHIGH,2,"RMS Gradient"," ",SUBLEN1,QREAL,2000,dummyproc);
   qboxstr(&qboxes[QTNKJN],&TNKwin,1,0,190,210,TNKRESY+TNKBWIDE-5,
        200,QBOXHIGH,2,"Job Name",NULL,SUBLEN2,0,2000,dummyproc);
   qboxstr(&qboxes[QARCH],&TNKwin,0,0,190,210,TNKRESY+2*TNKBWIDE-5,
        200,QBOXHIGH,2,"Archive Update Freq.",NULL,SUBLEN1,QPOSINT,2000,dummyproc);
   qboxstr(&qboxes[QMAXIT],&TNKwin,0,0,190,210,TNKRESY+3*TNKBWIDE-5,
        200,QBOXHIGH,2,"Max. Iteration",NULL,SUBLEN1,QPOSINT,2000,dummyproc);


   *currgrd = mxgrads[*tnkprg];
   sprintf(qboxes[QGRD].str,"%-9.3f",*currgrd);
   sprintf(qboxes[QARCH].str,"%d",*archfrq);
   sprintf(qboxes[QTNKJN].str,"molin");
   strcp(tnkjn,qboxes[QTNKJN].str,SUBLEN2);
   TrmStr(&qboxes[QTNKJN]);
   sprintf(qboxes[QMAXIT].str,"%d",*tnkit);
}

RedrawTNK()
{
  int i;

  butje(TNKwin,0,0,TNKWINW,TNKWINH,4,0,0,1,None,0,0,0);

  LineString(TNKwin, "Optimizer:",TNKOffx, TNKRESY+13);
  LineString(TNKwin, "Archive",TNKOffx, TNKRESY+2*TNKBWIDE+11);
  LineString(TNKwin, "Detach Job",TNKOffx, TNKRESY+TNKBWIDE+11);
  if (Progs == AmbProgs) {
	LineString(TNKwin, "Calc. Charge",TNKOffx, TNKRESY+3*TNKBWIDE+11);
	for (i=0; i<NBUTTNK; i++) DrwBut(&butTNK[i]);
  } else {
	for (i=0; i<NBUTTNK-1; i++) DrwBut(&butTNK[i]);
  }
  PromptBox(&qboxes[QGRD]);
  PromptBox(&qboxes[QARCH]);
  PromptBox(&qboxes[QTNKJN]);
  PromptBox(&qboxes[QMAXIT]);

}

int ButtonsTNK(i)
int i;
{

  switch (i) {
  case 0:	{
	LSSTRU List; 
	List.list = Progs; List.nents = nprogs;
	   if (DoPopUp(TNKwin,butTNK[0].x+4,butTNK[0].y+BUTTH-5,
		&List,tnkprg,0) == -1) break;
	   butTNK[0].str = Progs[*tnkprg];
	   *currgrd = mxgrads[*tnkprg];
	   sprintf(qboxes[QGRD].str,"%-9.3f",*currgrd);
	   PromptBox(&qboxes[QGRD]);
	   if (*tnkprg == 4) {
		List.list = xtinkopts; List.nents = 2;
		if (DoPopUp(TNKwin,butTNK[0].x-8,butTNK[0].y+BUTTH,
				&List,iqopt,0) == -1) {int idum; idum = 1;}
	   }
	   DrwBut(&butTNK[0]);
	}
	break;
  case 1:	
/* background */
	*tnkbg = ! TogBut(&butTNK[1]);
	break;
  case 2:
/* archive */
	*arch = ! TogBut(&butTNK[2]);
	break;
  case 3:
/* go */
#ifdef DOGL
	ogunsel();
#endif
	*currgrd = atof(qboxes[QGRD].str);
	*archfrq = atoi(qboxes[QARCH].str);
	*tnkit = atoi(qboxes[QMAXIT].str);
	cpstr(qboxes[QTNKJN].str,tnkjn,SUBLEN1);
	XDestroyWindow(display,TNKwin);
	TNKup = 0;
	if (*fftyp == 7) {
	   *iixyz = 11;
	} else {
           if (*tnkprg == 4) {
		*iixyz = 10;
	   } else {
		*iixyz = 6;
	   }
	}
	if (AddChrg) {
#if defined(VMS) || defined(UNDERSC)
	   clceem();
#else
#ifdef CRAY
	   CLCEEM();
#else
	   clceem_();
#endif
#endif
	}
	*Sinct = 151;
	return(1);
	break;
  case 4:	
/* close */
	*currgrd = atof(qboxes[QGRD].str);
	*archfrq = atoi(qboxes[QARCH].str);
	*tnkit = atoi(qboxes[QMAXIT].str);
	cpstr(qboxes[QTNKJN].str,tnkjn,SUBLEN1);
	XDestroyWindow(display,TNKwin);
	TNKup = 0;
	break;
  case 5:	
/* Calculate Charge */
	AddChrg = ! TogBut(&butTNK[5]);
	break;
  default:
	break;
  }
  return(0);
}

rearr(itarr,arr)
int *itarr;
int *arr;
{
   int j;

   for (j=0; j<*zmptr.nz; j++) {
	itarr[j] = arr[zmptr.imap[j]-1];
   }
   for (j=0; j<*zmptr.nz; j++) {
	arr[j] = itarr[j];
   }
}

rearrs(itarr,arr)
int *itarr;
short int *arr;
{
   int j;

   for (j=0; j<*zmptr.nz; j++) {
	itarr[j] = (int) arr[zmptr.imap[j]-1];
   }
   for (j=0; j<*zmptr.nz; j++) {
	arr[j] = (short int) itarr[j];
   }
}

rearrd(itarr,arr)
double *itarr;
double *arr;
{
   int j;

   for (j=0; j<*zmptr.nz; j++) {
	itarr[j] = arr[zmptr.imap[j]-1];
   }
   for (j=0; j<*zmptr.nz; j++) {
	arr[j] = itarr[j];
   }
}

rearrz(itarr)
int *itarr;
{
   int j;

   for (j=0; j<*zmptr.nz; j++) itarr[j] = -1;
   for (j=0; j<*zmptr.nz; j++) {
	if (zmptr.imap[j] > 0) {
	   itarr[zmptr.imap[j]-1] = j;
	}
   }
}

int mapchk()
{
   int j;

    if (*ialtyp) return(1);

    for (j=0; j<*zmptr.nz; j++) {
	if (zmptr.imap[j]-1 != j) {
	    return(0) ;
	}
    }
    return (1);
}

#if defined(VMS) || defined(UNDERSC)
int dozmt(ioke)
#else
#ifdef CRAY
int DOZMT(ioke)
#else
int dozmt_(ioke)
#endif
#endif
int *ioke;
{


        *ioke = 0;
        if (!xison) return;
	if (!*zmptr.ihaszm) { 
	   if (!DoCan(200,100,
		"Do You want to create a Z-matrix for this molecule ?",1)) {
	     *ioke = 1;
	     if (*xyz.iatoms > *zmptr.mxzat - 100) {
		*ioke = 0;
                if (AllocZMat(*xyz.mxnat)) *ioke = 1;
	     }
	   }
	}
}

int DoPDB()
{
int i,j,k;
double d;
int *iarr;
double *darr;
int imarr[NUMCAL];
int ioke;


	if (!*zmptr.ihaszm) { 
	   if (!DoCan(event.xbutton.x_root,event.xbutton.y_root,
		"Do You want to create a Z-matrix for this protein ?",1)) {
	     ioke = 1;
	     if (*xyz.iatoms > *zmptr.mxzat - 100) {
		ioke = 0;
		if (AllocZMat(*xyz.mxnat)) ioke = 1;
	     }
			
	     if (ioke) {
#if defined(VMS) || defined(UNDERSC)
		curs(&ONE);
		XSync(display, False);
        	pdbzmt();
#else
#ifdef CRAY
		CURS(&ONE);
		XSync(display, False);
        	PDBZMT();
#else
		curs_(&ONE);
		XSync(display, False);
        	pdbzmt_();
#endif
#endif
		if (*zmptr.ihaszm) {

		   if ((iarr = (int *) malloc((sizeof j)*(*zmptr.mxzat))) 
				!= NULL) {

			rearr(iarr,xyz.iatclr);
			rearr(iarr,xyz.iresid);
			rearr(iarr,xyz.iaton);
			rearrs(iarr,xyz.ityp);
			rearrs(iarr,xyz.ipdbt);

			rearrz(iarr);
			for (k=0; k<6; k++) {
			   for (j=0; j<calfptr->ncalf; j++) 
				imarr[j] = calfptr->icalf[j][k];

			   for (j=0; j<calfptr->ncalf; j++) {
				if (imarr[j]-1 >= 0)
				   calfptr->icalf[j][k] = iarr[imarr[j]-1]+1;
			   }
			}

			free(iarr);
		   }

		   if ((darr = (double *) malloc((sizeof d)*(*zmptr.mxzat))) 
				!= NULL) {

			rearrd(darr,xyz.qat);
			free(darr);
		   }

/* old, with centering */   /*conpdb();chkbck();docent();doclr();qupd();*/

#if defined(VMS) || defined(UNDERSC)
		   dumzm(xyz.coo,xyz.ianz,xyz.iatoms);
		   conpdb();chkbck();doclr();qupd();
		   if (backb) {
			for (i=0;i<4;i++) 
			   acthel(&ONE,&i,&scndcol[i],&ZERO);
		   }
#else
#ifdef CRAY
		   DUMZM(xyz.coo,xyz.ianz,xyz.iatoms);
		   CONPDB();CHKBCK();doclr();QUPD();
		   if (backb) {
			for (i=0;i<4;i++)
			   ACTHEL(&ONE,&i,&scndcol[i],&ZERO);
		   }
#else
		   dumzm_(xyz.coo,xyz.ianz,xyz.iatoms);
		   conpdb_();chkbck_();doclr();qupd_();
		   if (backb) {
			for (i=0;i<4;i++) 
			   acthel_(&ONE,&i,&scndcol[i],&ZERO);
		   }
#endif
#endif
		   make_aa();
		
		   if (ZMEup) {
			SetQZME();
			if (ZME_window_pos >= *zmptr.nz) ZME_window_pos = 0;
			RedrawZME();
			RedrawScroll(&zscroll);
		   }
		}
		SSdone = 0;
#if defined(VMS) || defined(UNDERSC)
		curs(&ZERO);
#else
#ifdef CRAY
		CURS(&ZERO);
#else
		curs_(&ZERO);
#endif
#endif
	 	return(1);
	      } else {
		sprintf(ZMEerr,
			"Couldnt allocate memory for Z-Matrix");
		RedrawStatus();
	      }
	   } else {
	      InitZME();
	   }
	}

	return(0);
}

DelCellAtoms()
{
int i,j,k,nstor,nold,kcon,ab,noab;

	i = 0; 
	nstor = *xyz.mxnat - *natc;
	while (i < *natc) {
	  if (xyz.iaton[i] == 2) {
	    for (j=i; j < *natc - 1; j++) {
		xyz.iatclr[nstor+j] = xyz.iatclr[nstor+j+1];
		xyz.ianz[nstor+j] = xyz.ianz[nstor+j+1];
		xyz.ipdbt[nstor+j] = xyz.ipdbt[nstor+j+1];
		xyz.ityp[nstor+j] = xyz.ityp[nstor+j+1];
		xyz.qat[j] = xyz.qat[j+1];
		for (k=0; k < 3; k++)
		   xyz.coo[(nstor+j)*3+k] = xyz.coo[(nstor+j+1)*3+k];
		kcon = 0;
		for (k=0; k < xyz.iconn[(nstor+j+1)*(MXCON+1)]; k++) {
		   noab = xyz.iconn[(nstor+j+1)*(MXCON+1)+k+1];
		   ab = ABS(noab);
		   if (ab > i+1) {
			if (noab > 0) {
			   xyz.iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab - 1;
			} else {
			   xyz.iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab + 1;
			}
			kcon++;
		   } else if (ab != i+1) {
			xyz.iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab;
			kcon++;
		   }
		}
		xyz.iconn[(nstor+j)*(MXCON+1)] = kcon;
		xyz.iaton[j] = xyz.iaton[j+1];
	    }
	    *natc = *natc - 1;
	    for (j=0; j < i; j++) {
		kcon = 0;
		for (k=0; k < xyz.iconn[(nstor+j)*(MXCON+1)]; k++) {
		   noab = xyz.iconn[(nstor+j)*(MXCON+1)+k+1];
		   ab = ABS(noab);
		   if (ab > i+1) {
			if (noab > 0) {
			   xyz.iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab - 1;
			} else {
			   xyz.iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab + 1;
			}
			kcon++;
		   } else if (ab != i+1) {
			xyz.iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab;
			kcon++;
		   }
		}
		xyz.iconn[(nstor+j)*(MXCON+1)] = kcon;
	    }
	  } else {
	    i++;
	  }
	}
	nold = nstor;
	nstor = *xyz.mxnat - *natc;
	for (j=*natc - 1; j >= 0; j--) {
	   xyz.iatclr[nstor+j] = xyz.iatclr[nold+j];
	   xyz.ianz[nstor+j] = xyz.ianz[nold+j];
	   xyz.ipdbt[nstor+j] = xyz.ipdbt[nold+j];
	   xyz.ityp[nstor+j] = xyz.ityp[nold+j];
 	   for (k=0; k < 3; k++)
		xyz.coo[(nstor+j)*3+k] = xyz.coo[(nold+j)*3+k];
	   for (k=0; k < xyz.iconn[(nold+j)*(MXCON+1)]+1; k++)
		xyz.iconn[(nstor+j)*(MXCON+1)+k] = xyz.iconn[(nold+j)*(MXCON+1)+k];
	}
	update_sel = 1;
}

MoveCellAtoms(CellTrans)
double *CellTrans;
{
int i,k,nstor;

	i = 0; 
	nstor = *xyz.mxnat - *natc;

	for (i=0; i < *natc; i++) {
	    if (xyz.iaton[i] == 2) {
		for (k=0; k < 3; k++)
		   xyz.coo[(nstor+i)*3+k] = 
			xyz.coo[(nstor+i)*3+k] + CellTrans[k];
	    }
	}
}

InitCellDelTrans(dtopt)
int dtopt;
{
  int i,CTdelbck;

  CTdelbck = CTdel;
  CTdel = dtopt;

  if (CTup) {
	if (dtopt != CTdelbck) RedrawCT();
	return;
  }

  CTup = 1;

  CTwin = CreateWindow("Translate / Delete Cell Atoms","-80-80",
			 CTBOXWIDE,CTBOXHIGH,infobg,infofg,(Window)0);
  XSelectInput(display, CTwin, 
	ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask);

  XMapWindow(display,CTwin);

  DefBut(&ctbut[0], CTwin, 70, 5+3*(BUTTN+5), 50, 23,
	"Apply", infobg, -15);

  DefBut(&ctbut[1], CTwin, 70+60, 5+3*(BUTTN+5), 50, 23,
	"Close", infobg, -15);

  DefBut(&ctbut[2], CTwin, 70, 5+2*(BUTTN+5), 50, 23,
	"Select", infobg, -15);

  DefBut(&ctbut[3], CTwin, 70+60, 5+2*(BUTTN+5), 70, 23,
	"DeSelect", infobg, -15);

  for (i=0; i<3; i++) {
	qboxstr(&qboxes[QCTA+i],&CTwin,0,0,190,CTBOXOFFX+i*80,CTBOXOFFY, 
		75,QBOXHIGH,2,cellvec[i],"0.0",9,QREAL,2000,dummyproc);
	qboxes[QCTA+i].dflt = &CellTran[i];
  }
}

RedrawCT()
{
  int i;

  butje(CTwin,0,0,CTBOXWIDE,CTBOXHIGH,4,0,0,1,None,0,0,0);
  for (i=0; i<NBUTCT; i++) DrwBut(&ctbut[i]);
  if (!CTdel) for (i=0; i<3; i++) PromptBox(&qboxes[QCTA+i]);
}

int ButtonsCT(x,y)
int x,y;
{
 int i,j;

 i = Clickwin(ctbut,NBUTCT,x,y,1);
 if (i>=0) {
	switch (i) {
	case 0:
	   if (CTdel) {
		DelCellAtoms();
	   } else {
		for (j=0; j<3; j++) 
		   CellTran[j] = atof(qboxes[QCTA+j].str);
		RedrawCT();
		MoveCellAtoms(CellTran);
	   }
	   SelDel = 0;
	   Selecting = 0;
	   if (!CTdel && CTconn) return(2);
	   else return(1);
	   break;

	case 1:
	   for (i=0; i < *xyz.iatoms; i++ ) 
		if (xyz.iaton[i] > 1) xyz.iaton[i] = 1;
	   SelDel = 0;
	   XDestroyWindow(display,CTwin);
	   CTup = 0;
	   break;
	case 2:
	   if (!CTsdone) {
		if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
		   selstr,0)) {}
		CTsdone = 1;
	   }
	   Selecting = 1; ZoomEnable = True;
	   Select = True; SelDel = 1;
	   break;
	case 3:
	   if (!CTdsdone) {
		if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
		   dselstr,0)) {}
		CTdsdone = 1;
	   }
	   Selecting = 1; ZoomEnable = True;
	   Select = False; SelDel = 1;
	   update_sel = 1;
	   break;
	default: break;
	}
 } else if (!CTdel) {
	i = ClickBox(&qboxes[QCTA],3,x,y);
	if (i>=0) {
		for (j=0; j<3; j++) qboxes[QCTA+j].active = 0;
		qboxes[QCTA+i].active = 1;
		RedrawCT();
	}

 }

 update_sel = 1;
 return(0);

}

make_aa()
{
   int i,nz,sidechainstart,iamino,ichi;

   for (i=0; i < calfptr->ncalf; i++) {
	aaptr[i].iamino = &(calfptr->iamino[i]);
	iamino = *aaptr[i].iamino;
        if (iamino < 1 || iamino > 23) continue;
	nz = calfptr->icalf[i][0] - 1;
	aaptr[i].phi = nz+1;
	aaptr[i].psi = nz+2;
	aaptr[i].omega = nz;

	aaptr[i].chi1 = -1; 
	aaptr[i].chi2 = -1; 
	aaptr[i].chi3 = -1; 
	aaptr[i].chi4 = -1;

	sidechainstart = nz+5;

	if (iamino == 15) {
	   sidechainstart = nz+4;
	   if (zmptr.ianz[nz+2] == 8) { 
		sidechainstart--; 
	   }
	} else {
/* if start residue there might be an N missing at nz+2 */

	   if (zmptr.ianz[nz+4] != 1 && zmptr.ianz[nz+3] == 1) 
		sidechainstart--; 
	}

	ichi = aminozmt[iamino-1].chis[0];
	if (ichi != -1)
	   aaptr[i].chi1 = sidechainstart-1+ichi;
	ichi = aminozmt[iamino-1].chis[1];
	if (ichi != -1) {
	   int hsi = 0;
	   int ispec = 0;

	   if (zmptr.ianz[sidechainstart-1+ichi] == 1) hsi = 1;
	   if (iamino == 4 || iamino == 3) ispec = 1;

	   if (!ispec || (ispec && hsi) ) {
		 aaptr[i].chi2 = sidechainstart-1+ichi;
	   }
	}
	ichi = aminozmt[iamino-1].chis[2];
	if (ichi != -1)
	   aaptr[i].chi3 = sidechainstart-1+ichi;
	ichi = aminozmt[iamino-1].chis[3];
	if (ichi != -1) 
	   aaptr[i].chi4 = sidechainstart-1+ichi;

/*
        fprintf(stderr,"%d \n",*aaptr[i].iamino - 1);
        fprintf(stderr,"aa %d %s %f %f %f\n",i,AminoAcids[*aaptr[i].iamino - 1],
		zmptr.bet[aaptr[i].phi],zmptr.bet[aaptr[i].psi],
		zmptr.bet[aaptr[i].omega]);
*/
   }

   if (calfptr->ncalf > 0) {
	ZMEAA = 1;
   } else {
	ZMEAA = 0;
   }
}

aaexp(aastr,sl)
char* aastr;
int sl;
{
   int i,j,k,istrt,nque,olfnd,exfnd,que[MXEXP];

   nque = -1;
   if (sl > MXEXP) sl = MXEXP;

   for (i=0; i < sl; i++) {
      for (j=0; j < 20; j++) {
	if (strncasecmp(&aastr[i],AAlet[j],1) == 0) {
	   nque++;
	   que[nque] = j + 1;
	}
      }
   }
   nque++;
   if (nque != sl) {
	strcpy(ZMEerr,"Unrecognized one letter");
	RedrawStatus();
	return;
   }

   istrt = 0;
   olfnd = 0;
   if (oqlen == nque) {
      olfnd = 1;
      for (j=0; j < nque; j++) if (que[j] != oque[j]) olfnd = 0;
      if (olfnd) istrt = oqpos + 1;
   }
   

   for (i=istrt; i < calfptr->ncalf; i++) {
      exfnd = 1;
      for (j=0; j < nque; j++) {
	if (calfptr->iamino[i+j] != que[j]) exfnd = 0;
      }
      if (exfnd) {
	ZME_window_pos = i;
	UpdateZME();
	RedrawScroll(&zscroll);
	for (k=0; k < nque; k++) oque[k] = que[k];
	oqlen = nque;
	oqpos = i;
        strcpy(ZMEerr,"Match!");
        RedrawStatus();
        return;
      }
   }

   if (olfnd) {
      oqpos = 0;
      strcpy(ZMEerr,"End of sequence!");
   } else {
      strcpy(ZMEerr,"NO match!");
   }
   RedrawStatus();
}
FreeAll()
{
	if (*xyz.mxnat != NUMAT) {
	   free(xyz.coo);
	   free(xyz.rzp);
	   free(xyz.qat);
	   free(xyz.isurf);
	   free(xyz.lwrit);
	   free(xyz.lring);
	   free(xyz.ianz);
	   free(xyz.iaton);
	   free(xyz.iatclr);
	   free(xyz.iresid);
	   free(xyz.ixp);
	   free(xyz.iyp);
	   free(xyz.iconn);
	   free(xyz.inat);
	   free(xyz.ityp);
	   free(xyz.ipdbt);
	}
	if (*dorb.mxorb != MAXORB) {
	   free(dorb.focc);
	   free(dorb.focb);
	   free(dorb.vectrs);
	   free(dorb.vectrb);
	   free(dorb.p);
	   free(dorb.paa);
	   free(dorb.eiga);
	   free(dorb.eigb);
	   free(dorb.stoalfa);
	   free(dorb.stobnorm);
	   free(dorb.istos);
	   free(orb.qd);
	   free(orb.pd);
	   free(orb.gd);
	   free(orb.hd);
	}
	if (*sgrd.mx3d != sgrd.mxorg) {
	   free(sgrd.denn);
	   free(sgrd.pmnn);
	   free(sgrd.dens);
	   free(sgrd.denst);
	   free(sgrd.edx);
	   free(sgrd.edy);
	   free(sgrd.rz);
	   free(sgrd.bucket);
	   free(sgrd.iedlog);
	   free(sgrd.ix);
	   free(sgrd.iy);
	}
	if (*geopntr.mxpnt != geopntr.mxorg) {
	   free(geopntr.formax);
	   free(geopntr.forrms);
	   free(geopntr.dismax);
	   free(geopntr.disrms);
	   free(geopntr.epoints);
	   free(geopntr.isav);
	}
	if (*zmptr.mxzat != MAXAT) {
	   free(zmptr.bl);
	   free(zmptr.ibl);
	   free(zmptr.alph);
	   free(zmptr.ialph);
	   free(zmptr.bet);
	   free(zmptr.imap);
	   free(zmptr.ianz);
	   free(zmptr.iz);
	   free(stoc.cstoc);
	   free(stoc.czstoc);
	   free(stoc.astoc);
	   free(stoc.bstoc);
	   free(stoc.ianstc);
	   free(IANZbox);
	   free(BLbox);
	   free(ALPHbox);
	   free(BETbox);
	   free(IZbox);
 	}
}

int AllocZMat(ZSize)
int ZSize;
{
   int memstat,i,j;
   double f;
   int ii;
   QBOXSTRU *TMPIANZbox;
   QBOXSTRU *TMPBLbox;
   QBOXSTRU *TMPALPHbox;
   QBOXSTRU *TMPBETbox;
   QBOXSTRU *TMPIZbox;

   memstat = 1;

   TMPzmptr = zmptr;
   TMPstoc = stoc;
   TMPIANZbox = IANZbox;
   TMPBLbox = BLbox;
   TMPALPHbox = ALPHbox;
   TMPBETbox = BETbox;
   TMPIZbox = IZbox;

   if ((zmptr.bl = (double *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptr.ibl = (int *) malloc((sizeof ii)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptr.alph = (double *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptr.ialph = (int *) malloc((sizeof ii)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptr.bet = (double *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptr.ibet = (int *) malloc((sizeof ii)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptr.imap = (int *) malloc((sizeof ii)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptr.ianz = (int *) malloc((sizeof ii)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptr.iz = (int *) malloc((sizeof ii)*ZSize*4)) == NULL) {
	memstat = 0;
   }

   if ((stoc.cstoc = (double *) malloc((sizeof f)*ZSize*3)) == NULL) {
	memstat = 0;
   }

   if ((stoc.czstoc = (double *) malloc((sizeof f)*ZSize*3)) == NULL) {
	memstat = 0;
   }

   if ((stoc.astoc = (double *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((stoc.bstoc = (double *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((stoc.ianstc = (int *) malloc((sizeof ii)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((IANZbox = (QBOXSTRU *) malloc((sizeof TMPbox)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((BLbox = (QBOXSTRU *) malloc((sizeof TMPbox)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((ALPHbox = (QBOXSTRU *) malloc((sizeof TMPbox)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((BETbox = (QBOXSTRU *) malloc((sizeof TMPbox)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((IZbox = (QBOXSTRU *) malloc((sizeof TMPbox)*ZSize*4)) == NULL) {
	memstat = 0;
   }

   if (!memstat) {
	fprintf(stderr,"Out of memory\n");
	zmptr = TMPzmptr;
	stoc = TMPstoc;
	return(0);
   } else {
	for (i=0; i < *zmptr.mxzat; i++) {
	   zmptr.bl[i] = TMPzmptr.bl[i];
	   zmptr.ibl[i] = TMPzmptr.ibl[i];
	   zmptr.alph[i] = TMPzmptr.alph[i];
	   zmptr.ialph[i] = TMPzmptr.ialph[i];
	   zmptr.bet[i] = TMPzmptr.bet[i];
	   zmptr.ibet[i] = TMPzmptr.ibet[i];
	   zmptr.imap[i] = TMPzmptr.imap[i];
	   zmptr.ianz[i] = TMPzmptr.ianz[i];
	   for (j=0; j<3; j++)
		zmptr.iz[i*4+j] = TMPzmptr.iz[i*4+j];
	   IANZbox[i] = TMPIANZbox[i];
	   BLbox[i] = TMPBLbox[i];
	   ALPHbox[i] = TMPALPHbox[i];
	   BETbox[i] = TMPBETbox[i];
	   for (j=0; j<3; j++)
		IZbox[i*4+j] = TMPIZbox[i*4+j];

	}
	*zmptr.mxzat = ZSize;
	return(ZSize);
   }
}

#if defined(VMS) || defined(UNDERSC)
allorb(ZSizep)
#else
#ifdef CRAY
ALLORB(ZSizep)
#else
allorb_(ZSizep)
#endif
#endif
int *ZSizep;
{
   int memstat;
   double d;
   float f;
   int i;
   int ZSize;

   ZSize = *ZSizep;
   memstat = 1;

   TMPdorb = dorb;
   TMPorb = orb;

   if ((dorb.focc = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorb.focb = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorb.vectrs = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorb.vectrb = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorb.p = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorb.paa = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorb.averag = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorb.eiga = (float *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorb.eigb = (float *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorb.stoalfa = (float *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorb.stobnorm = (float *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorb.istos = (int *) malloc((sizeof i)*ZSize*5)) == NULL) {
	memstat = 0;
   }

   if ((orb.qd = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((orb.pd = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((orb.gd = (double *) malloc((sizeof d)*ZSize*3)) == NULL) {
	memstat = 0;
   }

   if ((orb.hd = (double *) malloc((sizeof d)*ZSize*6)) == NULL) {
	memstat = 0;
   }

   if (!memstat) {
	fprintf(stderr,"Out of memory\n");
	dorb = TMPdorb;
	orb = TMPorb;
   } else {
	if (*TMPdorb.mxorb != MAXORB) {
	   free(TMPdorb.focc);
	   free(TMPdorb.focb);
	   free(TMPdorb.vectrs);
	   free(TMPdorb.vectrb);
	   free(TMPdorb.p);
	   free(TMPdorb.paa);
	   free(TMPdorb.eiga);
	   free(TMPdorb.eigb);
	   free(TMPdorb.stoalfa);
	   free(TMPdorb.stobnorm);
	   free(TMPdorb.istos);
	   free(TMPorb.qd);
	   free(TMPorb.pd);
	   free(TMPorb.gd);
	   free(TMPorb.hd);
	}
	*dorb.mxorb = ZSize;
   }
}

#define LNBUCK 10

#if defined(VMS) || defined(UNDERSC)
allgrd(ZSizep)
#else
#ifdef CRAY
ALLGRD(ZSizep)
#else
allgrd_(ZSizep)
#endif
#endif
int *ZSizep;
{
   int memstat;
   double d;
   int i;
   int ZSize;

   ZSize = *ZSizep;
   memstat = 1;

   TMPsgrd = sgrd;

   if ((sgrd.denn = (double *) malloc((sizeof d)*ZSize*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((sgrd.pmnn = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((sgrd.dens = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((sgrd.denst = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((sgrd.edx = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((sgrd.edy = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((sgrd.rz = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((sgrd.bucket = (double *) malloc((sizeof d)*(ZSize + LNBUCK))) == NULL) {
	memstat = 0;
   }

   if ((sgrd.iedlog = (int *) malloc((sizeof i)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((sgrd.ix = (int *) malloc((sizeof i)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((sgrd.iy = (int *) malloc((sizeof i)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }


   if (!memstat) {
	fprintf(stderr,"Out of memory\n");
	sgrd = TMPsgrd;
   } else {
	if (*TMPsgrd.mx3d != TMPsgrd.mxorg) {
	   free(TMPsgrd.denn);
	   free(TMPsgrd.pmnn);
	   free(TMPsgrd.dens);
	   free(TMPsgrd.denst);
	   free(TMPsgrd.edx);
	   free(TMPsgrd.edy);
	   free(TMPsgrd.rz);
	   free(TMPsgrd.bucket);
	   free(TMPsgrd.iedlog);
	   free(TMPsgrd.ix);
	   free(TMPsgrd.iy);
	}
	*sgrd.mx3d = ZSize;
	*sgrd.mx3d2 = ZSize*ZSize;
   }
}

#if defined(VMS) || defined(UNDERSC)
allgeo(ZSizep)
#else
#ifdef CRAY
ALLGEO(ZSizep)
#else
allgeo_(ZSizep)
#endif
#endif
int *ZSizep;
{
   int memstat;
   double d;
   int i;
   int ZSize;

   ZSize = *ZSizep;
   memstat = 1;

   TMPgeopntr = geopntr;

   if ((geopntr.formax = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((geopntr.forrms = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((geopntr.dismax = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((geopntr.disrms = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((geopntr.epoints = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((geopntr.isav = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if (!memstat) {
	fprintf(stderr,"Out of memory\n");
	geopntr = TMPgeopntr;
   } else {
	if (*TMPgeopntr.mxpnt != TMPgeopntr.mxorg) {
	   free(TMPgeopntr.formax);
	   free(TMPgeopntr.forrms);
	   free(TMPgeopntr.dismax);
	   free(TMPgeopntr.disrms);
	   free(TMPgeopntr.epoints);
	   free(TMPgeopntr.isav);
	}
	*geopntr.mxpnt = ZSize;
/*fprintf(stderr,"edr mxpnt %d\n",*geopntr.mxpnt);*/
   }
}

typedef struct {
  int ptr;
  float depth;
} DepthIndex;

DepthIndex dptdemo;
DepthIndex dpt[NUMAT];
DepthIndex *dptptr = dpt;

#if defined(VMS) || defined(UNDERSC)
allcoo(ZSizep)
#else
#ifdef CRAY
ALLCOO(ZSizep)
#else
allcoo_(ZSizep)
#endif
#endif
int *ZSizep;
{
   int memstat;
   double d;
   int i;
   short int j;
   int ZSize;

   ZSize = *xyz.mxnat + *ZSizep;
   memstat = 1;

   TMPxyz = xyz;

   if ((xyz.coo = (double *) malloc((sizeof d)*ZSize*3)) == NULL) {
	memstat = 0;
   }

   if ((xyz.rzp = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.qat = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.isurf = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.lwrit = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.lring = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.ianz = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.iaton = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.iatclr = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.iresid = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.ixp = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.iyp = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.iconn = (int *) malloc((sizeof i)*ZSize*(MXCON+1))) == NULL) {
	memstat = 0;
   }

   if ((xyz.inat = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.ityp = (short int *) malloc((sizeof j)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyz.ipdbt = (short int *) malloc((sizeof j)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dptptr = (DepthIndex *) malloc((sizeof dptdemo)*ZSize)) == NULL) {
	memstat = 0;
   }

   if (!memstat) {
	fprintf(stderr,"Out of memory\n");
	xyz = TMPxyz;
   } else {
	for (i=0; i < *xyz.iatoms; i++) {
	   for (j=0; j<3; j++)
		xyz.coo[i*3+j] = TMPxyz.coo[i*3+j];
	   xyz.qat[i] = TMPxyz.qat[i];
	   xyz.ianz[i] = TMPxyz.ianz[i];
	   xyz.iaton[i] = TMPxyz.iaton[i];
	   xyz.iatclr[i] = TMPxyz.iatclr[i];
	   xyz.iresid[i] = TMPxyz.iresid[i];
	   xyz.ityp[i] = TMPxyz.ityp[i];
	   xyz.ipdbt[i] = TMPxyz.ipdbt[i];
	   for (j=0; j<MXCON; j++)
		xyz.iconn[i*(MXCON+1)+j] = TMPxyz.iconn[i*(MXCON+1)+j];
	}
	if (*TMPxyz.mxnat != TMPxyz.mxorg) {
	   free(TMPxyz.coo);
	   free(TMPxyz.rzp);
	   free(TMPxyz.qat);
	   free(TMPxyz.isurf);
	   free(TMPxyz.lwrit);
	   free(TMPxyz.lring);
	   free(TMPxyz.ianz);
	   free(TMPxyz.iaton);
	   free(TMPxyz.iatclr);
	   free(TMPxyz.iresid);
	   free(TMPxyz.ixp);
	   free(TMPxyz.iyp);
	   free(TMPxyz.iconn);
	   free(TMPxyz.inat);
	   free(TMPxyz.ityp);
	   free(TMPxyz.ipdbt);
	}
	*xyz.mxnat = ZSize;
   }
}

#if defined(VMS) || defined(UNDERSC)
almgrd()
#else
#ifdef CRAY
ALMGRD()
#else
almgrd_()
#endif
#endif
{
   int memstat;
   double d;
   int ZSize;

   if (*mgrd.mx3d >= *sgrd.mx3d) return;

   ZSize = *sgrd.mx3d;
   memstat = 1;

   TMPmgrd = mgrd;

   if ((mgrd.fmap = (double *) malloc((sizeof d)*ZSize*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if (!memstat) {
	fprintf(stderr,"Out of memory\n");
	mgrd = TMPmgrd;
   } else {
	if (*TMPmgrd.mx3d != TMPmgrd.mxorg) {
	   free(TMPmgrd.fmap);
	}
	*mgrd.mx3d = ZSize;
   }
}

EditCOL()
{
   int i;
   XColor exact_def;
   
   ECOLup = 1;

   ECOLwin = CreateWindow("Color Editor","-0+0",ECOLWINW,ECOLWINH,
	 		 infobg,infofg,(Window)0);
   XSelectInput(display, ECOLwin, 
	KeyPressMask | ExposureMask | ButtonPressMask | ButtonReleaseMask 
		| ButtonMotionMask | LeaveWindowMask);
   XMapWindow(display,ECOLwin);

   DefBut(&butecol[0], ECOLwin, 100, 140, 50, 23,
	"Close", infobg, -15);

   for (i=0; i<3; i++) {
	ecolwn[i] = 70535; ecolwpos[i] = 0;
	DefScroll(&ecolscr[i],ECOLwin,20+i*40,30,20,100,&ecolwn[i],&ecolwpos[i],5000);
   }

   exact_def.pixel = colors[activecolor];
   XQueryColor(display, cmap, &exact_def);
   
   ecolwpos[0] = 65535 - exact_def.red;
   ecolwpos[1] = 65535 - exact_def.green;
   ecolwpos[2] = 65535 - exact_def.blue;
 
}

RedrawECOL()
{
   int i;

   if (!ECOLup) return;

   butje(ECOLwin,0,0,ECOLWINW,ECOLWINH,4,0,-15,1,None,0,0,0);
   ULineString(ECOLwin,"Red",20,20);
   ULineString(ECOLwin,"Green",60,20);
   ULineString(ECOLwin,"Blue",100,20);
   for (i=0; i<3; i++) RedrawScroll(&ecolscr[i]);
   XSetForeground(display, gc, colors[activecolor] );
   XFillRectangle(display, ECOLwin, gc, 140, 30, 100, 100);

   DrwBut(&butecol[0]);

}

SetPalCol(updateshades)
int updateshades;
{
   XColor exact_def;
   int r,g,b;

   r = (65535 - ecolwpos[0]);
   g = (65535 - ecolwpos[1]);
   b = (65535 - ecolwpos[2]);
   exact_def.red = (unsigned short) r;
   exact_def.green = (unsigned short) g;
   exact_def.blue = (unsigned short) b;

   XFreeColors(display, cmap,&colors[activecolor],1,0);

   if (XAllocColor(display, cmap, &exact_def) ) {
	colors[activecolor] = exact_def.pixel;
	colorr[activecolor] = exact_def.red;
	colorg[activecolor] = exact_def.green;
	colorb[activecolor] = exact_def.blue;
   }
   if (updateshades) {
	ParseBasicColor(activecolor,0);
	WriteRes();
   }
   RedrawECOL();
}

WriteRes()
{
   int i;
   unsigned short r,g,b;
   char wfile[500];
   char *hm;
   FILE *out;

#ifdef __CYGWIN__
   strcpy(wfile,".moldenrc");
#else
   hm = getenv("HOME");
   if (hm == NULL) return;
   strcpy(wfile,hm);
   strcat(wfile,"/.moldenrc");
#endif

   out = fopen(wfile,"w");
   if (out != NULL) {
	for (i=1; i<99; i++) {
	   fprintf(out,"%s %d %f\n",elements[i],scalptr->icol[i-1],
		scalptr->vdwr[i-1]);
	}
	fprintf(out,"background %d \n",IBGcolor);
	fprintf(out,"oglbackground %d \n",OBGcolor);
	fprintf(out,"backgroundmode %d \n",BGmode);
	fprintf(out,"palette ");
	for (i=1; i<15; i++) {
	   r = colorr[i] / 256; 
	   g = colorg[i] / 256;
	   b = colorb[i] / 256;
	   fprintf(out,"#%02X%02X%02X ",r,g,b);
	}
	fprintf(out,"\n");
	if (*ball) {
	   fprintf(out,"newrot\n");
	} else {
	   fprintf(out,"oldrot\n");
	}
	if (DelayRemember && *ideltm) {
	   fprintf(out,"delaytime %d\n",*ideltm);
	}
	   
   }
   fclose(out);
}


InitDPT()
{
   int i;
   
   DPTup = 1;

   DPTwin = CreateWindow("Depth Editor","-0+0",ECOLWINW,ECOLWINH,
	 		 infobg,infofg,(Window)0);
   XSelectInput(display, DPTwin, 
	KeyPressMask | ExposureMask | ButtonPressMask | ButtonReleaseMask 
		| ButtonMotionMask | LeaveWindowMask);
   XMapWindow(display,DPTwin);

   DefBut(&butdpt[0], DPTwin, 100, 140, 50, 23,
	"Close", infobg, -15);

   DefBut(&butdpt[1], DPTwin, 100, 10, 120, 23,
	"Max. Linewdith", infobg, -15);

   for (i=0; i<1; i++) {
	dptwn[i] = 240; dptwpos[i] = 100;
	DefScroll(&dptscr[i],DPTwin,20+i*40,30,20,100,&dptwn[i],&dptwpos[i],40);
   }

}

RedrawDPT()
{
   int i;

   if (!DPTup) return;

   butje(DPTwin,0,0,ECOLWINW,ECOLWINH,4,0,-15,1,None,0,0,0);
   ULineString(DPTwin,"Shade Depth",20,20);
   for (i=0; i<1; i++) RedrawScroll(&dptscr[i]);

   DrwBut(&butdpt[0]);
   DrwBut(&butdpt[1]);

}

UpdateDPT()
{
   double i;

   i = (double) ((dptwpos[0] - 100.0) / 10.0);

   if (i < 0 ) {
	*uscl = (1.0 / (-i));
   } else if (i > 0) {
	*uscl = i;
   } else {
	*uscl = 1.0;
   }
#ifdef DOGL
   if (has_opengl && *fancy) {
      if (*ipdbon && *xyz.iatoms > 200) {
         glFogf (GL_FOG_DENSITY, (*uscl)/(FFOGD*scl));
      } else {
         glFogf (GL_FOG_DENSITY, (*uscl)/(FFOGDS*scl));
      }
      dispsf();
   }
#endif
   
}

WriteCML()
{
  int i;
  char wfile[500];
  FILE *out;

  strcpy(wfile,"molecule.cml");

  out = fopen(wfile,"w");
  if (out != NULL) {
	fprintf(out,"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
	fprintf(out,"<!DOCTYPE molecule SYSTEM \"cml.dtd\" [\n");
	fprintf(out,"<!ATTLIST list convention CDATA #IMPLIED>\n");
	fprintf(out,"]>\n");

	fprintf(out,"<molecule id=\"mol\">\n");
	fprintf(out,"  <atomArray>\n");

        fprintf(out,"    <stringArray builtin=\"elementType\">\n");
	for (i=0; i<*xyz.iatoms; i++)
	   fprintf(out,"%s ",elements[xyz.ianz[i]]);
	fprintf(out,"\n");
	fprintf(out,"    </stringArray>\n");

	fprintf(out,"    <floatArray builtin=\"x3\">\n");
	fprintf(out,"      ");
	for (i=0; i<*xyz.iatoms; i++)
	   fprintf(out,"%lf ",xyz.coo[i*3]*toangs);
	fprintf(out,"\n");
	fprintf(out,"    </floatArray>\n");

	fprintf(out,"    <floatArray builtin=\"y3\">\n");
	fprintf(out,"      ");
	for (i=0; i<*xyz.iatoms; i++)
	   fprintf(out,"%lf ",xyz.coo[i*3+1]*toangs);
	fprintf(out,"\n");
	fprintf(out,"    </floatArray>\n");

	fprintf(out,"    <floatArray builtin=\"z3\">\n");
	fprintf(out,"      ");
	for (i=0; i<*xyz.iatoms; i++)
	   fprintf(out,"%lf ",xyz.coo[i*3+2]*toangs);
	fprintf(out,"\n");
	fprintf(out,"    </floatArray>\n");

	fprintf(out,"  </atomArray>\n");
	fprintf(out,"</molecule>\n");

	fclose(out);
  }
}

InitMAP()
{
  int i;
   
  MAPup = 1;

  MAPwin = CreateWindow("Mapped Surface","-0+0",MAPWINW,MAPWINH,
	 		 infobg,infofg,(Window)0);
  XSelectInput(display, MAPwin, 
	KeyPressMask | ExposureMask | ButtonPressMask | ButtonReleaseMask);
  XMapWindow(display,MAPwin);

  DefBut(&mapbut[0], MAPwin, 125, 340, 50, 23,
	"Apply", infobg, -15);

  DefBut(&mapbut[1], MAPwin, 375, 340, 50, 23,
	"Cancel", infobg, -15);

  DefBut(&mapbut[2], MAPwin, 370, 40, 120, 23, "wrlfile", infobg, 0);
  mapbut[2].str = mapopts[*imapopt];

  DefBut(&mapbut[3], MAPwin, 370, 70, 120, 23, "output", infobg, 0);
  mapbut[3].str = viropts[iviropt];

  qboxstr(&qboxes[QMFILE],&MAPwin,0,0,190,15,40, 
	350,QBOXHIGH,2,"Map file:        ","0.0",SUBLEN1,QSTRING,2000,dummyproc);
  strcp(mfile,qboxes[QMFILE].str,SUBLEN1);
  TrmStr(&qboxes[QMFILE]);

  qboxstr(&qboxes[QVFILE],&MAPwin,0,0,190,15,70, 
	350,QBOXHIGH,2,"VRML/OpenGL file:","0.0",SUBLEN1,QSTRING,2000,dummyproc);
  if (*ivtwo == 3) {
	strcp(oglfile,qboxes[QVFILE].str,SUBLEN1);
  } else {
	strcp(vfile,qboxes[QVFILE].str,SUBLEN1);
  }
  TrmStr(&qboxes[QVFILE]);

  if (*ipsi) {
	qboxstr(&qboxes[QCNTVAL],&MAPwin,0,0,190,15,MAPOFFY-40, 
	250,QBOXHIGH,2,"Contour Value    ","0.1",12,QREAL,2000,dummyproc);
  } else {
	qboxstr(&qboxes[QCNTVAL],&MAPwin,0,0,190,15,MAPOFFY-40, 
	250,QBOXHIGH,2,"Contour Value    ","0.02",12,QREAL,2000,dummyproc);
  }

  for (i=0; i<5; i++) {
	qboxstr(&qboxes[QCOLVAL1+i],&MAPwin,0,0,190,MAPOFFX,MAPOFFY+i*30, 
		180,QBOXHIGH,2,mapstr[i],"0.0",12,QREAL,2000,dummyproc);
	qboxes[QCOLVAL1+i].dflt = &mapval[i];
	sprintf(qboxes[QCOLVAL1+i].str,"%f",mapval[i]);
  }
  qboxes[QMFILE].active = 1;
}

RedrawMAP()
{
   int i;

   if (!MAPup) return;

   butje(MAPwin,0,0,MAPWINW,MAPWINH,4,0,-15,1,None,0,0,0);

   ULineString(MAPwin,"Select Types:",373,25);

/*
   XSetForeground(display, gc, colors[activecolor] );
   XFillRectangle(display, MAPwin, gc, 140, 30, 100, 100);
*/

   for (i=0; i<NBUTSM; i++) DrwBut(&mapbut[i]);
   for (i=0; i<8; i++) PromptBox(&qboxes[QVFILE+i]);

}

int ButtonsMAP(i)
int i;
{
   LSSTRU List;
   int j;

   switch(i) {
   case 0:
	*Sinct = 600;
	cpstr(qboxes[QCNTVAL].str,Sstr,strlen(qboxes[QCNTVAL].str));
	*Snstr = strlen(qboxes[QCNTVAL].str);
	for (j=0; j<5; j++) mapval[j] = atof(qboxes[QCOLVAL1+j].str);
	if (iviropt == 0) *ivtwo = 1;
	if (iviropt == 1) *ivtwo = 3;
	cpstr(qboxes[QMFILE].str,mfile,SUBLEN1);
	if (iviropt == 1) {
	    cpstr(qboxes[QVFILE].str,oglfile,SUBLEN1);
        } else {
	    cpstr(qboxes[QVFILE].str,vfile,SUBLEN1);
	}
	XDestroyWindow(display,MAPwin);MAPup = 0;
	*mapit = 1;
	return(1);
	break;
   case 1:
	XDestroyWindow(display,MAPwin);MAPup = 0;
	break;
   case 2: List.list = mapopts; List.nents = 2;
	   if (DoPopUp(MAPwin,mapbut[2].x+60,mapbut[2].y+BUTTH,
		&List,imapopt,1) == -1) break;
	   mapbut[2].str = mapopts[*imapopt];
	break;
   case 3: List.list = viropts; List.nents = 2;
	   if (DoPopUp(MAPwin,mapbut[3].x+60,mapbut[3].y+BUTTH,
		&List,&iviropt,1) == -1) break;
	   mapbut[3].str = viropts[iviropt];
	   if (iviropt == 1) {
		strcp(oglfile,qboxes[QVFILE].str,SUBLEN1);
	   } else {
		strcp(vfile,qboxes[QVFILE].str,SUBLEN1);
	   }
	   TrmStr(&qboxes[QVFILE]);
	   RedrawMAP();
	break;
   }
   return(0);
}

InitVIR()
{
   
  VIRup = 1;

  VIRwin = CreateWindow("VR file","-0+0",VIRWINW,VIRWINH,
	 		 infobg,infofg,(Window)0);
  XSelectInput(display, VIRwin, 
	KeyPressMask | ExposureMask | ButtonPressMask | ButtonReleaseMask);
  XMapWindow(display,VIRwin);

  DefBut(&virbut[0], VIRwin, 125, 110, 50, 23,
	"Apply", infobg, -15);

  DefBut(&virbut[1], VIRwin, 375, 110, 50, 23,
	"Cancel", infobg, -15);

  qboxstr(&qboxes[QSVFILE],&VIRwin,0,0,190,15,30, 
	450,QBOXHIGH,2,"Output file:","0.0",SUBLEN1,QSTRING,2000,dummyproc);

  switch(*ivtwo) {
	case 0:
	case 1:
		strcp(vfile,qboxes[QSVFILE].str,SUBLEN1);
		break;
	case 2:
		strcp(povfile,qboxes[QSVFILE].str,SUBLEN1);
		break;
	case 3:
		strcp(oglfile,qboxes[QSVFILE].str,SUBLEN1);
		break;
  }
  TrmStr(&qboxes[QSVFILE]);

  if (*ipsi) {
	qboxstr(&qboxes[QSCNT],&VIRwin,0,0,190,15,70, 
	250,QBOXHIGH,2,"Contour Value    ","0.1",12,QREAL,2000,dummyproc);
  } else {
	qboxstr(&qboxes[QSCNT],&VIRwin,0,0,190,15,70, 
	250,QBOXHIGH,2,"Contour Value    ","0.02",12,QREAL,2000,dummyproc);
  }

  qboxes[QSVFILE].active = 1;
}

RedrawVIR()
{
   int i;

   if (!VIRup) return;

   butje(VIRwin,0,0,VIRWINW,VIRWINH,4,0,-15,1,None,0,0,0);

   for (i=0; i<2; i++) DrwBut(&virbut[i]);
   for (i=0; i<2; i++) PromptBox(&qboxes[QSVFILE+i]);

}

int ButtonsVIR(i)
int i;
{

   switch(i) {
   case 0:
	*Sinct = 600;
	cpstr(qboxes[QSCNT].str,Sstr,strlen(qboxes[QSCNT].str));
	*Snstr = strlen(qboxes[QSCNT].str);
	switch(*ivtwo) {
	case 0:
	case 1:
		cpstr(qboxes[QSVFILE].str,vfile,SUBLEN1);
		break;
	case 2:
		cpstr(qboxes[QSVFILE].str,povfile,SUBLEN1);
		break;
	case 3:
		cpstr(qboxes[QSVFILE].str,oglfile,SUBLEN1);
		break;
	}
	XDestroyWindow(display,VIRwin);VIRup = 0;
	return(1);
	break;
   case 1:
	XDestroyWindow(display,VIRwin);VIRup = 0;
	break;
   }
   return(0);
}

#define MAXONIERR 70
static char ONIerr[MAXONIERR];

CreateONI()
{
  int i;
   
  ONIup = 1;

  ONIwin = CreateWindow("Oniom","-80-80",
                         OBOXWIDE,OBOXHIGH,infobg,infofg,(Window)0);
  subONI = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],ONIwin);
  XSelectInput(display, ONIwin,
        ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask |
		PointerMotionMask | EnterWindowMask | LeaveWindowMask);

  XMapWindow(display,ONIwin);

  DefBut(&onbut[OMETHH], ONIwin, OBOXOFFX, 30,         OBOXBLEN, 23,
        "Method", infobg, -15);
  onbut[OMETHH].explstr = "Method for the High quality layer";

  DefBut(&onbut[OBASSH], ONIwin, OBOXOFFX, 30+BUTTN,   OBOXBLEN, 23,
        "Basis Set", infobg, -15);
  onbut[OBASSH].explstr = "Basis Set for the High quality layer\nIf applicable";

  DefBut(&onbut[OCHARH], ONIwin, OBOXOFFX, 30+2*BUTTN, OBOXBLEN, 23,
        "Charge", infobg, -15);
  onbut[OCHARH].explstr = "Total charge of the High quality layer";

  DefBut(&onbut[OMULTH], ONIwin, OBOXOFFX, 30+3*BUTTN, OBOXBLEN, 23,
        "Multiplicity", infobg, -15);
  onbut[OMULTH].explstr = "Spin multiplicity of the High quality layer";

  DefBut(&onbut[OALLH],  ONIwin, OBOXOFFX, 30+4*BUTTN, OBOXBLEN, 23, 
        "All H", infobg, -ONIHCOL);
  onbut[OALLH].explstr = "All atoms are assigned to the High quality layer";

  DefBut(&onbut[OSELH],  ONIwin, OBOXOFFX, 35+6*BUTTN, OBOXBLEN, 23, 
        "Apply H", infobg, -ONIHCOL);
  onbut[OSELH].explstr = "Assign currently selected atoms\nto the High quality layer";


  DefBut(&onbut[OMETHM], ONIwin, OBOXOFFX+110, 30,         OBOXBLEN, 23,
        "Method", infobg, -15);
  onbut[OMETHM].explstr = "Method for the Medium quality layer";

  DefBut(&onbut[OBASSM], ONIwin, OBOXOFFX+110, 30+BUTTN,   OBOXBLEN, 23,
        "Basis Set", infobg, -15);
  onbut[OBASSM].explstr = "Basis Set for the Medium quality layer\nIf applicable";

  DefBut(&onbut[OCHARM], ONIwin, OBOXOFFX+110, 30+2*BUTTN, OBOXBLEN, 23,
        "Charge", infobg, -15);
  onbut[OCHARM].explstr = "Total charge of the Medium quality layer";

  DefBut(&onbut[OMULTM], ONIwin, OBOXOFFX+110, 30+3*BUTTN, OBOXBLEN, 23,
        "Multiplicity", infobg, -15);
  onbut[OMULTM].explstr = "Spin multiplicity of the Medium quality layer";

  DefBut(&onbut[OALLM],  ONIwin, OBOXOFFX+110, 30+4*BUTTN, OBOXBLEN, 23,
        "All M", infobg,-ONIMCOL);
  onbut[OALLM].explstr = "All atoms are assigned to\nthe Medium quality layer";

  DefBut(&onbut[OSELM],  ONIwin, OBOXOFFX+110, 35+6*BUTTN, OBOXBLEN, 23,
        "Apply M", infobg,-ONIMCOL);
  onbut[OSELM].explstr = "Assign currently selected atoms\nto the Medium quality layer";


  DefBut(&onbut[OMETHL], ONIwin, OBOXOFFX+220, 30,         OBOXBLEN, 23,
        "Method", infobg, -15);
  onbut[OMETHL].explstr = "Method for the Low quality layer";

  DefBut(&onbut[OBASSL], ONIwin, OBOXOFFX+220, 30+BUTTN,   OBOXBLEN, 23,
        "Basis Set", infobg, -15);
  onbut[OBASSL].explstr = "Basis Set for the Low quality layer\nIf applicable";

  DefBut(&onbut[OCHARL], ONIwin, OBOXOFFX+220, 30+2*BUTTN, OBOXBLEN, 23,
        "Charge", infobg, -15);
  onbut[OCHARL].explstr = "Total charge of the Low quality layer";

  DefBut(&onbut[OMULTL], ONIwin, OBOXOFFX+220, 30+3*BUTTN, OBOXBLEN, 23,
        "Multiplicity", infobg, -15);
  onbut[OMULTL].explstr = "Spin multiplicity of the Low quality layer";

  DefBut(&onbut[OALLL],  ONIwin, OBOXOFFX+220, 30+4*BUTTN, OBOXBLEN, 23,
        "All L", infobg,-ONILCOL);
  onbut[OALLL].explstr = "All atoms are assigned to\nthe Low quality layer";

  DefBut(&onbut[OSELL],  ONIwin, OBOXOFFX+220, 35+6*BUTTN, OBOXBLEN, 23,
        "Apply L", infobg,-ONILCOL);
  onbut[OSELL].explstr = "Assign currently selected atoms\nto the Low quality layer";


  DefBut(&onbut[OSEL],   ONIwin, OBOXOFFX,     35+5*BUTTN, OBOXBLEN+20, 23,
        "Select by pointer", infobg, -15);
  onbut[OSEL].explstr = "Select atoms to be assigned to layer\nSelect: Left mouse button+drag+release";

  DefBut(&onbut[OUSEL],  ONIwin, OBOXOFFX+125, 35+5*BUTTN, OBOXBLEN-20, 23,
        "DeSelect", infobg,-15);
  onbut[OUSEL].explstr = "Deselect atoms to be assigned to layer\nDeselect: Left mouse button+drag+release";

  DefBut(&onbut[OSELR],  ONIwin, OBOXOFFX+220, 35+5*BUTTN, OBOXBLEN, 23,
        "Select residue", infobg,-15);
  onbut[OSELR].explstr = "Select residue to be assigned to layer\nSelect: click residue with left mouse button";
  if (*ipdbon == 0) ActBut(&onbut[OSELR],0);


  DefBut(&onbut[OCOLO],  ONIwin, OBOXOFFX+10, 35+10*BUTTN, 15, 15,
        " ", infobg,-15);
  onbut[OCOLO].explstr = "Use different colors for each layer";

  DefBut(&onbut[OCLOS],  ONIwin, OBOXOFFX+110, 35+11*BUTTN, OBOXBLEN, 23,
        "Close", infobg,-15);

  DefBut(&onbut[OAMBCH], ONIwin, OBOXOFFX+120, 35+10*BUTTN, 15, 15,
        " ", infobg,-15);
  onbut[OAMBCH].explstr = "Write amber charges and atom types\nas part of the atom label";

  onbut[OMETHH].str = mopt[imopth];
  onbut[OBASSH].str = bopt[ibopth];
  onbut[OCHARH].str = copt[*icopth+3];
  onbut[OMULTH].str = spopt[*ispopth-1];
  onbut[OMETHL].str = mopt[imoptl];
  onbut[OBASSL].str = bopt[iboptl];
  onbut[OCHARL].str = copt[*icoptl+3];
  onbut[OMULTL].str = spopt[*ispoptl-1];
  onbut[OMETHM].str = mopt[imoptm];
  onbut[OBASSM].str = bopt[iboptm];
  onbut[OCHARM].str = copt[*icoptm+3];
  onbut[OMULTM].str = spopt[*ispoptm-1];

  if (*fftyp != 3) {
     for (i=0;i<*xyz.iatoms;i++) {
	xyz.ityp[i] = 0;
     }
  }

  ParseLine();

  if (*atcol) {
	TogUp(&onbut[OCOLO]);
  } else {
	TogDown(&onbut[OCOLO]);
  }

  if (*ambchg) {
	TogDown(&onbut[OAMBCH]);
  } else {
	TogUp(&onbut[OAMBCH]);
  }
}

RedrawONI()
{
  int i;

  butje(ONIwin,0,0,OBOXWIDE,OBOXHIGH,4,0,0,1,None,0,0,0);
  ULineString(ONIwin,"High",OBOXOFFX+30,21);
  ULineString(ONIwin,"Medium",OBOXOFFX+140,21);
  ULineString(ONIwin,"Low",OBOXOFFX+250,21);
  ULineString(ONIwin,"Color by Layer",OBOXOFFX+30,46+10*BUTTN);
  ULineString(ONIwin,"write amber charges",OBOXOFFX+140,46+10*BUTTN);
  for (i=0; i<NBUTSO; i++) DrwBut(&onbut[i]);

  RedrawONIStatus();

}

int ButtonsONI(i)
int i;
{
  LSSTRU List;
  int ret=0;
  int nat;

  switch (i) {
  case OMETHH:
                List.list = mopt; List.nents = moptn;
                if (DoPopUp(ONIwin,
			onbut[OMETHH].x+OBOXBLEN/2,onbut[OMETHH].y+BUTTH,
                        &List,&imopth,1) == -1) break;
                onbut[OMETHH].str = mopt[imopth];
                break;
  case OBASSH:
                List.list = bopt; List.nents = boptn;
                if (DoPopUp(ONIwin,
			onbut[OBASSH].x+OBOXBLEN/2,onbut[OBASSH].y+BUTTH,
                        &List,&ibopth,1) == -1) break;
                onbut[OBASSH].str = bopt[ibopth];
                break;
  case OMETHL:
                List.list = mopt; List.nents = moptn;
                if (DoPopUp(ONIwin,
			onbut[OMETHL].x+OBOXBLEN/2,onbut[OMETHL].y+BUTTH,
                        &List,&imoptl,1) == -1) break;
                onbut[OMETHL].str = mopt[imoptl];
                break;
  case OBASSL:
                List.list = bopt; List.nents = boptn;
                if (DoPopUp(ONIwin,
			onbut[OBASSL].x+OBOXBLEN/2,onbut[OBASSL].y+BUTTH,
                        &List,&iboptl,1) == -1) break;
                onbut[OBASSL].str = bopt[iboptl];
                break;
  case OMETHM:
                List.list = mopt; List.nents = moptn;
                if (DoPopUp(ONIwin,
			onbut[OMETHM].x+OBOXBLEN/2,onbut[OMETHM].y+BUTTH,
                        &List,&imoptm,1) == -1) break;
                onbut[OMETHM].str = mopt[imoptm];
                break;
  case OBASSM:
                List.list = bopt; List.nents = boptn;
                if (DoPopUp(ONIwin,
			onbut[OBASSM].x+OBOXBLEN/2,onbut[OBASSM].y+BUTTH,
                        &List,&iboptm,1) == -1) break;
                onbut[OBASSM].str = bopt[iboptm];
                break;
  case OALLH:
                strcpy(ONIerr,"H level for all atoms");
                RedrawONIStatus();
                for ( i = 0; i < *xyz.iatoms; i++ ) {
                   if (xyz.ityp[i] >= 10000) 
			xyz.ityp[i] -= (xyz.ityp[i]/10000)*10000
;
                   xyz.iatclr[i] = ONIHCOL;
                }
		ret = 1;
                break;
  case OALLM:
                strcpy(ONIerr,"M level for all atoms");
                RedrawONIStatus();
                for ( i = 0; i < *xyz.iatoms; i++ ) {
                   if (xyz.ityp[i] >= 20000) {
                      xyz.ityp[i] -= 10000;
                   } else {
                      if (xyz.ityp[i]<10000) xyz.ityp[i] += 10000;
                   }
                   xyz.iatclr[i] = ONIMCOL;
                }
		ret = 1;
                break;
  case OALLL:
                strcpy(ONIerr,"L level for all atoms");
                RedrawONIStatus();
                for ( i = 0; i < *xyz.iatoms; i++ ) {
                   if (xyz.ityp[i] < 20000) 
			xyz.ityp[i] += (2-xyz.ityp[i]/10000)*10000;
                   xyz.iatclr[i] = ONILCOL;
                }
		ret = 1;
                break;
  case OSELH:
                Selecting = 0;
                nat = 0;
                for ( i = 0; i < *xyz.iatoms; i++ ) if (xyz.iaton[i] > 1) nat++;
                if (!nat) {
                        strcpy(ONIerr,"Invalid Selection: No atoms selected");
                        if (*ibell) XBell(display,0);
                        RedrawONIStatus();
                        return(0);
                }
                if (nat > *zmptr.mxzat) {
                   strcpy(ONIerr,"Invalid Selection: Too many atoms selected");
                   if (*ibell) XBell(display,0);
                   RedrawONIStatus();
                   for ( i = 0; i < *xyz.iatoms; i++ )
                        if (xyz.iaton[i] >= 2) xyz.iaton[i] = 1;
                   ret = 1;
                }
                else {
                   strcpy(ONIerr,"Selected atoms at H level");
                   RedrawONIStatus();
                   for ( i = 0; i < *xyz.iatoms; i++ ) {
                        if (xyz.iaton[i] >= 2) {
                            if (xyz.ityp[i] >= 10000) xyz.ityp[i] -= 
                                (xyz.ityp[i] /10000)*10000;
                                xyz.iatclr[i] = ONIHCOL;
                        }
                        xyz.iaton[i] = 1;
                   }
		   ret = 1;
                }
                break;
  case OSELM:
		Selecting = 0;
		nat = 0;
		for ( i = 0; i < *xyz.iatoms; i++ ) if (xyz.iaton[i] > 1) nat++;
		if (!nat) {
			strcpy(ONIerr,"Invalid Selection: No atoms selected");
			if (*ibell) XBell(display,0);
			RedrawONIStatus();
			return(0);
		}
		if (nat > *zmptr.mxzat) {
		   strcpy(ONIerr,"Invalid Selection: Too many atoms selected");
		   if (*ibell) XBell(display,0);
		   RedrawONIStatus();
		   for ( i = 0; i < *xyz.iatoms; i++ ) 
			if (xyz.iaton[i] >= 2) xyz.iaton[i] = 1;
	  	   ret = 1;
		}
		else {
		   strcpy(ONIerr,"Selected atoms at M level");
		   RedrawONIStatus();
		   for ( i = 0; i < *xyz.iatoms; i++ ) {
			if (xyz.iaton[i] >= 2) {
				if (xyz.ityp[i] >= 20000) {
		      		   xyz.ityp[i] -= 10000;
		   		} else {
		   	   	   if (xyz.ityp[i] < 10000) 
				   xyz.ityp[i] += 10000;
		   		}
			       xyz.iatclr[i] = ONIMCOL;
			}
			xyz.iaton[i] = 1;
		   }
		   ret = 1;
	        }
		break;
  case OSELL:
		Selecting = 0;
		nat = 0;
		for ( i = 0; i < *xyz.iatoms; i++ ) if (xyz.iaton[i] > 1) nat++;
		if (!nat) {
			strcpy(ONIerr,"Invalid Selection: No atoms selected");
			if (*ibell) XBell(display,0);
			RedrawONIStatus();
			return(0);
		}
		if (nat > *zmptr.mxzat) {

		   strcpy(ONIerr,"Invalid Selection: Too many atoms selected");
		   if (*ibell) XBell(display,0);
		   RedrawONIStatus();
		   for ( i = 0; i < *xyz.iatoms; i++ ) 
			if (xyz.iaton[i] >= 2) xyz.iaton[i] = 1;
	  	   ret = 1;

		} else {

		   strcpy(ONIerr,"Selected atoms at L level");
		   RedrawONIStatus();
		   for ( i = 0; i < *xyz.iatoms; i++ ) {
			if (xyz.iaton[i] >= 2) {
			   if (xyz.ityp[i] < 20000) xyz.ityp[i] += 
                              (2-xyz.ityp[i]/10000)*10000;
			   xyz.iatclr[i] = ONILCOL;
			}
			xyz.iaton[i] = 1;
		   }
		   ret = 1;

  	        }
		break;
  case OSEL:
                strcpy(ONIerr,selstr);
                RedrawONIStatus();
                DeActZME();
                Selecting = 1;
                ZoomEnable = True;Select = True;
                break;
  case OUSEL:
                strcpy(ONIerr,dselstr);
                RedrawONIStatus();
                ZoomEnable = True;Select = False;
                break;
  case OSELR:
		if (*ipdbon) {
		   strcpy(ONIerr,"Pick a residue");
		   RedrawONIStatus();
		   bflag = 1; bretval = 565;
		   XDefineCursor(display,win,AtomCursor);
		} else {
		   ActBut(&onbut[OSELR],0);
		}
                break;
  case OCOLO:
		TogBut(&cbut[BATCOL]);
		TogBut(&onbut[OCOLO]);
		if (*atcol) *atcol = 0;
		else *atcol = 1;
                *Sinct = 400;*Sincp = 0; 
		ret = 1;
                break;
  case OCLOS:
	        XDestroyWindow(display,ONIwin);ONIup = 0;
		return(0);
                break;
  case OCHARH:
		List.list = copt; List.nents = 7;
		if (DoPopUp(ONIwin,
			onbut[OCHARH].x+OBOXBLEN/2,onbut[OCHARH].y+BUTTH,
			&List,icopth,1) == -1) break;
		*icopth = *icopth - 3;
		onbut[OCHARH].str = copt[*icopth+3];
		break;
  case OMULTH:
		List.list = spopt; List.nents = 8;
		if (DoPopUp(ONIwin,
			onbut[OMULTH].x+OBOXBLEN/2,onbut[OMULTH].y+BUTTH,
			&List,ispopth,1) == -1) break;
		*ispopth = *ispopth + 1;
		onbut[OMULTH].str = spopt[*ispopth-1];
		break;
  case OCHARM:
		List.list = copt; List.nents = 7;
		if (DoPopUp(ONIwin,
			onbut[OCHARM].x+OBOXBLEN/2,onbut[OCHARM].y+BUTTH,
			&List,icoptm,1) == -1) break;
		*icoptm = *icoptm - 3;
		onbut[OCHARM].str = copt[*icoptm+3];
		break;
  case OMULTM:
		List.list = spopt; List.nents = 8;
		if (DoPopUp(ONIwin,
			onbut[OMULTM].x+OBOXBLEN/2,onbut[OMULTM].y+BUTTH,
			&List,ispoptm,1) == -1) break;
		*ispoptm = *ispoptm + 1;
		onbut[OMULTM].str = spopt[*ispoptm-1];
		break;
  case OCHARL:
		List.list = copt; List.nents = 7;
		if (DoPopUp(ONIwin,
			onbut[OCHARL].x+OBOXBLEN/2,onbut[OCHARL].y+BUTTH,
			&List,icoptl,1) == -1) break;
		*icoptl = *icoptl - 3;
		onbut[OCHARL].str = copt[*icoptl+3];
		break;
  case OMULTL:
		List.list = spopt; List.nents = 8;
		if (DoPopUp(ONIwin,
			onbut[OMULTL].x+OBOXBLEN/2,onbut[OMULTL].y+BUTTH,
			&List,ispoptl,1) == -1) break;
		*ispoptl = *ispoptl + 1;
		onbut[OMULTL].str = spopt[*ispoptl-1];
		break;
  case OAMBCH:
		TogBut(&onbut[OAMBCH]);
		if (*ambchg) *ambchg = 0;
		else *ambchg = 1;
		break;
  default: break;
  }

  if (SUBup) {
     RedrawSUB();
     ParseLine();
     PromptBox(&qboxes[QGLIN1]);
     PromptBox(&qboxes[QGLIN2]);
  }
  RedrawONI();

  update_sel = 1;

  if (ret) {
     return(1);
  } else {
     return(0);
  }

}


RedrawONIStatus()
{

 if (!ONIup) return;

 butje(ONIwin,0,220,OBOXWIDE-1,40,1,0,0,1,None,0,0,0);
 butje(ONIwin,ZMEZOffx,220+10,OBOXWIDE-2*ZMEZOffx,20,2,0,2,0,None,0,0,0);
 XSetForeground(display, gc, infobg);
 XDrawString(display,ONIwin,gc,ZMEZOffx+5,220+24,ONIerr,strlen(ONIerr));
}


DeActOButs()
{
  ActBut(&onbut[OMETHL],2);
  ActBut(&onbut[OBASSL],2);
  ActBut(&onbut[OALLL],2);
  ActBut(&onbut[OSELL],2);
}

ActOButs()
{
  ActBut(&onbut[OMETHL],1);
  ActBut(&onbut[OBASSL],1);
  ActBut(&onbut[OALLL],1);
  ActBut(&onbut[OSELL],1);
}


calc_spectrum() {

  int i, j, spnew;
  double intensity, frq, center, rel_offset;
  double (*lineshape)(double);

  if (hwhm < 1.0e-10) {
    fprintf(stderr, "The specified HWHM of %f is too small.\n", hwhm);
    fprintf(stderr, "This program is exiting in calc_intensities\n");
    exit(1);
  }

  if (lorentzian) {
    lineshape = lorentz;
  }
  else {
    lineshape = gauss;
  }

  n_freqs = 1 + (max_freq - min_freq)/freq_step;

  spnew = sizeof(double)*2*n_freqs;

  if (spnew > specsize) {
     if (specsize > 0) free(out_spec);
     if ((out_spec = (double *) malloc(spnew)) == NULL) {
	fprintf(stderr, "Memory allocation error for spectrum\n");
	return;
     } else {
	specsize = spnew;
     }
  }

  for (i=0; i < n_freqs; i++) {
    intensity = 0.0;
    frq = min_freq + i*freq_step;
    for (j=0; j < *nfreq; j++) {
      center = (double) freq[j]*freq_scale;
      rel_offset = (frq - center) / hwhm;
      intensity += spint[j] * lineshape(rel_offset);
    }
    out_spec[i] = intensity;
  }


/*
  for (i=1; i < n_freqs; i++) {
     fprintf(stderr,"%d %11.6f\n",i,out_spec[i]);
  }
*/
  return;
}

write_spectrum(char *fname) {

	specps = 1;
	spout = fopen(fname,"w");
	fprintf(spout,"%%!PS-Adobe-1.0%\n");
	fprintf(spout,"%%%%Title: Molden\n");
	fprintf(spout,"%%%%BoundingBox: 0 0 612 792\n");
	fprintf(spout,"/m { moveto } def\n");
	fprintf(spout,"/l { lineto } def\n");
	fprintf(spout,"/Helvetica-Bold findfont [ 5   0   0  5   0   0] makefont setfont\n");
	fprintf(spout,"%%%%EndProlog\n");
	fprintf(spout,"0 setgray\n");
	fprintf(spout,"90 rotate\n");
	fprintf(spout,"1.3 2.0 scale\n");
	fprintf(spout,"10 0 translate\n");
        drwspec();
	fprintf(spout,"showpage\n");
	fclose(spout);
	specps = 0;
}

write_xmgr(char *fname) {
int i;
double frq;

	spout = fopen(fname,"w");
	for (i=0; i < n_freqs; i++) {
	   frq = min_freq + i*freq_step;
	   fprintf(spout,"%11.6f %11.6f\n",frq,out_spec[i]);
	}
	fclose(spout);
}

wrtcallb(char *str)
{
	write_spectrum(str);
	drwspec();
}

void updcallb(char *str)
{
	calc_spectrum();
	drwspec();
}

int ButtonsSPC(i)
int i;
{

  switch (i) {
  case 0:	{
	LSSTRU List;
	List.list = pktyp; List.nents = 2;
	if (DoPopUp(winspec,spbut[0].x+20,spbut[0].y,
		&List,&lorentzian,0) == -1) return 0;
	   spbut[0].str = pktyp[lorentzian];
	   DrwBut(&spbut[0]);
        }
        break;
  case 1:	{
	LSSTRU List;
	List.list = sptyp; List.nents = 2;
	if (DoPopUp(winspec,spbut[1].x+20,spbut[1].y,
		&List,&spmode,0) == -1) return 0;
	   spbut[1].str = sptyp[spmode];
           if (spmode) {
		spint = ramint; 
	   } else {
		spint = frint; 
	   }
	   DrwBut(&spbut[1]);
        }
        break;
  case 2:	{
        XDestroyWindow(display,winspec);
        specup = 0;
	return(0);
        }
        break;
  case 3:
	qboxstr(&qboxes[QSFIL],NULL,1,0,-1,DEFQX,DEFQY,
		QBOXWIDE,QBOXHIGH,0,"Filename ? ",NULL,
		0,0,2000,wrtcallb);
        break;
  case 4:
	qboxstr(&qboxes[QSFIL],NULL,1,0,-1,DEFQX,DEFQY,
		QBOXWIDE,QBOXHIGH,0,"Filename ? ",NULL,
		0,0,2000,write_xmgr);
        break;
  }
  hwhm = atof(qboxes[QHW].str);
  freq_scale = atof(qboxes[QSSCAL].str);
  min_freq = atoi(qboxes[QMINF].str);
  max_freq = atoi(qboxes[QMAXF].str);
  spec_mx = atof(qboxes[QIMAX].str);
  calc_spectrum();

  if (i == 1) {
      spec_mx = spec_mn = out_spec[0];
      for (i=1; i < n_freqs; i++) {
        if (out_spec[i] > spec_mx) {
    	   spec_mx = out_spec[i];
        }
        if (out_spec[i] < spec_mn) {
    	   spec_mn = out_spec[i];
        }
      }
      sprintf(qboxes[QIMAX].str,"%-4.2f",spec_mx);
  }

  drwspec();
}

InitDelay()
{
   
  DELup = 1;

  DELAYwin = CreateWindow("Delay Time","-0+0",DELWINW,DELWINH,
	 		 infobg,infofg,(Window)0);
  XSelectInput(display, DELAYwin, 
	KeyPressMask | ExposureMask | ButtonPressMask | ButtonReleaseMask);
  XMapWindow(display,DELAYwin);

  DefBut(&delbut[0], DELAYwin, 50, 75, 50, 23,
	"Apply", infobg, -15);
  DefBut(&delbut[1], DELAYwin, 200, 75, 50, 23,
	"Close", infobg, -15);
  DefBut(&delbut[2], DELAYwin, 125, 75, 50, 23,
	"Save", infobg, -15);

  qboxstr(&qboxes[QDEL],&DELAYwin,0,0,190,15,30, 
	250,QBOXHIGH,2,"Delay Time [msec] Next Structure ","1",12,QPOSINT,2000,dummyproc);

  qboxes[QDEL].iflt = ideltm;
  sprintf(qboxes[QDEL].str,"%d",*ideltm);
  qboxes[QDEL].active = 1;
}

RedrawDEL()
{

   if (!DELup) return;

   butje(DELAYwin,0,0,DELWINW,DELWINH,4,0,0,1,None,0,0,0);

   DrwBut(&delbut[0]);
   DrwBut(&delbut[1]);
   DrwBut(&delbut[2]);
   PromptBox(&qboxes[QDEL]);

}

int ButtonsDEL(i)
int i;
{

   switch(i) {
   case 0:
	*ideltm = atoi(qboxes[QDEL].str);
	break;
   case 1:
	*ideltm = atoi(qboxes[QDEL].str);
	XDestroyWindow(display,DELAYwin);DELup = 0;
	break;
   case 2:
	DelayRemember = 1;
	WriteRes();
	break;
   }
}

#if defined(VMS) || defined(UNDERSC)
srfclr()
#else
#ifdef CRAY
SRFCLR()
#else
srfclr_()
#endif
#endif
{
    int i;

    if (*ipdbon) NSurf = 10;
    else NSurf = 0;
#ifdef DOGL
    dispsf();
#endif
}

static int cmprot(a,b)
RESROTSTRU *a, *b;
{
    if (a->etot > b->etot) return 1;
    else
       if (a->etot == b->etot) return  0;
       else          return -1;
}

RescoreResrot()
{
   int i,j,l,n,i7=7;
   char wfile[500];

/* fftyp ? , charges ? (only when also doing ligand ?)
   PMF score and ambfor use same array
*/

/*
   if (itypBackup == NULL) {
      if ((itypBackup = (short int *) malloc((sizeof(short int))*(*xyz.mxnat))) == NULL) {
	fprintf(stderr, "Memory allocation error for itypBackup\n");
	return;
      } else {
          for (i=0; i<*xyz.mxnat; i++) itypBackup[i] = xyz.ityp[i];
      }
   }
*/
   *fftyp = 7;
   *ichx = 0;

#if defined(VMS) || defined(UNDERSC)
   dotyp(ichx);
#else
#ifdef CRAY
   DOTYP(ichx);
#else
   dotyp_(ichx);
#endif
#endif

   tnk_single = 1;
   for (j=0; j<nresrot; j++) {
	showresrot(j);
	sprintf(wfile, "rescore%03d",j);
	cpstr(wfile,tnkjn,SUBLEN1);
#if defined(VMS) || defined(UNDERSC)
	wrtsng();
#else
#ifdef CRAY
	WRTSNG();
#else
	wrtsng_();
#endif
#endif
	doamb(wfile);
	resrot[j].etot = newen;
   }
   tnk_single = 0;
   for (j=0; j<nresrot; j++) flxen[j] = resrot[j].etot;
#ifdef DOGL
   for (j=0; j<resrot[0].ndrs; j++) ogres(resrot[0].idrs[j],1,0);
   dispsf();
#endif
   RedrawList(&flxlist);
}

SaveResrot()
{
   int i,j, istat;
   char wfile[500];
   FILE *out;

   istat = 18;
   strcpy(wfile,"resrot");

   out = fopen(wfile,"w");
   if (out != NULL) {
	fprintf(out,"%d %d\n",nresrot,resrot[0].ndrs);
	for (i=0; i<nresrot; i++) {
	   fprintf(out,"ResRot %d etot %8.3f\n",i,resrot[i].etot);
	   for (j=0; j<resrot[0].ndrs; j++) {
		fprintf(out,"%d %d\n",
		resrot[i].idrs[j],resrot[i].rot[j]);
	   }
	}
	fclose(out);
	   
#if defined(VMS) || defined(UNDERSC)
	messg(&istat);
#else
#ifdef CRAY
	MESSG(&istat);
#else
	messg_(&istat);
#endif
#endif
   }
}

LoadResrot()
{
   int i,itmp,j, istat;
   double etmp;
   char wfile[500];
   char stmp1[6];
   char stmp2[4];
   char stmp3[8];
   FILE *out;

   istat = 19;
   strcpy(wfile,"resrot");

   out = fopen(wfile,"r");
   if (out != NULL) {
	fscanf(out,"%d %d",&nresrot,&resrot[0].ndrs);
        fprintf(stderr,"nresrot %d ndrs %d\n",nresrot,resrot[0].ndrs);
	for (i=0; i<nresrot; i++) {
	   resrot[i].ndrs = resrot[0].ndrs;
	   fscanf(out,"%6s %d %4s %8s",stmp1,&itmp,stmp2,stmp3);
	   sscanf(stmp3,"%lf",&etmp);
           resrot[i].etot = etmp;
	   for (j=0; j<resrot[0].ndrs; j++) {
		fscanf(out,"%d %d\n",
		&resrot[i].idrs[j],&resrot[i].rot[j]);
	   }
	}
	fclose(out);
	for (j=0; j<nresrot; j++) flxen[j] = resrot[j].etot;
	for (j=0; j<resrot[0].ndrs; j++) {
	   for (i=0; i < *xyz.iatoms; i++) {
		if (xyz.iresid[i] == resrot[0].idrs[j]) xyz.iatclr[i] = 1;
	   }
#ifdef DOGL
	   ogres(resrot[0].idrs[j],1,0);
#endif
	}
#ifdef DOGL
	dispsf();
#endif
	RedrawList(&flxlist);

   } else {
	   
#if defined(VMS) || defined(UNDERSC)
	messg(&istat);
#else
#ifdef CRAY
	MESSG(&istat);
#else
	messg_(&istat);
#endif
#endif
   }
}

initflx()
{
  if (FLXup) return;   

#if defined(VMS) || defined(UNDERSC)
   dfipar();
#else
#ifdef CRAY
   DFIPAR();
#else
   dfipar_();
#endif
#endif

  FLXup = 1;
  pmfrot->ndrs = 0;
  FLXwin = CreateWindow("Scan Rotamer Space","-0+0",FLXWINW,FLXWINH,
	 		 infobg,infofg,(Window)0);
  XSelectInput(display, FLXwin, ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask);

  XMapWindow(display,FLXwin);

  DefBut(&flxbut[0], FLXwin, 30, 10, 140, 23,
	"Scan Rotamer Space", infobg, -15);
  DefBut(&flxbut[2], FLXwin, 180, 10, 120, 23,
	"Clear Flex. Res.", infobg, -15);
  DefBut(&flxbut[1], FLXwin,  30, 215, 60, 23,
	"Close", infobg, -15);
  DefBut(&flxbut[3], FLXwin,  30, 185, 60, 23,
	"Save", infobg, -15);
  DefBut(&flxbut[4], FLXwin, 120, 185, 60, 23,
	"Load", infobg, -15);
  DefBut(&flxbut[5], FLXwin,  30, 155, 60, 23,
	"Rescore", infobg, -15);
  DefBut(&flxbut[6], FLXwin, 120, 155, 60, 23,
	"Sort", infobg, -15);
  DefBut(&flxbut[7], FLXwin, 30, 130, 20, 20,
	" ", infobg, -15);
  DefList(&flxlist,FLXwin,DIRX,DIRY,DIRW,80,
	NULL,5,NULL,NULL,flxen,&nresrot);

  if (*idoh) TogDown(&flxbut[7]);
  else TogUp(&flxbut[7]);

}

RedrawFLX()
{
   int i;

   if (!FLXup) return;

   butje(FLXwin,0,0,FLXWINW,FLXWINH,4,0,0,1,None,0,0,0);

   for (i=0; i < 8; i++) DrwBut(&flxbut[i]);

   LineString(FLXwin, "Include H...H potential", 60, 145);

   RedrawList(&flxlist);

}

int ButtonsFLX(i)
int i;
{
   int j,k,l;

   switch(i) {
   case 0:
	opt3rot();
	RedrawList(&flxlist);
	break;
   case 1:
	update_model = 0;
	pmfrot->ndrs = 0;
	XDestroyWindow(display,FLXwin);FLXup = 0;
	break;
   case 2:
	nresrot = 0;
#if defined(VMS) || defined(UNDERSC)
        chkbck();
#else
#ifdef CRAY
	CHKBCK();
#else
	chkbck_();
#endif
#endif
	for (l=0; l<resrot[0].ndrs; l++) {
	   for (i=0; i < *xyz.iatoms; i++) {
		if (xyz.iresid[i] == resrot[0].idrs[l]) {
		   xyz.iatclr[i] = 12;
		}
	   }
#ifdef DOGL
	   ogres(resrot[0].idrs[l],1,0);
#endif
	}
	resrot[0].ndrs = 0;
	pmfrot->ndrs = 0;
	update_model = 0;
#ifdef DOGL
	dispsf();
#endif
	RedrawList(&flxlist);
	break;
   case 3:
	SaveResrot();
	break;
   case 4:
	LoadResrot();
	break;
   case 5:
	RescoreResrot();
	break;
   case 6:
	qsort((RESROTSTRU *) resrot, nresrot, sizeof(RESROTSTRU), cmprot);
	for (j=0; j<nresrot; j++) flxen[j] = resrot[j].etot;
	RedrawList(&flxlist);
	break;
   case 7:
	if (*idoh) {
	   *idoh = 0;
	   TogUp(&flxbut[7]);
	} else {
	   *idoh = 1;
	   TogDown(&flxbut[7]);
	}
	break;
   }
}

InitPar()
{
  PARup = 1;
  PARwin = CreateWindow("H-bond parameters","-0+0",PARWINW,PARWINH,
	 		 infobg,infofg,(Window)0);
  XSelectInput(display, PARwin, ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask);

  XMapWindow(display,PARwin);

  DefBut(&parbut[0], PARwin, 25, 210, 70, 23,
	"Close", infobg, -15);

  DefBut(&parbut[1], PARwin, 25, 180, 200, 23,
	"Recalculate H-bonds", infobg, -15);

  DefBut(&parbut[2], PARwin, 230, 180, 60, 23,
	"Reset", infobg, -15);

   qboxstr(&qboxes[QHBMIN],&PARwin,0,0,190,30,15+0*QBOXHIGH,
	255,QBOXHIGH,2,"Min. H-bond distance   (Ang):"," ",
	SUBLEN2,QPOSREAL,2000,
	dummyproc);

   qboxstr(&qboxes[QHBMAX],&PARwin,0,0,190,30,15+1*QBOXHIGH,
	255,QBOXHIGH,2,"Max. H-bond distance   (Ang):"," ",
	SUBLEN2,QPOSREAL,2000,
	dummyproc);

   qboxstr(&qboxes[QHAMIN],&PARwin,0,0,190,30,15+2*QBOXHIGH,
	255,QBOXHIGH,2,"Min. angle Donor-H..Acc(Deg):"," ",
	SUBLEN2,QPOSREAL,2000,
	dummyproc);

   qboxstr(&qboxes[QHAMAX],&PARwin,0,0,190,30,15+3*QBOXHIGH,
	255,QBOXHIGH,2,"Max. angle Donor-H..Acc(Deg):"," ",
	SUBLEN2,QPOSREAL,2000,
	dummyproc);

   sprintf(qboxes[QHBMIN].str,"%f",hbpars->hdmin*toangs);
   sprintf(qboxes[QHBMAX].str,"%f",hbpars->hdmax*toangs);
   sprintf(qboxes[QHAMIN].str,"%f",hbpars->hamin);
   sprintf(qboxes[QHAMAX].str,"%f",hbpars->hamax);

   qboxes[QHBMIN].active = 1;
   qboxes[QHBMAX].active = 0;
   qboxes[QHAMIN].active = 0;
   qboxes[QHAMAX].active = 0;
}

RedrawPAR()
{
   int i;

   if (!PARup) return;

   butje(PARwin,0,0,PARWINW,PARWINH,4,0,0,1,None,0,0,0);

   for (i=0; i < 3; i++) DrwBut(&parbut[i]);

   PromptBox(&qboxes[QHBMIN]);
   PromptBox(&qboxes[QHBMAX]);
   PromptBox(&qboxes[QHAMIN]);
   PromptBox(&qboxes[QHAMAX]);
}

int ButtonsPAR(i)
int i;
{

   switch(i) {
   case 0:
	update_model = 0;
	hbpars->hdmin = atof(qboxes[QHBMIN].str)/toangs;
	hbpars->hdmax = atof(qboxes[QHBMAX].str)/toangs;
	hbpars->hamin = atof(qboxes[QHAMIN].str);
	hbpars->hamax = atof(qboxes[QHAMAX].str);
	XDestroyWindow(display,PARwin);PARup = 0;
	break;
   case 1:
	update_model = 1;
	hbpars->hdmin = atof(qboxes[QHBMIN].str)/toangs;
	hbpars->hdmax = atof(qboxes[QHBMAX].str)/toangs;
	hbpars->hamin = atof(qboxes[QHAMIN].str);
	hbpars->hamax = atof(qboxes[QHAMAX].str);
#if defined(VMS) || defined(UNDERSC)
	nohcon();
	dohcon(&ZERO);
#else
#ifdef CRAY
	NOHCON();
	DOHCON(&ZERO);
#else
	nohcon_();
	dohcon_(&ZERO);
#endif
#endif
	update_struct();
	return(1);
	break;
   case 2:
	hbpars->hdmin = 1.50/toangs;
	hbpars->hdmax = 3.15/toangs;
	hbpars->hamin = 145.0;
	hbpars->hamax = 215.0;
	sprintf(qboxes[QHBMIN].str,"%f",hbpars->hdmin*toangs);
	sprintf(qboxes[QHBMAX].str,"%f",hbpars->hdmax*toangs);
	sprintf(qboxes[QHAMIN].str,"%f",hbpars->hamin);
	sprintf(qboxes[QHAMAX].str,"%f",hbpars->hamax);
	PromptBox(&qboxes[QHBMIN]);
	PromptBox(&qboxes[QHBMAX]);
	PromptBox(&qboxes[QHAMIN]);
	PromptBox(&qboxes[QHAMAX]);
	break;
   }
   return(0);
}

inichg(iret)
int iret;
{
  int i,ne = 0;

  if (!xison) return(0);

  for (i=0; i<*xyz.iatoms; i++) {
     if (xyz.ianz[i] >= 0 && xyz.ianz[i] < 99) {
	ne = ne + xyz.ianz[i];
     }
  }

  if (ne % 2) {
	strcpy(chgtmp,"Hint: The neutral molecule has unpaired electrons");
  } else {
	strcpy(chgtmp,"Hint: The neutral molecule has NO unpaired electrons");
  }

  CHGup = 1;
  CHGwin = CreateWindow("Select Total Charge","-200+200",CHGWINW,CHGWINH,
	 		 infobg,infofg,(Window)0);
  XSelectInput(display, CHGwin, ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask);

  XMapWindow(display,CHGwin);

  DefBut(&chgbut[0], CHGwin, 225, 20+BUTTN, 70, 23,
	"Charge", infobg, -15);

  DefBut(&chgbut[1], CHGwin, 25, 20+3*BUTTN, 70, 23,
	"Apply", infobg, -15);
  icopt = 3;
  chgbut[0].str = copt[icopt];
  CHGret = iret;
}

RedrawCHG()
{
   int i;

   if (!CHGup) return;

   butje(CHGwin,0,0,CHGWINW,CHGWINH,4,0,0,1,None,0,0,0);

   for (i=0; i < 2; i++) DrwBut(&chgbut[i]);

   LineString(CHGwin, chgtmp, 25, 35);
   LineString(CHGwin, "Total Charge: ", 25, 35+BUTTN);
}

int ButtonsCHG(i)
int i;
{
   LSSTRU List;

   switch(i) {
   case 0:
	List.list = copt; List.nents = 7;
	if (DoPopUp(CHGwin,
	        chgbut[0].x+35,chgbut[0].y-2*BUTTH,
	        &List,&icopt,1) == -1) break;
	chgbut[0].str = copt[icopt];
	DrwBut(&chgbut[0]);
	return(0);
	break;
   case 1:
	XDestroyWindow(display,CHGwin);CHGup = 0;
	*Sinct = 580;
	*Sincp = CHGret+1;
	*itot = icopt - 3;
	return(1);
	break;
   }
   return(0);
}

#if defined(VMS) || defined(UNDERSC)
initsrf()
#else
#ifdef CRAY
INITSRF()
#else
initsrf_()
#endif
#endif
{
  if (SRFup) return;   

  SRFup = 1;

  srfsep = 1;
  SRFwin = CreateWindow("Create Surface","-0+0",SRFWINW,SRFWINH,
	 		 infobg,infofg,(Window)0);
  XSelectInput(display, SRFwin, 
	KeyPressMask | ExposureMask | ButtonPressMask | ButtonReleaseMask);
  XMapWindow(display,SRFwin);

  DefBut(&srfbut[0], SRFwin, 50, 25, 15, 15,
	" ", infobg, -15);
  DefBut(&srfbut[1], SRFwin, 50, 50, 15, 15,
	" ", infobg, -15);
  DefBut(&srfbut[2], SRFwin, 50, 100, 100, 23,
	"Create Surface", infobg, -15);
  DefBut(&srfbut[3], SRFwin, 210, 25, 50, 23,
	"Color", infobg, -15);
  DefBut(&srfbut[4], SRFwin, 50, 75, 15, 15,
	" ", infobg, -15);
  srfbut[3].fg = -cursrfcoli;

  if (*srfmap) {
	TogDown(&srfbut[0]);
  } else {
	TogUp(&srfbut[0]);
  }

  if (*srfloc) {
	TogDown(&srfbut[1]);
  } else {
	TogUp(&srfbut[1]);
  }

  if (srfsep) {
	TogDown(&srfbut[4]);
  } else {
	TogUp(&srfbut[4]);
  }
}


RedrawSRF()
{
   if (!SRFup) return;

   butje(SRFwin,0,0,SRFWINW,SRFWINH,4,0,0,1,None,0,0,0);

   DrwBut(&srfbut[0]);
   DrwBut(&srfbut[1]);
   DrwBut(&srfbut[2]);
   DrwBut(&srfbut[3]);
   DrwBut(&srfbut[4]);

   LineString(SRFwin, "Map Electrostatic Pot.", 70, 35);
   LineString(SRFwin, "Local potential (fast)", 70, 60);
   LineString(SRFwin, "Each Res. Separate Surf.", 70, 85);

}

int ButtonsSRF(i)
int i;
{
   int j,k,calc;

   switch(i) {
   case 0:
	*srfmap = 1 - TogBut(&srfbut[0]);
	break;
   case 1:
	*srfloc = 1 - TogBut(&srfbut[1]);
	break;
   case 2:
	update_model = 0;
	XDestroyWindow(display,SRFwin);SRFup = 0;
	calc = 1;
	if (*srfmap) *srfmap = 3;
	if (srfsep) {
	   if (DEBUG) fprintf(stderr,"surface residues\n");
	   for (j=0; j<calfptr->ncalf; j++) {
		if (iams[j]) {
		   if (DEBUG) fprintf(stderr,"%d\n",j);
                   for (k=0; k<*xyz.iatoms; k++) {
			if (xyz.iresid[k] == j+1) {xyz.isurf[k] = 1;}
			else {xyz.isurf[k] = 0;}
		   }
#if defined(VMS) || defined(UNDERSC)
	   	   asurf(srfmap,&calc);csrft(xyz.isurf);
#else
#ifdef CRAY
	   	   ASURF(srfmap,&calc);CSRFT(xyz.isurf);
#else
	   	   asurf_(srfmap,&calc);csrft_(xyz.isurf);
#endif
#endif
		}
	   }
	   for (j=4; j<NHetAtm; j++) {
		if (ihets[j]) {
		   if (DEBUG) fprintf(stderr,"%d\n",j);
                   for (k=0; k<*xyz.iatoms; k++) {
			if (xyz.iresid[k] == -j) {xyz.isurf[k] = 1;}
			else {xyz.isurf[k] = 0;}
		   }
#if defined(VMS) || defined(UNDERSC)
	   	   asurf(srfmap,&calc);csrft(xyz.isurf);
#else
#ifdef CRAY
	   	   ASURF(srfmap,&calc);CSRFT(xyz.isurf);
#else
	   	   asurf_(srfmap,&calc);csrft_(xyz.isurf);
#endif
#endif
		}
	   }
	} else {
#if defined(VMS) || defined(UNDERSC)
	   alasrf();asurf(srfmap,&calc);csrft(xyz.isurf);
#else
#ifdef CRAY
	   ALASRF();ASURF(srfmap,&calc);CSRFT(xyz.isurf);
#else
	   alasrf_();asurf_(srfmap,&calc);csrft_(xyz.isurf);
#endif
#endif
	}
	for (j=0; j<calfptr->ncalf; j++) iams[j] = 0;
	for (j=0; j<MXHETA; j++) ihets[j] = 0;
	for (j=0; j<4; j++) diffuseColor[NSurf-1][j] = cursrfcol[0][j];
	dispsf();
	break;
   case 3:
	if (DoPopUp(SRFwin,
		srfbut[3].x-8,srfbut[3].y+BUTTH,
		NULL,&cursrfcoli,0) == -1) break;
#ifdef DOGL
	if (has_opengl) {
           cursrfcoli++;
	   cursrfcol[0][0] = ((GLfloat) colorr[cursrfcoli]) / 65535.0 ;
	   cursrfcol[0][1] = ((GLfloat) colorg[cursrfcoli]) / 65535.0 ;
	   cursrfcol[0][2] = ((GLfloat) colorb[cursrfcoli]) / 65535.0 ;
	   cursrfcol[0][3] = 1.0;
	   srfbut[3].fg = -cursrfcoli;
	   DrwBut(&srfbut[3]);
	}
#endif
	break;
   case 4:
	srfsep = 1 - TogBut(&srfbut[4]);
   }
}

#if defined(VMS) || defined(UNDERSC)
dlystr()
#else
#ifdef CRAY
DLYSTR()
#else
dlystr_()
#endif
#endif
{

   if (! *ideltm) return;
#ifdef HASTIMER
	Timer(*ideltm,0);
#endif
}

delayt()
{
   if (! *ideltm) return;
#ifdef HASTIMER
   fprintf(stderr,"ideltm %d\n",*ideltm);
   Timer(*ideltm,1);
#endif
}

WinName(Window win,char *wname)
{
   if (XStringListToTextProperty(&wname,1,&windowProp)) {
	XSetWMName(display,win, &windowProp);
	XFree(windowProp.value);
   }
}

int AddAce(ires)
int ires;
{
   int hs[3],i,iatje,atm,row,itel;

/* look for N to which cap is to be attached */

   if (ires == -1) {

	row = GetRow(1);
	if (row < 0) return(0);

	row = izz(row,0)-1;
	if (row < 0) return(0);

	atm = zmptr.imap[row]-1;
	if (atm < 0) return(0);

   } else {
	atm = calfptr->icalf[ires-1][1]-1;
	if (atm < 0) return(0);
   }

   itel = 0;
   for (i=0; i < xyz.iconn[atm*(MXCON+1)]; i++) {
	iatje = xyz.iconn[atm*(MXCON+1)+1+i]-1;
	if (xyz.ianz[iatje] == 1 && itel < 3) {
		hs[itel] = MapAtom(iatje+1);
		itel++;
	}
   }

   if (hs[0] > hs[1]) {
	itel = hs[0]; hs[0] = hs[1]; hs[1] = itel;
   }

   if (hs[0] > hs[2]) {
	itel = hs[0]; hs[0] = hs[2]; hs[1] = itel;
   }

   for (i=0; i < 3; i++) {
      if (hs[i] < 0) return(0);
   }

   AddFrag(ACE,6,120.0,0.0,hs[1],1,1); 
   zmptr.bet[hs[1]] = 180.0;
   SetQZME();
   DelLine(hs[2],1,0,NULL);
   SetQZME();
   make_aa();
   UpdateZME();

   return(1);
}

int AddCap(ires)
int ires;
{
   int icap,row,orow,iatje,i;

   icap = 0;
   for (i=0; i < calfptr->nchain; i++) {
	if (ires == calfptr->ianf[i]) icap = 1;
	if (ires == calfptr->islu[i]) icap = 2;
   }
   if (icap == 0) {
	strcpy(ZMEerr,"Not end or begin chain !");
	RedrawStatus();
   } else if (icap == 1) {
	if (!AddAce(ires)) return(0);
	SetQZME();
	update_res = -1;
	update_model = 1;
   } else if (icap == 2) {
	row = calfptr->icalf[ires-1][2]-1;
	if (row < 0) return(0);
	orow = -1;
	for (i=0; i < xyz.iconn[row*(MXCON+1)]; i++) {
	   iatje = xyz.iconn[row*(MXCON+1)+1+i]-1;
	   if (xyz.ianz[iatje] == 8) {
		orow = MapAtom(iatje+1);
		break;
	   }
	}
	if (orow < 0) return(0);
	AddFrag(NME,6,109.471,180.0,orow,1,1);
	SetQZME();
	update_res = -1;
	update_model = 1;
   }
   return(1);

}

int GetFrag(int iopt, int x, int y)
{
   LSSTRU List; int ifrg; int perio; int ichl; int iamin; int iret; int minone;
   int idomp; 

   if (iopt) {
      List.list = fragmnts; List.nents = nfrags; 
      if (*ipdbon) List.nents = nfrags + 4;
   } else {
      List.list = fragments; List.nents = nfrag; 
   }

   iret = -1;

   if ( ! (ZMEup && ! ZMEsel && ! ZMEmode && ! Selecting)) return(iret);


   if (iopt) {
	if (DoPopUp(win,x,y,&List,&ifrg,0) == -1) return(iret);
   } else {
	if (DoPopUp(ZMEwin,
		ZMEbut[ZMEFRG].x+1,ZMEbut[ZMEFRG].y-7*BUTTH,
		&List,&ifrg,0) == -1) return(iret);
   }
   if (iopt) ifrg++;

   if (ifrg < 19) calfptr->issdon = 0;

   idomp = 0;
   if (ialtyp == NULL) idomp = 1;
   else if (*ialtyp != 1) idomp = 1;
   else idomp = 0;

   if (idomp) map_prop();

   switch (ifrg) {
	case 0: 
	   if (iopt) break;
	   qboxstr(&qboxes[QFRAG],NULL,1,0,-1,DEFQX,DEFQY,
		QBOXWIDE,QBOXHIGH,0,"Filename ? ",NULL,0,0,
		540,dummyproc);
	   break;
	case 1: AddXH3(6,1); iret = 1; break;
	case 2: AddFrag(CHCH2,5,120.0,180.0,-1,1,1); iret = 1; break;
	case 3: AddFrag(CHO,3,120.0,180.0,-1,1,1); iret = 1; break;
	case 4: AddFrag(COOH,4,120.0,180.0,-1,1,1); iret = 1; break;
	case 5: AddXH3(7,1); iret = 1; break;
	case 6: AddFrag(OH,2,109.471,180.0,-1,1,1); iret = 1; break;
	case 7: AddFrag(CHCH,5,90.0,180.0,-1,1,1); iret = 1; break;
	case 8: AddCycloHexane(); iret = 1; break;
	case 9: AddFrag(benzyl,BENZLEN,120.0,180.0,-1,1,1); iret = 1; break;
	case 10: AddFrag(CL,1,109.471,180.0,-1,1,1); iret = 1; break;
	case 11: AddFrag(BR,1,109.471,180.0,-1,1,1); iret = 1; break;
	case 12: AddFrag(I,1,109.471,180.0,-1,1,1); iret = 1; break;
	case 13: AddFrag(OCH3,5,109.471,180.0,-1,1,1); iret = 1; break;
	case 14: AddFrag(SH,2,109.471,180.0,-1,1,1); iret = 1; break;
	case 15: AddFrag(NO2,3,117.38,180.0,-1,1,1); iret = 1; break;
	case 16: AddFrag(CH4,5,117.38,180.0,-1,1,1); iret = 1; break;
	case 17: 
		if (iopt) {
		   if (!AddAce(-1)) return;
		   iret = 1; break;
		}
		RedrawZME(); XFlush(display); XSync(display,False);
		List.list = Periodic; List.nents = 2;
		if (DoPopUp(ZMEwin,
			ZMEbut[ZMEFRG].x+1,ZMEbut[ZMEFRG].y-6*BUTTH,
			&List,&perio,0) == -1) break;
		List.list = ChainLength; List.nents = 10;
		RedrawZME(); XFlush(display); XSync(display,False);
		if (perio == 2) break;
		if (DoPopUp(ZMEwin,
			ZMEbut[ZMEFRG].x+1,ZMEbut[ZMEFRG].y-6*BUTTH,
			&List,&ichl,0) == -1) break;
		*ipdbon = 0;
		scrfrg(perio,ichl); iret = 1; break;
	case 18: 

        /* add FOR cap (iopt==1) or add amino acid */

		if (iopt) {
		   AddFrag(FOR,3,120.0,180.0,-1,1,1); 
		   iret = 1; break;
		}
		RedrawZME(); XFlush(display); XSync(display,False);
		List.list = AmiOpt; List.nents = 4;
		if (DoPopUp(ZMEwin,
			ZMEbut[ZMEFRG].x+1,ZMEbut[ZMEFRG].y+7*BUTTH,
			&List,&iamin,0) == -1) break;
		if (iamin == 1 || iamin == 2 || iamin == 3) {
  	   	   if (DoCan(event.xbutton.x_root,
			event.xbutton.y_root,
			"Click on an atom of the residue",0)) {
		   }
		   bflag = 1; 
		   if (iamin == 1) bretval = 321;
		   else bretval = 322;
		   if (iamin == 3) ReplaceAmino = 1;
		} else {
		   List.list = AminoCaps; List.nents = NAminos+4;
		   if (DoPopUp(ZMEwin,
			ZMEbut[ZMEFRG].x+1,ZMEbut[ZMEFRG].y-10*BUTTH,
			&List,&iamin,0) == -1) break;
		   minone = -1;
		   if (iamin == 14) {
			AddAmino(iamin,&minone, -70.0,113.0, 
			NULL,NULL,NULL,NULL,NULL,iconform,1,1); 
		   } else if (iamin == 20) {
			AddFrag(ACE,6,120.0,180.0,-1,1,1); 
		   } else if (iamin == 21) {
			AddFrag(FOR,3,120.0,180.0,-1,1,1); 
		   } else if (iamin == 22) {
			AddFrag(NME,6,109.471,180.0,-1,1,1); 
		   } else if (iamin == 23) {
			AddXH3(7,1);
		   } else {
			AddAmino(iamin,&minone, -119.0,113.0, 
			NULL,NULL,NULL,NULL,NULL,iconform,1,1); 
			calfptr->reson[calfptr->ncalf-1] = 1;
			update_model = 1;
		   }
		}
		iret = 1; break;
	case 19: 
		if (iopt) {
		   AddFrag(NME,6,120.0,180.0,-1,1,1); 
		   iret = 1; break;
		}
		if (SEQup) {
		    XMapRaised(display,SEQwin);
		    RedrawSEQ();
		} else {
		    InitSEQ(event.xbutton.x_root,
			event.xbutton.y_root+20);
		}
		iret = 0; break;
	case 20: 
		AddFrag(NH2,3,120.0,180.0,-1,1,1); 
		iret = 1; break;
	}

  return(iret);
}

motion_screen(inct,incp)
int *inct;
int *incp;
{

   if (expldat.active) return;

   if (event.xmotion.window == win) {
      if ( *ball && (moving || gmoving)) {
        update_model = 0;
	if (XCheckMaskEvent(display,ButtonReleaseMask,&event)) {
	   if (*fancy && has_opengl) motion(event.xmotion.x, event.xmotion.y, 1);
		   moving = 0;
	} else {
	   while (XCheckMaskEvent(display,ButtonMotionMask,&event));
	   *incp = (event.xmotion.x - startx);
	   if (btype == 0) { 
		*inct = 421;
	   } else if (btype == 1) {
		*inct = 415;
	   } else if (btype == 2) {
		*inct = 417;
	   } else if (btype == 3) {
		*inct = 422;
	   }
	   doclr();
#if defined(VMS) || defined(UNDERSC)
	   mktrn(inct,incp);
#else
#ifdef CRAY
       	   MKTRN(inct,incp);
#else
       	   mktrn_(inct,incp);
#endif
#endif
	   *incp = (event.xmotion.y - starty);
	   if (btype == 0) { 
		*inct = -421;
	   } else if (btype == 1) {
		*inct = 416;
	   }

#if defined(VMS) || defined(UNDERSC)
	   mktrn(inct,incp);
           if (*fancy && has_opengl) 
		motion(event.xmotion.x, event.xmotion.y, 0);
	   else qupd();
#else
#ifdef CRAY
       	   MKTRN(inct,incp);
	   if (*fancy && has_opengl) 
		motion(event.xmotion.x, event.xmotion.y, 0);
	   else QUPD();
#else
           mktrn_(inct,incp);
	   if (*fancy && has_opengl) 
		motion(event.xmotion.x, event.xmotion.y, 0);
	   else qupd_();
#endif
#endif
	   startx = event.xmotion.x;
	   starty = event.xmotion.y;
	   *inct = 0;
	   XFlush(display);
	   if (!expldat.active) XSync(display, False);
	}
   } else {
	int Ca;

	if (!ZoomSelection && !denmode) {

	     if (*ipdbon) {

	        if (*fancy) {
		   Ca = FindCa(xyz.iaton,xyz.iyp,xyz.ixp,
			event.xmotion.x,event.xmotion.y,MINDIFF);

		   if (Ca >= 0) {
		       parse_label(Ca,0,xyz.ixp,xyz.iyp);
		   } else {
		       Ca = FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
				event.xmotion.x,event.xmotion.y,MINDIFF);
		       if (Ca>=0) parse_labelp(xyz.iresid[Ca]-1,Ca,xyz.ixp,xyz.iyp);
		       else parse_labelp(RESUND,0,xyz.ixp,xyz.iyp);
		   }

	        } else {

		   Ca = FindCaP(event.xmotion.x,event.xmotion.y,MINDIFF);

		   if (Ca >= 0) {
		       parse_labelp(Ca,0,xyz.ixp,xyz.iyp);
		   } else {
		       Ca = FindSel(xyz.iaton,xyz.iyp,xyz.ixp,*xyz.iatoms,
				event.xmotion.x,event.xmotion.y,MINDIFF);
		       if (Ca>=0) parse_labelp(xyz.iresid[Ca]-1,Ca,xyz.ixp,xyz.iyp);
		       else parse_labelp(RESUND,0,xyz.ixp,xyz.iyp);
		   }
	        }
	     }

	}
      }
   }

}

#if defined(VMS) || defined(UNDERSC)
void setsup()
#else
#ifdef CRAY
void SETSUP()
#else
void setsup_()
#endif
#endif
{
   update_sel = 1;
}

static FILE *out;
static int dowrt = 0;
#define MAXNAM 512
static char ogfil[MAXNAM];
static double z0[] = {0.0,0.0,0.0};
static double zx[] = {1.0,0.0,0.0};
static double zy[] = {0.0,1.0,0.0};

void launchViewer(opt)
int opt;
{
    int pid;

    pid = fork();
    switch(pid) {
    case -1:
          fprintf(stderr,"Couldnt Fork\n");
          break;
    case 0:       /*child */
#ifdef __CYGWIN__
	  if (opt) {
             execlp("./mogl","mogl","-r","-b","0",ogfil,NULL);
	  } else {
             execlp("./mogl","mogl",ogfil,NULL);
	  }
#else
	  if (opt) {
             execlp("moldenogl","moldenogl","-r","-b","0",ogfil,NULL);
	  } else {
             execlp("moldenogl","moldenogl",ogfil,NULL);
	  }
#endif
	  exit(0);
          break;
    default:      /*parent*/
          break;
    }
}

#if defined(VMS) || defined(UNDERSC)
void oginsp(double *r, double *adjus, int *natoms, int *nat, int *iatclr, int *icol,
#else
#ifdef CRAY
void OGINSP(double *r, double *adjus, int *natoms, int *nat, int *iatclr, int *icol,
#else
void oginsp_(double *r, double *adjus, int *natoms, int *nat, int *iatclr, int *icol,
#endif
#endif

       double *xsym, double *ysym, double *zsym, double *vdwr, 
       int *mopt, int *conn, int *nconn, int *iconn, int *ofil)
{

    dowrt = 1;
    out = fopen(ogfil,"w");

    if (out == NULL) {
          fprintf(stderr,"Unable to open file %s\n",ogfil);
	  dowrt = 0;
	  return;
    }

    fprintf(out,"[MOLDENOGL]\n");
    ogwrmol(r,adjus,natoms,nat,xsym,ysym,zsym,vdwr);

}

#if defined(VMS) || defined(UNDERSC)
void ognorm(double *v1, double *v2, double *v3)
#else
#ifdef CRAY
void OGNORM(double *v1, double *v2, double *v3)
#else
void ognorm_(double *v1, double *v2, double *v3)
#endif
#endif
{
      if (dowrt) fprintf(out,"%f %f %f\n",*v1,*v2,*v3);
}

#if defined(VMS) || defined(UNDERSC)
void ogvert(double *v1, double *v2, double *v3)
#else
#ifdef CRAY
void OGVERT(double *v1, double *v2, double *v3)
#else
void ogvert_(double *v1, double *v2, double *v3)
#endif
#endif
{
      if (dowrt) fprintf(out,"%f %f %f\n",*v1,*v2,*v3);
}

#if defined(VMS) || defined(UNDERSC)
void ogcol(double *v1, double *v2, double *v3)
#else
#ifdef CRAY
void OGCOL(double *v1, double *v2, double *v3)
#else
void ogcol_(double *v1, double *v2, double *v3)
#endif
#endif
{
      if (dowrt) fprintf(out,"%f %f %f\n",*v1,*v2,*v3);
}

ogwrmol(double *r, double *adjus, int *natoms, int *nat, 
        double *xsym, double *ysym, double *zsym, double *vdwr)
{
      int i,j,k,ia,ja,nconn;
      double dmaxsq, dijsq, st, tmp1[3], tmp2[3];
      int iconn[30];

      if (!dowrt) return;

      if (*adjus != 1.0) {
         fprintf(out,"[MOLECULE] AU CONN\n");
      } else {
         fprintf(out,"[MOLECULE] CONN\n");
      }

      fprintf(out,"%f %f %f\n",r[0],r[1],r[2]);
      fprintf(out,"%d\n",*natoms);
      for (i=0; i<*natoms; i++) {

         ia = nat[i];
	 tmp1[0] = -1.0 * ysym[i] / r[0];
	 tmp1[1] = -1.0 * xsym[i] / r[0];
	 tmp1[2] = -1.0 * zsym[i] / r[0];


         nconn = 0;
         for (j=0; j<*natoms; j++) {

            ja = nat[j];
	    tmp2[0] = -1.0 * ysym[j] / r[0];
	    tmp2[1] = -1.0 * xsym[j] / r[0];
	    tmp2[2] = -1.0 * zsym[j] / r[0];

            dmaxsq = (vdwr[ia] + vdwr[ja]);
            dmaxsq = dmaxsq * dmaxsq;

            dijsq = 0.0;

            st = (xsym[i] - xsym[j])*(*adjus);
	    st *= st;
	    dijsq = dijsq + st;

	    st = (ysym[i] - ysym[j])*(*adjus);
	    st *= st;
	    dijsq = dijsq + st;

	    st = (zsym[i] - zsym[j])*(*adjus);
	    st *= st;
	    dijsq = dijsq + st;

            if (i != j && dijsq < dmaxsq) {
		iconn[nconn] = j+1;
		nconn++;
            }

         }
         fprintf(out,"%d %f %f %f %d",nat[i],xsym[i],ysym[i],zsym[i],nconn);
	 for (k=0; k<nconn; k++)
	   fprintf(out," %d",iconn[k]);
         fprintf(out,"\n");
      }

}

#if defined(VMS) || defined(UNDERSC)
void oginid(double *r, double *adjus, int *natoms, int *nat, int *icol,
#else
#ifdef CRAY
void OGINID(double *r, double *adjus, int *natoms, int *nat, int *icol,
#else
void oginid_(double *r, double *adjus, int *natoms, int *nat, int *icol,
#endif
#endif
       double *xsym, double *ysym, double *zsym, double *vdwr,
       double *cnst, int *nnpts1, int *nnpts2, double *dens)
{

   dowrt = 1;
   out = fopen(ogfil,"w");

   if (out == NULL) {
       fprintf(stderr,"Unable to open file %s\n",ogfil);
       dowrt = 0;
       return;
   }

   fprintf(out,"[MOLDENOGL]\n");
   ogwrmol(r,adjus,natoms,nat,xsym,ysym,zsym,vdwr);
   BuildList(r,cnst,nnpts1,nnpts2,dens);

   if (dowrt) fclose(out);

   launchViewer(1);

}

#if defined(VMS) || defined(UNDERSC)
void ogspst()
#else
#ifdef CRAY
void OGSPST()
#else
void ogspst_()
#endif
#endif
{

    if (dowrt) fclose(out);

    launchViewer(1);

}

#if defined(VMS) || defined(UNDERSC)
parogf(str,nlen)
#else
#ifdef CRAY
PAROGF(str,nlen)
#else
parogf_(str,nlen)
#endif
#endif

#ifdef VMS
struct dsc$descriptor_s *str;
#else
#ifdef CRAY
_fcd str;
#else
char *str;
#endif
#endif
int *nlen;

{
  int i;

  if (*nlen >= MAXNAM) { 
	fprintf(stderr,"filename too long !\n");
	*nlen = MAXNAM - 1;
  }
#ifdef VMS
  for (i=0; i<*nlen; i++)
         ogfil[i] = str->dsc$a_pointer[i];
#else
#ifdef CRAY
   strncpy(ogfil,_fcdtocp(str),*nlen);
#else
   for (i=0; i<*nlen+1; i++) ogfil[i] = '\0';
   strncpy(ogfil,str,*nlen);
#endif
#endif

}

#if defined(VMS) || defined(UNDERSC)
void viewer()
#else
#ifdef CRAY
void VIEWER()
#else
void viewer_()
#endif
#endif
{
	    launchViewer(0);
}

BuildList(r,cnst,nnpts1,nnpts2,dens)
double *r;
double *cnst;
int *nnpts1;
int *nnpts2;
double *dens;
{

     int i,j,noff1,noff2,npts1,npts2;
     double v[3], rpts;
     double vec1[3], vn1[3];
     float hinv1,hinv2;

/*
     a grid of n*n points has n-1*n-1 squares
     and twice as much triangular polygons
     so 2*(npts-1)**2
     npts is 80 at maximum so lets make it 12800
*/

      npts1 = *nnpts1;
      npts2 = *nnpts2;
      noff1 = npts1/2;
      noff2 = npts2/2;
      rpts = (double) (npts1-1);
      hinv1 = r[1]/ (npts2*r[0]);
      hinv2 = 1.0/ npts1;

      if (dowrt) fprintf(out,"[ELEVATIONGRID]\n");

      for (i=0; i<npts1-1; i++) {
         for (j=0; j<npts2-1; j++) {
/*
        first triangle
*/
            vec1[0] = (double) (j-noff2);
            vec1[1] = (double) (i-noff1);
            vec1[2] = dens[j+i*npts2]*(*cnst)*rpts;

	    znorm(rpts,*cnst,dens,vn1,npts1,npts2,i,j);

#if defined(VMS) || defined(UNDERSC)
            ognorm(&vn1[0],&vn1[1],&vn1[2]);
#else
#ifdef CRAY
            OGNORM(&vn1[0],&vn1[1],&vn1[2]);
#else
            ognorm_(&vn1[0],&vn1[1],&vn1[2]);
#endif
#endif

	    v[0] = vec1[0]*hinv1;
	    v[1] = vec1[1]*hinv2;
	    v[2] = vec1[2]*hinv1;
#if defined(VMS) || defined(UNDERSC)
	    ogvert(&v[0],&v[1],&v[2]);
#else
#ifdef CRAY
	    OGVERT(&v[0],&v[1],&v[2]);
#else
	    ogvert_(&v[0],&v[1],&v[2]);
#endif
#endif

            vec1[0] = (double) (j+1-noff2);
            vec1[1] = (double) (i-noff1);
            vec1[2] = dens[j+1+i*npts2]*(*cnst)*rpts;

	    znorm(rpts,*cnst,dens,vn1,npts1,npts2,i,j+1);

#if defined(VMS) || defined(UNDERSC)
            ognorm(&vn1[0],&vn1[1],&vn1[2]);
#else
#ifdef CRAY
            OGNORM(&vn1[0],&vn1[1],&vn1[2]);
#else
            ognorm_(&vn1[0],&vn1[1],&vn1[2]);
#endif
#endif

	    v[0] = vec1[0]*hinv1;
	    v[1] = vec1[1]*hinv2;
	    v[2] = vec1[2]*hinv1;
#if defined(VMS) || defined(UNDERSC)
	    ogvert(&v[0],&v[1],&v[2]);
#else
#ifdef CRAY
	    OGVERT(&v[0],&v[1],&v[2]);
#else
	    ogvert_(&v[0],&v[1],&v[2]);
#endif
#endif

            vec1[0] = (double) (j+1-noff2);
            vec1[1] = (double) (i+1-noff1);
            vec1[2] = dens[j+1+(i+1)*npts2]*(*cnst)*rpts;

	    znorm(rpts,*cnst,dens,vn1,npts1,npts2,i+1,j+1);

#if defined(VMS) || defined(UNDERSC)
            ognorm(&vn1[0],&vn1[1],&vn1[2]);
#else
#ifdef CRAY
            OGNORM(&vn1[0],&vn1[1],&vn1[2]);
#else
            ognorm_(&vn1[0],&vn1[1],&vn1[2]);
#endif
#endif

	    v[0] = vec1[0]*hinv1;
	    v[1] = vec1[1]*hinv2;
	    v[2] = vec1[2]*hinv1;
#if defined(VMS) || defined(UNDERSC)
	    ogvert(&v[0],&v[1],&v[2]);
#else
#ifdef CRAY
	    OGVERT(&v[0],&v[1],&v[2]);
#else
	    ogvert_(&v[0],&v[1],&v[2]);
#endif
#endif

            vec1[0] = (double) (j-noff2);
            vec1[1] = (double) (i+1-noff1);
            vec1[2] = dens[j+(i+1)*npts2]*(*cnst)*rpts;

	    znorm(rpts,*cnst,dens,vn1,npts1,npts2,i+1,j);

#if defined(VMS) || defined(UNDERSC)
            ognorm(&vn1[0],&vn1[1],&vn1[2]);
#else
#ifdef CRAY
            OGNORM(&vn1[0],&vn1[1],&vn1[2]);
#else
            ognorm_(&vn1[0],&vn1[1],&vn1[2]);
#endif
#endif

	    v[0] = vec1[0]*hinv1;
	    v[1] = vec1[1]*hinv2;
	    v[2] = vec1[2]*hinv1;
#if defined(VMS) || defined(UNDERSC)
	    ogvert(&v[0],&v[1],&v[2]);
#else
#ifdef CRAY
	    OGVERT(&v[0],&v[1],&v[2]);
#else
	    ogvert_(&v[0],&v[1],&v[2]);
#endif
#endif

         }
      }


}

void crpsin(a,b,c,d)
double *a;
double *b;
double *c;
double *d;
{
/*

       calculates cross product:  (b-a) x (c-a) = d
                                   ---     ---    -
*/
      int i;
      double v1[3],v2[3],dlen;

      for (i=0; i<3; i++) {
         v1[i] = b[i]-a[i];
         v2[i] = c[i]-a[i];
      }

      d[0] = v2[1]*v1[2]-v2[2]*v1[1];
      d[1] = v2[2]*v1[0]-v2[0]*v1[2];
      d[2] = v2[0]*v1[1]-v2[1]*v1[0];
      dlen = sqrt(d[0]*d[0]+d[1]*d[1]+d[2]*d[2]);

      if (dlen > 0 ) for (i=0; i<3; i++) d[i] = d[i] / dlen;
}

double vln( double *a)
{
      double vl;
      double tot;

      tot = a[0]*a[0]+a[1]*a[1]+a[2]*a[2];

      vl = 0.0;
      if (tot > 0.0) vl = sqrt(tot);

      return(vl);

}

void znorm(double rpts, double cnst, double *dens, double *vn,
	   int npts1, int npts2, int i, int j)
{
     double vl,z1[3],z2[3],z3[3],nx[3],ny[3];
     int k;

     if (j+1 < npts2) {
         z1[0] = 1.0; z1[1] = 0.0;
         z1[2] = cnst*rpts*(dens[j+1+i*npts2]-dens[j+i*npts2]);
         crpsin(z0,z1,zy,z2);
     } else {
         for (k=0; k<3; k++) z2[k] = z0[k];
     }

     if (j-1 >= 0) {
         z1[0] = -1.0; z1[1] = 0.0;
         z1[2] = cnst*rpts*(dens[j-1+i*npts2]-dens[j+i*npts2]);
         crpsin(z0,zy,z1,z3);
     } else {
         for (k=0; k<3; k++) z3[k] = z0[k];
     }

     for (k=0; k<3; k++) nx[k] = z3[k] + z2[k];
     vl = vln(nx);
     for (k=0; k<3; k++) nx[k] = nx[k] / vl;

     if (i+1 < npts1) {
         z1[0] = 0.0; z1[1] = 1.0;
         z1[2] = cnst*rpts*(dens[j+(i+1)*npts2]-dens[j+i*npts2]);
         crpsin(z0,z1,zx,z2);
     } else {
         for (k=0; k<3; k++) z2[k] = z0[k];
     }

     if (i-1 >= 0) {
         z1[0] = 0.0; z1[1] = -1.0;
         z1[2] = cnst*rpts*(dens[j+(i-1)*npts2]-dens[j+i*npts2]);
         crpsin(z0,zx,z1,z3);
     } else {
         for (k=0; k<3; k++) z3[k] = z0[k];
     }

     for (k=0; k<3; k++) ny[k] = z3[k] + z2[k];
     vl = vln(ny);
     for (k=0; k<3; k++) ny[k] = ny[k] / vl;

     for (k=0; k<3; k++) vn[k] = ny[k] - nx[k];
     vl = vln(vn);
     for (k=0; k<3; k++) vn[k] = vn[k] / vl;

}

#if defined(VMS) || defined(UNDERSC)
void initog(int *iwrt)
#else
#ifdef CRAY
void INITOG(int *iwrt)
#else
void initog_(int *iwrt)
#endif
#endif
{
 int i;

 /* just dummy */

  i = *iwrt;

}

#if defined(VMS) || defined(UNDERSC)
void ogbeg(isurf)
#else
#ifdef CRAY
void OGBEG(isurf)
#else
void ogbeg_(isurf)
#endif
#endif
int *isurf;
{
      int surf,surfabs;

      if (!dowrt) return;

      surf = *isurf;
      surfabs = abs(surf);

      if (surfabs == 3) {
	   fprintf(out,"[SURFACE] MAPPED\n");
      } else {
	if (surf<0) {
	   fprintf(out,"[SURFACE] TRANS COLOR 1.0 1.0 0.0\n");
	} else {
	   fprintf(out,"[SURFACE]\n");
	}
      }

}

#if defined(VMS) || defined(UNDERSC)
void ogend()
#else
#ifdef CRAY
void OGEND()
#else
void ogend_()
#endif
#endif
{
      int i;

      i = 0;
}

#if defined(VMS) || defined(UNDERSC)
void ogreset()
#else
#ifdef CRAY
void OGRESET()
#else
void ogreset_()
#endif
#endif
{
      if (denmode) NSurf = 0;
}

#ifdef DOGL

#ifndef __glut_h__
/* Mouse buttons. */
#define GLUT_LEFT_BUTTON                0
#define GLUT_MIDDLE_BUTTON              1
#define GLUT_RIGHT_BUTTON               2

/* Mouse button  state. */
#define GLUT_DOWN                       0
#define GLUT_UP                         1

/* glutGetModifiers return mask. */
#define GLUT_ACTIVE_SHIFT               1
#define GLUT_ACTIVE_CTRL                2
#define GLUT_ACTIVE_ALT                 4

#endif

#define TRDEF 0.6

static float ribcol[7][4] =
{
  {0.0,0.0,1.0,0.8},
  {1.0,0.0,1.0,0.8},
  {0.0,1.0,0.0,0.8},
  {0.6,0.6,0.6,0.8},
  {0.5,1.0,0.5,0.8},
  {1.0,1.0,1.0,0.8},
  {1.0,0.5,0.5,0.8}
};
 

static int started_ogl = 0;
static int ecol = 2;
static int gbgcol = 6;
static double tr_val = TRDEF;
static int hires = 1;
static int perspon = 1;
static GLfloat poszz = 0.0;
static int lines = 0;
static int TRANS;
static int PERSP = 0;
static int AXES = 0;
static int l1on = 0;
static int l2on = 0;
static int l3on = 1;
static int stacks = 10;
static int DoLines = 0;
static int DoCap = 0;
static GLfloat fdens = 0.03;
static int DoLights = 0;
static int ColBG = -1;

/* Some <math.h> files do not define M_PI... */
#ifndef M_PI
#define M_PI 3.141592654
#endif
#define TORAD M_PI/180.0

static GLdouble RR[4][4] = { 
{1.0,0.0,0.0,0.0}, {0.0,1.0,0.0,0.0}, {0.0,0.0,1.0,0.0}, {0.0,0.0,0.0,1.0} 
};

static float ambientColor[4] = {0.1,0.1,0.1,0.1};
static float ambientDColor[4] = {0.2,0.2,0.2,0.2};
static float specColor[4] = {0.8,0.8,0.8,1.0};
static float specularColor[MAXSURF][4] =
         { {0.8,0.8,0.8,1.0} , {0.8,0.8,0.8,1.0}, {0.9,0.8,0.8,1.0},
           {0.8,0.8,0.8,1.0} , {0.8,0.8,0.8,1.0}, {0.9,0.8,0.8,1.0},
           {0.8,0.8,0.8,1.0} , {0.8,0.8,0.8,1.0}, {0.9,0.8,0.8,1.0},
           {0.8,0.8,0.8,1.0} , {0.8,0.8,0.8,1.0}, {0.9,0.8,0.8,1.0},
};

static float materialColor[8][4] =
{
  {0.8, 0.8, 0.8, 1.0},
  {0.8, 0.0, 0.0, 1.0},
  {0.0, 0.8, 0.0, 1.0},
  {0.0, 0.0, 0.8, 1.0},
  {0.0, 0.8, 0.8, 1.0},
  {0.8, 0.0, 0.8, 1.0},
  {0.8, 0.8, 0.0, 1.0},
  {1.0, 0.5, 0.5, 1.0},
};

static float AmbientNul[4] = {0.1,0.1,0.1,0.0};

static float light0_position[] = {-2.0, -2.0, 0.0, 1};
static float light1_position[] = {4.0, 4.0, 4.0, 1};
static float light2_position[] = {0.0, 0.0, 4.0, 1};
static float light2_position_def[] = {0.0, 0.0, 4.0, 1};

#define MXMOL 1000
static int molon = 1;
static int AmbAndDiff = 0;
static int mmoving = 0;
static int mstartx, mstarty;
static GLfloat posx = 0.0;
static GLfloat posy = 0.0;
static GLfloat posz = -20.0;

static int smoving = 0;
static int sstarty;

static GLuint theSurf[MAXSURF];
static int NMols = -1;
static int CMols = 0;
static int Anim = 1;
static int AnimSlow = 0;
static int AnimCount = 1;
static GLuint theMol[MXMOL];
static GLuint theLines = -1;
static GLuint theForces = -1;
static GLuint theDipole = -1;
static GLuint theAxes = -1;
static GLuint theRes[NUMCAL];
static GLuint theBck[NUMCAL];
static GLuint theMon;
static GLuint theSel;
static GLuint theOther = -1;
static GLUquadricObj *cyl;
static GLUquadricObj *sphere;
static GLUquadricObj *disk;

#define ROTINCR 5.0
static GLfloat xrot = -45.0;
static GLfloat yrot = 240.0;

void bckgrad() 
{

    glDisable(GL_LIGHTING);           
    glDisable(GL_DEPTH_TEST);         
    glDepthMask(GL_FALSE);            

    glDisable(GL_POLYGON_STIPPLE);    
    glDisable(GL_BLEND);              

    glMatrixMode(GL_MODELVIEW);       
    glPushMatrix();
    glLoadIdentity();                 

    glMatrixMode (GL_PROJECTION);     
    glPushMatrix();
    glLoadIdentity();
    gluOrtho2D(0.0, 1.0, 0.0, 1.0);   

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();                 

    glBegin(GL_QUADS);
      glColor3fv(&gradcol[1][0]);
      glVertex2f(0.0f, 0.0f);
      glColor3fv(&gradcol[0][0]);
      glVertex2f(0.0f, 1.0f);
      glColor3fv(&gradcol[0][0]);
      glVertex2f(1.0f, 1.0f);
      glColor3fv(&gradcol[1][0]);
      glVertex2f(1.0f, 0.0f);
    glEnd();

    glPopMatrix();                     

    glMatrixMode (GL_PROJECTION);
    glPopMatrix();                     

    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();                     

    glEnable(GL_DEPTH_TEST);           
    glDepthMask(GL_TRUE);              
    glEnable(GL_LIGHTING);             
}

static GLuint base;

void makeRasterFont(Display *dpy)
{
    Font id;
    GLuint first, last;
    
    id = mfinfo->fid;
    first = (GLuint) mfinfo->min_char_or_byte2;
    last = (GLuint) mfinfo->max_char_or_byte2;

    last++;

    base = glGenLists((GLsizei) last);
    if (base == 0) {
        fprintf(stderr,"out of display lists\n");
        exit(0);
    }
    glXUseXFont(id, first, last, base);
}

void initPrintStrings(int front)
{
	glXMakeCurrent(display,win,cx);
	if (front) glDrawBuffer(GL_FRONT);
	glDisable(GL_LIGHTING);           
	glDisable(GL_DEPTH_TEST);         
	glDepthMask(GL_FALSE);            
	glPushAttrib( GL_TRANSFORM_BIT | GL_VIEWPORT_BIT );

	glMatrixMode( GL_PROJECTION );
	glPushMatrix();
	glLoadIdentity();
	glMatrixMode( GL_MODELVIEW );
	glPushMatrix();
}

void endPrintStrings()
{
	glPopMatrix();
	glMatrixMode( GL_PROJECTION );
	glPopMatrix();

	glPopAttrib();

	glFlush();
	glDrawBuffer(GL_BACK);
	glEnable(GL_DEPTH_TEST);           
	glDepthMask(GL_TRUE);              
	glEnable(GL_LIGHTING);             
}

void printString(int x, int y, int init, char *s)
{
   if (init) initPrintStrings(1);

	glLoadIdentity();

	y = height  - y;

	glViewport( x - 1, y - 1, 0, 0 );

	glRasterPos4f( 0, 0, 1, 1 );

	glColor3f(1.0,1.0,1.0);
	glPushAttrib(GL_LIST_BIT);
	glListBase((GLuint) base);
	glCallLists(strlen(s), GL_UNSIGNED_BYTE, (unsigned *) s);
	glPopAttrib();

   if (init) endPrintStrings();
}


static void
setColor(int c)
{
      GLfloat ambientColor[4] = {0.0, 0.0, 0.0, 0.0};
      GLfloat mat_specular[4] = {0.8, 0.8, 0.8, 1.0 };

      glMaterialfv(GL_FRONT_AND_BACK,
        GL_AMBIENT, ambientColor);
      glMaterialfv(GL_FRONT_AND_BACK,
        GL_DIFFUSE, &materialColor[c][0]);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
      glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 130);
}


void cross(float *a,float *b, float *c)
{
/*

       calculates cross product:   a x b = c
                                   -   -   -
*/
 
      c[0] = a[1]*b[2] - a[2]*b[1];
      c[1] = a[2]*b[0] - a[0]*b[2];
      c[2] = a[0]*b[1] - a[1]*b[0];

}

float veclen(float *a)
{
      float vl;
      double tot;

      tot = a[0]*a[0]+a[1]*a[1]+a[2]*a[2];

      vl = 0.0;
      if (tot > 0.0) vl = (float) sqrt(tot);

      return(vl);

}

void improd(float *a, float *b, double *c)
{
      int i;
      float rimp, al, bl;

      rimp = 0.0;

      for (i=0; i<3; i++) rimp = rimp + a[i]*b[i];

      al = veclen(a);
      bl = veclen(b);

      if (al > 0.0 && bl > 0.0) {
         *c = (double) rimp / (veclen(a)*veclen(b));
      } else {
         *c = 0.0;
      }

}

void setAtomColor(int c)
{
      GLfloat tmp_Color[4];
      int i;
      GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };

      tmp_Color[0] = ((GLfloat) colorr[c+1]) / 65535.0 ; 
      tmp_Color[1] = ((GLfloat) colorg[c+1]) / 65535.0 ; 
      tmp_Color[2] = ((GLfloat) colorb[c+1]) / 65535.0 ; 
      tmp_Color[3] = 0.5;

      if (AmbAndDiff) {
         glMaterialfv(GL_FRONT_AND_BACK,
           GL_AMBIENT_AND_DIFFUSE, tmp_Color);
      } else {
         glMaterialfv(GL_FRONT_AND_BACK,
           GL_AMBIENT, AmbientNul);
         glMaterialfv(GL_FRONT_AND_BACK,
           GL_DIFFUSE, tmp_Color);
      }
      glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
      glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100);

}


void ogrod(int ic, float *p1, float *p2, double rad, int hiresol, int dsk)
{
      int i;
      double cosa;
      float angle, vl;
      float v1[3], v2[3], v3[3], p3[3];
      float todeg;

      
      todeg = 45.0 / atan(1.0);

      for (i=0; i<3; i++) {
         v1[i] = p2[i] - p1[i];
         v2[i] = 0.0;
         p3[i] = v1[i]/2.0 + p1[i];
      }
      v2[2] = 1.0;

      improd(v1,v2,&cosa);

      if (abs(cosa) == 1.0) {

         for (i=0; i<3; i++) v3[i] = 0.0;
         v3[1] = 1.0;
         angle = 0.0;
	 if (cosa < 0) angle = 180.0;

      } else {

         angle = (float) acos(cosa)*todeg;
         cross(v2,v1,v3);
         vl = veclen(v3);
         for (i=0; i<3; i++) v3[i] = v3[i] / vl;

      }


      glPushMatrix();
      glTranslatef(p1[0],p1[1],p1[2]);
      glRotatef(angle,v3[0],v3[1],v3[2]);
      setAtomColor(ic);
      vl = veclen(v1);
      if (hiresol) {
	 gluCylinder( cyl, rad, rad, vl, 15, 1 );
      } else {
	 gluCylinder( cyl, rad, rad, vl, 6, 1 );
	 gluQuadricOrientation(disk, (GLenum)GLU_INSIDE);
	 if (dsk) gluDisk(disk, 0, rad, 6, 1);
         glTranslatef(0.0,0.0,vl);
	 if (dsk == 2) gluDisk(disk, 0, rad, 6, 1);
	 gluQuadricOrientation(disk, (GLenum)GLU_OUTSIDE);
      }
      glPopMatrix();

}

void ogarrow(int ic, float *p1, float *p2, double rad)
{
      int i;
      double cosa, radf;
      float angle, vl, conelen;
      float v1[3], v2[3], v3[3], p3[3];
      float todeg;

      
      radf = 0.5*rad;
      conelen = 0.3;
      todeg = 45.0 / atan(1.0);

      for (i=0; i<3; i++) {
         v1[i] = p2[i] - p1[i];
         v2[i] = 0.0;
         p3[i] = v1[i]/2.0 + p1[i];
      }
      v2[2] = 1.0;

      improd(v1,v2,&cosa);

      if (abs(cosa) == 1.0) {

         for (i=0; i<3; i++) v3[i] = 0.0;
         v3[1] = 1.0;
         angle = 0.0;
	 if (cosa < 0) angle = 180.0;

      } else {

         angle = (float) acos(cosa)*todeg;
         cross(v2,v1,v3);
         vl = veclen(v3);
         for (i=0; i<3; i++) v3[i] = v3[i] / vl;

      }


      glPushMatrix();
      glTranslatef(p1[0],p1[1],p1[2]);
      glRotatef(angle,v3[0],v3[1],v3[2]);
      if (ic >= 0) setAtomColor(ic);
      vl = veclen(v1);
      v3[0] = 0.0; v3[1] = 0.0; v3[2] = vl - conelen;
      if (v3[2] <= 0.0) v3[2] = conelen;
      gluCylinder( cyl, radf, radf, v3[2], 15, 1 );
      glTranslatef(v3[0],v3[1],v3[2]);
      gluCylinder( cyl, rad, 0.0, conelen, 15, 1 );
      glPopMatrix();

}

void ogsphere(int ic, float *p1, double rad, int hiresol)
{

      glPushMatrix();
      glTranslatef(p1[0],p1[1],p1[2]);
      setAtomColor(ic);
      if (hiresol) {
	 if (*ipdbon && *xyz.iatoms > 500) {
	    gluSphere(sphere, rad, 12, 12);
	 } else {
	    gluSphere(sphere, rad, 20, 20);
	 }
      } else {
	 if (*ipdbon) {
	    gluSphere(sphere, rad, 5, 5);
	 } else {
	    gluSphere(sphere, rad, 10, 10);
	 }
      }
      glPopMatrix();

}

void ogatbnd(iatom,dijsq)
int iatom;
double *dijsq;
{
    double roddef;
    float tmp1[3],tmp2[3], tmp3[3];
    int i,j,k,l, ia,ja,ic,jc,it, ido, dsurf, dcell, doclr;
    int cell_up, cell_low;
    int issolv, ncon, lowres;

    for (l=0; l<3; l++) 
	tmp1[l] = (float) xyz.coo[iatom*3+l];
    *dijsq = tmp1[0]*tmp1[0] + tmp1[1]*tmp1[1] + tmp1[2]*tmp1[2];

    if (xyz.iaton[iatom] <= 0 || iatom < 0) return;

    cell_low = cell_up = 0;
    if (cellpnt->iclon) {
	cell_low = cellpnt->iclpnt[0]-1;
	cell_up = cell_low + 7;
    }

    lowres = 0;
    if (*ipdbon && !backb && *xyz.iatoms > 500 ) lowres = 1;

    doclr = 0;
    if (xyz.iatclr != NULL && !*atcol) doclr = 1;

    if (xyz.iaton[iatom] >= 1  && !(xyz.iresid[iatom] <= 0 
	&& xyz.iresid[iatom] >= -3 && xyz.ianz[iatom] == 100)) {

	 dsurf = 0;
	 if (iatom > *natorg-1 && *natorg != 0) dsurf = 1;

	 dcell = 0;
 	 if (dsurf && (iatom <= cell_up && iatom >= cell_low)) dcell = 1;

         ia = xyz.ianz[iatom];

	 if (doclr) {
            ic = xyz.iatclr[iatom]-1;
	 } else {
            ic = scalptr->icol[ia-1]-1;
	 }

	 if (!(dsurf && !dcell)) {

	 if (*ivdwpl && !dsurf) {

	   if (idorad) {
	      roddef = xyz.qat[iatom]/0.52917706;
	   } else {
	      roddef = scalptr->vdwr[ia-1]*1.4/0.52917706;
	   }
           ogsphere(ic,tmp1,roddef,hires);

	 } else {

	   issolv = 0;
	   it = xyz.iconn[iatom*(MXCON+1)];
	   if (*ipdbon && xyz.iresid[iatom] == -(*ishoh) && it) issolv = 1;

           roddef = 0.13/0.52917706;

           if (!issolv) {
              if ((lowres && !it) || !lowres) ogsphere(ic,tmp1,roddef,0);
	   }

           for (k=0; k<xyz.iconn[iatom*(MXCON+1)]; k++) {

            j = ABS(xyz.iconn[iatom*(MXCON+1)+k+1]) - 1;

	    if (xyz.iconn[iatom*(MXCON+1)+k+1] < 0) 
		    roddef = (0.13/0.52917706)/4.0;
            ja = xyz.ianz[j];
	    if (doclr) {
               jc = xyz.iatclr[j]-1;
	    } else {
               jc = scalptr->icol[ja-1]-1;
	    }
            for (l=0; l<3; l++) 
		tmp2[l] = (float) xyz.coo[j*3+l];

            ido = 1;

            if (ic == jc) {
               if (j > iatom) {
                  for (l=0; l<3; l++) tmp3[l] = tmp2[l];
		  ido = 2;
               } else {
                  ido = 0;
               }
            } else {
               for (l=0; l<3; l++) 
                  tmp3[l] = (tmp2[l] - tmp1[l])/2.0 + tmp1[l];
            }
  
            if (ido) {
		if (issolv)
		   ogrod(ic,tmp1,tmp3,roddef,0,0);
		else
		   if (lowres) ogrod(ic,tmp1,tmp3,roddef,0,ido);
		   else ogrod(ic,tmp1,tmp3,roddef,1,0);
	    }

	   } /* end for k */
	 } /* end if (*ivdwpl && !dsurf)*/
	 } 
     } /* end if (xyz.iaton[i] >= 1 */
}

#if defined(VMS) || defined(UNDERSC)
void ogmon()
#else
#ifdef CRAY
void OGMON()
#else
void ogmon_()
#endif
#endif
{
    int i,i1,i2,j,l,doclr,ia,ic;
    double roddef;
    float tmp1[3],tmp2[3], tmp3[3];

      roddef = (0.13/0.52917706)/4.0;
      doclr = 0;
      if (xyz.iatclr != NULL && !*atcol) doclr = 1;

      theMon = glGenLists(1);
      glNewList(theMon, GL_COMPILE_AND_EXECUTE);

      for (i=0; i<monptr->ndm; i++) {

	 i1 = monptr->idmon[i][0] - 1;
	 i2 = monptr->idmon[i][1] - 1;

	 for (l=0; l<3; l++) 
	    tmp1[l] = (float) xyz.coo[i1*3+l];
	 for (l=0; l<3; l++) 
	    tmp2[l] = (float) xyz.coo[i2*3+l];
	 for (l=0; l<3; l++) 
	    tmp3[l] = (tmp2[l] - tmp1[l])/2.0 + tmp1[l];

         ia = xyz.ianz[i1];
	 if (doclr) {
            ic = xyz.iatclr[i1]-1;
	 } else {
            ic = scalptr->icol[ia-1]-1;
	 }

	 ogrod(ic,tmp1,tmp3,roddef,0,0);

         ia = xyz.ianz[i2];
	 if (doclr) {
            ic = xyz.iatclr[i2]-1;
	 } else {
            ic = scalptr->icol[ia-1]-1;
	 }

	 ogrod(ic,tmp2,tmp3,roddef,0,0);
      }

      glEndList();
}

void ogunsel()
{
 int j;

    for (j=0; j < *zmptr.nz; j++) xyz.iaton[j] = 1;
    update_sel = 1;
}

void ogsel()
{
  int i;
  float tmp[3];
  GLdouble srad;

  theSel = glGenLists(1);
  glNewList(theSel, GL_COMPILE_AND_EXECUTE);

  for (i=0; i<*xyz.iatoms; i++) {
        tmp[0] = (float) (xyz.coo[i*3]);
        tmp[1] = (float) (xyz.coo[i*3+1]);
        tmp[2] = (float) (xyz.coo[i*3+2]);
        if (xyz.iaton[i] >= 2)  {
           if (ZMEup || cflag || ATMup || SelDel || ONIup || scoup) {
	      srad = 3.0;
	      if (!*ivdwpl) srad = (1.5*0.13/0.52917706);
	      ogsphere(rimcols[xyz.iaton[i]]-1,tmp,srad,0);
	   }
	}
  }
  glEndList();
  update_sel = 0;
}

void ogbck(isec)
int isec;
{
      int i,j,ires;
      double dijsq;

	if (!(has_opengl && *fancy)) return;

	for (ires = 1; ires < calfptr->ncalf+1; ires++ ) {
	   if (isal[ires-1] == isec) {
#if defined(VMS) || defined(UNDERSC)
		getpdb(&ires,ipdb,ihpdb);
#else
#ifdef CRAY
		GETPDB(&ires,ipdb,ihpdb);
#else
		getpdb_(&ires,ipdb,ihpdb);
#endif
#endif
		theBck[ires-1] = glGenLists(1);
		glNewList(theBck[ires-1], GL_COMPILE);
		
		for (i=0; i<3; i++) {
		   xyz.iaton[ipdb[i]-1] = 1;
		   ogatbnd(ipdb[i]-1,&dijsq);
		}
		glEndList();
	   }

	}
}

void ogres(ires,iopt,iupd)
int ires;
int iopt;
int iupd;
{
      int i,j;
      double dijsq;

      if (!(*fancy && has_opengl)) {
	update_struct();
	return;
      }

      if (!calfptr->reson[ires-1]) return;
/*
      glDeleteLists(theRes[ires-1],1);
      theRes[ires-1] = -1;
*/


#if defined(VMS) || defined(UNDERSC)
      getpdb(&ires,ipdb,ihpdb);
#else
#ifdef CRAY
      GETPDB(&ires,ipdb,ihpdb);
#else
      getpdb_(&ires,ipdb,ihpdb);
#endif
#endif

      if (!glIsList(theRes[ires-1])) theRes[ires-1] = glGenLists(1);
      glNewList(theRes[ires-1], GL_COMPILE);

      for (i=0; i<MXSYM; i++) {
	if (ipdb[i] > 0) {
	   ogatbnd(ipdb[i]-1,&dijsq);
	   if (!iopt && (!addfile || !poszset) ) if (dijsq > posz) posz = dijsq;
	}
      }
      for (i=0; i<3*MXHSYM; i++) {
	if (ihpdb[i] > 0) {
	   ogatbnd(ihpdb[i]-1,&dijsq);
	   if (!iopt && (!addfile || !poszset) ) if (dijsq > posz) posz = dijsq;
	}
      }

      glEndList();
      if (iupd) dispsf();
}


void ogpdb(int iopt)
{
    double roddef, dijsq;
    float tmp1[3];
    int ires, i,j,k,l,m, doclr, ioff, num_atoms;
    int cell_low, cell_up;

    if (!*fancy) return;

    glXMakeCurrent(display, win, cx);
    if (!iopt && !addfile) posz = 0.0;

    glPopMatrix();
    glPushMatrix();

    if (NMols >= MXMOL - 1) return;

    if (NMols != -1 && !iopt) {
       NMols = -1;
       NMols++;
/*
       glDeleteLists(theMol[NMols],1);
       theMol[NMols] = -1;
*/
    } else NMols++;

    if (*xyz.iatoms == 0) return;

    if (iopt) {
	glDeleteLists(theMol[1],1);
	theMol[1] = -1;
	NMols = 1;
    }

/* do residues */

    for (ires=0;ires < calfptr->ncalf;ires++) {
	l = calfptr->icalf[ires][0];
	for (i=0; i<3; i++) 
	   tmp1[i] = (float) xyz.coo[l*3+i];
	dijsq = tmp1[0]*tmp1[0] + tmp1[1]*tmp1[1] + tmp1[2]*tmp1[2];
	if (!iopt && (!addfile || !poszset) ) if (dijsq > posz) posz = dijsq;
    }

    if (!iopt) {
	for ( ires = 1; ires < calfptr->ncalf+1; ires++ ) {
	   ogres(ires,iopt,0);
	}
    }


/* do other non amino atoms */

    theMol[NMols] = glGenLists(1);
    glNewList(theMol[NMols], GL_COMPILE);

    ioff = 0;
    num_atoms = *xyz.iatoms;
    if (!iopt && (*irtcel && *ialtyp) && *iscst < num_atoms) 
	num_atoms = *iscst;
    if (iopt) {
	ioff = *iscst;
        num_atoms = *nscnd;
    }

    for (i=ioff; i<ioff+num_atoms; i++) {
       if (xyz.iresid[i] < -3) {
	ogatbnd(i,&dijsq);
	if (!iopt && (!addfile || !poszset) ) if (dijsq > posz) posz = dijsq;
       }
    } 

    glEndList();

    if (!iopt && (!addfile || !poszset) ) {
       if (posz > 0.0) posz = sqrt(posz);
       scl = posz;
       if (scl == 0.0) scl = 1.0;
       posz = -1.6*posz;
       for (l=0; l<3; l++) light2_position[l] = light2_position_def[l]*scl*5.0;
       poszset = 1;
    }

    dispsf();
}


void ogmoll(int iopt)
{
    double dijsq;
    int i,j,k,l, doclr, ioff, num_atoms;
    int cell_low, cell_up;


    if (!*fancy) return;

    if (*ipdbon) {
	ogpdb(iopt);
	return;
    }

    glXMakeCurrent(display, win, cx);
    if (!iopt && !addfile) posz = 0.0;

    glPopMatrix();
    glPushMatrix();

    if (NMols >= MXMOL - 1) return;

    if (NMols != -1 && !iopt) {
       NMols = -1;
       NMols++;
       glDeleteLists(theMol[NMols],1);
       theMol[NMols] = -1;
    } else NMols++;

    if (*xyz.iatoms == 0) return;

    if (iopt) {
	glDeleteLists(theMol[1],1);
	theMol[1] = -1;
	NMols = 1;
    }

    theMol[NMols] = glGenLists(1);
    glNewList(theMol[NMols], GL_COMPILE);


    ioff = 0;
    num_atoms = *xyz.iatoms;
    if (!iopt && (*irtcel && *ialtyp) && *iscst < num_atoms) 
	num_atoms = *iscst;
    if (iopt) {
	ioff = *iscst;
        num_atoms = *nscnd;
    }

    for (i=ioff; i<ioff+num_atoms; i++) {
       ogatbnd(i,&dijsq);
       if (!iopt && (!addfile || !poszset) ) if (dijsq > posz) posz = dijsq;
    } 

    glEndList();

    if (!iopt && (!addfile || !poszset) ) {
       if (posz > 0.0) posz = sqrt(posz);
       scl = posz;
       if (scl == 0.0) scl = 1.0;
       posz = -1.6*posz;
       for (l=0; l<3; l++) light2_position[l] = light2_position_def[l]*scl*5.0;
       poszset = 1;
    }

    dispsf();
}

void ogmlxyz()
{
    double roddef, dmaxsq, dijsq, dsq, adj;
    float tmp1[3],tmp2[3], tmp3[3];
    int i,j,k,l, ia, ic, ja, ido;


    if (!*ifdogl) return;

#if defined(VMS) || defined(UNDERSC)
    dodcnt();
#else
#ifdef CRAY
    DODCNT();
#else
    dodcnt_();
#endif
#endif

    adj = *adjuss;
    glXMakeCurrent(display, win, cx);
    posz = 0.0;
    dijsq = 0.0;

    roddef = (0.13/adj);

    glPopMatrix();
    glPushMatrix();

    glDeleteLists(theMol[0],1);
    theMol[0] = -1;
    NMols = 1;

    theMol[0] = glGenLists(1);
    glNewList(theMol[0], GL_COMPILE);


    for (i=0; i<*natoms; i++) {

         ia = NAT[i];
         ic = scalptr->icol[ia-1]-1;


         for (l=0; l<3; l++) 
            tmp1[l] = (float) XYZ->xyz[i][l];

	 dijsq = tmp1[0]*tmp1[0] + tmp1[1]*tmp1[1] + tmp1[2]*tmp1[2];
	 if (dijsq > 0.0) dijsq = sqrt(dijsq);
	 if (dijsq > posz) posz = dijsq;


	 if (*ivdwpl) {

	   roddef = scalptr->vdwr[ia-1]*1.4/adj;
           ogsphere(ic,tmp1,roddef,hires);

	 } else {

           roddef = (0.13/adj);

           ogsphere(ic,tmp1,roddef,0);

           for (j=0; j<*natoms; j++) {

            ja = NAT[j];
            for (l=0; l<3; l++) 
	       tmp2[l] = (float) XYZ->xyz[j][l];

	    dsq = 0;
            for (l=0; l<3; l++) {
                tmp3[l] = (tmp2[l] - tmp1[l]);
		dsq = dsq + tmp3[l]*tmp3[l];
	    }
            dmaxsq = (scalptr->vdwr[ia-1] + scalptr->vdwr[ja-1])/adj;
            dmaxsq = dmaxsq * dmaxsq;

	    if (dsq < dmaxsq) ido = 1;
	    else ido = 0;

            if (ja == ia) {
               if (j > i) {
                  for (l=0; l<3; l++) tmp3[l] = tmp2[l];
               } else {
                  ido = 0;
               }
            } else {
               for (l=0; l<3; l++) 
                  tmp3[l] = (tmp2[l] - tmp1[l])/2.0 + tmp1[l];
            }
  
            if (ido) ogrod(ic,tmp1,tmp3,roddef,1,0);

	   } /* end for k */
	 } /* end if (*ivdwpl)*/
    } /* end for (i=0; i<*natoms; i++) { */


    glEndList();

    scl = posz;
    if (scl == 0.0) scl = 1.0;
    posz = -1.6*posz;
    for (l=0; l<3; l++) light2_position[l] = light2_position_def[l]*scl*5.0;

    dispsf();
}

void oglines()
{
    double dmaxsq, dijsq, colv[3];
    float tmp1[3],tmp2[3], tmp3[3];
    int i,j,k,l, ia, ic, ja, ido, doclr, dsurf ;



    doclr = 0;
    if (xyz.iatclr != NULL && !*atcol) doclr = 1;

    if (NMols >= MXMOL - 1) return;
    if (*xyz.iatoms == 0) return;

    if (theLines > 0) glDeleteLists(theLines,1);
    theLines = -1;

    theLines = glGenLists(1);
    glNewList(theLines, GL_COMPILE);
    glDisable(GL_LIGHTING);
    glEnable(GL_COLOR_MATERIAL);
    glBegin(GL_LINES);

    for (i=0; i<*xyz.iatoms; i++) {

	if (xyz.iaton[i] >= 1  && 
	   !(xyz.iresid[i] <= 0 && xyz.iresid[i] >= -3 && xyz.ianz[i] == 100)) {

	 dsurf = 0;
	 if (i >= *natorg && *natorg != 0) dsurf = 1;

	 if (dsurf) {

            ia = xyz.ianz[i];
	    if (doclr || *doesp) {
               ic = xyz.iatclr[i]-1;
	    } else {
               ic = scalptr->icol[ia-1]-1;
            }
            for (l=0; l<3; l++) 
               tmp1[l] = (float) xyz.coo[i*3+l];


           for (k=0; k<xyz.iconn[i*(MXCON+1)]; k++) {

            j = ABS(xyz.iconn[i*(MXCON+1)+k+1]) - 1;
            ja = xyz.ianz[j];

            for (l=0; l<3; l++) 
	       tmp2[l] = (float) xyz.coo[j*3+l];


            ido = 1;
            if (ja == ia) {
               if (j > i) {
                  for (l=0; l<3; l++) tmp3[l] = tmp2[l];
               } else {
                  ido = 0;
               }
            } else {
               for (l=0; l<3; l++) 
                  tmp3[l] = (tmp2[l] - tmp1[l])/2.0 + tmp1[l];
            }
 
            if (ido) {
	       colv[0] = ((GLdouble) colorr[ic+1]) / 65535.0 ; 
	       colv[1] = ((GLdouble) colorg[ic+1]) / 65535.0 ; 
	       colv[2] = ((GLdouble) colorb[ic+1]) / 65535.0 ; 
	       glColor4d(colv[0],colv[1],colv[2],tr_val);
	       glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
	       glVertex3d(tmp3[0],tmp3[1],tmp3[2]);

	    }

	   }
	 }
	}
    }


    glEnd();
    glDisable(GL_COLOR_MATERIAL);
    glEnable(GL_LIGHTING);
    glEndList();

}

void ogforces()
{
    double colv[3], roddef;
    float tmp1[3],tmp2[3], tmp3[3];
    int i,j,k,l,ic;

    roddef = (0.13/0.52917706);

    if (theForces > 0) glDeleteLists(theForces,1);
    theForces = -1;
    theForces = glGenLists(1);
    glNewList(theForces, GL_COMPILE);

    ic = 0;

    for (i=0; i<*xyz.iatoms; i++) {

	if (xyz.iaton[i] >= 1  && 
	   !(xyz.iresid[i] <= 0 && xyz.iresid[i] >= -3 && xyz.ianz[i] == 100)) {



           for (k=0; k<3; k++) 
             tmp1[k] = (float) xyz.coo[i*3+k];

           for (k=0; k<3; k++) 
             tmp3[k] = (float) fcptr->fc[i][k];

 
	   colv[0] = ((GLdouble) colorr[ic+1]) / 65535.0 ; 
	   colv[1] = ((GLdouble) colorg[ic+1]) / 65535.0 ; 
	   colv[2] = ((GLdouble) colorb[ic+1]) / 65535.0 ; 
/*
	   glColor4d(colv[0],colv[1],colv[2],tr_val);
	   glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
	   glVertex3d(tmp3[0],tmp3[1],tmp3[2]);
*/
           ogarrow(ic,tmp1,tmp3,roddef);


	}
    }


    glEndList();

}

void ogdipole()
{
    double colv[3], tmp2[3], roddef;
    float tmp1[3], tmp3[3];
    int i,k,ic;

    roddef = (0.13/0.52917706);

    glDeleteLists(theDipole,1);

    theDipole = -1;
    theDipole = glGenLists(1);

    glNewList(theDipole, GL_COMPILE);

    ic = 2;

#if defined(VMS) || defined(UNDERSC)
    cntvec(
#else

#ifdef CRAY
    CNTVEC(
#else
    cntvec_(
#endif
#endif
	tmp2,xyz.coo,xyz.ianz,xyz.iatoms);

    for (k=0; k<3; k++) 
        tmp1[k] = (float) tmp2[k];

    for (k=0; k<3; k++) 
        tmp3[k] = (float) (qdpptr->dipo[k] + tmp2[k]);

    colv[0] = ((GLdouble) colorr[ic+1]) / 65535.0 ; 
    colv[1] = ((GLdouble) colorg[ic+1]) / 65535.0 ; 
    colv[2] = ((GLdouble) colorb[ic+1]) / 65535.0 ; 

    ogarrow(ic,tmp1,tmp3,roddef);

    glEndList();

}

void ogaxes()
{
    double roddef;
    int i,ic=-1;

    roddef = (0.13/0.52917706);

    glDeleteLists(theAxes,1);

    theAxes = -1;
    theAxes = glGenLists(1);

    glNewList(theAxes, GL_COMPILE);

    
    ogsphere(1,&AxesXYZ[0][0],0.5*roddef,0);

    for (i=1; i<4; i++) {
	glMaterialfv(GL_FRONT_AND_BACK,
           GL_AMBIENT_AND_DIFFUSE, &AxesCol[i][0]);
	ogarrow(ic,&AxesXYZ[0][0],&AxesXYZ[i][0],roddef);
    }

    glEndList();

}

#if defined(VMS) || defined(UNDERSC)
void ogbegg(isurf,mapped)
#else
#ifdef CRAY
void OGBEGG(isurf,mapped)
#else
void ogbegg_(isurf,mapped)
#endif
#endif
int *isurf;
int *mapped;
{
      int itrns,isf,i;

      glXMakeCurrent(display, win, cx);
      glPopMatrix();
      glPushMatrix();

      itrns = 0;
      if (*isurf < 0) {
	  itrns = 1;
      }
      TRANS = itrns;
      isf = abs(*isurf); isf--;

      NSurf++;
      if (theSurf[NSurf-1] > 0) glDeleteLists(theSurf[NSurf-1],1);
      theSurf[NSurf-1] = -1;
      theSurf[NSurf-1] = glGenLists(1);
      SSon[NSurf-1] = 1;

      for (i=0; i<3; i++) {
	diffuseColor[NSurf-1][i] = cursrfcol[isf][i];
	specularColor[NSurf-1][i] = specColor[i];
      }

      glNewList(theSurf[NSurf-1], GL_COMPILE);

      if (*mapped) {
        glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE);
	glEnable(GL_COLOR_MATERIAL);
      }

      glBegin(GL_TRIANGLES);
}

#if defined(VMS) || defined(UNDERSC)
void ogendd()
#else
#ifdef CRAY
void OGENDD()
#else
void ogendd_()
#endif
#endif
{
      glEnd();
      glDisable(GL_BLEND);
      glDisable(GL_COLOR_MATERIAL);
      glDisable(GL_CULL_FACE);
      glEndList();
}

#if defined(VMS) || defined(UNDERSC)
void ogcoll(double *v1, double *v2, double *v3)
#else
#ifdef CRAY
void OGCOLL(double *v1, double *v2, double *v3)
#else
void ogcoll_(double *v1, double *v2, double *v3)
#endif
#endif
{
	glColor4d(*v1,*v2,*v3,tr_val);
}

void ogelev()
{
      int i;

      glPopMatrix();
      glPushMatrix();

      NSurf++;
      theSurf[NSurf-1] = glGenLists(1); 
      glNewList(theSurf[NSurf-1], GL_COMPILE);

      for (i=0; i<4; i++)
	diffuseColor[NSurf-1][i] = materialColor[ecol][i];

      glBegin(GL_QUADS);
}

#if defined(VMS) || defined(UNDERSC)
void ogribb()
#else
#ifdef CRAY
void OGRIBB()
#else
void ogribb_()
#endif
#endif
{
      int i;

      glPopMatrix();
      glPushMatrix();

      NSurf++;
      if (theSurf[NSurf-1] > 0) glDeleteLists(theSurf[NSurf-1],1);
      theSurf[NSurf-1] = -1;
      theSurf[NSurf-1] = glGenLists(1); 
      glNewList(theSurf[NSurf-1], GL_COMPILE);

      glBegin(GL_QUADS);
}

putbyte(outf,val)
FILE *outf;
unsigned char val;
{
        unsigned char buf[1];

        buf[0] = val;
        fwrite(buf,1,1,outf);
}

putshort(outf,val)
FILE *outf;
unsigned short val;
{
        unsigned char buf[2];

        buf[0] = (val>>8);
        buf[1] = (val>>0);
        fwrite(buf,2,1,outf);
    }

static int putlong(outf,val)
FILE *outf;
unsigned long val;
{
	unsigned char buf[4];

	buf[0] = (val>>24);
	buf[1] = (val>>16);
	buf[2] = (val>>8);
	buf[3] = (val>>0);
	return fwrite(buf,4,1,outf);
}

int WOGLGIF(filename)
    char *filename;
{
  int   ColorMapSize, BitsPerPixel;
  int   i,j,nc;
  int   numcols;
  Byte *imag;
  Byte  rmap[256],gmap[256],bmap[256];

  int rowlen;
  GLubyte *rgbbuf;
  GLint viewport[4];

  GIFFile = fopen(filename,"w");
  if (!GIFFile) {
	fprintf(stderr,"Output Error: Unable to create GIF file %s\n",filename);
	return(0);
  }

  glGetIntegerv(GL_VIEWPORT, viewport);

  rowlen = viewport[2];
  if (width < rowlen) rowlen = width;

  glPixelStorei(GL_PACK_ROW_LENGTH,rowlen);
  glPixelStorei(GL_PACK_ALIGNMENT,1);

  rgbbuf = (GLubyte *)malloc(3*rowlen*height*sizeof(GLubyte));
  if (!rgbbuf) {
       fprintf(stderr,"moldenogl: couldn't allocate memory\n");
       fclose(GIFFile);
       return(1);
  }
  glReadBuffer(GL_FRONT);
  glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,rgbbuf);

  numcols = 256;
  imag = (Byte *) malloc((size_t) (width * height));

  if (!imag) {
	fprintf(stderr,"Unable to malloc in WriteGIF()");
	return(1);
  }

  clmap[0] = (unsigned char *) rmap;
  clmap[1] = (unsigned char *) gmap;
  clmap[2] = (unsigned char *) bmap;

  if (quant((Byte *) rgbbuf, width, height, imag, numcols) ) {
	free(imag);  return(1); 
  }
  
  for (i=0; i<numcols; i++) { 
	pix2col[i] = red[i] = green[i] = blue[i] = 0;
  }

  nc = 0;

  for (i=0; i<numcols; i++) {
    for (j=0; j<i; j++) {
      if (rmap[i] == rmap[j] && gmap[i] == gmap[j] && 
	  bmap[i] == bmap[j]) break;
    }

    if (j==i) {
      pix2col[i] = nc;
      red[nc]   = rmap[i];
      green[nc] = gmap[i];
      blue[nc]  = bmap[i];
      nc++;
    }
    else pix2col[i] = pix2col[j];
  }

  for (BitsPerPixel=1; BitsPerPixel<8; BitsPerPixel++)
    if ( (1<<BitsPerPixel) >= nc) break;
  
  ColorMapSize = 1 << BitsPerPixel;
	
  fwrite("GIF87a", (size_t) 1, (size_t) 6, GIFFile);
  fputc(width&0xff,GIFFile);  fputc((width>>8)&0xff,GIFFile);
  fputc(height&0xff,GIFFile);  fputc((height>>8)&0xff,GIFFile);

  fputc(0xf0|(BitsPerPixel-1),GIFFile);
  fputc(0, GIFFile);
  fputc(0, GIFFile);

  for (i=0; i<ColorMapSize; i++) { 
      fputc(red[i], GIFFile);
      fputc(green[i], GIFFile);
      fputc(blue[i], GIFFile);
  }

  fputc( ',', GIFFile );

  fputc(0x00,GIFFile); fputc(0x00,GIFFile);
  fputc(0x00,GIFFile); fputc(0x00,GIFFile);
  fputc(width&0xff,GIFFile); fputc((width>>8)&0xff,GIFFile);
  fputc(height&0xff,GIFFile); fputc((height>>8)&0xff,GIFFile);
  fputc(0x00,GIFFile); fputc(BitsPerPixel,GIFFile);

  compress(BitsPerPixel, nc, imag, 2);

  fputc(';',GIFFile);
  fclose(GIFFile);
  free(rgbbuf);
  free(imag);

  return(0);
}

save_rgb(rgbfile)
char *rgbfile;
{
	FILE *of;
        char iname[80];
        int i, k, x, y, rowlen;
	int Xsize, Ysize;
	GLubyte *rgbbuf;
	GLint viewport[4];

        of = fopen(rgbfile,"w");

        if (!of) {
            fprintf(stderr,"moldenogl: can't open output file\n");
            return;
        }

	glGetIntegerv(GL_VIEWPORT, viewport);
	Xsize = width;
	Ysize = height;

	rowlen = viewport[2];
	if (width < rowlen) rowlen = width;

	glPixelStorei(GL_PACK_ROW_LENGTH,rowlen);
	glPixelStorei(GL_PACK_ALIGNMENT,1);

	rgbbuf = (GLubyte *)malloc(3*rowlen*height*sizeof(GLubyte));
	if (!rgbbuf) {
	   fprintf(stderr,"moldenogl: couldn't allocate memory\n");
	   fclose(of);
	   return;
	}
	glReadBuffer(GL_FRONT);
	glReadPixels(viewport[0],viewport[1],Xsize,Ysize,GL_RGB,GL_UNSIGNED_BYTE,rgbbuf);

        putshort(of,474);	/* MAGIC		*/
        putbyte(of,0);		/* STORAGE is VERBATIM	*/
        putbyte(of,257);	/* BPC is 257          	*/
        putshort(of,3);		/* DIMENSION is 3	*/
        putshort(of,Xsize);	/* XSIZE               	*/
        putshort(of,Ysize);	/* YSIZE               	*/
        putshort(of,3);		/* ZSIZE               	*/
        putlong(of,0);		/* PIXMIN is 0         	*/
        putlong(of,255);	/* PIXMAX is 255       	*/
        for(i=0; i<4; i++)	/* DUMMY 4 bytes 	*/
            putbyte(of,0);
        strcpy(iname,"Moldenogl");
        fwrite(iname,80,1,of);	/* IMAGENAME  		*/
        putlong(of,0);		/* COLORMAP is 0 	*/

        for(i=0; i<404; i++)
            putbyte(of,0);

/* red */
        k=0;
        for(i=0;i< Xsize*Ysize; i++){
         fwrite( &rgbbuf[k] ,sizeof(*rgbbuf), 1, of);
         k=k+3;
        }

/* green */
        k=0;
        for(i=0;i< Xsize*Ysize; i++){
         fwrite( &rgbbuf[k+1] ,sizeof(*rgbbuf), 1, of);
         k=k+3;
        }

/* blue */
        k=0;
        for(i=0;i< Xsize*Ysize; i++){
         fwrite( &rgbbuf[k+2] ,sizeof(*rgbbuf), 1, of);
         k=k+3;
        }

        fclose(of);
	free(rgbbuf);
}

unsigned char bmp_header[]=
{ 'B','M', 0,0,0,0, 0,0, 0,0, 54,0,0,0,
  40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0, 24,0, 0,0,0,0, 0,0,0,0,
  0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };

static void WLSBL(val,arr)
    int val;
    char* arr;
{
    arr[0] = (char) (val&0xff);
    arr[1] = (char) ((val>>8) &0xff);
    arr[2] = (char) ((val>>16)&0xff);
    arr[3] = (char) ((val>>24)&0xff);
}

save_bmp()
{ int i,j;
  FILE *fp;
  GLubyte *rgbbuf;
  GLubyte rgbtmp[3];
  int Xsize, Ysize, rowlen;
  int pad;

#ifdef WIN32
  if ((fp=fopen("mogl.bmp","wb"))==NULL) return(1);
#else
  if ((fp=fopen("moldenogl.bmp","wb"))==NULL) return(1);
#endif

  Xsize = width;
  Ysize = height;

  rowlen = Vsize;
  if (Xsize < Vsize) rowlen = Xsize;

  glPixelStorei(GL_PACK_ROW_LENGTH,rowlen);
  glPixelStorei(GL_PACK_ALIGNMENT,1);

  rgbbuf = (GLubyte *)malloc(3*rowlen*Ysize*sizeof(GLubyte));
  if (!rgbbuf) {
	fprintf(stderr,"moldenogl: couldn't allocate memory\n");
	fclose(fp);
	return;
  }
  glReadBuffer(GL_FRONT);
  glReadPixels(0,0,Xsize,Ysize,GL_RGB,GL_UNSIGNED_BYTE,rgbbuf);

/* The number of bytes on a screenline should be wholly devisible by 4 */

  pad = (Xsize*3)%4;
  if (pad) pad = 4 - pad;

  WLSBL((int) (3*Xsize+pad)*Ysize+54,bmp_header+2);
  WLSBL((int) Xsize,bmp_header+18);
  WLSBL((int) Ysize,bmp_header+22);
  WLSBL((int) 3*Xsize*Ysize,bmp_header+34);

  fwrite(bmp_header,1,54,fp);

  for (i=0;i<Ysize;i++) {
    for (j=0;j<Xsize;j++) {
	rgbtmp[0] = rgbbuf[(j+Xsize*i)*3+2];
	rgbtmp[1] = rgbbuf[(j+Xsize*i)*3+1];
	rgbtmp[2] = rgbbuf[(j+Xsize*i)*3+0];
	fwrite(rgbtmp,3,1,fp);
    }
    rgbtmp[0] = (char) 0;
    for (j=0;j<pad;j++) fwrite(rgbtmp,1,1,fp);
  }

  fclose(fp);
  free(rgbbuf);
}


void empty_model()
{
  int i;

  glDeleteLists(theMol[0],1);
  theMol[0] = (GLuint) -1;
  for (i=0; i<NSurf; i++) {
      glDeleteLists(theSurf[i],1);
      theSurf[i] = -1;
      if (!addfile) SSon[i] = 0;
  }
  if (*ipdbon) {
      for (i=0; i<calfptr->ncalf; i++) {
	glDeleteLists(theRes[i],1);
	theRes[i] = -1;
      }
  }
  glDeleteLists(theLines,1);
  theLines = -1;
  glDeleteLists(theForces,1);
  theForces = -1;
  glDeleteLists(theMon,1);
  theMon = -1;
  glDeleteLists(theSel,1);
  theSel = -1;
  SSdone = 0;
  NSurf = 0;

  if (((*fancy && !denmode) || (*ifdogl && denmode)) && has_opengl) dispsf();
}

void dispsf()
{
  int i,j,Ca,sizt;
  int zero = 0;
  double ca,sa,x,y,z,tn[3],sc;
  GLdouble modelMatrix[16];
  GLdouble projMatrix[16];
  GLint viewport[4];
  GLdouble tmp1[3],xt,yt,zt,srad;
  float tmp[3];
  float axes_light[] = {0.0, 0.0, -4.0, 1};

  glXMakeCurrent(display, win, cx);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

  for (i=0; i < 3; i++) {
     RR[i][1] = rotptr->rx[i];
     RR[i][0] = -rotptr->ry[i];
     RR[i][2] = rotptr->rz[i];
  }

  sizt = width;
  if (height > width) sizt = height;
  if (Vsize != sizt) Reshape();

  if (BGmode) bckgrad();

  if (AXES) {

/* create the projection and model matrix for the axes */

     glMatrixMode(GL_PROJECTION);
     glLoadIdentity();
     glMatrixMode(GL_MODELVIEW);
     glLoadIdentity();
     glLightfv(GL_LIGHT2, GL_POSITION, axes_light);
     glScalef(1.0,1.0,-1.0);
     glTranslatef(-0.8 ,-0.8, 0.0);
     glScalef(0.1,0.1,0.1);
     glMultMatrixd((const GLdouble *) RR);
     glCallList(theAxes);

     glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
     glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
     glGetIntegerv(GL_VIEWPORT,viewport);

     for (i=1; i<4; i++) {
        if (gluProject((GLdouble) AxesXYZ[i][0],(GLdouble) AxesXYZ[i][1],(GLdouble) AxesXYZ[i][2],modelMatrix,projMatrix,viewport,&xt,&yt,&zt)) {
           AxesProj[i][0] = (height - (int) yt);
           AxesProj[i][1] = (int) xt;
	}
     }
/* 
   remark: there is a difference between lighting in xwindow and OpenGL
           the opengl z-axis is pointing the opposite direction of the
           xwindows z-axis (with respect to shading
   The glScalef(1.0,1.0,-1.0); has to do with that
*/
  }

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  if (*persp) {
	glFrustum(-0.2,0.2,-0.2,0.2,0.3,600);
  } else {
	glOrtho(1.0,-1.0,1.0,-1.0,-10.0,300.0);
  }

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  if (*persp) {
	glTranslatef( 1.0*posptr->yv, -1.0*posptr->xv, -2.0*posptr->zv);
  } else {
	sc = -1.0 / scalptr->scal;
	glScalef(sc,sc,-1.0*sc);
	glTranslatef( 1.0*posptr->yv, -1.0*posptr->xv, 0.0);
  }

  glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
  if (DoLights) {
     glPushMatrix();
     glTranslatef(light0_position[0],light0_position[1],light0_position[2]);
     gluSphere(sphere, 1, 10, 10);
     glPopMatrix();
  }

  glLightfv(GL_LIGHT1, GL_POSITION, light1_position);
  if (DoLights) {
     glPushMatrix();
     glTranslatef(light1_position[0],light1_position[1],light1_position[2]);
     gluSphere(sphere, 1, 10, 10);
     glPopMatrix();
  }

  glLightfv(GL_LIGHT2, GL_POSITION, light2_position);
  if (DoLights) {
     glPushMatrix();
     glTranslatef(light2_position[0],light2_position[1],light2_position[2]);
     gluSphere(sphere, 1, 10, 10);
     glPopMatrix();
  }

  EnableFog();

  glMultMatrixd((const GLdouble *) RR);

  if (denmode) glTranslatef(-rotptr->td[0] ,-rotptr->td[1],-rotptr->td[2]);
  else glTranslatef(-rotptr->t[0] ,-rotptr->t[1],-rotptr->t[2]);

  glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
  glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
  glGetIntegerv(GL_VIEWPORT,viewport);

  for (i=0; i<*xyz.iatoms; i++) {
        tmp1[0] = (GLdouble) (xyz.coo[i*3]);
        tmp1[1] = (GLdouble) (xyz.coo[i*3+1]);
        tmp1[2] = (GLdouble) (xyz.coo[i*3+2]);
        if (gluProject(tmp1[0],tmp1[1],tmp1[2],modelMatrix,projMatrix,viewport,&xt,&yt,&zt)) {
           xyz.ixp[i] = (height - (int) yt);
           xyz.iyp[i] = (int) xt;
           xyz.rzp[i] = (double) zt;
	   if (*persp && zt > 1.0) xyz.rzp[i] = -1.0;
	}
  }


  if (update_sel) {
     ogsel();
  } else {
     glCallList(theSel);
  }

  if (*ipdbon) {
	for (i=0; i<calfptr->ncalf; i++) {
          if (calfptr->reson[i]) {glCallList(theRes[i]);}
	  else {
	     if (!calfptr->ihet[isal[i]]) {glCallList(theBck[i]);}
	  }
	}
  }

  glCallList(theMol[0]);
  if (*irtcel && *ialtyp) glCallList(theMol[1]);

  if (monptr->ndm) glCallList(theMon);

  glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
  glCallList(theLines);

  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  if (*forces_yes_no) glCallList(theForces);
  if (qdpptr->idipon) glCallList(theDipole);

  if (DoLines) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
  else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

  for (i=0; i<NSurf; i++) {

    if (SSon[i]) {
      if (TRANS) {
         glEnable(GL_BLEND);
         glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	 diffuseColor[i][3] = tr_val;
      } else {
	 diffuseColor[i][3] = 1.0;
         glDisable(GL_BLEND);
      }

      glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, &diffuseColor[i][0]);
      if (denmode) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambientDColor);
      else glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambientColor);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, &specularColor[i][0]);
      glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100);
      
      glCallList(theSurf[i]);
    }

  }

  glFlush();
  glXWaitGL();
  if (StarNet) glXSwapBuffers(display, win);
  if (!gmoving && !mmoving && !smoving) {
    glXWaitGL();
    if (StarNet) XSetForeground(display, gc, colors[15]);
    if (!StarNet) initPrintStrings(0);
    if (*dolabs && !denmode) {
     for (i=0; i<*xyz.iatoms; i++) {
        j = i + 1;
        if (xyz.iaton[i] >= 1 && xyz.rzp[i] > 0.0 )  {
#if defined(VMS) || defined(UNDERSC)
   	   pllab(&xyz.ixp[i],&xyz.iyp[i],&xyz.ianz[i],&j,
#else
#ifdef CRAY
   	   PLLAB(&xyz.ixp[i],&xyz.iyp[i],&xyz.ianz[i],&j,
#else
   	   pllab_(&xyz.ixp[i],&xyz.iyp[i],&xyz.ianz[i],&j,
#endif
#endif
			   &xyz.qat[i],&zero,iqon,&xyz.iresid[i],&zero);
        }
     }
#if defined(VMS) || defined(UNDERSC)
     plalab(iqon);
#else
#ifdef CRAY
     PLALAB(iqon);
#else
     plalab_(iqon);
#endif
#endif
    }
#if defined(VMS) || defined(UNDERSC)
     pldstg();
#else
#ifdef CRAY
     PLDSTG();
#else
     pldstg_();
#endif
#endif
     if (AXES) {
	for (i=1; i<4; i++) {
#if defined(VMS) || defined(UNDERSC)
	   drwstr(&AxesProj[i][0],&AxesProj[i][1],AxesStr[i],&ONE);
#else
#ifdef CRAY
	   DRWSTR(&AxesProj[i][0],&AxesProj[i][1],AxesStr[i],&ONE);
#else
	   drwstr_(&AxesProj[i][0],&AxesProj[i][1],AxesStr[i],&ONE);
#endif
#endif
	}
    }
    if (cellpnt->iclon) {
	for (i=0; i<4; i++) {
	   j = cellpnt->iclpnt[i] - 1;
#if defined(VMS) || defined(UNDERSC)
	   drwstr(&xyz.ixp[j],&xyz.iyp[j],CellStr[i],&TWO);
#else
#ifdef CRAY
	   DRWSTR(&xyz.ixp[j],&xyz.iyp[j],CellStr[i],&TWO);
#else
	   drwstr_(&xyz.ixp[j],&xyz.iyp[j],CellStr[i],&TWO);
#endif
#endif
	}
    }
    if (!StarNet) endPrintStrings();
    if (*doesp && !denmode) PlotColIndex();
  }
  if (!StarNet) glXSwapBuffers(display, win);
  rsold = RESUND;

  if (DEBUG) fprintf( stderr, "dispsf \n");

}


void Reshape()
{
  int dx,dy;

  gmoving = 0;
  dx = dy = 0;
  Vsize = width;
  if (height > width) Vsize = height;
  if (height > width) dx = (GLint) -(height - width)/2;
  else dy = (GLint) ABS(height - width)/2;
  update_model = 0;

  glViewport(dx, dy, Vsize, Vsize);
  dispsf();
}


void Reshapi()
{
  int dx,dy;

  dx = dy = 0;
  Vsize = width;
  if (height > width) Vsize = height;
  if (height > width) dx = (GLint) -(height - width)/2;
  else dy = (GLint) ABS(height - width)/2;

  glViewport(dx, dy, Vsize, Vsize);
}


void Key( unsigned char key)
{

   if (gmoving) return;

   update_model = 0;

   switch (key) {
   case 'x':
      light0_position[0] += 0.5;
      break;
   case 'X':
      light0_position[0] -= 0.5;
      break;
   case 'y':
      light0_position[1] += 0.5;
      break;
   case 'Y':
      light0_position[1] -= 0.5;
      break;
   case 'z':
      light0_position[2] += 0.5;
      break;
   case 'Z':
      light0_position[2] -= 0.5;
      break;
   case 'i':
      light1_position[0] += 0.5;
      break;
   case 'I':
      light1_position[0] -= 0.5;
      break;
   case 'j':
      light1_position[1] += 0.5;
      break;
   case 'J':
      light1_position[1] -= 0.5;
      break;
   case 'k':
      light1_position[2] += 0.5;
      break;
   case 'K':
      light1_position[2] -= 0.5;
      break;
   case '<':
   case ',':
      light2_position[2] += 0.5;
      break;
   case '>':
   case '.':
      light2_position[2] -= 0.5;
      break;
   case 'l':
      if (DoLines) {
	DoLines = 0;
      } else {
	DoLines = 1;
      }
      break;
   case 'P':
   case 'p':
      if (*persp) *persp = 0;
      else *persp = 1;
      TogBut(&cbut[BPERSP]);
      break;
   case 'T':
   case 't':
      if (TRANS) TRANS = 0;
      else TRANS = 1;
      break;
   case '+':
   case '=':
      if (AXES) AXES = 0;
      else AXES = 1;
      break;
   case 'U':
   case 'u':
      if (idorad) idorad = 0;
      else idorad = 1;
      update_model = 1;
      break;
   case '1':
      if (l1on) {
	l1on = 0;
	glDisable(GL_LIGHT0);
      } else {
	l1on = 1;
	glEnable(GL_LIGHT0);
      }
      break;
   case '2':
      if (l2on) {
	l2on = 0;
	glDisable(GL_LIGHT1);
      } else {
	l2on = 1;
	glEnable(GL_LIGHT1);
      }
      break;
   case '3':
      if (l3on) {
	l3on = 0;
	glDisable(GL_LIGHT2);
      } else {
	l3on = 1;
	glEnable(GL_LIGHT2);
      }
      break;
   case '0':
      if (DoLights) {
	DoLights = 0;
      } else {
	DoLights = 1;
      }
      break;
   case 'N':
   case 'n':
      CMols++;
      if (CMols >= NMols) CMols = 0;
      break;
   case 'w':
      if (hires) hires = 0;
      else hires = 1;
      update_model = 1;
      break;
   case 'g':
      break;
   }
   update_struct();
}

EnableFog()
{
      if (!*shade || denmode) {
          glDisable(GL_FOG);	  
      } else {
         glEnable(GL_FOG);
         glFogi (GL_FOG_MODE, GL_EXP2);
         glFogfv (GL_FOG_COLOR, fogColor);
	 if (*ipdbon && *xyz.iatoms > 200) {
	    glFogf (GL_FOG_DENSITY, (*uscl)/(FFOGD*scl));
	 } else {
	    glFogf (GL_FOG_DENSITY, (*uscl)/(FFOGDS*scl));
	 }
         glHint (GL_FOG_HINT, GL_DONT_CARE);
         glFogf (GL_FOG_START, scl);
         glFogf (GL_FOG_END, -scl);
       }
}

extern void
motion(int x, int y, int iopt)
{
 int i;

  if (iopt) {
     gmoving = 0;
     mmoving = 0;
     smoving = 0;
#if defined(VMS) || defined(UNDERSC)
     qupd();
#else
#ifdef CRAY
     QUPD();
#else
     qupd_();
#endif
#endif
     return;
  }

  if (mmoving) {
    posx = posx + (x - mstartx) / 600.0;
    posy = posy - (y - mstarty) / 600.0;
    mstartx = x;
    mstarty = y;
  }
  if (smoving) {
    posz = posz - (y - sstarty) / 60.0;
    /*
    if (posz < 0.005 && !PERSP) posz = 0.005;
    */
    sstarty = y;
  }
#if defined(VMS) || defined(UNDERSC)
  qupd();
#else
#ifdef CRAY
  QUPD();
#else
  qupd_();
#endif
#endif
}

void mouseu(int button, int state, int x, int y)
{

  if (button == GLUT_LEFT_BUTTON || button == GLUT_MIDDLE_BUTTON) {
      gmoving = 0;
      mmoving = 0;
      smoving = 0;
  }
}

void moused(int button, unsigned int state, int x, int y)
{

  if (button == GLUT_LEFT_BUTTON || button == GLUT_MIDDLE_BUTTON) {
      if (state & ShiftMask) {
         mmoving = 1;
         mstartx = x;
         mstarty = y;
      } else if (state & ControlMask) {
         smoving = 1;
         sstarty = y;
      } else {
         gmoving = 1;
      }
  }
}

void setobg()
{
   float colv[4];
   int i;
   colv[0] = ((GLfloat) colorr[OBGcolor]) / 65535.0 ;
   colv[1] = ((GLfloat) colorg[OBGcolor]) / 65535.0 ;
   colv[2] = ((GLfloat) colorb[OBGcolor]) / 65535.0 ;

   for (i=0; i<3; i++) gradcol[0][i] = colv[i];

   glClearColor(colv[0],colv[1],colv[2],1.0);

   fogColor[0] = ((GLfloat) colorr[OBGcolor]) / 65535.0 ;
   fogColor[1] = ((GLfloat) colorg[OBGcolor]) / 65535.0 ;
   fogColor[2] = ((GLfloat) colorb[OBGcolor]) / 65535.0 ;
}

void initOpengl()
{

    int i,bgmenu,animmenu,trmenu,capmenu;

    static float lmodel_ambient[] = {0.2, 0.2, 0.2, 0.2};
    static float lmodel_twoside[] = {GL_TRUE};
    static float lmodel_local[] = {GL_FALSE};
    static float light0_ambient[] = {0.1, 0.1, 0.1, 1.0};
    static float light0_diffuse[] = {1.0, 1.0, 1.0, 0.0};
    static float light0_specular[] = {1.0, 1.0, 1.0, 0.0};
    static float light1_ambient[] = {0.1, 0.1, 0.1, 1.0};
    static float light1_diffuse[] = {1.0, 1.0, 1.0, 1.0};
    static float light1_specular[] = {1.0, 1.0, 1.0, 0.0};
    static float light2_ambient[] = {0.1, 0.1, 0.1, 1.0};
    static float light2_diffuse[] = {0.8, 0.8, 0.8, 1.0};
    static float light2_specular[] = {0.8, 0.8, 0.8, 0.0};
    int argc = 2;
#ifdef WIN32
    char *argv[] = {"mogl","yes"};
#else
    char *argv[] = {"moldenogl","yes"};
#endif

    if (started_ogl) return;
    started_ogl = 1;

    glXMakeCurrent(display, win, cx);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glEnable(GL_DEPTH_TEST);

    if (l1on) glEnable(GL_LIGHT0);
    else glDisable(GL_LIGHT0);
    if (l2on) glEnable(GL_LIGHT1);
    else glDisable(GL_LIGHT1);
    if (l3on) glEnable(GL_LIGHT2);
    else glDisable(GL_LIGHT2);

    glLightfv(GL_LIGHT0, GL_AMBIENT, light0_ambient);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse);
    glLightfv(GL_LIGHT0, GL_SPECULAR, light0_specular);
    glLightfv(GL_LIGHT0, GL_POSITION, light0_position);

    glLightfv(GL_LIGHT1, GL_AMBIENT, light1_ambient);
    glLightfv(GL_LIGHT1, GL_DIFFUSE, light1_diffuse);
    glLightfv(GL_LIGHT1, GL_SPECULAR, light1_specular);
    glLightfv(GL_LIGHT1, GL_POSITION, light1_position);

    glLightfv(GL_LIGHT2, GL_AMBIENT, light2_ambient);
    glLightfv(GL_LIGHT2, GL_DIFFUSE, light2_diffuse);
    glLightfv(GL_LIGHT2, GL_SPECULAR, light2_specular);
    glLightfv(GL_LIGHT2, GL_POSITION, light2_position);

    glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, lmodel_local);
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside);
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);

    glEnable(GL_LIGHTING);

    glEnable(GL_NORMALIZE);
    glShadeModel(GL_SMOOTH);
    glLineWidth(1.5);

    OBGcolor = *ibgclo;
    BGmode = *ibgmod;
    setobg();

    PERSP = perspon;
    
    glClearIndex(0.0);
    glClearDepth(1);

    glPushMatrix();
    glLoadIdentity();

    cyl = gluNewQuadric();
    sphere = gluNewQuadric();
    disk = gluNewQuadric();

    ogaxes();

    Reshapi();

}


void ogind()
{
 int i;


    oglines();
    if (*forces_yes_no) ogforces();
    if (denmode) {
	ogmlxyz();
	update_model = 0;
    }
    else {
	if (*irtcel && *ialtyp) {
	   if (NMols != 1) ogmoll(0);
	   ogmoll(1);
	}
	else {
	   ogmoll(0);
	}
    }

    if (*ipdbon && !SSdone) {
       NSurf = 0;
#if defined(VMS) || defined(UNDERSC)
       ribogl();
#else
#ifdef CRAY
       RIBOGL();
#else
       ribogl_();
#endif
#endif
       SSdone = 1;
    }
    glXWaitGL();
    dispsf();
}

void DelHet(het)
int het;
{
 int i,j,k,istart,iend,fnd,ndel;
 int tmpres,kcon, ab, noab;

    fnd = 0;
    istart = 0;
    iend = -1;

    for (j=0; j < *xyz.iatoms; j++) {
	if (xyz.iresid[j] == het) {
	   if (!fnd) {
	      istart = j; 
	      fnd = 1;
	   }
	   iend = j;
	}
    }

    if (iend == -1 ) return;
    ndel = iend - istart + 1;
    
    for (j=istart; j < *xyz.iatoms - ndel; j++) {
	xyz.iatclr[j] = xyz.iatclr[j+ndel];
	tmpres = xyz.iresid[j+ndel];
	if (tmpres < het) tmpres++;
	xyz.iresid[j] = tmpres;
	xyz.iaton[j] = xyz.iaton[j+ndel];
	xyz.ianz[j] = xyz.ianz[j+ndel];
	xyz.ipdbt[j] = xyz.ipdbt[j+ndel];
	xyz.ityp[j] = xyz.ityp[j+ndel];
	if (*ihasq) xyz.qat[j] = xyz.qat[j+ndel];
	for (k=0; k < 3; k++) {
	   xyz.coo[j*3+k] = xyz.coo[(j+ndel)*3+k];
	}
	kcon = 0;
	for (k=0; k < xyz.iconn[(j+ndel)*(MXCON+1)]; k++) {
	   noab = xyz.iconn[(j+ndel)*(MXCON+1)+k+1];
	   ab = ABS(noab) - 1;
	   if (ab > istart + ndel) {
		if (noab > 0) {
		   xyz.iconn[j*(MXCON+1)+kcon+1] = noab - ndel;
		} else {
		   xyz.iconn[j*(MXCON+1)+kcon+1] = noab + ndel;
		}
		kcon++;
	   } else if (ab < istart) {
		xyz.iconn[j*(MXCON+1)+kcon+1] = noab;
		kcon++;
	   }
	}
	xyz.iconn[j*(MXCON+1)] = kcon;
    }

    for (j=0; j < istart; j++) {
	kcon = 0;
	for (k=0; k < xyz.iconn[j*(MXCON+1)]; k++) {
	   noab = xyz.iconn[j*(MXCON+1)+k+1];
	   ab = ABS(noab) - 1;
	   if (ab > istart + ndel) {
		if (noab > 0) {
		   xyz.iconn[j*(MXCON+1)+kcon+1] = noab - ndel;
		} else {
		   xyz.iconn[j*(MXCON+1)+kcon+1] = noab + ndel;
		}
		kcon++;
	   } else if (ab < istart) {
		xyz.iconn[j*(MXCON+1)+kcon+1] = noab;
		kcon++;
	   }
	}
	xyz.iconn[j*(MXCON+1)] = kcon;
    }

    for (j=0; j < calfptr->ncalf; j++) {
	for (k=0; k < 4; k++) 
	   if (calfptr->icalf[j][k] >= istart) 
		calfptr->icalf[j][k] = calfptr->icalf[j][k] - ndel;
    }

    for (j=ABS(het); j < NHetAtm; j++) {
	HetAtm[j] = HetAtm[j+1];
	calfptr->ihet[j] = calfptr->ihet[j+1];
    }
    NHetAtm--;

    *xyz.iatoms = *xyz.iatoms - ndel;
    *zmptr.ihaszm = 0;
    update_model = 1;
}

#if defined(VMS) || defined(UNDERSC)
void ognrm(double *v1, double *v2, double *v3)
#else
#ifdef CRAY
void OGNRM(double *v1, double *v2, double *v3)
#else
void ognrm_(double *v1, double *v2, double *v3)
#endif
#endif
{
      glNormal3d(*v1,*v2,*v3);
}

#if defined(VMS) || defined(UNDERSC)
void ogvrt(double *v1, double *v2, double *v3)
#else
#ifdef CRAY
void OGVRT(double *v1, double *v2, double *v3)
#else
void ogvrt_(double *v1, double *v2, double *v3)
#endif
#endif
{
      glVertex3d(*v1,*v2,*v3);
}

#if defined(VMS) || defined(UNDERSC)
void sribcol(int *iribc)
#else
#ifdef CRAY
void SRIBCOL(int *iribc)
#else
void sribcol_(int *iribc)
#endif
#endif
{
	int i;

	for (i=0; i<3; i++) diffuseColor[NSurf-1][i] = ribcol[*iribc][i];
}

#if defined(VMS) || defined(UNDERSC)
bldlst()
#else
#ifdef CRAY
BLDLST()
#else
bldlst_()
#endif
#endif
{

     int i,j,k,npts1,npts2;
     double v[3], rpts,vl, g[3], c[3];
     double vec1[3], vn1[3],sc;
     float hinv1,hinv2;

/*
     a grid of n*n points has n-1*n-1 squares
     and twice as much triangular polygons
     so 2*(npts-1)**2
     npts is 80 at maximum so lets make it 12800
*/

      if (!*ifdogl) return;

#if defined(VMS) || defined(UNDERSC)
      curs(&ONE);
      cvtcom();
#else
#ifdef CRAY
      CURS(&ONE);
      CVTCOM();
#else
      curs_(&ONE);
      cvtcom_();
#endif
#endif
      update_model = 1;
      NSurf = 1;
      if (theSurf[0] > 0) glDeleteLists(theSurf[NSurf-1],1);
      theSurf[0] = -1;
      theSurf[0] = glGenLists(1);
      SSon[0] = 1;
      diffuseColor[0][0] = 0.0;
      diffuseColor[0][1] = 1.0;
      diffuseColor[0][2] = 0.0;
      diffuseColor[0][3] = 0.8;
      for (i=0; i<3; i++) {
	specularColor[0][i] = specColor[i];
      }

      glNewList(theSurf[0], GL_COMPILE);
      glBegin(GL_QUADS);

      npts1 = *nps1;
      npts2 = *nps2;
      sc = -1.0*(*scle);
/*
      rpts = (double) (npts1-1);
*/
      rpts = (double) (npts1);
      hinv1 = 1.0/ npts2;
      hinv2 = 1.0/ npts1;

      for (i=0; i<npts1-1; i++) {
         for (j=0; j<npts2-1; j++) {
/*
        first triangle
*/
            vec1[0] = (double) (j);
            vec1[1] = (double) (i);
            vec1[2] = sgrd.dens[j+i*npts2]*sc*rpts;

	    znorm(rpts,sc,sgrd.dens,vn1,npts1,npts2,i,j);

#if defined(VMS) || defined(UNDERSC)
            rtgbck(&vn1[0],&vn1[1],&vn1[2],g);
            ognrm(&g[0],&g[1],&g[2]);
#else
#ifdef CRAY
            RTGBCK(&vn1[0],&vn1[1],&vn1[2],g);
            OGNRM(&g[0],&g[1],&g[2]);
#else
            rtgbck_(&vn1[0],&vn1[1],&vn1[2],g);
            ognrm_(&g[0],&g[1],&g[2]);
#endif
#endif

	    v[0] = vec1[0]*hinv1;
	    v[1] = vec1[1]*hinv2;
	    v[2] = vec1[2]*hinv1;
#if defined(VMS) || defined(UNDERSC)
            rttbck(&v[0],&v[1],&v[2],c);
	    ogvrt(&c[0],&c[1],&c[2]);
#else
#ifdef CRAY
            RTTBCK(&v[0],&v[1],&v[2],c);
	    OGVRT(&c[0],&c[1],&c[2]);
#else
            rttbck_(&v[0],&v[1],&v[2],c);
	    ogvrt_(&c[0],&c[1],&c[2]);
#endif
#endif

            vec1[0] = (double) (j+1);
            vec1[1] = (double) (i);
            vec1[2] = sgrd.dens[j+1+i*npts2]*sc*rpts;

	    znorm(rpts,sc,sgrd.dens,vn1,npts1,npts2,i,j+1);

#if defined(VMS) || defined(UNDERSC)
            rtgbck(&vn1[0],&vn1[1],&vn1[2],g);
            ognrm(&g[0],&g[1],&g[2]);
#else
#ifdef CRAY
            RTGBCK(&vn1[0],&vn1[1],&vn1[2],g);
            OGNRM(&g[0],&g[1],&g[2]);
#else
            rtgbck_(&vn1[0],&vn1[1],&vn1[2],g);
            ognrm_(&g[0],&g[1],&g[2]);
#endif
#endif

	    v[0] = vec1[0]*hinv1;
	    v[1] = vec1[1]*hinv2;
	    v[2] = vec1[2]*hinv1;
#if defined(VMS) || defined(UNDERSC)
            rttbck(&v[0],&v[1],&v[2],c);
	    ogvrt(&c[0],&c[1],&c[2]);
#else
#ifdef CRAY
            RTTBCK(&v[0],&v[1],&v[2],c);
	    OGVRT(&c[0],&c[1],&c[2]);
#else
            rttbck_(&v[0],&v[1],&v[2],c);
	    ogvrt_(&c[0],&c[1],&c[2]);
#endif
#endif

            vec1[0] = (double) (j+1);
            vec1[1] = (double) (i+1);
            vec1[2] = sgrd.dens[j+1+(i+1)*npts2]*sc*rpts;

	    znorm(rpts,sc,sgrd.dens,vn1,npts1,npts2,i+1,j+1);

#if defined(VMS) || defined(UNDERSC)
            rtgbck(&vn1[0],&vn1[1],&vn1[2],g);
            ognrm(&g[0],&g[1],&g[2]);
#else
#ifdef CRAY
            RTGBCK(&vn1[0],&vn1[1],&vn1[2],g);
            OGNRM(&g[0],&g[1],&g[2]);
#else
            rtgbck_(&vn1[0],&vn1[1],&vn1[2],g);
            ognrm_(&g[0],&g[1],&g[2]);
#endif
#endif

	    v[0] = vec1[0]*hinv1;
	    v[1] = vec1[1]*hinv2;
	    v[2] = vec1[2]*hinv1;
#if defined(VMS) || defined(UNDERSC)
            rttbck(&v[0],&v[1],&v[2],c);
	    ogvrt(&c[0],&c[1],&c[2]);
#else
#ifdef CRAY
            RTTBCK(&v[0],&v[1],&v[2],c);
	    OGVRT(&c[0],&c[1],&c[2]);
#else
            rttbck_(&v[0],&v[1],&v[2],c);
	    ogvrt_(&c[0],&c[1],&c[2]);
#endif
#endif

            vec1[0] = (double) (j);
            vec1[1] = (double) (i+1);
            vec1[2] = sgrd.dens[j+(i+1)*npts2]*sc*rpts;

	    znorm(rpts,sc,sgrd.dens,vn1,npts1,npts2,i+1,j);

#if defined(VMS) || defined(UNDERSC)
            rtgbck(&vn1[0],&vn1[1],&vn1[2],g);
            ognrm(&g[0],&g[1],&g[2]);
#else
#ifdef CRAY
            RTGBCK(&vn1[0],&vn1[1],&vn1[2],g);
            OGNRM(&g[0],&g[1],&g[2]);
#else
            rtgbck_(&vn1[0],&vn1[1],&vn1[2],g);
            ognrm_(&g[0],&g[1],&g[2]);
#endif
#endif

	    v[0] = vec1[0]*hinv1;
	    v[1] = vec1[1]*hinv2;
	    v[2] = vec1[2]*hinv1;
#if defined(VMS) || defined(UNDERSC)
            rttbck(&v[0],&v[1],&v[2],c);
	    ogvrt(&c[0],&c[1],&c[2]);
#else
#ifdef CRAY
            RTTBCK(&v[0],&v[1],&v[2],c);
	    OGVRT(&c[0],&c[1],&c[2]);
#else
            rttbck_(&v[0],&v[1],&v[2],c);
	    ogvrt_(&c[0],&c[1],&c[2]);
#endif
#endif

         }
      }

      glEnd();
      glDisable(GL_BLEND);
      glDisable(GL_COLOR_MATERIAL);
      glDisable(GL_CULL_FACE);
      glEndList();
      dispsf();
#if defined(VMS) || defined(UNDERSC)
      curs(&ZERO);
#else
#ifdef CRAY
      CURS(&ZERO);
#else
      curs_(&ZERO);
#endif
#endif

}

static int surf_info = 1;

molsrf(SurfCol)
int SurfCol;
{
   char cmdfil[MAXCMD];
   char cmdtmp[MAXCMD] = "surf ";
   char *tmpf;
   int i,j, iat;
   float r;
   double g[3], c[3];
   FILE *out, *inp;

#if defined(VMS) || defined(UNDERSC)
   curs(&ONE);
#else
#ifdef CRAY
   CURS(&ONE);
#else
   curs_(&ONE);
#endif
#endif

   tmpf = tmpnam(NULL);

   inp = fopen(tmpf,"w");

   if (inp == NULL) return;

   for (i=0; i < *xyz.iatoms; i++ ) {
     if (xyz.iresid[i] > 0) {
	switch (xyz.ianz[i]) {
	case 1:
	    r = 1.0;
	    break;
	case 5:
	    r = 1.75;
	    break;
	case 6:
	    r = 1.85;
	    break;
	case 8:
	    r = 1.6;
	    break;
	case 15:
	    r = 2.0;
	    break;
	case 16:
	    r = 2.0;
	    break;
	default:
	    r = 1.5;
	}
	fprintf(inp,"%d %f %8.3f %8.3f %8.3f\n", i,r,
	   xyz.coo[i*3]*toangs,xyz.coo[i*3+1]*toangs,xyz.coo[i*3+2]*toangs);
     }
   }

   fclose(inp);

   sprintf(cmdfil,"%ssurf",exepath[0]);

   if (! (access(cmdfil,F_OK) == 0 && !isdir(cmdfil))) {
	sprintf(cmdfil,"%ssurf/surf",exepath[0]);
	if (!access(cmdfil,F_OK) == 0) {
	   sprintf(cmdfil,"surf");
	}
   }

   
   if (surf_info) {
      fprintf(stderr,"\nThis surface is made with SURF from UNC-Chapel Hill.\n");
      fprintf(stderr,"  The reference is:\n\n");
      fprintf(stderr,"A. Varshney, F. P. Brooks, W. V. Wright, \n");
      fprintf(stderr,"Linearly Scalable Computation \n");
      fprintf(stderr,"of Smooth Molecular Surfaces, \n");
      fprintf(stderr,"IEEE Comp. Graphics and Applications, \n");
      fprintf(stderr,"v. 14 (1994) pp. 19-25.\n\n");
      surf_info = 0;
   }

   strcpy(cmdtmp,cmdfil);
   strcat(cmdtmp," -W 1 ");
   strcat(cmdtmp,tmpf);

   system(cmdtmp);

   strcpy(cmdtmp,tmpf);
   strcat(cmdtmp,".tri");

   if ((out = fopen(cmdtmp, "r")) == NULL) {
      fprintf(stderr,"Can not open triangle file !\n");
      return;
   }

   SetSurfColor(NSurf,SurfCol);

   theSurf[NSurf] = glGenLists(1);
   SSon[NSurf] = 1;

   glNewList(theSurf[NSurf], GL_COMPILE);
   NSurf++;

/* if color per triangle */

   if (0) {
        glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE);
        glEnable(GL_COLOR_MATERIAL);
   }

   glBegin(GL_TRIANGLES);

   if (out != NULL) {
	   while (fscanf(out,"%d",&iat) != EOF) {
	     for (i=0; i < 3; i++ ) {
		fscanf(out,"%lf %lf %lf %lf %lf %lf",
		  &c[0],&c[1],&c[2],&g[0],&g[1],&g[2]);

		for (j=0; j < 3; j++ ) c[j] = c[j]/toangs;
		glNormal3d(g[0],g[1],g[2]);
		glVertex3d(c[0],c[1],c[2]);
	     }

	   }
	   glEnd();
	   glEndList();
	   fclose(out);
	   unlink(tmpf);
	   unlink(cmdtmp);
	   dispsf();
   }

#if defined(VMS) || defined(UNDERSC)
   curs(&ZERO);
#else
#ifdef CRAY
   CURS(&ZERO);
#else
   curs_(&ZERO);
#endif
#endif
}

#else

/* =====================================
 * backup functions for no openGL 
 * =====================================
*/

#if defined(VMS) || defined(UNDERSC)
bldlst()
#else
#ifdef CRAY
BLDLST()
#else
bldlst_()
#endif
#endif
{
  int i;

  i = 0;
}

molsrf(SurfCol)
int SurfCol;
{
  int dummy;

  dummy = 0;
}

#if defined(VMS) || defined(UNDERSC)
void ogbegg(isurf,mapped)
#else
#ifdef CRAY
void OGBEGG(isurf,mapped)
#else
void ogbegg_(isurf,mapped)
#endif
#endif
int *isurf;
int *mapped;
{
  int i;

  i = 0;
}

#if defined(VMS) || defined(UNDERSC)
void ogcoll(double *v1, double *v2, double *v3)
#else
#ifdef CRAY
void OGCOLL(double *v1, double *v2, double *v3)
#else
void ogcoll_(double *v1, double *v2, double *v3)
#endif
#endif
{
  int i;

  i = 0;
}

#if defined(VMS) || defined(UNDERSC)
void ognrm(double *v1, double *v2, double *v3)
#else
#ifdef CRAY
void OGNRM(double *v1, double *v2, double *v3)
#else
void ognrm_(double *v1, double *v2, double *v3)
#endif
#endif
{
  int i;

  i = 0;
      
}

#if defined(VMS) || defined(UNDERSC)
void ogvrt(double *v1, double *v2, double *v3)
#else
#ifdef CRAY
void OGVRT(double *v1, double *v2, double *v3)
#else
void ogvrt_(double *v1, double *v2, double *v3)
#endif
#endif
{
  int i;

  i = 0;
      
}

#if defined(VMS) || defined(UNDERSC)
void sribcol(int *iribc)
#else
#ifdef CRAY
void SRIBCOL(int *iribc)
#else
void sribcol_(int *iribc)
#endif
#endif
{

  int i;

  i = 0;
      
}

#if defined(VMS) || defined(UNDERSC)
void ogribb()
#else
#ifdef CRAY
void OGRIBB()
#else
void ogribb_()
#endif
#endif
{
      int i;

      i = 0;
}

#if defined(VMS) || defined(UNDERSC)
void ogmon()
#else
#ifdef CRAY
void OGMON()
#else
void ogmon_()
#endif
#endif
{
      int i;

      i = 0;
}

#if defined(VMS) || defined(UNDERSC)
void ogendd()
#else
#ifdef CRAY
void OGENDD()
#else
void ogendd_()
#endif
#endif
{
      int i;

      i = 0;
}

void dispsf()
{
  int i;

  i = 0;
}

void ogind()
{
  int i;

  i = 0;
}

void ogmoll(int iopt)
{
  int i;

  i = 0;
}

void  Key(unsigned char key)
{
  int i;

  i = 0;
}

void moused(int button, unsigned int state, int x, int y)
{
  int i;

  i = 0;
}

void mouseu(int button, int state, int x, int y)
{
  int i;

  i = 0;
}

void motion(int x, int y, int iopt)
{
  int i;

  i = 0;
}

void Reshape()
{
  int i;

  i = 0;
}

void empty_model()
{
  int i;

      i = 0;
}

void DelHet(int het)
{
  int i;

      i = 0;
}

#endif

#include <math.h>

static union
{   double d;
    struct
    {
#ifdef LITTLE_ENDIAN
      int j, i;
#else
      int i, j;
#endif
    } n;
} _eco;

#define EXPA (1048576/M_LN2)
#define EXPC 60801

#define EXP(y) (_eco.n.i = EXPA*(y) + (1072693248 - EXPC), _eco.d)

#if defined(VMS) || defined(UNDERSC)
double fexp(y)
#else
#ifdef CRAY
double FEXP(y)
#else
double fexp_(y)
#endif
#endif
double *y;
{
  return (EXP(*y));
}
/*
typedef struct {
  int ptr;
  float depth;
} DepthIndex;

DepthIndex dpt[NUMAT];
*/

static int
compare(const void *a, const void *b)
{
  DepthIndex *p1 = (DepthIndex *) a;
  DepthIndex *p2 = (DepthIndex *) b;
  float diff = p2->depth - p1->depth;

  if (diff > 0.0) {
    return -1;
  } else if (diff < 0.0) {
    return 1;
  } else {
    return 0;
  }
}


#if defined(VMS) || defined(UNDERSC)
void rqsrt(n,rzp,inat)
#else
#ifdef CRAY
void RQSRT(n,rzp,inat)
#else
void rqsrt_(n,rzp,inat)
#endif
#endif
int *n;
double *rzp;
int *inat;
{
   int i;

   for (i=0; i<*n; i++) {
	dptptr[i].depth = (float) rzp[i];
	dptptr[i].ptr = i + 1; 
   }
   qsort(dptptr,*n, sizeof(DepthIndex), compare);
   for (i=0; i<*n; i++) inat[i] = dptptr[i].ptr;
}

void SaveResXYZ(ires)
int ires;
{
   int i,j;


   if (ResChanged == NULL) {
      if ((ResChanged = (int *) malloc((sizeof(int))*NUMCAL)) == NULL) {
	fprintf(stderr, "Memory allocation error for ResChanged\n");
	return;
      } else {
          for (i=0; i<NUMCAL; i++) ResChanged[i] = 0;
      }
   }

   CurrRes = ires;

   if (!ResChanged[ires-1]) {
#if defined(VMS) || defined(UNDERSC)
      getpdb(&ires,ipdb,ihpdb);
#else
#ifdef CRAY
      GETPDB(&ires,ipdb,ihpdb);
#else
      getpdb_(&ires,ipdb,ihpdb);
#endif
#endif
      for (i=0; i<MXSYM; i++) for (j=0; j<3; j++)
	xyzpdb[i][j] = xyz.coo[(ipdb[i]-1)*3+j];

      for (i=0; i<MXHSYM*3; i++) for (j=0; j<3; j++)
	xyzhpdb[i][j] = xyz.coo[(ihpdb[i]-1)*3+j];

      ResChanged[ires-1] = 1;
   }


}

double rmsdres()
{
   int i,j, numatoms;
   int tmpipdb[MXSYM], tmpihpdb[MXHSYM*3];
   double rmsd,rmsdh, rtmp;


   for (i=0; i<MXSYM; i++) tmpipdb[i] = 0;
   for (i=0; i<MXHSYM*3; i++) tmpihpdb[i] = 0;

#if defined(VMS) || defined(UNDERSC)
   getpdb(&CurrRes,tmpipdb,tmpihpdb);
#else
#ifdef CRAY
   GETPDB(&CurrRes,tmpipdb,tmpihpdb);
#else
   getpdb_(&CurrRes,tmpipdb,tmpihpdb);
#endif
#endif

   rmsd = 0;
   numatoms = 0;

   for (i=0; i<MXSYM; i++) {
        if (tmpipdb[i]) {
           numatoms++;
           fprintf(stderr,"%d org %f %f %f rot %f %f %f \n",i+1,xyzpdb[i][0]*toangs,xyzpdb[i][1]*toangs,xyzpdb[i][2]*toangs,xyz.coo[(tmpipdb[i]-1)*3]*toangs,xyz.coo[(tmpipdb[i]-1)*3+1]*toangs,xyz.coo[(tmpipdb[i]-1)*3+2]*toangs);
           for (j=0; j<3; j++) { 
	      rtmp = (xyzpdb[i][j] - xyz.coo[(tmpipdb[i]-1)*3+j]);
	      rmsd = rmsd + rtmp*rtmp;
	   }
	}
   }

   rmsd = toangs*sqrt(rmsd/((float) numatoms));
   fprintf(stderr,"RMSD current rotamer with starting geometry: %f\n",rmsd); 

   numatoms = 0;
   rmsdh = 0;

   for (i=0; i<MXHSYM*3; i++) {
        if (tmpihpdb[i]) {
           numatoms++;
           for (j=0; j<3; j++) {
	      rtmp = (xyzhpdb[i][j] - xyz.coo[(tmpihpdb[i]-1)*3+j]);
	      rmsdh = rmsdh + rtmp*rtmp;
	   }
	}
   }

   rmsdh = toangs*sqrt(rmsdh/((float) numatoms));
   fprintf(stderr,"RMSDH current rotamer with starting geometry: %f\n",rmsdh); 

   return(rmsd);
}

void zmt2cor(ires,iopt)
int ires;
int iopt;
{

#if defined(VMS) || defined(UNDERSC)
   dumzm(xyz.coo,xyz.ianz,xyz.iatoms);
   doclr();
   if (iopt) conpdb();
#ifdef DOGL
   ogres(ires,ONE,1);
   update_model = 0;
#endif
   qupd();
   curs(&ZERO);
#else
#ifdef CRAY
   DUMZM(xyz.coo,xyz.ianz,xyz.iatoms);
   doclr();
   if (iopt) CONPDB();
#ifdef DOGL
   ogres(ires,ONE,1);
   update_model = 0;
#endif
   QUPD();
   CURS(&ZERO);
#else
   dumzm_(xyz.coo,xyz.ianz,xyz.iatoms);
   doclr();
   if (iopt) conpdb_();
#ifdef DOGL
   ogres(ires,ONE,1);
   update_model = 0;
#endif
   qupd_();
   curs_(&ZERO);
#endif
#endif
   presetp();
}

void scanrot(ires,aminotyp)
int ires;
int aminotyp;
{
   int i,OptRot;
   double rmsd,rtmp;


   SaveResXYZ(ires);

#if defined(VMS) || defined(UNDERSC)
   curs(&ONE);
#else
#ifdef CRAY
   CURS(&ONE);
#else
   curs_(&ONE);
#endif
#endif

   rmsd = 1000000.0;
   OptRot = -1;

   for (i=0; i<aminozmt[aminotyp].nrots; i++) {

      if (aminozmt[aminotyp].chis[0] != -1) 
	zmptr.bet[aaptr[ires-1].chi1] = aminozmt[aminotyp].rots[i].rots[0];
      if (aminozmt[aminotyp].chis[1] != -1) 
	zmptr.bet[aaptr[ires-1].chi2] = aminozmt[aminotyp].rots[i].rots[1];
      if (aminozmt[aminotyp].chis[2] != -1) 
	zmptr.bet[aaptr[ires-1].chi3] = aminozmt[aminotyp].rots[i].rots[2];
      if (aminozmt[aminotyp].chis[3] != -1) 
	zmptr.bet[aaptr[ires-1].chi4] = aminozmt[aminotyp].rots[i].rots[3];
      SetQZME();

      FindZRange(ires);

#if defined(VMS) || defined(UNDERSC)
      dumzm(xyz.coo,xyz.ianz,xyz.iatoms);
#else
#ifdef CRAY
      DUMZM(xyz.coo,xyz.ianz,xyz.iatoms);
#else
      dumzm_(xyz.coo,xyz.ianz,xyz.iatoms);
#endif
#endif
      rtmp = rmsdres();
      if (rtmp < rmsd) {
	  rmsd = rtmp;
	  OptRot = i;
      }

   }

   fprintf(stderr,"\nBest Rotamer fit: %d\n",OptRot+1);

   if (aminozmt[aminotyp].chis[0] != -1) 
	zmptr.bet[aaptr[ires-1].chi1] = aminozmt[aminotyp].rots[OptRot].rots[0];
   if (aminozmt[aminotyp].chis[1] != -1) 
	zmptr.bet[aaptr[ires-1].chi2] = aminozmt[aminotyp].rots[OptRot].rots[1];
   if (aminozmt[aminotyp].chis[2] != -1) 
	zmptr.bet[aaptr[ires-1].chi3] = aminozmt[aminotyp].rots[OptRot].rots[2];
   if (aminozmt[aminotyp].chis[3] != -1) 
	zmptr.bet[aaptr[ires-1].chi4] = aminozmt[aminotyp].rots[OptRot].rots[3];

   SetQZME();

   if (ZME_window_pos >= calfptr->ncalf) ZME_window_pos = 0;
   if (calfptr->ncalf < ZME_window_high) RedrawZME();
   else UpdateZME();
   RedrawScroll(&zscroll);

   FindZRange(ires);
   zmt2cor(ires,0);
}


void bestrot();

void onerot(ires)
int ires;
{

#if defined(VMS) || defined(UNDERSC)
   dfipar();
#else
#ifdef CRAY
   DFIPAR();
#else
   dfipar_();
#endif
#endif

   pmfrot->ndrs = 1;
   pmfrot->idrs[0] = ires;
   (void) bestrot();
}

void setrot(irs,irot)
int irs;
int irot;
{
	int aminotyp;

	aminotyp = calfptr->iamino[irs-1]-1;
        if (aminozmt[aminotyp].chis[0] != -1) 
   	   zmptr.bet[aaptr[irs-1].chi1] = aminozmt[aminotyp].rots[irot].rots[0];
        if (aminozmt[aminotyp].chis[1] != -1) 
	   zmptr.bet[aaptr[irs-1].chi2] = aminozmt[aminotyp].rots[irot].rots[1];
        if (aminozmt[aminotyp].chis[2] != -1) 
	   zmptr.bet[aaptr[irs-1].chi3] = aminozmt[aminotyp].rots[irot].rots[2];
        if (aminozmt[aminotyp].chis[3] != -1) 
	   zmptr.bet[aaptr[irs-1].chi4] = aminozmt[aminotyp].rots[irot].rots[3];

}

void bestrot()
{
   int i,l,l1,irs,aminotyp,OptRot[MXDRES];
   double scor,rtmp;


/* assign atom types */

#if defined(VMS) || defined(UNDERSC)
   curs(&ONE);
   dfiass();
#else
#ifdef CRAY
   CURS(&ONE);
   DFIASS();
#else
   curs_(&ONE);
   dfiass_();
#endif
#endif

/* 
   Calculate (once) the static interaction between flexible residues 
   (all rotamers) and the non-flexible-residues 
*/
   fprintf(stderr,"ndrs %d\n",pmfrot->ndrs);
   for (l=0; l<pmfrot->ndrs; l++) {

      scor = 1000000.0;
      OptRot[l] = -1;

      irs = pmfrot->idrs[l];
      aminotyp = calfptr->iamino[irs-1]-1;

      for (i=0; i<aminozmt[aminotyp].nrots; i++) {

	 setrot(irs,i);

         SetQZME();

         FindZRange(irs);

	 pmfrot->lrots[l] = i + 1;
	 l1 = l + 1;

/*
dfirot: rotamer with all non flexible sidechains and 
        rotamer with backbone part of flexible sidechains and 
        internal rotamer energy (fixed or self pmf ?)
*/

#if defined(VMS) || defined(UNDERSC)
         dumzm(xyz.coo,xyz.ianz,xyz.iatoms);
         dfirot(&l1);
#else
#ifdef CRAY
         DUMZM(xyz.coo,xyz.ianz,xyz.iatoms);
         DFIROT(&l1);
#else
         dumzm_(xyz.coo,xyz.ianz,xyz.iatoms);
         dfirot_(&l1);
#endif
#endif

      

         rtmp = pmfrot->estat[i][l];
   fprintf(stderr,"\nRotamer %d %f\n",i,rtmp);
         if (rtmp < scor) {
	     scor = rtmp;
	     OptRot[l] = i;
         }

      }
   }
   fprintf(stderr,"\nBest Rotamer fit: %d\n",OptRot[0]+1);

   for (l=0; l<pmfrot->ndrs; l++) {

      irs = pmfrot->idrs[l];

      setrot(irs,OptRot[l]);

   }

   SetQZME();

   if (ZME_window_pos >= calfptr->ncalf) ZME_window_pos = 0;
   if (calfptr->ncalf < ZME_window_high) RedrawZME();
   else UpdateZME();
   RedrawScroll(&zscroll);

   if (pmfrot->ndrs == 1) FindZRange(pmfrot->idrs[0]);

#if defined(VMS) || defined(UNDERSC)
   dumzm(xyz.coo,xyz.ianz,xyz.iatoms);
   doclr();
#ifdef DOGL
   for (l=0; l<pmfrot->ndrs; l++)
	ogres(pmfrot->idrs[l],ONE,0);
   update_model = 0;
#endif
   qupd();
   curs(&ZERO);
#else
#ifdef CRAY
   DUMZM(xyz.coo,xyz.ianz,xyz.iatoms);
   doclr();
#ifdef DOGL
   for (l=0; l<pmfrot->ndrs; l++)
	ogres(pmfrot->idrs[l],ONE,0);
   update_model = 0;
#endif
   QUPD();
   CURS(&ZERO);
#else
   dumzm_(xyz.coo,xyz.ianz,xyz.iatoms);
   doclr();
#ifdef DOGL
   for (l=0; l<pmfrot->ndrs; l++)
	ogres(pmfrot->idrs[l],ONE,0);
   update_model = 0;
#endif
   qupd_();
   curs_(&ZERO);
#endif
#endif
   presetp();

}

prresrot(eupl)
double eupl;
{
   int i,j;

   fprintf(stderr,"nresrot %d eupl %f\n",nresrot,eupl);
   for (i=0; i<MXROTRES; i++) {
      fprintf(stderr,"ResRot %d ",i);
      for (j=0; j<resrot[0].ndrs; j++) {
          fprintf(stderr,"res%2d %d rot %d, ",
		j,resrot[i].idrs[j],resrot[i].rot[j]);
      }
      fprintf(stderr," etot %8.3f\n",resrot[i].etot);
   }
}

showresrot(sol)
int sol;
{
   int l;


   for (l=0; l<resrot[sol].ndrs; l++) {

      setrot(resrot[sol].idrs[l],resrot[sol].rot[l]);

   }

   *imx = resrot[sol].mx;
   *imn = resrot[sol].mn;

   SetQZME();

   if (ZME_window_pos >= calfptr->ncalf) ZME_window_pos = 0;
   if (calfptr->ncalf < ZME_window_high) RedrawZME();
   else UpdateZME();
   RedrawScroll(&zscroll);

#if defined(VMS) || defined(UNDERSC)

   dumzm(xyz.coo,xyz.ianz,xyz.iatoms);
   doclr();
#ifdef DOGL
   for (l=0; l<resrot[sol].ndrs; l++)
	ogres(resrot[sol].idrs[l],ONE,0);
   update_model = 0;
#endif
   qupd();
   curs(&ZERO);

#else

#ifdef CRAY

   DUMZM(xyz.coo,xyz.ianz,xyz.iatoms);
   doclr();
#ifdef DOGL
   for (l=0; l<resrot[sol].ndrs; l++)
	ogres(resrot[sol].idrs[l],ONE,0);
   update_model = 0;
#endif
   QUPD();
   CURS(&ZERO);

#else

   dumzm_(xyz.coo,xyz.ianz,xyz.iatoms);
   doclr();
#ifdef DOGL
   for (l=0; l<resrot[sol].ndrs; l++)
	ogres(resrot[sol].idrs[l],ONE,0);
   update_model = 0;
#endif
   qupd_();
   curs_(&ZERO);

#endif

#endif
   presetp();
}


opt3rot()
{
   int i,j,k,l,l1,m,n,mx,mn,aminotyp,debug;
   int irs0,irs[6],rots[6],j0,j1,j2,j3,j4,j5;
   double etot,eupl;

   debug = 0;

   if (pmfrot->ndrs == 0) return;

/* assign atom types */

#if defined(VMS) || defined(UNDERSC)
   curs(&ONE);
   dfiass();
#else
#ifdef CRAY
   CURS(&ONE);
   DFIASS();
#else
   curs_(&ONE);
   dfiass_();
#endif
#endif

/* 
   Calculate (once) the static interaction between flexible residues 
   (all rotamers) and the non-flexible-residues 
*/

   fprintf(stderr,"ndrs %d\n",pmfrot->ndrs);

   *idcur = 0;
   for (l=0; l<pmfrot->ndrs; l++) {

      irs0 = pmfrot->idrs[l];
      aminotyp = calfptr->iamino[irs0-1]-1;

      for (i=0; i<aminozmt[aminotyp].nrots; i++) {

	 setrot(irs0,i);

         SetQZME();

         FindZRange(irs0);

	 pmfrot->lrots[l] = i + 1;
	 l1 = l + 1;

/*
dfirot: rotamer with all non flexible sidechains and 
        rotamer with backbone part of flexible sidechains and 
        internal rotamer energy (fixed or self pmf ?)
*/

#if defined(VMS) || defined(UNDERSC)
         dumzm(xyz.coo,xyz.ianz,xyz.iatoms);
         dfirot(&l1);
#else
#ifdef CRAY
         DUMZM(xyz.coo,xyz.ianz,xyz.iatoms);
         DFIROT(&l1);
#else
         dumzm_(xyz.coo,xyz.ianz,xyz.iatoms);
         dfirot_(&l1);
#endif
#endif

      


      }
   }

   mx = -1; mn = *zmptr.mxzat;

   for (l=0; l<6; l++) rots[l] = 1;
   for (l=0; l<pmfrot->ndrs; l++) {
      if (pmfrot->ndrs >= l+1) {
	irs[l] = pmfrot->idrs[l];
	rots[l] = aminozmt[calfptr->iamino[irs[l]-1]-1].nrots;
	FindZRange(irs[l]);
	if (*imx > mx) mx = *imx;
	if (*imn < mn) mn = *imn;
      }
   }
   *imx = mx; *imn = mn;

   nresrot = 1;
   resrot[0].etot = 100000.0;
   eupl = 100000.0;

/*
   fprintf(stderr,"rots[0] %d rots[1] %d\n",rots[0],rots[1]);
*/

   for (j0=0; j0<rots[0]; j0++) {
	setrot(irs[0],j0);

	for (j1=0; j1<rots[1]; j1++) {
	   if (pmfrot->ndrs > 1) setrot(irs[1],j1);

	   for (j2=0; j2<rots[2]; j2++) {
		if (pmfrot->ndrs > 2) setrot(irs[2],j2);

		for (j3=0; j3<rots[3]; j3++) {
		   if (pmfrot->ndrs > 3) setrot(irs[3],j3);

		   for (j4=0; j4<rots[4]; j4++) {
			if (pmfrot->ndrs > 4) setrot(irs[4],j4);

			for (j5=0; j5<rots[5]; j5++) {
			   if (pmfrot->ndrs > 5) setrot(irs[5],j5);

		SetQZME();
#if defined(VMS) || defined(UNDERSC)
		dumzm(xyz.coo,xyz.ianz,xyz.iatoms);
		dfiflx(&etot);
#else
#ifdef CRAY
		DUMZM(xyz.coo,xyz.ianz,xyz.iatoms);
		DFIFLX(&etot);
#else
		dumzm_(xyz.coo,xyz.ianz,xyz.iatoms);
		dfiflx_(&etot);
#endif
#endif

/* sum in static contributions */

		etot = etot + pmfrot->estat[j0][0];
		if (pmfrot->ndrs > 1)  etot = etot + pmfrot->estat[j1][1];
		if (pmfrot->ndrs > 2)  etot = etot + pmfrot->estat[j2][2];
		if (pmfrot->ndrs > 3)  etot = etot + pmfrot->estat[j3][3];
		if (pmfrot->ndrs > 4)  etot = etot + pmfrot->estat[j4][4];
		if (pmfrot->ndrs > 5)  etot = etot + pmfrot->estat[j5][5];
/*
   fprintf(stderr,"\nRotcomb res1 %d rot %d, res2 %d rot %d, res3 %d rot %d etot %8.3f eupl %8.3f\n",pmfrot->idrs[0],j0,pmfrot->idrs[1],j1,pmfrot->idrs[2],j2,etot,eupl);
*/

/* 
   copy rotamer sequence with corres. energy to results array 
   when its energy etot is smaller than the higest energy of the current
   array (eupl)
   Since the first element is set at the start to a HIGH value, the condition
   etot < eupl will always be satisfied untill the HIGH value is in the last 
   element of the array and then will disappear.
*/


		if (etot < eupl) {
			for (n=0; n < nresrot; n++) {
			   if (etot < resrot[n].etot) {
				for (k=nresrot-1; k >= n; k--) {
				   if (k+1 <MXROTRES) {
					resrot[k+1] = resrot[k];
				   }
				}
		   		resrot[n].ndrs = pmfrot->ndrs;
		   		resrot[n].etot = etot;
		   		resrot[n].idrs[0] = pmfrot->idrs[0];
		   		resrot[n].idrs[1] = pmfrot->idrs[1];
		   		resrot[n].idrs[2] = pmfrot->idrs[2];
		   		resrot[n].idrs[3] = pmfrot->idrs[3];
		   		resrot[n].idrs[4] = pmfrot->idrs[4];
		   		resrot[n].idrs[5] = pmfrot->idrs[5];
		   		resrot[n].rot[0] = j0;
		   		resrot[n].rot[1] = j1;
		   		resrot[n].rot[2] = j2;
		   		resrot[n].rot[3] = j3;
		   		resrot[n].rot[4] = j4;
		   		resrot[n].rot[5] = j5;
		   		resrot[n].mx = *imx;
		   		resrot[n].mn = *imn;
				if (nresrot < MXROTRES ) nresrot++;
			        eupl = resrot[nresrot-1].etot;
				break;
			   }
			}
		}
                if (debug) prresrot(eupl);
			}
		    }
		}
	    }
	}
   }


   fprintf(stderr,"\nRotOpt ");
   for (j=0; j<resrot[0].ndrs; j++) {
          fprintf(stderr,"res%2d %d rot %d, ",
		j,resrot[0].idrs[j],resrot[0].rot[j]);
   }
   fprintf(stderr," etot %8.3f\n",resrot[0].etot);

   for (j=0; j<nresrot; j++) flxen[j] = resrot[j].etot;

   showresrot(0);
   *idcur = 1;
}

#define MAGIC 1993
#define MAXFNAME 512
#define TOANGS 0.52917706e0
#define MAXFRM 100000

/* little <-> big endian swap */

void bswp(void *v) {
  int *P;

  P = (int *) v;
  *P = (*P&0xff000000)>>24 | (*P&0x00ff0000)>> 8  |
       (*P&0x0000ff00)<< 8 | (*P&0x000000ff)<<24 ;

}

void bswp8(void *v) {
  int *P;
  int b1, b2;

  P = (int *) v;

  b1 = P[0];
  b1 = (b1&0xff000000)>>24 | (b1&0x00ff0000)>>8  |
       (b1&0x0000ff00)<<8  | (b1&0x000000ff)<<24;

  b2 = P[1];
  b2 = (b2&0xff000000)>>24 | (b2&0x00ff0000)>>8  |
       (b2&0x0000ff00)<<8  | (b2&0x000000ff)<<24;

  P[0] = b2;
  P[1] = b1;
}

int trint(FILE *fptr, int *i)
{
   if (fread(i, 4, 1, fptr) != 1) return -1;
   if (strx.swap) bswp(i);
   return 0;
}

int trdble(FILE *fptr, double *r)
{
   float dum;

   if (strx.prec == sizeof(float)) {
	if (fread(&dum, (size_t) strx.prec, 1, fptr) != (size_t) 1) return -1;
	if (strx.swap) bswp(&dum);
	*r = (double) dum;
   } else if (strx.prec == sizeof(double)) {
	if (fread(r, (size_t) strx.prec, 1, fptr) != (size_t) 1) return -1;
	if (strx.swap) bswp8(r);
   }
   return 0;
}

int trstr(FILE *fptr, char *str)
{
   int nstr;

   if (trint(fptr,&nstr) < 0) return -1;

   if (fread(str,1,(size_t) nstr,fptr) != (size_t) nstr) return -1;
   str[nstr] = '\n';
   return nstr;
}

int cntstr(FILE *fptr, char *str)
{
   int nstr,tup,pad;

   if (trint(fptr, &nstr) < 0) return -1;

   tup = nstr/sizeof(int);
   pad = nstr - tup*sizeof(int);
   if (pad) nstr = (tup+1)*sizeof(int);

   if (fread(str,1,(size_t) nstr,fptr) != (size_t) nstr) return -1;
   str[nstr] = '\n';
   return nstr;
}

#if defined(VMS) || defined(UNDERSC)
void gettrr(int *step,int *istat)
#else
#ifdef CRAY
void GETTRR(int *step,int *istat)
#else
void gettrr_(int *step,int *istat)
#endif
#endif
{
   int iframe,debug,istp1,istp2;
   char filename[MAXFNAME];

   debug = 0;

   strcpy(filename,grostr[0]);
   *istat = 0;

   if (init_trr(filename) < 0) {
        *istat = -1;
   } else {

	*geopntr.gcvav = 1;
	*geopntr.ifmxav = 0;
	*geopntr.ifrmav = 0;
	*geopntr.idmxav = 0;
	*geopntr.idrmav = 0;
	*geopntr.ieav = 0;
	*geopntr.ngeoms = 0;
	*geopntr.nepnts = 0;
	*geopntr.dmaxt = 0.0;
	*geopntr.fmaxt = 0.0;
	*geopntr.drmst = 0.0;
	*geopntr.frmst = 0.0;
	iframe = 1;
	while(!gfrm(&iframe,step,0)) {
	   if (iframe == 1) istp1 = *step;
	   if (iframe == 2) istp2 = *step;
	   iframe++;
	}
	*geopntr.ngeoms = strx.nframes = iframe;
	if (debug) fprintf(stderr,"# frames %d\n",strx.nframes);
 	*step = istp2 - istp1;
   }
 
}

void cltrr()
{
   fclose(strx.fptr);
}

int init_trr(char *fileroot)
{
   char filename[MAXFNAME];

   strx.box = strx.vir = strx.pres = strx.x = strx.natoms = strx.swap = 0;
   strx.fpos = (long *) malloc(sizeof(long)*MAXFRM); 
   memset(strx.fpos,-1,sizeof(long)*MAXFRM);

   sprintf(filename,"%s.trr",fileroot);

   strx.fptr = fopen(filename, "rb");
   if (strx.fptr == NULL) {
	fprintf(stderr,"Didnt find trajectory file: %s\n\n",filename);
	return -1;
   }
   return 0;
}

int header_trr(int *step)
{
   char sdummy[80];
   int magic;
   int dummy;
   double rdum;

   if (trint(strx.fptr,&magic) < 0) return -1;
   if (magic != MAGIC) {
	bswp(&magic);
	if (magic != MAGIC) {
	   fprintf(stderr,"Magic number mismatch\n");
	   return -1;
	}
	strx.swap = 1;
   }

   if (trint(strx.fptr,&dummy) < 0) return -1;
   if (trstr(strx.fptr,sdummy) < 0) return -1;
   if (trint(strx.fptr,&dummy) < 0) return -1;
   if (trint(strx.fptr,&dummy) < 0) return -1;
   if (trint(strx.fptr,&strx.box) < 0) return -1;
   if (trint(strx.fptr,&strx.vir) < 0) return -1;
   if (trint(strx.fptr,&strx.pres) < 0) return -1;
   if (trint(strx.fptr,&dummy) < 0) return -1;
   if (trint(strx.fptr,&dummy) < 0) return -1;
   if (trint(strx.fptr,&strx.x) < 0) return -1;
   if (trint(strx.fptr,&strx.v) < 0) return -1;
   if (trint(strx.fptr,&strx.f) < 0) return -1;
   if (trint(strx.fptr,&strx.natoms) < 0) return -1;
   if (trint(strx.fptr,step) < 0) return -1;
   if (trint(strx.fptr,&dummy) < 0) return -1;

/*
   fprintf(stderr,"box %d vir %d pres %d x %d v %d f %d natoms %d\n",
       strx.box,strx.vir,strx.pres,strx.x,strx.v,strx.f,strx.natoms);
*/

   if (strx.x) strx.prec = strx.x/(strx.natoms*3);
   else if (strx.v) strx.prec = strx.v/(strx.natoms*3);
   else if (strx.f) strx.prec = strx.f/(strx.natoms*3);

   if (trdble(strx.fptr,&rdum) < 0) return -1;
   if (trdble(strx.fptr,&rdum) < 0) return -1;

   return 0;
}

#if defined(VMS) || defined(UNDERSC)
void gtfrm(int *frame)
#else
#ifdef CRAY
void GTFRM(int *frame)
#else
void gtfrm_(int *frame)
#endif
#endif
{
   int idum,step;

   idum = 0;

   if (gfrm(frame,&step,1)) idum = 1;
}

int gfrm(int *frame,int *step,int set)
{
   int i,j,frame_done,ioff;
   double v[3][3],rdum,vdum[3];
/*
should set coordinate atom first read of trr (to set fpos)
because only after rdgro, coordinates are converted to bohr
we need them in angs after rdgro and in bohr after gfrm
*/

   if (!strx.fptr) return -1;

   if (strx.fpos[(*frame)-1] == -1) {
	strx.fpos[(*frame)-1] = ftell(strx.fptr);
        frame_done = 0;
   } else {
	fseek(strx.fptr, strx.fpos[(*frame)-1], SEEK_SET);
        frame_done = 1;
   }

   if (header_trr(step) < 0) return -1;

   if (strx.box) {
      for (i=0; i < 3; i++) {
	for (j=0; j < 3; j++) {
	   if (trdble(strx.fptr,&v[i][j]) < 0) return -1;
	   v[i][j] = v[i][j]*10.0/TOANGS;
	}
      }
      if (cellpnt->iclon) {
	ioff = cellpnt->iclpnt[0];
	if (set) {
	   for (i=0; i < 3; i++)
	      for (j=0; j < 3; j++) xyz.coo[(i+ioff)*3+j] = v[i][j];
	   for (j=0; j < 3; j++) xyz.coo[(ioff+3)*3+j] = v[0][j] + v[1][j];
	   for (j=0; j < 3; j++) xyz.coo[(ioff+4)*3+j] = v[1][j] + v[2][j];
	   for (j=0; j < 3; j++) xyz.coo[(ioff+5)*3+j] = v[0][j] + v[2][j];
	   for (j=0; j < 3; j++) xyz.coo[(ioff+6)*3+j] = v[0][j] + v[1][j] + v[2][j];
	}
      }
   }
   if (strx.vir) {
      for (i=0; i < 9; i++)
	if (trdble(strx.fptr,&rdum) < 0) return -1;
   }
   if (strx.pres) {
      for (i=0; i < 9; i++)
	if (trdble(strx.fptr,&rdum) < 0) return -1;
   }

   if (strx.x) {
      for (i=0; i < strx.natoms; i++) {
	for (j=0; j < 3; j++) {
	   if (trdble(strx.fptr,&vdum[j]) < 0) return -1;
	   if (set) xyz.coo[i*3+j] = vdum[j]*10.0/TOANGS;
	}
      }
   }      

   if (frame_done) return 0;

   if (strx.v) {
      for (i=0; i < strx.natoms; i++) {
	for (j=0; j < 3; j++) {
	   if (trdble(strx.fptr,&vdum[j]) < 0) return -1;
	}
      }
   }      

   if (strx.f) {
      for (i=0; i < strx.natoms; i++) {
	for (j=0; j < 3; j++) {
	   if (trdble(strx.fptr,&vdum[j]) < 0) return -1;
	}
      }
   }      

   return 0;
}

void cledr()
{
   fclose(stre.fptr);
}

#if defined(VMS) || defined(UNDERSC)
void getene(int *nstep,int *istat)
#else
#ifdef CRAY
void GETENE(int *nstep,int *istat)
#else
void getene_(int *nstep,int *istat)
#endif
#endif
{
   int i,iframe,iold,step,istp1,istp2,nestp,nepnts,nepntst;
   double ener,eprepos,rfrac;
   char filename[MAXFNAME];

/* preposterous value */

   eprepos = 1.54321e-20;
   strcpy(filename,grostr[0]);
   *istat = 0;

   *geopntr.ieav = 0;

MOREMEM:

   if (init_edr(filename) < 0) {
        *istat = -1;
   } else {

	*geopntr.nepnts = 0;
	for (i=0;i<*geopntr.mxpnt;i++) geopntr.epoints[i] = eprepos;
	iframe = 0;
	while(!efrm(&step,&ener)) {
	   if (iframe == 0) istp1 = step;
	   if (iframe == 1) {
		istp2 = step;
		nestp = istp2 - istp1;
		rfrac = (double) nestp / (double) *nstep;
	   }
	   iframe++;
	   nepntst = nepnts = (int) (((double)(iframe-1))*rfrac);
	   if (nepnts <= *geopntr.mxpnt) geopntr.epoints[nepnts] = ener;
	}
	if (nepntst > *geopntr.mxpnt) {
	   
	   nepntst++;
#if defined(VMS) || defined(UNDERSC)
	   allgeo(&nepntst);
#else
#ifdef CRAY
	   ALLGEO(&nepntst);
#else
	   allgeo_(&nepntst);
#endif
#endif
	   rewind(stre.fptr);
	   goto MOREMEM;
	}
	*geopntr.nepnts = nepnts+1;
	*geopntr.ieav = 1;
	iold = 0;
	for (i=0;i<*geopntr.nepnts;i++) {
	   if (geopntr.epoints[i] == eprepos) 
		geopntr.epoints[i] = geopntr.epoints[iold];
	   else iold = i;
	}
	(void) cledr();
#if defined(VMS) || defined(UNDERSC)
	gmmcnv(geopntr.formax,geopntr.forrms,geopntr.dismax,geopntr.disrms,
		geopntr.epoints,geopntr.isav);
#else
#ifdef CRAY
	GMMCNV(geopntr.formax,geopntr.forrms,geopntr.dismax,geopntr.disrms,
		geopntr.epoints,geopntr.isav);
#else
	gmmcnv_(geopntr.formax,geopntr.forrms,geopntr.dismax,geopntr.disrms,
		geopntr.epoints,geopntr.isav);
#endif
#endif
	
   }
 
}

int init_edr(char *fileroot)
{
   char filename[MAXFNAME];
   char sdummy[80];
   int i,nre;

   sprintf(filename,"%s.edr",fileroot);

   stre.fptr = fopen(filename, "rb");
   if (!stre.fptr) {
	fprintf(stderr,"Didnt find energy file: %s\n\n",filename);
	return -1;
   }

   if (trint(stre.fptr,&nre) < 0) return -1;

   for (i=0;i<nre;i++) {
	if (cntstr(stre.fptr,sdummy) < 0) return -1;
	if (strstr(sdummy,"Total Energy")) stre.etot = i;
   }

   return 0;
}

int header_edr(int *step,int *nre)
{
   int i;
   int dummy, nblock;
   double rdum;

/* edr does not work with magic number ? */

/* t, step, nre, ndisre, nblock, esize, dsize dum */

   if (trdble(stre.fptr,&rdum) < 0) return -1;
   if (trint(stre.fptr,step) < 0) return -1;
   if (trint(stre.fptr,nre) < 0) return -1;
   if (trint(stre.fptr,&dummy) < 0) return -1;
   if (trint(stre.fptr,&nblock) < 0) return -1;
   for (i=0;i<nblock;i++)
	if (trint(stre.fptr,&dummy) < 0) return -1;
   if (trint(stre.fptr,&dummy) < 0) return -1;
   if (trint(stre.fptr,&dummy) < 0) return -1;
   if (trint(stre.fptr,&dummy) < 0) return -1;

   return 0;
}


int efrm(int *step,double *ener)
{
   int i,nre;
   double rdum;

   if (header_edr(step,&nre) < 0) return -1;

   for (i=0; i < nre; i++) {
	if (trdble(stre.fptr,&rdum) < 0) return -1;
	if (i == stre.etot) *ener = rdum;
	if (trdble(stre.fptr,&rdum) < 0) return -1;
	if (trdble(stre.fptr,&rdum) < 0) return -1;
	if (trdble(stre.fptr,&rdum) < 0) return -1;
   }

   return 0;
}

SetExplButton(win,x,y)
Window win;
int x,y;
{
   BSTRU *arr; int nbut,fnd,i,j; Window sub;
   QBOXSTRU *qbptr[5] = {IANZbox,BLbox,ALPHbox,BETbox,IZbox};
   int *winup = NULL;

   if (expldat.active) return;

   if (win == ZMEwin) {
	if (ZMEmode) {
	    arr = ZMEBbut; nbut = 3;
	} else {
	    arr = ZMEbut; nbut = ZMEBUTTS;
	}
	sub = subZM;
	winup = &ZMEup;
   } else if (win == ATMwin) {
	arr = butATM; nbut = NBUTATM;
	sub = subATM;
	winup = &ATMup;
   } else if (win == winMC) {
	arr = cbut; nbut = NBUTTS2;
	sub = subMC;
   } else if (win == winC) {
	arr = dbut; nbut = NBUTTS;
	sub = subC;
	winup = &denmode;
   } else if (win == ONIwin) {
	arr = onbut; nbut = NBUTSO;
	sub = subONI;
	winup = &ONIup;
   } else if (win == TNKwin) {
	arr = butTNK; nbut = NBUTTNK;
	sub = subTNK;
	winup = &TNKup;
   } else if (win == DISTwin) {
	arr = clbut; nbut = NCLBUT;
	sub = subDIST;
	winup = &distup;
   } else if (win == winspec) {
	arr = spbut; nbut = NSBUTTS;
	sub = subSPEC;
	winup = &specup;
   } else {
	return;
   }

   fnd = 0;

   i = Clickwin(arr,nbut,x,y,0);

   if (i >= 0) {

	if (arr[i].explstr != NULL && arr[i].active) {

		expldat.button = i;
		expldat.win = sub;
		expldat.winup = winup;
		expldat.barr = arr;
		expldat.borq = 0;
		fnd = 1;
	}

   } else {
	i = CheckBox(qboxes,NQBOX,win,x,y);
	if (i >= 0) {
	   if (qboxes[i].explstr != NULL) {
		expldat.button = i;
		expldat.win = sub;
		expldat.winup = winup;
		expldat.qarr = qboxes;
		expldat.borq = 1;
		fnd = 1;
	   }
	}
	if (!fnd && win == ZMEwin) {
	   for (j=0; j < 5; j++) {
	     if (!fnd) {
		int n;
		n = *zmptr.nz;
		if (j == 4) n = *zmptr.nz*4;
		i = CheckBox(qbptr[j],n,win,x,y);
		if (i >= 0) {
		   if ((qbptr[j])[i].explstr != NULL) {
			expldat.button = i;
			expldat.win = sub;
			expldat.winup = winup;
			expldat.qarr = qbptr[j];
			expldat.borq = 1;
			fnd = 1;
		   }
		}
	     }
	   }
	}
   }

   if (fnd) {
#ifdef HASTIMER
	Timer(1500,2);
#else
	signal(SIGALRM,handle_explalarm);
	alarm(2);
#endif
   } else {
	signal(SIGALRM,SIG_IGN);
   }
}

#if defined(VMS) || defined(UNDERSC)
void chktmp()
#else
#ifdef CRAY
void CHKTMP()
#else
void chktmp_()
#endif
#endif
{
#ifdef __CYGWIN__
int status;

   if (access("/cygdrive/c/tmp",F_OK) != 0) {
	status = mkdir("/cygdrive/c/tmp", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
	if (status == -1) fprintf(stderr,"Directory C:\\tmp not found\n");
   }

#endif

}

struct stat s_buf;

int dos2u(path)
char *path;
{
	FILE *in, *out;
	int ch, rval = 0;
	char temppath [16];
	struct utimbuf { time_t actime, modtime; } ut_buf;

	strcpy (temppath, "./clntmp");
	strcat (temppath, "XXXXXX");
	mktemp (temppath);

	if ((in=fopen (path, "r")) == (FILE *) 0) return 1;

	if ((out=fopen (temppath, "w")) == (FILE *) 0) {
	   fclose (in);
	   return 1;
	}

	while ((ch = getc(in)) != EOF) {
	   if ( (ch != '\015' && ch != '\032') &&
		(putc (ch, out) == EOF) ) {
		rval = 1;
		break;
	   }
	}

	if (fclose(in) == EOF) rval = 1;
	if (fclose(out) == EOF) rval = 1;

	ut_buf.actime = s_buf.st_atime;
	ut_buf.modtime = s_buf.st_mtime;
	if (utime(temppath, &ut_buf) == -1) rval = 1;

	if (unlink(path) == -1) rval = 1;

	if (rval) {
	   unlink(temppath);
	   return 1;
	}

	if (link(temppath,path) == -1) {
	   fprintf (stderr, "Problems renaming '%s' to '%s'\n", temppath, path);
	} else {
	   unlink (temppath);
	}
	return 0;
}

