#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
#if defined(DARWIN) || defined(FREEBSD)
#else
#include <malloc.h>
#endif
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <stddef.h>
sigset_t block_alarm;
sigset_t waiting_mask;
sigset_t base_mask;

#ifdef HASTIMER
#include <sys/time.h>
static struct itimerval it[3],ot;
#endif

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


#if defined(CRAY) || defined(DARWIN)
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 LFONT "-*-helvetica-bold-r-*-*-24-*-*-*-*-*-*-*"
#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 DoFreq = 0;
static int DoEig = 0;
static int *movie;
static int *iuhf;
static int ibeta;
static double *esp;
static double *pol;
static double *pol2;
static double *dmao;
static int *nor;
typedef struct { 
	double *cl; 
	double *rij; 
	double *qpix;
	double *qpjx;
	double *dmao;
	int *nor;
	int *iord;
	int *iir; } BOYSPNT;
static BOYSPNT boy = { NULL,NULL,NULL,NULL,NULL,NULL };
typedef struct { 
	double *xden; 
	double *yden; 
	double *zden;
	} FSTGRD;
static FSTGRD fsgrd = { NULL,NULL,NULL};
static int *ipsa;
static int *icpsa;
static int *idtpsa;
static double cntval = 0.01;
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;
static int *normc;     

typedef struct { 
		 int natc;
		 int norg;
		 int icent;
		 int inorm;
		 int ncon;
		 int nspg;
		 int kz;
		 int ichx;
		 int icrtp;
		 int nopr;
		 short int ir[3][3][192];
		 short int it[3][192];
		 double xyzc[6];
		 double cellc[6];
               } CELLSTRU;
static CELLSTRU *cell;

typedef struct { int iclon;
		 int iclpnt[4];
               } CELLSTRUC;
static CELLSTRUC *cellpnt;
static char *CellStr[] = {" O"," A"," B"," C"};

typedef struct { 
		 int ipoints;
		 int ipnt;
               } PNTSTRU;
static PNTSTRU *pnt;

typedef struct { 
		 int *nzm;
		 int *nso;
		 int *nio;
		 int *nzo;
		 int *ioropt;
		 int *ifor;
		 int *ixyz98;
		 int *iopr;
		 int *isymm;
		 int *irc;
		 int *imp2;
		 int *icntp;
		 int *msucc;
		 int *ioni;
		 int *mopopt;
		 int *isbin;
		 int *irtype;
		 int *ipdbgro;
		 int *ifav;
		 int *ioxyz;
		 int *iconv;
		 int *ircus;
		 int *nscnd;
		 int *iscst;
		 int *ialtyp;
               } PPOISTRU;
static PPOISTRU ptrpoi;

typedef struct { 
		 int nzm;
		 int nso;
		 int nio;
		 int nzo;
		 int ioropt;
		 int ifor;
		 int ixyz98;
		 int iopr;
		 int isymm;
		 int irc;
		 int imp2;
		 int icntp;
		 int msucc;
		 int ioni;
		 int mopopt;
		 int isbin;
		 int irtype;
		 int ipdbgro;
		 int ifav;
		 int ioxyz;
		 int iconv;
		 int ircus;
		 int nscnd;
		 int iscst;
		 int ialtyp;
               } POISTRU;
static POISTRU poi;

typedef struct { 
		 double abc[3];
		 int ibox;
		 int icell;
		 int igfmap;
               } PBCSTRUC;
static PBCSTRUC *pbc;

static char *alphbet[] = {"alpha","beta"};
static char *strsnd[] = {"HELIXOUT","STRANDTOP","RNA","COIL"};
static char *rwopt[] = {"Read","Write"};
static char *cubeopt[] = {"Gaussian","Vasp","Jaguar"};
static char *labels[] = {"atom","atom+number","ForceF.Type","atom+charge","PDBsymbol","Residue","Nuc. Shld."};
#ifdef MPFIT
static char *pots[] = {"True Electrost. Pot.","Multipole Derived","Charges Derived","Topol. PSA","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","GRID kont","Ramachandran","Fit MultiPoles"};
#else
static char *pots[] = {"True Electrost. Pot.","Multipole Derived","Charges Derived","Topol. PSA","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","GRID kont","Ramachandran"};
#endif
static char *eems[] = {"EEM NPA","EEM Mull","EEM PESP","EEM ESFF","Gasteiger"};
static char *pots2[] = {"True Electrost. Pot.","Multipole Derived","Charges Derived"};
static char *readgrd[] = {"Replace Grid","Subtract"};
static char *surftyp[] = {"Van der Waals","IsoDensity (Slow)","DMAPSA"};
static char *hyds[] = {"Excl. All Hydrogens","Excl. H except H-bond","(Re)calculate H-bond","H-bond parameters","Opt. H positions"};
static char *postopt[] = {"Mono","Color"};
static char *srfopt[] = {"Mono-colored surface","Elec. Pot. Mapped"};
static char *srf2opt[] = {"Elec. Density Surf.","Solv. Acc. Surf."};
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","Surfaces","Chains","Blur","Occlusion","Shadows"};
static char *occlopt[] = {"Best","Good"};
static char *bgopt[] = {"Solid Color","Gradient Color"};
static char *spdopt[] = {"Normal Density","Spin Density"};
static int *ivdwpl;
static char *vdwstr[]={ "Sticks", "Space Filling", "Ball & Sticks"};
static char *alnopt[]={ "Align 2 molecules", "Interactive Docking"};
static char *dckopt[]={ "Read from PDB file", "Pick Molecule on Screen"};
static int ieemopt = 1;
static int *icolps;
static int *idelx;
static int *ivtwo;
static int *ixyz;
static int *iixyz;
static int *ipnt;     
static int *iwropt;
static int denmode = 0;
static int inactMC;
static int inafMC;
static int *ispd;
static int *ibgcol;
static int *ibgclo;
static int *ibgmod;
static int iupres[500];
static int nupres = 0;

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 createspec(int dowin);
void butje(Window bwin,int x,int y,int w,int h,int r,int bgcol,int sh_ind,int iopt,Pixmap pix,int pw,int ph,int rec);
void doclr();
void drwspec();
void glpnt(int wide,int high,double x,double y,int *xr,int *yr,int iframe);
void drwsco();
void Timer(int msec,int timopt);
#if defined(VMS) || defined(UNDERSC)
void drwgeo();
#else
#ifdef CRAY
void DRWGEO();
#else
void drwgeo_();
#endif
#endif
void drwgl(Window gwin,int wide,int high,double x1,double y1,double x2,double y2,int icol,int icross,int iframe,int isdash);
void RedrawWin();
void  Key(unsigned char key);
static Bool gijsup = 0;
static Bool ramaup = 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 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 int *backb;
static Bool isdash = 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 int THREE = 3;
static int FOUR = 4;
static int FIVE = 5;
static int EIGHTEEN = 18;
static double THRESH = 3.5;
static Colormap cmap;
static int StarNetOld = 0;
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 int inited = 0;
static Bool ZoomEnable = True, ZoomSelection = False;
static Bool Select = True;
static Cursor ZoomCursor;
static Cursor AtomCursor;
static Cursor WaitCursor;
static int *jring;
static int *isimpl;
static int *fancy;
static int *istaro;
static int *atcol;
static int *shade;
static int *persp;
static int TRANS;
static int TRANSb;
static int DoShadow = 0;
static int DoLines = 0;
static int DoBlur = 0;
static int DoSSAO = 0;
static int DoShad = 0;
static int DoMIPMAP = 1;
static int SSAO_type = 1;
static int aflag = 0,anum,acnt;
static int bflag = 0;
static int cflag = 0;
static int dflag = 0;
static int eflag = 0;
static int doalign = 0;
static int bretval = 320;
static int omapr = 0;
static int omapfol = 0;
static int omaplck = 0;
static int omaphlp = 0;
static int omapCa = -1;
static int omapPandN = 0;
#define MINDIFF 15
static int asel[6];
static int aselkeep[2];
static int monmode = 2;
static float aret;
static float toangs = 0.52917706e0;

static Window win,winC,subC,winMC,subMC,winau,wincnv,wingeo,winspec,subSPEC,winsco,winpmf,winrama; 			
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;
static XFontStruct *labinfo;
Pixmap icon_pixmap;
Region region;
void filecall(char *str);
void fwincall(char *str);
void substrcall(char *str);
void getpdbcall(char *str);
static int addfile = 0;
static int poszset = 0;
static float poszbck = 0;

static int xlx, yly ;			/* more statics for     */
static int start_xlx, start_yly;	/* line drawing		*/
static int isgl2D = 0;
#ifdef DOGL
static GLuint theDens;
static GLfloat gxlx, gyly ;			/* more statics for     */
static GLfloat gstart_xlx, gstart_yly;	/* line drawing		*/
static float CV[6][3] = {
  {0.4,0.0,0.0},
  {0.0,0.4,0.0},
  {0.0,0.0,0.4},
  {-0.4,0.0,0.0},
  {0.0,-0.4,0.0},
  {0.0,0.0,-0.4}
};
#endif
static unsigned int width, height;		/* window size		*/
static float Aspect = 1.0;
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;
const char *glExtensions;
static int attributeList[] = {GLX_RGBA, GLX_DEPTH_SIZE,16, 
GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, 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;
static char *unknown  = "Unknown";

#define MAXSTRLEN 80 
#define MAXSTRLMW 40 
#define MAXNAMES 10000
#define MAXDIRS 500
#define MAXDIRLEN 1024
#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 rwi = 300;
static int rhi = 300;
static int rwiold = 300;
static int rhiold = 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 *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 *gfile;
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 gfile;
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 *gfile;
static char *oglfile;
static char *povfile;
#endif
#endif

#define MAXCMD 256
static char cmdstr[MAXCMD];
static int cycle = 0;
static int delcyclefile = 0;
/*static int fndfile = 0;*/
volatile sig_atomic_t fndfile;
/*static int uping = 0;*/
volatile sig_atomic_t uping;
static int tnkfrk = 0;
static int tnkpid = 0;
static int tnkupd = 0;
volatile sig_atomic_t tnkupf = 0;
static int tnkesc = 0;
static int tnkloop = 0;
static int handle = 0;
static int tnk_single = 0;
static int opttim = 0;
static int icyco = 0;
static int TIMi = 100;
#define NCYCO 5
static long timo[NCYCO];
static double newen;
static int hasmpi = 0;
static char mpicmd[MAXCMD];
static char mpilib[MAXCMD];
static char npth[MAXCMD];
static int maxproc = 0;
static int useproc = 1;
static int usempi = 0;

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 void (*ptr_void_proc)();

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;

void DrwBut(BSTRU *bp);

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 */
		 ptr_void_proc callback;/* callback routine */
               } 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 *slst;		/* pointer into selected 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 struct { Window win;            /* parent window */
		 LISTSTRU flist;
		 LISTSTRU dirlist;
		 BSTRU rbut[5];
		 char  *files[MAXNAMES];
		 char  *dirs[MAXDIRS];
		 char  lastdir[MAXDIRLEN];
		 char  label[MAXSTRLEN];
		 char  substr[MAXSTRLEN];
		 char *pntr;
		 int nfiles;
		 int ndirs;
		 int qbrfile;
		 int inct;
		 int parse;
		 int subopt;
               } FSELSTRU;

void getfiles(FSELSTRU *fs, char* dirname);
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;

void PromptBox(QBOXSTRU *qp);

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

static SRFSTRU *surface;

typedef struct { Window win;            /* parent window */
		 int x,y;		/* pos. of scroll rectangle */
                 unsigned int w,h;      /* size of scroll rectangle */
		 int sh;		/* slider height */
		 int *wn;		/* max slider position */
		 int *wpos;		/* slider position */
		 float *ratio;		/* ratio */
		 ptr_void_proc callback;/* callback routine */
               } SLIDESTRU;

#define MXTITL 41
static char *mlftit[MXTITL];
static int ntits = 0;
static double *scle;
static double *adjuss;
static double *rng1;
static double *rng2;
static double *vlcnt;
static double *vlcnt2;

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 *ambwopts[] = {"Without Cell","With Cell"};

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;
                 int *isav;
		 int mxorg;
               } GEOPSTRU;

static GEOPSTRU geopntr;
static GEOPSTRU TMPgeopntr;

static GEOPSTRU *geop = &geopntr;

#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 { int ihasd;
		 int isgau;
		 int ido5d;
		 int ido7f;
		 int ido9g;
		 int ihasg;
               } GAUSTRU;
static GAUSTRU *slagau;

#define MAXFAT 1000
#define MAXFRQ MAXFAT*3
typedef struct { float freq[MAXFRQ];
		 float a[MAXFAT][3];
		 double fcoo[MAXFAT][3];
		 double frint[MAXFRQ];
		 double ramint[MAXFRQ];
		 int nfreq;
		 int ihasi;
               } FRQSTRU;
static FRQSTRU *FRQ;

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;
		 int mxzorg;
		} ZMSTRU;

static ZMSTRU zmptr;
static ZMSTRU TMPzmptr;
static ZMSTRU *zmptrp = &zmptr;

typedef struct { int ipart;
		 int imn;
		 int imx;
		 int idcur;
		} ZMPARTSTRU;

static ZMPARTSTRU *zmpart;

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;
static STOCSTRU *stocp = &stoc;

#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;
static ORBSTRU *orbp = &orb;

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;
		 int mxorg;
               } DORBSTRU;

static DORBSTRU dorb;
static DORBSTRU TMPdorb;
static DORBSTRU *dorbp = &dorb;

#define NUMPRM 1600
#define NUMCEX NUMPRM*3

typedef struct { double exx[NUMCEX];
		 double c1[NUMCEX];
		 double c2[NUMCEX];
		 double c3[NUMCEX];
		 double c4[NUMCEX];
		 double c5[NUMCEX];
		 int shladf[NUMPRM];
		 double gx[NUMPRM];
		 double gy[NUMPRM];
		 double gz[NUMPRM];
		 int jan[NUMPRM];
		 int shella[NUMPRM];
		 int shelln[NUMPRM];
		 int shellt[NUMPRM];
		 int shellc[NUMPRM];
		 int aos[NUMPRM];
		 int nshell;
		 int maxtyp;
               } BASSTRU;
static BASSTRU *BAS;

#define NUMATM 2000

typedef struct { int ipseud;
		 int ivale[NUMATM];
               } PSEUDSTRU;
static PSEUDSTRU *PSEUD;

typedef struct { int nfirst[NUMATM];
		 int nlast[NUMATM];
		 int npq[NUMATM];
		 int pqn[NUMATM];
		 double emus[NUMATM];
		 double emup[NUMATM];
		 double emud[NUMATM];
		 double consts[NUMATM];
		 double constp[NUMATM];
		 double constd[NUMATM];
		 int npqref[54];
               } MOPSTRU;
static MOPSTRU *MOP;

typedef struct { double px;
		 double py;
		 double pz;
		 double cx;
		 double cy;
		 double cz;
		 double r[3];
		 double v1[3];
		 double v2[3];
		 int iplat;
               } PLANESTRU;
static PLANESTRU *plane;

typedef struct { double ca;
		 double cb;
		 double sa;
		 double sb;
		 double cc;
		 double sc;
               } EULSTRU;
static EULSTRU *eul;

typedef struct { double xsym[NUMATM];
		 double ysym[NUMATM];
		 double zsym[NUMATM];
		 int isym[NUMATM];
               } PROJSTRU;
static PROJSTRU *proj;

typedef struct { 
		 double nucshld[NUMATM];
		 int ihsnmr;
               } NMRSTRU;
static NMRSTRU *nmrptr;
static double *jcoupl = NULL;

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;

#define MAXMOL 100

typedef struct { int nmols;
		 int imol;
		 int iendmf;
		 int ielin;
		 int mollin[MAXMOL];
		} MFSTRU;

static MFSTRU *mfdata;

#define MXPLEV 5
typedef struct { double grdw;
		 double plevel[MXPLEV];
		 int ipcol[MXPLEV+1];
		 int nplev;
		} POTSTRU;

static POTSTRU *potcom;

typedef struct { int nps1;
		 int nps2;
		 int nps3;
		 int srfmap;
		 int srfloc;
		 int ifogl;
		 int itsrf;
		} HSRFSTRU;

static HSRFSTRU *hlpsrf;

typedef struct { int ito;
		 int imo;
		 int ibo;
		 int itotc;
		 int imult;
		 int ibatch;
		 int ihs;
		 int itm;
		 int iwxyz;
		 int icopth;
		 int icoptm;
		 int icoptl;
		 int ispopth;
		 int ispoptm;
		 int ispoptl;
		} JOBSTRU;

static JOBSTRU *jobcom;

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;
		} POSSTRU;

static POSSTRU *posptr;

typedef struct { 
		 double scal;
		 double fscal;
		 double scali;
		 double smag;
		 int iscupd;
               } SCALSTRU;

static SCALSTRU *scalptr;

#define NUMCAL 10000
#define MXCHAI 50
#define MXRES 42
#define MXHETA 150
#define MXALN 20

typedef struct { 
		 double rphi[NUMCAL];
		 double rpsi[NUMCAL];
		 int icalf[NUMCAL][6];
		 int ncalf;
		 int ianf[MXCHAI];
		 int islu[MXCHAI];
		 int nchain;
		 int iamino[NUMCAL];
		 int ihet[MXHETA];
		 int iclhet[MXHETA];
		 int reson[NUMCAL];
		 int issdon;
		 int icxp[NUMCAL];
		 int icyp[NUMCAL];
		 int iams[NUMCAL];
		 int ihets[MXHETA];
		 int ibck[4];
		 int isal[NUMCAL];
		 int irsnr[NUMCAL];
		 int ihashb;
		 int ishoh;
		 int achain[NUMCAL];
		} CALFSTRU;

static CALFSTRU *calfptr;

typedef struct { int ihashz;
		 int ihetq[MXHETA];
		 int ihqset[MXHETA];
		 int ihhadd[MXHETA];
		} CLFSTRU;

static CLFSTRU *clfstrptr;

typedef struct { int nalign;
		 int istst[MXALN];
		 int istch[MXALN];
		 int istres[MXALN];
		 int istcol[MXALN];
		 char *istptr[MXALN];
		} ALNSTRU;

static ALNSTRU *alnptr;

static char  *HetAtm[MXHETA];
static int NHetAtm = 0;

#define MXHETLAB 5000
typedef struct { int iat[MXHETLAB];
		 char  *HetLab[MXHETLAB];
		 int NHetLab;
		} HETLABSTRU;
static HETLABSTRU hetlab = {.NHetLab = 0};

typedef struct { 
		 int isndcl[4];
		 int iamicl[MXRES];
		 int ichcol[MXCHAI];
		} CLFHSTR;

static CLFHSTR *clfhptr;

static int *iftyp;

typedef struct { double *coo;
		 double *rzp;
		 double *qat;
		 int *isurf;
		 int *icont;
		 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 *ncont;
		 int mxorg;
               } COOSTRU;

static COOSTRU xyz;
static COOSTRU TMPxyz;
static COOSTRU *xyzp = &xyz;

/* static dimension density coordinates*/


typedef struct { double xyz[NUMATM][3]; 
	} XYZSTRU;
static XYZSTRU *XYZ;

typedef struct { 
		int natoms;
		int norbs;
		int nelecs;
		int nat[NUMATM]; 
	} NATSTRU;
static NATSTRU *NAT;

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

static CHGDIP *qdpptr;

#define MXEL 100
#define MAXSTRUCT 100
typedef struct { COOSTRU coo;
		 CALFSTRU calf;
		 CLFSTRU clfstr;
		 ALNSTRU alnstr;
		 ROTSTRU rot;
		 POSSTRU pos;
		 SCALSTRU scal;
		 CELLSTRU cell;
		 CELLSTRUC cellpnt;
		 CNVSTRU cnv;
		 GEO1STRU geo;
		 GEOPSTRU geop;
		 POISTRU poi;
		 XYZSTRU XYZ;
		 NATSTRU NAT;
		 ZMSTRU zmt;
		 QBOXSTRU *IANZbox;
		 QBOXSTRU *BLbox;
		 QBOXSTRU *ALPHbox;
		 QBOXSTRU *BETbox;
		 QBOXSTRU *IZbox;
		 STOCSTRU stoc;
		 DORBSTRU dorb;
		 ORBSTRU orb;
		 BASSTRU bas;
		 GAUSTRU gau;
		 MOPSTRU mop;
		 FRQSTRU frq;
		 PSEUDSTRU pseud;
		 PLANESTRU plane;
		 EULSTRU eul;
		 PROJSTRU proj;
		 MFSTRU mfdata;
		 POTSTRU potcom;
		 ZMPARTSTRU zmpart;
		 JOBSTRU jobcom;
		 CHGDIP qdpptr;
		 HSRFSTRU hlpsrf;
		 HETLABSTRU hetlab;
		 NMRSTRU nmr;
		 PBCSTRUC pbc;
		 double *jcoupl;
		 sttrr strx;
		 int ipoints;
		 char *HetAtm[MXHETA];
		 int NHetAtm;
		 char *frsym[MAXFRQ];
		 char *mlftit[MXTITL];
		 int ntits;
		 char *fname;
		 char *pdbcode;
		 int iatoms;
		 int mxnat;
		 int pdb;
		 int backb;
		 int iftyp;
		 int natorg;
		 int nz;
		 int ihaszm;
		 int mxzat;
		 int ncols;
		 int ncolb;
		 int nocc;
		 int nocb;
		 int naorbs;
		 int mxorb;
		 int uhf;
		 int spd;
		 int ipsi;
		 int inact;
		 int inaf;
		 int atcol;
		 int ZMEAA;
		 int doesp;
		 int fftyp;
		 int irtcel;
		 int normc;
		 int icst;
		 int ibox;
		 int igfmap;
		 int iresrd;
		 int fancy;
		 int ihasex;
		 double uscl;
		 double adjus;
               } STRUSTRU;

static STRUSTRU *COO[MAXSTRUCT];
static char  *strfiles[MAXSTRUCT];

static int nstruct = 0;
static int istruct = 0;
static int sstruct = 0;

static int *multstruct;

typedef struct { float vert[3]; int type;} VRTSTRU;

#ifdef DOGL
#define MAXSURF 500
#else
#define MAXSURF 15
#endif

static int SSon[MAXSTRUCT][MAXSURF];
static int SStyp[MAXSTRUCT][MAXSURF];
static int Schain[MAXSTRUCT][MAXSURF];
static int clp[MAXSTRUCT][MAXSURF];
static int trns[MAXSTRUCT][MAXSURF];
static int SSdone[MAXSTRUCT];
static int NSurf[MAXSTRUCT];
static int NMols[MAXSTRUCT];
static int CMols[MAXSTRUCT];
static double scl[MAXSTRUCT];
static char *sndstr[MAXSTRUCT][MAXSURF];
static int nwater[MAXSTRUCT];
static double *watcoo[MAXSTRUCT];
static int *watanz[MAXSTRUCT];
static int *watres[MAXSTRUCT];
static int *watcon[MAXSTRUCT];
static int *watmap[MAXSTRUCT];

#define MXVERT 5000
#define MXVERT2 10000
#define MXVERT3 100000
#define MXVERT4 200000
#define MXVERT5 300000
#define MXVERT6 400000
#define MXVERT7 500000
#define MXVERT8 1000000
#define MXVERT9 2000000
#define MXVERT10 3000000
#define MXVERT11 4000000
#define MXVERT12 5000000
static int dovrt = 1;
static VRTSTRU *srfvert[MAXSTRUCT][MAXSURF];
static int nvert[MAXSTRUCT][MAXSURF];
static int nvrtmx[MAXSTRUCT][MAXSURF];

static float diffuseColor[MAXSTRUCT][MAXSURF][4];
static float diffColor[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}
};

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},
};

typedef struct {int nhelx;
		int nbeta;
		int nrna;
		int ncoil; 
		int start[4];
		int end[4];
	} RIBIND;

static RIBIND RIBindex[MAXSTRUCT];

#define NHETRES -4
static char *fragments[] = {"Read","-CH3","-CH=CH2","-HC=O","-COOH","-NH2","-OH","-CHCH","-CycloHexane","-Phenyl","-CycloPentane","-Pyrrole","-Cl","-Br","-I","-OCH3","-SH","-NO2","CH4","Period. Chain","Amino Acid","Sequence"};
static int nfrag = 22;
static char *fragmnts[] = {"-CH3","-CH=CH2","-HC=O","-COOH","-NH2","-OH","-CHCH","-CycloHexane","-Phenyl","-CycloPentane","-Pyrrole","-Cl","-Br","-I","-OCH3","-SH","-NO2","CH4","ACE","FOR","NME","NH2"};
static int nfrags = 18;
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","Contacts+Surf","Calculate Charges","Delete Molecule","Mol.->Structure","Add Hydrogens","Color","Add to Surface"};
static char *HisOpt[] = {"HIP","HID","HIE"};
static char *AmiBOpt[] = {"Switch On","Switch Off","Center","Contacts","Contacts+Surf","Add to Surface","Delete","Insert","Replace","Cap Residue","Rotamer","Fit Rotamer","Best Rotamer","Change Rot. Libr.","Add to Flex. Resid.","Add"};
static char *AmiNQOpt[] = {"Switch On","Switch Off","Center","Contacts","Flip","Contacts+Surf","Add to Surface","Delete","Insert","Replace","Cap Residue","Rotamer","Fit Rotamer","Best Rotamer","Change Rot. Libr.","Add to Flex. Resid.","Add"};
static char *AmiHOpt[] = {"Switch On","Switch Off","Center","Contacts","Prot. State","Contacts+Surf","Add to Surface","Delete","Insert","Replace","Cap Residue","Rotamer","Fit Rotamer","Best Rotamer","Change Rot. Libr.","Add to Flex. Resid.","Add"};
static char *AmiBOptS[] = {"Switch On","Switch Off","Center","Contacts","Delete","Insert","Replace","Cap Residue","Rotamer","Fit Rotamer","Best Rotamer","Change Rot. Libr.","Add to Flex. Resid.","Add"};
static char *AmiNQOptS[] = {"Switch On","Switch Off","Center","Contacts","Flip","Delete","Insert","Replace","Cap Residue","Rotamer","Fit Rotamer","Best Rotamer","Change Rot. Libr.","Add to Flex. Resid.","Add"};
static char *AmiHOptS[] = {"Switch On","Switch Off","Center","Contacts","Prot. State","Delete","Insert","Replace","Cap Residue","Rotamer","Fit Rotamer","Best Rotamer","Change Rot. Libr.","Add to Flex. Resid.","Add"};
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;

static char *Chains[] = {
"Chain1","Chain2","Chain3","Chain4","Chain5","Chain6","Chain7",
"Chain8","Chain9","Chain10", "Chain11","Chain12","Chain13","Chain14",
"Chain15","Chain16","Chain17","Chain18","Chain19","Chain20"};

static char *Processors[] = {
	" 1"," 2"," 3"," 4"," 5"," 6"," 7"," 8"," 9","10",
	"11","12","13","14","15","16","17","18","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"};
#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}
				};

#define PENT 14
#define CCPENT 1.546
#define CHPENT 1.103
static ZLINESTRU cyclopentane[PENT] = { {6,{0,0,0,0},0.0,0.0,0.0},
				{6,{1,0,0,0},CCPENT,0.0,0.0},
				{6,{2,1,0,0},CCPENT,102.5,0.0},
				{6,{3,2,1,0},CCPENT,102.5,45.42},
				{6,{4,3,2,0},CCPENT,102.5,-36.20},
				{1,{2,3,4,0},CHPENT,109.47,-71.2},
				{1,{2,3,4,0},CHPENT,109.47,167.0},
				{1,{3,2,1,0},CHPENT,109.47,-71.2},
				{1,{3,2,1,0},CHPENT,109.47,167.0},
				{1,{4,3,2,0},CHPENT,109.47,-160.0},
				{1,{4,3,2,0},CHPENT,109.47,80.9},
				{1,{5,4,3,0},CHPENT,109.47,-106.8},
				{1,{5,4,3,0},CHPENT,109.47,133.2},
				{1,{1,2,3,0},CHPENT,109.47,80.9}
				};

#define PYRROLE 9
#define CHPYRR 1.090
static ZLINESTRU pyrrole[PYRROLE] = { {7,{0,0,0,0},0.0,0.0,0.0},
				{6,{1,0,0,0},1.301,0.0,0.0},
				{6,{2,1,0,0},1.335,107.6,0.0},
				{6,{3,2,1,0},1.469,105.5,0.0},
				{6,{1,2,3,0},1.301,113.9,0.0},
				{1,{5,1,2,0},CHPYRR,126.6,180.0},
				{1,{4,3,2,0},CHPYRR,127.3,180.0},
				{1,{3,2,1,0},CHPYRR,127.3,180.0},
				{1,{2,1,5,0},CHPYRR,126.6,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,{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,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,12,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,12,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;


/* start dimension dynamic molecule coordinates*/

#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;

#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];
		 double wo[3];
		 double sl[3];
		 int isl;
               } COMSRFSTRU;

static COMSRFSTRU *comsrfptr;

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

static FCSTRU *fcptr;

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

static MONSTRU *monptr;


#define MXEL 100
typedef struct { 
		 double vdwr[MXEL];
		 double vrad[MXEL];
		 int icol[MXEL];
               } ELMSTRU;

static ELMSTRU *elmptr;

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 MXCOLNAM 20
static char  *ColNam[MXCOLNAM];
static int NColNam = 0;

void dummyproc();
static void DoExpl();
static void ogunsel();
static void handle_explalarm();
void InitOmap(int opt);
void dispsf(void);
void ogbox();
void ogelem();
void ogsetel20(int j);
void ogsetel20_bs(int j);
void ogsetel12(int j);
void ogsetel12_bs(int j);
void GetPDBWWW(char *het, char *retstr);
int GetOMAPWWW(char *het, char *retstr);
void LigandHydroPBE(int ihet);
void LigandHydroQ(int DoHyd,int DoChg,int DoFF,int CHGtot);
void LigandQ(int ihet);
int Ligand2Amino(int ihet);
int ParseFile(char *strname, char *shortname);
static int hasWGET = 0;
int CheckWGET();
void update_struct();
void oghet(int iopt);
void oglines();
void ogsel();
#if defined(VMS) || defined(UNDERSC)
void ogmon();
#else
#ifdef CRAY
void OGMON();
#else
void ogmon_();
#endif
#endif
void ogforces();
void ogmoll(int iopt);
void ogbck(int isec);
void ogres(int ires, int iopt,int iupd);
void ResetRes();
void ressel();
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(int update);
void empty_model(int sel,int updis);
void empty_ribb();
void MoveOne(int i);
void initOpengl();
void initthe();
void initnthe();
void initOne(int i);
void setobg();
void DelHet(int het);
void znorm(double rpts, double cnst, double *dens, double *vn,
	   int npts1, int npts2, int i, int j);
void printString(int x, int y, int init, char *s);
void makeRasterFont(Display *dpy);
#ifdef DOGL
typedef struct { 
	GLfloat fogcolor[4]; 
	GLint fstart; 
	GLint fend; 
	GLfloat fscale;} FOG;

static FOG fog;

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"};

static int has_shader = 0;
static int has_fbo = 0;
#ifdef GL_COLOR_ATTACHMENT0_EXT
static int fbo_type = GL_RGBA32F_ARB;
#else
static int fbo_type = 4;
#endif

#define NUM_PROG 13
GLenum program[NUM_PROG];
GLenum vertex_shader[NUM_PROG], fragment_shader[NUM_PROG];

#define NUM_FBOS 4
struct FBO {
        GLuint frame[NUM_FBOS], depth[NUM_FBOS],
	texid[NUM_FBOS],texid1[NUM_FBOS],texid2[NUM_FBOS],texid3[NUM_FBOS];
};

struct FBO fbo;

char vertex_shader_source0[] = "\
uniform int doshad;\n\
uniform int dofog;\n\
varying float Blur;\n\
varying vec3 vertex_normal;\n\
varying vec3 eyeVec;\n\
varying vec4 ShadowCoord;\n\
\n\
void main() {\n\
	vertex_normal = normalize(gl_NormalMatrix * gl_Normal);\n\
	eyeVec = -vec3(gl_ModelViewMatrix * gl_Vertex);\n\
	Blur = clamp(abs(eyeVec.z - 10.0) / 60.0, 0.0, 1.0);\n\
	gl_FrontColor = gl_Color;\n\
	gl_BackColor = gl_Color;\n\
	gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n\
	gl_FogFragCoord = abs(eyeVec.z);\n\
	ShadowCoord = vec4(0.0);\n\
	if (doshad == 1) {\n\
	   ShadowCoord = gl_TextureMatrix[7]*gl_Vertex;\n\
	   gl_FrontColor = gl_Color;\n\
	}\n\
}\n";

char fragment_shader_source0[] = "\
uniform int colmat;\n\
uniform int dofog;\n\
uniform int doblur;\n\
uniform int dossao;\n\
uniform int dotrns;\n\
uniform int doshad;\n\
uniform sampler2D ShadowMap;\n\
varying vec3 vertex_normal;\n\
varying vec3 eyeVec;\n\
varying float Blur;\n\
varying vec4 ShadowCoord;\n\
vec4 ShadowCoordPostW;\n\
\n\
float chebyshevUpperBound( float distance)\n\
{\n\
	vec2 moments = texture2D(ShadowMap,ShadowCoordPostW.xy).rg;\n\
	float lit = 0.0;\n\
\n\
	if (distance <= moments.x) return 1.0 ;\n\
\n\
	float E_x2 = moments.y;\n\
	float Ex_2 = moments.x*moments.x;\n\
	float vsmEps = 0.00003;\n\
	float litFactor = 0.0;\n\
	if (distance <= moments.x) {\n\
	   litFactor = 1.0;\n\
	}\n\
	float variance = min(max(E_x2-Ex_2,0.0)+vsmEps,1.0);\n\
	variance = max(variance,0.00002);\n\
\n\
	float d = (distance - moments.x)/distance;\n\
	//float p = variance / (variance + d*d);\n\
	float p = variance / (variance + 0.008*abs(d));\n\
        lit = max(p, float (distance <= moments.x));\n\
\n\
	//return smoothstep(0.2,1, max(litFactor,p));\n\
	return lit;\n\
}\n\
\n\
void main() {\n\
   vec3 lightDir = normalize(vec3(gl_LightSource[2].position));\n\
   vec3 eyeVecNormal = normalize(eyeVec);\n\
   vec3 reflectVec = normalize(-reflect(lightDir, vertex_normal));\n\
   vec4 diff = gl_LightSource[2].diffuse * max(dot(vertex_normal,lightDir),0.0);\n\
   vec4 specularf = gl_FrontMaterial.specular * pow(max(dot(reflectVec, eyeVecNormal), 0.0), gl_FrontMaterial.shininess);\n\
   vec4 specularb = vec4(0.0,0.0,0.0,0.0);\n\
\n\
   vec4 fcolor;\n\
   vec4 Colb;\n\
   vec4 Colf;\n\
   if (doshad == 1) {\n\
   ShadowCoordPostW = ShadowCoord / ShadowCoord.w;\n\
   ShadowCoordPostW.z += 0.00005;\n\
   }\n\
   float fogFactor = (gl_Fog.end-gl_FogFragCoord)*gl_Fog.scale;\n\
   if (colmat == 1) {\n\
	if (dossao == 1) {\n\
	   fcolor = gl_Color*(gl_LightSource[2].ambient+diff);\n\
	} else {\n\
	   fcolor = gl_Color*(gl_LightSource[2].ambient+diff+specularf);\n\
	}\n\
	if (dotrns == 1) {\n\
	   fcolor.w = 0.6;\n\
	} else {\n\
	   fcolor.w = gl_FrontMaterial.diffuse.w;\n\
	}\n\
   } else { \n\
	vec4 ambientf = gl_LightSource[2].ambient * gl_FrontMaterial.ambient;\n\
	vec4 diffusef = diff * gl_FrontMaterial.diffuse;\n\
	reflectVec = normalize(-reflect(lightDir, -vertex_normal));\n\
	vec4 ambientb = gl_LightSource[2].ambient * gl_BackMaterial.ambient;\n\
	specularb = gl_BackMaterial.specular * pow(max(dot(reflectVec, eyeVecNormal), 0.0), gl_BackMaterial.shininess);\n\
	vec4 diffuseb= gl_LightSource[2].diffuse * max(dot(-vertex_normal,lightDir),0.0) * gl_BackMaterial.diffuse;\n\
\n\
	if (dossao == 1) {\n\
	   //vec4 Colb = ambientb + specularb + diffuseb;\n\
	   //vec4 Colf = ambientf + specularf + diffusef;\n\
	   Colb = ambientb + diffuseb;\n\
	   Colf = ambientf + diffusef;\n\
	   fcolor = (Colb + Colf);\n\
	} else {\n\
	   Colb = ambientb + specularb + diffuseb;\n\
	   Colf = ambientf + specularf + diffusef;\n\
	   fcolor = (Colb + Colf);\n\
	}\n\
   } \n\
\n\
   float shadow = 1.0;\n\
   if (doshad == 1) {\n\
       shadow = chebyshevUpperBound(ShadowCoordPostW.z);\n\
       if (shadow < 0.5) shadow = 0.5;\n\
   }\n\
   gl_FragData[1] = vec4(shadow)*fcolor;\n\
   gl_FragData[2] = (specularb+specularf);\n\
\n\
   if (dofog == 1) {\n\
      fcolor = mix(gl_Fog.color, vec4(shadow)*fcolor, fogFactor);\n\
      gl_FragData[2].w = fogFactor;\n\
   }\n\
\n\
   gl_FragData[0] = vec4(shadow)*fcolor;\n\
\n\
   if (doblur == 1) {\n\
      gl_FragData[0].a = Blur;\n\
   }\n\
   \n\
}\n";

char vertex_shader_source1[] = "\
\n\
void main(void)\n\
{\n\
	gl_Position = ftransform();\n\
	gl_TexCoord[0] = gl_MultiTexCoord0;\n\
}\n";

char fragment_shader_source1[] = "\
uniform sampler2D gdepth;\n\
uniform int dofog;\n\
uniform int Width;\n\
uniform int Height;\n\
uniform int ssaotyp;\n\
\n\
#define PI 3.14159265\n\
\n\
float near = 1.0; //Z-near\n\
float far = 600.0; //Z-far\n\
int samples;\n\
int rings;\n\
\n\
vec2 texCoord = gl_TexCoord[0].st;\n\
\n\
vec2 rand(in vec2 coord) {\n\
   float noiseX = (fract(sin(dot(coord ,vec2(12.9898,78.233))) * 43758.5453));\n\
   float noiseY = (fract(sin(dot(coord ,vec2(12.9898,78.233)*2.0)) * 43758.5453));\n\
   if (ssaotyp == 1) {\n\
      return vec2(noiseX,noiseY)*0.0004;\n\
   } else {\n\
      return vec2(noiseX,noiseY)*0.004;\n\
   }\n\
}\n\
\n\
float LinearizeDepth(vec2 uv) {\n\
  float z = texture2D(gdepth, uv).x;\n\
  return (2.0 * near) / (far + near - z * (far - near));\n\
}\n\
\n\
float compareDepths( in float depth1, in float depth2 ) {\n\
   float aoCap = 1.0;\n\
   float aoMultiplier = 150.0;\n\
   float depthTolerance = 0.0000;\n\
   float aorange = 600.0;\n\
   float diff = sqrt(clamp(1.0-(depth1-depth2) / (aorange/(far-near)),0.0,1.0));\n\
   float ao = min(aoCap,max(0.0,depth1-depth2-depthTolerance) * aoMultiplier) * diff;\n\
   if (ssaotyp != 1) {\n\
	if (diff < 0.9) ao = 0.0;\n\
   }\n\
   return ao;\n\
}\n\
\n\
void main(void)\n\
{\n\
   float depth = LinearizeDepth(texCoord);\n\
   float d;\n\
   float aspect = float(Width)/float(Height);\n\
   vec2 noise = rand(texCoord);\n\
   float nmul = 1.0;\n\
   samples = 6;\n\
   rings = 6;\n\
   if (ssaotyp == 0) nmul = 20.0;\n\
   if (ssaotyp == 0) samples = 3;\n\
\n\
   float w = (1.0 / float(Width))/clamp(depth,0.05,1.0)+nmul*(noise.x*(1.0-noise.x));\n\
   float h = (1.0 / float(Height))/clamp(depth,0.05,1.0)+nmul*(noise.y*(1.0-noise.y));\n\
\n\
   float pw;\n\
   float ph;\n\
   float ao;\n\
   float s = 0.0;\n\
\n\
   for (int i = -rings ; i < rings; i += 1) {\n\
      for (int j = -samples ; j < samples; j += 1) {\n\
	float step = PI*2.0 / float(samples*i);\n\
	pw = (cos(float(j)*step)*float(i));\n\
	ph = (sin(float(j)*step)*float(i))*aspect;\n\
	d = LinearizeDepth(vec2(texCoord.s+pw*w,texCoord.t+ph*h));\n\
	ao += compareDepths(depth,d);\n\
	s += 1.0;\n\
      }\n\
   }\n\
\n\
   ao /= s;\n\
   ao = 1.0-ao;\n\
\n\
   gl_FragColor = vec4(ao,ao,ao,1.0);\n\
}\n";

char vertex_shader_source2[] = "\
void main(void)\n\
{\n\
	gl_Position = ftransform();\n\
	gl_TexCoord[0] = gl_MultiTexCoord0;\n\
}\n";

char fragment_shader_source2[] = "\
uniform sampler2D Tex0;\n\
\n\
void main (void)\n\
{\n\
	gl_FragData[0] = texture2D(Tex0, gl_TexCoord[0].st);\n\
	//gl_FragData[0] = vec4(texture2D(Tex0, gl_TexCoord[0].st).rgb, Blur);\n\
}\n";

char vertex_shader_source3[] = "\
varying vec2 Tap[4], TapNeg[3];\n\
uniform int Width;\n\
\n\
void main(void)\n\
{\n\
	vec2 horzTapOffs[7];\n\
	vec2 TexCoord = gl_MultiTexCoord0.st;\n\
\n\
	float dx = 1.0/float(Width);\n\
	horzTapOffs[0] = vec2(0.0, 0.0);\n\
	horzTapOffs[1] = vec2(1.3366 * dx, 0.0);\n\
	horzTapOffs[2] = vec2(3.4295 * dx, 0.0);\n\
	horzTapOffs[3] = vec2(5.4264 * dx, 0.0);\n\
	horzTapOffs[4] = vec2(7.4359 * dx, 0.0);\n\
	horzTapOffs[5] = vec2(9.4436 * dx, 0.0);\n\
	horzTapOffs[6] = vec2(11.4401 * dx, 0.0);\n\
\n\
	Tap[0] = TexCoord;\n\
	Tap[1] = TexCoord + horzTapOffs[1];\n\
	Tap[2] = TexCoord + horzTapOffs[2];\n\
	Tap[3] = TexCoord + horzTapOffs[3];\n\
\n\
	TapNeg[0] = TexCoord - horzTapOffs[1];\n\
	TapNeg[1] = TexCoord - horzTapOffs[2];\n\
	TapNeg[2] = TexCoord - horzTapOffs[3];\n\
\n\
	gl_Position = ftransform();\n\
	gl_TexCoord[0] = gl_MultiTexCoord0;\n\
}\n";

char fragment_shader_source3[] = "\
varying vec2 Tap[4], TapNeg[3];\n\
uniform sampler2D Tex0;\n\
uniform int Width;\n\
\n\
void main (void)\n\
{\n\
	vec2 horzTapOffs[7];\n\
	vec2 Tap4[3], TapNeg4[3];\n\
\n\
	// Thresholds for computing sample weights\n\
	const vec4 Thresh0 = vec4(0.1, 0.3, 0.5, -0.01);\n\
	const vec4 Thresh1 = vec4(0.6, 0.7, 0.8, 0.9);\n\
\n\
	// Samples\n\
	vec4 s[7], Weights4;\n\
	vec3 Weights3, ColorSum;\n\
	float WeightSum;\n\
\n\
	float dx = 1.0/float(Width);\n\
	horzTapOffs[0] = vec2(0.0, 0.0);\n\
	horzTapOffs[1] = vec2(1.3366 * dx, 0.0);\n\
 	horzTapOffs[2] = vec2(3.4295 * dx, 0.0);\n\
	horzTapOffs[3] = vec2(5.4264 * dx, 0.0);\n\
	horzTapOffs[4] = vec2(7.4359 * dx, 0.0);\n\
	horzTapOffs[5] = vec2(9.4436 * dx, 0.0);\n\
	horzTapOffs[6] = vec2(11.4401 * dx, 0.0);\n\
\n\
\n\
	// Sample taps with coordinates from VS\n\
	s[0] = texture2D(Tex0, Tap[0]);\n\
	s[1] = texture2D(Tex0, Tap[1]);\n\
	s[2] = texture2D(Tex0, Tap[2]);\n\
	s[3] = texture2D(Tex0, Tap[3]);\n\
	s[4] = texture2D(Tex0, TapNeg[0]);\n\
	s[5] = texture2D(Tex0, TapNeg[1]);\n\
	s[6] = texture2D(Tex0, TapNeg[2]);\n\
\n\
	// Compute weights for 4 first samples (including center tap)\n\
	// by thresholding blurriness (in sample alpha)\n\
	Weights4.x = clamp(s[1].a - Thresh0.x, 0.0, 1.0);\n\
	Weights4.y = clamp(s[2].a - Thresh0.y, 0.0, 1.0);\n\
	Weights4.z = clamp(s[3].a - Thresh0.x, 0.0, 1.0);\n\
	Weights4.w = clamp(s[0].a - Thresh0.w, 0.0, 1.0);\n\
\n\
	// Accumulate weighted samples\n\
	ColorSum = vec3(s[0] * Weights4.x + s[1] * Weights4.y + s[2] * Weights4.z + s[3] * Weights4.w);\n\
\n\
	// Sum weights using DOT\n\
	WeightSum = dot(Weights4, vec4(1.0));\n\
\n\
	// Compute weights for 3 remaining samples\n\
	Weights3.x = clamp(s[4].a - Thresh0.x, 0.0, 1.0);\n\
	Weights3.y = clamp(s[5].a - Thresh0.y, 0.0, 1.0);\n\
	Weights3.z = clamp(s[6].a - Thresh0.z, 0.0, 1.0);\n\
\n\
	// Accumulate weighted samples\n\
	ColorSum += vec3(s[4] * Weights3.x + s[4] * Weights3.y + s[6] * Weights3.z);\n\
\n\
	// Sum weights using DOT\n\
	WeightSum += dot(Weights3, vec3(1.0));\n\
\n\
	// Compute tex coords for other taps\n\
	Tap4[0] = Tap[0] + horzTapOffs[4];\n\
	Tap4[1] = Tap[0] + horzTapOffs[5];\n\
	Tap4[2] = Tap[0] + horzTapOffs[6];\n\
	TapNeg4[0] = Tap[0] - horzTapOffs[4];\n\
	TapNeg4[1] = Tap[0] - horzTapOffs[5];\n\
	TapNeg4[2] = Tap[0] - horzTapOffs[6];\n\
\n\
	// Sample the taps\n\
	s[0] = texture2D(Tex0, Tap4[0]);\n\
	s[1] = texture2D(Tex0, Tap4[1]);\n\
	s[2] = texture2D(Tex0, Tap4[2]);\n\
	s[3] = texture2D(Tex0, TapNeg4[0]);\n\
	s[4] = texture2D(Tex0, TapNeg4[1]);\n\
	s[5] = texture2D(Tex0, TapNeg4[2]);\n\
\n\
	// Compute weights for 3 samples\n\
	Weights3.x = clamp(s[0].a - Thresh1.x, 0.0, 1.0);\n\
	Weights3.y = clamp(s[1].a - Thresh1.y, 0.0, 1.0);\n\
	Weights3.z = clamp(s[2].a - Thresh1.z, 0.0, 1.0);\n\
	\n\
	// Accumulate weighted samples\n\
	ColorSum += vec3(s[0] * Weights3.x + s[1] * Weights3.y + s[2] * Weights3.z);\n\
\n\
	// Sum weights using DOT\n\
	WeightSum += dot(Weights3, vec3(1.0));\n\
\n\
	// Compute weights for 3 samples\n\
	Weights3.x = clamp(s[3].a - Thresh1.x, 0.0, 1.0);\n\
	Weights3.y = clamp(s[4].a - Thresh1.y, 0.0, 1.0);\n\
	Weights3.z = clamp(s[5].a - Thresh1.z, 0.0, 1.0);\n\
\n\
	// Accumulate weighted samples\n\
	ColorSum += vec3(s[3] * Weights3.x + s[4] * Weights3.y + s[5] * Weights3.z);\n\
\n\
	// Sum weights using DOT\n\
	WeightSum += dot(Weights3, vec3(1.0));\n\
\n\
	// Divide weighted sum of samples by sum of all weights\n\
	ColorSum /= WeightSum;\n\
	WeightSum = clamp(WeightSum,0.0,1.0);\n\
\n\
	// Color and weights sum output\n\
	gl_FragData[0] = vec4(ColorSum, WeightSum);\n\
}\n";

char vertex_shader_source4[] = "\
varying vec2 Tap[4], TapNeg[3];\n\
uniform int Height;\n\
\n\
void main(void)\n\
{\n\
	vec2 vertTapOffs[7];\n\
	vec2 TexCoord = gl_MultiTexCoord0.st;\n\
\n\
	float dy = 1.0/float(Height);\n\
	vertTapOffs[0] = vec2(0.0, 0.0);\n\
	vertTapOffs[1] = vec2(0.0, 1.3366 * dy);\n\
	vertTapOffs[2] = vec2(0.0, 3.4295 * dy);\n\
	vertTapOffs[3] = vec2(0.0, 5.4264 * dy);\n\
	vertTapOffs[4] = vec2(0.0, 7.4359 * dy);\n\
	vertTapOffs[5] = vec2(0.0, 9.4436 * dy);\n\
	vertTapOffs[6] = vec2(0.0, 11.4401 * dy);\n\
\n\
	Tap[0] = TexCoord;\n\
	Tap[1] = TexCoord + vertTapOffs[1];\n\
	Tap[2] = TexCoord + vertTapOffs[2];\n\
	Tap[3] = TexCoord + vertTapOffs[3];\n\
\n\
	TapNeg[0] = TexCoord - vertTapOffs[1];\n\
	TapNeg[1] = TexCoord - vertTapOffs[2];\n\
	TapNeg[2] = TexCoord - vertTapOffs[3];\n\
\n\
	gl_Position = ftransform();\n\
	gl_TexCoord[0] = gl_MultiTexCoord0;\n\
}\n";

char fragment_shader_source4[] = "\
varying vec2 Tap[4], TapNeg[3];\n\
uniform sampler2D Tex0;\n\
uniform int Height;\n\
\n\
void main (void)\n\
{\n\
	vec2 vertTapOffs[7];\n\
	vec2 Tap4[3], TapNeg4[3];\n\
\n\
	const vec4 Weights0 = vec4(0.080, 0.075, 0.070, 0.100);\n\
	const vec4 Weights1 = vec4(0.065, 0.060, 0.055, 0.050);\n\
\n\
	// Samples\n\
	vec4 s[7];\n\
	// Acumulated color and weights\n\
	vec4 ColorWeightSum;\n\
\n\
	float dy = 1.0/float(Height);\n\
	vertTapOffs[0] = vec2(0.0, 0.0);\n\
	vertTapOffs[1] = vec2(0.0, 1.3366 * dy);\n\
	vertTapOffs[2] = vec2(0.0, 3.4295 * dy);\n\
	vertTapOffs[3] = vec2(0.0, 5.4264 * dy);\n\
	vertTapOffs[4] = vec2(0.0, 7.4359 * dy);\n\
	vertTapOffs[5] = vec2(0.0, 9.4436 * dy);\n\
	vertTapOffs[6] = vec2(0.0, 11.4401 * dy);\n\
\n\
\n\
	// Sample taps with coordinates from VS\n\
	s[0] = texture2D(Tex0, Tap[0]);\n\
	s[1] = texture2D(Tex0, Tap[1]);\n\
	s[2] = texture2D(Tex0, Tap[2]);\n\
	s[3] = texture2D(Tex0, Tap[3]);\n\
	s[4] = texture2D(Tex0, TapNeg[0]);\n\
	s[5] = texture2D(Tex0, TapNeg[1]);\n\
	s[6] = texture2D(Tex0, TapNeg[2]);\n\
\n\
	// Modulate sampled color values by the weights stored\n\
	// in the alpha channel of each sample\n\
	s[0].rgb = s[0].rgb * s[0].a;\n\
	s[1].rgb = s[1].rgb * s[1].a;\n\
	s[2].rgb = s[2].rgb * s[2].a;\n\
	s[3].rgb = s[3].rgb * s[3].a;\n\
	s[4].rgb = s[4].rgb * s[4].a;\n\
	s[5].rgb = s[5].rgb * s[5].a;\n\
	s[6].rgb = s[6].rgb * s[6].a;\n\
\n\
	// Aggregate all samples weighting them with pre-defined\n\
	// kernel weights, weight sum in alpha\n\
	ColorWeightSum = s[0] * Weights0.w +\n\
      (s[1] + s[4]) * Weights0.x +\n\
      (s[2] + s[5]) * Weights0.y +\n\
      (s[3] + s[6]) * Weights0.z;\n\
\n\
	// Compute tex coords for other taps\n\
	Tap4[0] = Tap[0] + vertTapOffs[4];\n\
	Tap4[1] = Tap[0] + vertTapOffs[5];\n\
	Tap4[2] = Tap[0] + vertTapOffs[6];\n\
	TapNeg4[0] = Tap[0] - vertTapOffs[4];\n\
	TapNeg4[1] = Tap[0] - vertTapOffs[5];\n\
	TapNeg4[2] = Tap[0] - vertTapOffs[6];\n\
\n\
	// Sample the taps\n\
	s[0] = texture2D(Tex0, Tap4[0]);\n\
	s[1] = texture2D(Tex0, Tap4[1]);\n\
	s[2] = texture2D(Tex0, Tap4[2]);\n\
	s[3] = texture2D(Tex0, TapNeg4[0]);\n\
	s[4] = texture2D(Tex0, TapNeg4[1]);\n\
	s[5] = texture2D(Tex0, TapNeg4[2]);\n\
\n\
	// Modulate sampled color values by the weights stored\n\
	// in the alpha channel of each sample\n\
	s[0].rgb = s[0].rgb * s[0].a;\n\
	s[1].rgb = s[1].rgb * s[1].a;\n\
	s[2].rgb = s[2].rgb * s[2].a;\n\
	s[3].rgb = s[3].rgb * s[3].a;\n\
	s[4].rgb = s[4].rgb * s[4].a;\n\
	s[5].rgb = s[5].rgb * s[5].a;\n\
\n\
	 // Aggregate all samples weighting them with pre-defined\n\
	// kernel weights, weight sum in alpha\n\
	ColorWeightSum += (s[1] + s[3]) * Weights1.x +\n\
      (s[1] + s[4]) * Weights1.y +\n\
      (s[2] + s[5]) * Weights1.z;\n\
\n\
	// Average combined sample for all samples in the kernel\n\
	ColorWeightSum.rgb /= ColorWeightSum.a;\n\
\n\
	// Final sum output\n\
	gl_FragData[0] = ColorWeightSum;\n\
}\n";

char vertex_shader_source5[] = "\
void main(void)\n\
{\n\
	gl_Position = ftransform();\n\
	gl_TexCoord[0] = gl_MultiTexCoord0;\n\
	gl_TexCoord[1] = gl_MultiTexCoord1;\n\
}\n";

char fragment_shader_source5[] = "\
uniform sampler2D Tex0, Tex1;\n\
\n\
void main (void)\n\
{\n\
	vec4 Fullres = texture2D(Tex0, gl_TexCoord[0].st);\n\
	vec4 Blurred = texture2D(Tex1, gl_TexCoord[1].st);\n\
\n\
	// HLSL linear interpolation function\n\
	gl_FragData[0] = Fullres + Fullres.a * (Blurred - Fullres);\n\
}\n";


char vertex_shader_source6[] = "\
void main(void)\n\
{\n\
	gl_Position = ftransform();\n\
	gl_TexCoord[0] = gl_MultiTexCoord0;\n\
}\n";

char fragment_shader_source6[] = "\
uniform sampler2D Tex0;\n\
\n\
void main (void)\n\
{\n\
	vec4 colorMap = texture2D(Tex0, gl_TexCoord[0].st);\n\
	gl_FragColor = colorMap;\n\
}\n";

char vertex_shader_source7[] = "\
\n\
varying vec4 v_position;\n\
void main(void)\n\
{\n\
	gl_Position = ftransform();\n\
	v_position = gl_Position;\n\
	gl_TexCoord[0] = gl_MultiTexCoord0;\n\
}\n";

char fragment_shader_source7[] = "\
uniform sampler2D gnormals;\n\
uniform sampler2D gdepth;\n\
uniform sampler2D gdiffuse;\n\
uniform sampler2D grandom;\n\
\n\
float LinearizeDepth(vec2 uv) {\n\
  float n = 1.0;\n\
  float f = 100.0;\n\
  float z = texture2D(gdepth, uv).x;\n\
  return (2.0 * n) / (f + n - z * (f - n));\n\
}\n\
\n\
vec3 readNormal(vec2 coord) {\n\
   vec3 v1 = vec3(1.0);\n\
   vec3 vout = normalize(texture2D(gnormals, coord).stp*2.0  - v1);  \n\
   return vout;\n\
}\n\
\n\
vec3 posFromDepth(vec2 coord) {\n\
   float d = texture2D(gdepth, coord).r;\n\
   vec3 tray = vec3(gl_ProjectionMatrixInverse*\n\
	vec4((coord.x-0.5)*2.0,(coord.y-0.5)*2.0,1.0,0.0));\n\
   return tray*d;\n\
}\n\
\n\
//Ambient Occlusion form factor:    \n\
\n\
float aoFF(in vec3 ddiff,in vec3 cnorm, in float c1, in float c2) {\n\
   vec3 vv = normalize(ddiff);\n\
   float rd = length(ddiff);\n\
   return (1.0-\n\
	clamp(dot(readNormal(gl_TexCoord[0].st+vec2(c1,c2)),-vv),0.0,1.0)) *\n\
	clamp(dot(cnorm,vv),0.0,1.0)*(1.0 - 1.0/sqrt(1.0/(rd*rd) + 1.0));\n\
}\n\
\n\
//GI form factor:    \n\
\n\
float giFF(vec3 ddiff, vec3 cnorm, float c1, float c2) {\n\
   vec3 vv = normalize(ddiff);\n\
   float rd = length(ddiff);\n\
   return 1.0*\n\
	clamp(dot(readNormal(gl_TexCoord[0].st+vec2(c1,c2)),-vv),0.0,1.0)*\n\
	clamp(dot(cnorm,vv),0.0,1.0)/ (rd*rd+1.0);\n\
}\n\
\n\
void main() {\n\
\n\
    //read current normal,position and color.\n\
\n\
    vec3 n = readNormal(gl_TexCoord[0].st);\n\
    vec3 p = posFromDepth(gl_TexCoord[0].st);\n\
    vec3 col = vec3(texture2D(gdiffuse, gl_TexCoord[0].st));\n\
\n\
    //randomization texture\n\
\n\
    vec2 fres = vec2(800.0/64.0*5.0,800.0/64.0*5.0);\n\
    vec3 random = vec3(texture2D(grandom, gl_TexCoord[0].st*fres.xy));\n\
    random = random*2.0-vec3(1.0);\n\
\n\
    //initialize variables:\n\
\n\
    float ao = 0.0;\n\
    vec3 gi = vec3(0.0,0.0,0.0);\n\
    float incx = 1.0/800.0*0.1;\n\
    float incy = 1.0/800.0*0.1;\n\
    float pw = incx;\n\
    float ph = incy;\n\
    float cdepth = LinearizeDepth(gl_TexCoord[0].st);\n\
\n\
    for (float i=0.0; i<3.0; ++i) {\n\
\n\
       float npw = (pw+0.0007*random.x)/cdepth;\n\
       float nph = (ph+0.0007*random.y)/cdepth;\n\
\n\
       vec3 ddiff  = posFromDepth(gl_TexCoord[0].st+vec2(npw,nph))-p;\n\
       vec3 ddiff2 = posFromDepth(gl_TexCoord[0].st+vec2(npw,-nph))-p;\n\
       vec3 ddiff3 = posFromDepth(gl_TexCoord[0].st+vec2(-npw,nph))-p;\n\
       vec3 ddiff4 = posFromDepth(gl_TexCoord[0].st+vec2(-npw,-nph))-p;\n\
       vec3 ddiff5 = posFromDepth(gl_TexCoord[0].st+vec2(0.0,nph))-p;\n\
       vec3 ddiff6 = posFromDepth(gl_TexCoord[0].st+vec2(0.0,-nph))-p;\n\
       vec3 ddiff7 = posFromDepth(gl_TexCoord[0].st+vec2(npw,0.0))-p;\n\
       vec3 ddiff8 = posFromDepth(gl_TexCoord[0].st+vec2(-npw,0.0))-p;\n\
\n\
       ao+=  aoFF(ddiff ,n,npw,nph);\n\
       ao+=  aoFF(ddiff2,n,npw,-nph);\n\
       ao+=  aoFF(ddiff3,n,-npw,nph);\n\
       ao+=  aoFF(ddiff4,n,-npw,-nph);\n\
       ao+=  aoFF(ddiff5,n,0.0,nph);\n\
       ao+=  aoFF(ddiff6,n,0.0,-nph);\n\
       ao+=  aoFF(ddiff7,n,npw,0.0);\n\
       ao+=  aoFF(ddiff8,n,-npw,0.0);\n\
\n\
       gi+=  giFF(ddiff,n,npw,nph)*\n\
		texture2D(gdiffuse, gl_TexCoord[0].st+vec2(npw,nph)).rgb;\n\
       gi+=  giFF(ddiff2,n,npw,-nph)*\n\
		texture2D(gdiffuse, gl_TexCoord[0].st+vec2(npw,-nph)).rgb;\n\
       gi+=  giFF(ddiff3,n,-npw,nph)*\n\
		texture2D(gdiffuse, gl_TexCoord[0].st+vec2(-npw,nph)).rgb;\n\
       gi+=  giFF(ddiff4,n,-npw,-nph)*\n\
		texture2D(gdiffuse, gl_TexCoord[0].st+vec2(-npw,-nph)).rgb;\n\
       gi+=  giFF(ddiff5,n,0.0,nph)*\n\
		texture2D(gdiffuse, gl_TexCoord[0].st+vec2(0.0,nph)).rgb;\n\
       gi+=  giFF(ddiff6,n,0.0,-nph)*\n\
		texture2D(gdiffuse, gl_TexCoord[0].st+vec2(0.0,-nph)).rgb;\n\
       gi+=  giFF(ddiff7,n,npw,0.0)*\n\
		texture2D(gdiffuse, gl_TexCoord[0].st+vec2(npw,0.0)).rgb;\n\
       gi+=  giFF(ddiff8,n,-npw,0.0)*\n\
		texture2D(gdiffuse, gl_TexCoord[0].st+vec2(-npw,0.0)).rgb;\n\
\n\
       //increase sampling area:\n\
\n\
       pw += incx;\n\
       ph += incy;\n\
    }\n\
    ao/=24.0;\n\
    gi/=24.0;\n\
\n\
    //gl_FragColor = vec4(col-vec3(ao)+gi*5.0,1.0);\n\
    gl_FragColor = vec4(col-vec3(ao),1.0);\n\
}\n";

char fragment_shader_source8[] = "\
uniform sampler2D sampler0;\n\
uniform int width;\n\
uniform int height;\n\
\n\
void main(void)\n\
{\n\
    vec2 tc_offset[9];\n\
    vec4 sample[9];\n\
    float xinc,yinc;\n\
\n\
    xinc = 1.0/float(width);\n\
    yinc = 1.0/float(height);\n\
    for (int i = 0; i < 2; i++) {\n\
	for (int j = 0; j < 2; j++) {\n\
	   tc_offset[(i*3)+j] = \n\
		vec2((float(i)-1.0)*xinc,(float(j)-1.0)*yinc);\n\
	}\n\
    }\n\
    for (int i = 0; i < 9; i++) {\n\
        sample[i] = texture2D(sampler0,\n\
                              gl_TexCoord[0].st + tc_offset[i]);\n\
    }\n\
\n\
    gl_FragColor = (sample[0] + (2.0*sample[1]) + sample[2] + \n\
                    (2.0*sample[3]) + sample[4] + (2.0*sample[5]) + \n\
                    sample[6] + (2.0*sample[7]) + sample[8]) / 13.0;\n\
}\n";

char fragment_shader_source9[] = "\
uniform sampler2D gcolor;\n\
uniform sampler2D glum;\n\
uniform sampler2D aotex;\n\
uniform int dofog;\n\
vec2 texCoord = gl_TexCoord[0].st;\n\
void main(void)\n\
{\n\
   float fogFactor = texture2D(glum,texCoord).w;\n\
   vec3 color = texture2D(gcolor,texCoord).rgb;\n\
   vec3 luminance = texture2D(glum,texCoord).rgb;\n\
   vec3 ao = texture2D(aotex,texCoord).rgb;\n\
   vec4 fcolor = vec4(color*ao+luminance,1.0);\n\
   if (dofog == 1) {\n\
	fcolor = mix(gl_Fog.color, fcolor, fogFactor);\n\
   }\n\
   gl_FragColor = fcolor;\n\
}\n";

char vertex_shader_source10[] = "\
varying vec4 ShadowCoord;\n\
\n\
void main()\n\
{\n\
        ShadowCoord = gl_TextureMatrix[7] * gl_Vertex;\n\
        gl_Position = ftransform();\n\
        gl_FrontColor = gl_Color;\n\
}\n";

char fragment_shader_source10[] = "\
uniform sampler2D ShadowMap;\n\
varying vec4 ShadowCoord;\n\
vec4 ShadowCoordPostW;\n\
\n\
float chebyshevUpperBound( float distance)\n\
{\n\
	vec2 moments = texture2D(ShadowMap,ShadowCoordPostW.xy).rg;\n\
	float lit = 0.0;\n\
\n\
	if (distance <= moments.x) return 1.0 ;\n\
\n\
	float variance = moments.y - (moments.x*moments.x);\n\
	//variance = max(variance,0.00002);\n\
	variance = max(variance,0.02);\n\
\n\
	float d = distance - moments.x;\n\
	float p_max = variance / (variance + d*d);\n\
        lit = max(p_max, float (distance <= moments.x));\n\
\n\
	return lit;\n\
}\n\
\n\
void main()\n\
{\n\
	ShadowCoordPostW = ShadowCoord / ShadowCoord.w;\n\
	float shadow = chebyshevUpperBound(ShadowCoordPostW.z);\n\
	gl_FragColor = vec4(shadow ) *gl_Color;\n\
}\n";

char vertex_shader_source11[] = "\
varying vec4 v_position;\n\
\n\
void main()\n\
{\n\
	gl_Position = ftransform();\n\
	v_position = gl_Position;\n\
}\n";

char fragment_shader_source11[] = "\
varying vec4 v_position;\n\
\n\
void main()\n\
{\n\
	float depth = v_position.z / v_position.w;\n\
	depth = depth * 0.5 + 0.5;\n\
	float moment1 = depth;\n\
	float moment2 = depth * depth;\n\
	float dx = dFdx(depth);\n\
	float dy = dFdy(depth);\n\
	moment2 += 0.25*(dx*dx+dy*dy);\n\
	//moment2 += (dx*dx+dy*dy);\n\
\n\
	gl_FragColor = vec4( moment1,moment2, 0.0, 0.0 );\n\
}\n";

char vertex_shader_source12[] = "\
\n\
void main()\n\
{\n\
	gl_Position = ftransform();\n\
	gl_TexCoord[0] =  gl_MultiTexCoord0;\n\
}\n";

char fragment_shader_source12[] = "\
uniform int width;\n\
uniform int height;\n\
uniform sampler2D tex;\n\
\n\
void main()\n\
{\n\
	vec4 color = vec4(0.0);\n\
	float scx = 1.0 / float(width);\n\
	float scy = 1.0 / float(height);\n\
\n\
	color += texture2D(tex, gl_TexCoord[0].st + vec2(-3.0*scx,-3.0*scy)) * 0.015625;\n\
	color += texture2D(tex, gl_TexCoord[0].st + vec2(-2.0*scx,-2.0*scy))*0.09375;\n\
	color += texture2D(tex, gl_TexCoord[0].st + vec2(-1.0*scx,-1.0*scy))*0.234375;\n\
	color += texture2D(tex, gl_TexCoord[0].st + vec2(0.0 , 0.0) )*0.3125;\n\
	color += texture2D(tex, gl_TexCoord[0].st + vec2(1.0*scx,1.0*scy))*0.234375;\n\
	color += texture2D(tex, gl_TexCoord[0].st + vec2(2.0*scx,2.0*scy))*0.09375;\n\
	color += texture2D(tex, gl_TexCoord[0].st + vec2(3.0*scx,-3.0*scy)) * 0.015625;\n\
\n\
	gl_FragColor = color;\n\
}\n";

char *vert_shader[NUM_PROG] = {vertex_shader_source0,vertex_shader_source1,vertex_shader_source2,vertex_shader_source3,vertex_shader_source4,vertex_shader_source5,vertex_shader_source6,vertex_shader_source7,vertex_shader_source7,vertex_shader_source7,vertex_shader_source10,vertex_shader_source11,vertex_shader_source12};
char *frag_shader[NUM_PROG] = {fragment_shader_source0,fragment_shader_source1,fragment_shader_source2,fragment_shader_source3,fragment_shader_source4,fragment_shader_source5,fragment_shader_source6,fragment_shader_source7,fragment_shader_source8,fragment_shader_source9,fragment_shader_source10,fragment_shader_source11,fragment_shader_source12};

#ifdef GL_ARB_shader_objects
void printInfoLog(GLhandleARB obj)
	{
	    int infologLength = 0;
	    int charsWritten = 0;
	    int status;
	    char *infoLog;
	
	    glGetObjectParameterivARB(obj, GL_OBJECT_COMPILE_STATUS_ARB,&status);
	    /*printf(" compile status %d\n",status);*/
	    glGetObjectParameterivARB(obj, GL_OBJECT_INFO_LOG_LENGTH_ARB,
						 &infologLength);

	    if (infologLength > 0) {
	
		infoLog = (char *) malloc(infologLength);


		glGetInfoLogARB(obj, infologLength, &charsWritten, infoLog);

		/*printf("%s\n",infoLog);*/
	    }
	}
#endif

GLint rndid;
GLint colmat;
GLint DoShadLoc;
GLint dofog;
GLint dofog2;
GLint dofog3;
GLint doblur;
GLint dossao;
GLint dotrns;
#ifdef GL_COLOR_ATTACHMENT0_EXT
GLenum buffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT};
#endif

#ifdef GL_ARB_shader_objects
int load_shader(GLenum *program, int prg)
{

	program[prg] = glCreateProgramObjectARB();
	vertex_shader[prg] = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
	fragment_shader[prg] = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);

	glShaderSourceARB(fragment_shader[prg], 1, &frag_shader[prg], NULL);
	glShaderSourceARB(vertex_shader[prg], 1, &vert_shader[prg], NULL);

	glCompileShaderARB(vertex_shader[prg]);
	printInfoLog(vertex_shader[prg]);
	glCompileShaderARB(fragment_shader[prg]);
	printInfoLog(fragment_shader[prg]);

	glAttachObjectARB(program[prg], vertex_shader[prg]);
	glAttachObjectARB(program[prg], fragment_shader[prg]);

	glLinkProgramARB(program[prg]);
}

void del_shader()
{
    int i;

    for (i = 0; i < NUM_PROG; i++) {
	glDeleteObjectARB(vertex_shader[i]);
	glDeleteObjectARB(fragment_shader[i]);
	glDeleteObjectARB(program[i]);
    }
}

int check_shader(const char *ext)
{
   GLint loc;

   if (!ext || !ext[0]) return;

   if (strstr(ext,"GL_ARB_vertex_shader") 
	&& strstr(ext,"GL_ARB_fragment_shader")) {

	load_shader(program,0);
	load_shader(program,1);
	load_shader(program,2);
	load_shader(program,3);
	load_shader(program,4);
	load_shader(program,5);
	load_shader(program,6);
	load_shader(program,7);
	load_shader(program,8);
	load_shader(program,9);
	load_shader(program,10);
	load_shader(program,11);
	load_shader(program,12);

/* passing Uniforms */

	glUseProgramObjectARB(program[0]);

	colmat   = glGetUniformLocationARB(program[0], "colmat");
	dofog    = glGetUniformLocationARB(program[0], "dofog");
	doblur   = glGetUniformLocationARB(program[0], "doblur");
	dossao   = glGetUniformLocationARB(program[0], "dossao");
	dotrns   = glGetUniformLocationARB(program[0], "dotrns");
	DoShadLoc   = glGetUniformLocationARB(program[0], "doshad");
	loc      = glGetUniformLocationARB(program[0], "ShadowMap");
	glUniform1iARB(loc, 7);

	glUniform1iARB(colmat, 0);
	glUniform1iARB(dofog, 0);
	glUniform1iARB(doblur, 0);
	glUniform1iARB(dossao, 0);
	glUniform1iARB(dotrns, 0);
	glUniform1iARB(DoShadLoc, 0);

	glUseProgramObjectARB(program[1]);

	loc    = glGetUniformLocationARB(program[1], "gdepth");
	glUniform1iARB(loc, 0);
	dofog2 = glGetUniformLocationARB(program[1], "dofog");
	glUniform1iARB(dofog2, 0);
	loc    = glGetUniformLocationARB(program[1], "Width");
	glUniform1iARB(loc, width);
	loc    = glGetUniformLocationARB(program[1], "Height");
	glUniform1iARB(loc, height);
	loc    = glGetUniformLocationARB(program[1], "ssaotyp");
	glUniform1iARB(loc, SSAO_type);

	glUseProgramObjectARB(program[3]);
	loc   = glGetUniformLocationARB(program[3], "Width");
	glUniform1iARB(loc, width*2);

	glUseProgramObjectARB(program[4]);
	loc   = glGetUniformLocationARB(program[4], "Height");
	glUniform1iARB(loc, height*2);

	glUseProgramObjectARB(program[5]);
	loc   = glGetUniformLocationARB(program[5], "Tex0");
	glUniform1iARB(loc, 0);
	loc   = glGetUniformLocationARB(program[5], "Tex1");
	glUniform1iARB(loc, 1);

	glUseProgramObjectARB(program[6]);
	loc   = glGetUniformLocationARB(program[6], "Tex0");
	glUniform1iARB(loc, 0);

	glUseProgramObjectARB(program[8]);
	loc   = glGetUniformLocationARB(program[8], "width");
	glUniform1iARB(loc, width);
	loc   = glGetUniformLocationARB(program[8], "height");
	glUniform1iARB(loc, height);

	glUseProgramObjectARB(program[9]);
	loc    = glGetUniformLocationARB(program[9], "gcolor");
	glUniform1iARB(loc, 0);
	loc    = glGetUniformLocationARB(program[9], "glum");
	glUniform1iARB(loc, 1);
	loc    = glGetUniformLocationARB(program[9], "aotex");
	glUniform1iARB(loc, 2);
	dofog3 = glGetUniformLocationARB(program[9], "dofog");
	glUniform1iARB(dofog3, 0);
/*
	glUseProgramObjectARB(program[10]);
	loc    = glGetUniformLocationARB(program[9], "ShadowMap");
	glUniform1iARB(loc, 7);
*/

	glUseProgramObjectARB(program[12]);
	loc   = glGetUniformLocationARB(program[8], "width");
	glUniform1iARB(loc, width);
	loc   = glGetUniformLocationARB(program[8], "height");
	glUniform1iARB(loc, height);
	loc    = glGetUniformLocationARB(program[9], "tex");
	glUniform1iARB(loc, 7);

	glUseProgramObjectARB(0);

	return(1);
   }

   return(0);
}
#endif

#ifdef GL_COLOR_ATTACHMENT0_EXT
int init_fbo(struct FBO *fbo,int fbo_type,const char *ext)
{
   int i,maxColorBuffers,maxBuffers;
   GLenum status;

   if (!ext || !ext[0]) return(0);

   if (strstr(ext,"GL_EXT_framebuffer_object")) {

	glGetIntegerv( GL_MAX_COLOR_ATTACHMENTS_EXT, &maxColorBuffers );
	if (maxColorBuffers < 4) return(0);

#if defined(GL_ARB_draw_buffers)
	glGetIntegerv( GL_MAX_DRAW_BUFFERS, &maxBuffers );
	if (maxBuffers < NUM_FBOS || maxBuffers <= 0) {
	    //fprintf(stderr,"maxBuffers %d < NUM_FBOS %d\n",maxBuffers,NUM_FBOS);
	    return(0);
	}
#else
	return(0);
#endif

	glGenFramebuffersEXT(1, &(fbo->frame[0]));
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->frame[0]);

	glGenRenderbuffersEXT(1, &(fbo->depth[0]));
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, fbo->depth[0]);
	//glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24,
	//	width, height);
	glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT,
		width, height);
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, 
					GL_DEPTH_ATTACHMENT_EXT,
					GL_RENDERBUFFER_EXT,fbo->depth[0]);

	glGenTextures(1, &fbo->texid[0]);
	glBindTexture(GL_TEXTURE_2D, fbo->texid[0]);
	glTexImage2D(GL_TEXTURE_2D, 0, fbo_type,  
		width, height, 0,
		GL_RGBA, GL_FLOAT, NULL);
	if (DoMIPMAP) glGenerateMipmapEXT(GL_TEXTURE_2D);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, 
			GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, 
			GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
		GL_TEXTURE_2D, fbo->texid[0], 0);

	glGenTextures(1, &fbo->texid1[0]);
	glBindTexture(GL_TEXTURE_2D, fbo->texid1[0]);
	glTexImage2D(GL_TEXTURE_2D, 0, fbo_type,  
		width, height, 0,
		GL_RGBA, GL_FLOAT, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT,
		GL_TEXTURE_2D, fbo->texid1[0], 0);

	glGenTextures(1, &fbo->texid2[0]);
	glBindTexture(GL_TEXTURE_2D, fbo->texid2[0]);
	glTexImage2D(GL_TEXTURE_2D, 0, fbo_type,  
		width, height, 0,
		GL_RGBA, GL_FLOAT, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT2_EXT,
		GL_TEXTURE_2D, fbo->texid2[0], 0);

	glGenTextures(1, &fbo->texid3[0]);
	glBindTexture(GL_TEXTURE_2D, fbo->texid3[0]);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24,  
		width, height, 0,
		GL_DEPTH_COMPONENT, GL_FLOAT, NULL);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
		GL_TEXTURE_2D, fbo->texid3[0], 0);

	status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
		/*printf("FBO[0] Error: 0x%x\n", status);*/
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
		return(0);
	}

	for (i = 1; i < NUM_FBOS; i++) {
		glGenFramebuffersEXT(1, &(fbo->frame[i]));
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->frame[i]);

		glGenTextures(1, &fbo->texid[i]);

		glBindTexture(GL_TEXTURE_2D, fbo->texid[i]);
		glTexImage2D(GL_TEXTURE_2D, 0, fbo_type, 
			width, height, 
			0, GL_RGBA, GL_FLOAT, NULL);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
		glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );

		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, 
		  GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbo->texid[i], 0);

		status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
		if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
			/*printf("FBO[%d] Error: 0x%x\n", i, status);*/
			glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
			return(0);
		}
	}

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	return(1);
   }
   return(0);
}

void del_fbo(struct FBO *fbo)
{
  int i;

  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  glDeleteRenderbuffersEXT(1, &(fbo->depth[0]));
  glDeleteTextures(1, &fbo->texid1[0]);
  glDeleteTextures(1, &fbo->texid2[0]);
  glDeleteTextures(1, &fbo->texid3[0]);

  for (i = 0; i < NUM_FBOS; i++) {
	glDeleteTextures(1, &fbo->texid[i]);
	glDeleteFramebuffersEXT(1, &(fbo->frame[i]));
  }
   
}
#endif

void DoQuad()
{
  glBegin(GL_QUADS);
	glTexCoord2f(0.0f, 0.0f);
	glVertex2d(-1, -1);
	glTexCoord2f(1.0f, 0.0f);
	glVertex2d(1, -1);
	glTexCoord2f( 1.0f, 1.0f);
	glVertex2d(1, 1);
	glTexCoord2f(0.0f, 1.0f);
	glVertex2d(-1, 1);
  glEnd();
}

void DoQuad2()
{
  glBegin(GL_QUADS);
	glTexCoord2d(0,0);
	glVertex2f(-width/2,-height/2);
	glTexCoord2d(1,0);
	glVertex2f( width/2,-height/2);
	glTexCoord2d(1,1);
	glVertex2f( width/2, height/2);
	glTexCoord2d(0,1);
	glVertex2f(-width/2, height/2);
  glEnd();
}

void setupMatrices(pos_x,pos_y,pos_z,lookx,looky,lookz)
float pos_x;
float pos_y;
float pos_z;
float lookx;
float looky;
float lookz;
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	if (*persp) {
	   glFrustum(-0.2*Aspect,0.2*Aspect,-0.2,0.2,0.3,600.0);
	} else {
	   glOrtho(1.0*Aspect,-1.0*Aspect,1.0,-1.0,-10.0,300.0);
	}
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	gluLookAt(pos_x,pos_y,pos_z,
		  0.0,0.0,0.0,0.0,1.0,0.0);
}

void blurShadowMap()
{
	GLint loc;

#ifdef GL_COLOR_ATTACHMENT0_EXT
        glDepthMask(GL_FALSE);
        glDisable(GL_DEPTH_TEST);

        glPushMatrix();
        glLoadIdentity();
        glMatrixMode(GL_PROJECTION);
        glPushMatrix();
        glLoadIdentity();

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,fbo.frame[1]);	
	glUseProgramObjectARB(program[12]);
	loc   = glGetUniformLocationARB(program[12], "width");
	glUniform1iARB(loc, width);
	loc   = glGetUniformLocationARB(program[12], "height");
	glUniform1iARB(loc, 0);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D,fbo.texid[0]);

	DoQuad();
		
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,fbo.frame[0]);	
	loc   = glGetUniformLocationARB(program[12], "width");
	glUniform1iARB(loc, 0);
	loc   = glGetUniformLocationARB(program[12], "height");
	glUniform1iARB(loc, height);

	glBindTexture(GL_TEXTURE_2D,fbo.texid[1]);

	DoQuad();
		
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
#endif
}

void DepthBlur()
{
	GLint loc;

#ifdef GL_COLOR_ATTACHMENT0_EXT

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[2]);
	glDrawBuffers(1,buffers);
	glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, fbo.texid[0]);
	glUseProgramObjectARB(program[2]);

	DoQuad();

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[3]);
	glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glBindTexture(GL_TEXTURE_2D, fbo.texid[2]);
	glUseProgramObjectARB(program[3]);
	loc   = glGetUniformLocationARB(program[3], "Width");
	glUniform1iARB(loc, width*2);

	DoQuad();

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[2]);
	glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glBindTexture(GL_TEXTURE_2D, fbo.texid[3]);
	glUseProgramObjectARB(program[4]);
	loc   = glGetUniformLocationARB(program[4], "Height");
	glUniform1iARB(loc, height*2);

	DoQuad();

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	glDrawBuffer(GL_BACK);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, fbo.texid[0]);
	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, fbo.texid[2]);
	glUseProgramObjectARB(program[5]);

	glBegin(GL_QUADS);
		glMultiTexCoord2f(GL_TEXTURE0, 0.0f, 0.0f);
		glMultiTexCoord2f(GL_TEXTURE1, 0.0f, 0.0f);
		glVertex2d(-1, -1);
		glMultiTexCoord2f(GL_TEXTURE0, 1.0f, 0.0f);
		glMultiTexCoord2f(GL_TEXTURE1, 1.0f, 0.0f);
		glVertex2d(1, -1);
		glMultiTexCoord2f(GL_TEXTURE0, 1.0f, 1.0f);
		glMultiTexCoord2f(GL_TEXTURE1, 1.0f, 1.0f);
		glVertex2d(1, 1);
		glMultiTexCoord2f(GL_TEXTURE0, 0.0f, 1.0f);
		glMultiTexCoord2f(GL_TEXTURE1, 0.0f, 1.0f);
		glVertex2d(-1, 1);
	glEnd();

	glXSwapBuffers(display, win);
#endif
}

void SSAO()
{
	GLint loc;

#ifdef GL_COLOR_ATTACHMENT0_EXT
	glDepthMask(GL_FALSE);
	glDisable(GL_DEPTH_TEST);

	glPushMatrix();
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[1]);
	glDrawBuffers(1,buffers);
	glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, fbo.texid3[0]);
	glUseProgramObjectARB(program[1]);
	if (*shade) {
	   glUniform1iARB(dofog2, 1);
	} else {
	   glUniform1iARB(dofog2, 0);
	}

	DoQuad();

	if (SSAO_type) {

	   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[2]);
	   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	   glBindTexture(GL_TEXTURE_2D, fbo.texid[1]);
	   glUseProgramObjectARB(program[8]);

	   DoQuad();

	} else {

	   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[2]);
	   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	   glBindTexture(GL_TEXTURE_2D, fbo.texid[1]);
	   glUseProgramObjectARB(program[3]);
	   loc   = glGetUniformLocationARB(program[3], "Width");
	   glUniform1iARB(loc, width);

	   DoQuad();

	   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[1]);
	   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	   glBindTexture(GL_TEXTURE_2D, fbo.texid[2]);
	   glUseProgramObjectARB(program[4]);
	   loc   = glGetUniformLocationARB(program[4], "Height");
	   glUniform1iARB(loc, height);

	   DoQuad();

	}

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	glDrawBuffer(GL_BACK);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, fbo.texid1[0]);
	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, fbo.texid2[0]);
	glActiveTexture(GL_TEXTURE2);

	if (SSAO_type) {
	   glBindTexture(GL_TEXTURE_2D, fbo.texid[2]);
	} else {
	   glBindTexture(GL_TEXTURE_2D, fbo.texid[1]);
	}

	glUseProgramObjectARB(program[9]);
	if (*shade) {
	   glUniform1iARB(dofog3, 1);
	} else {
	   glUniform1iARB(dofog3, 0);
	}

	glBegin(GL_QUADS);
		glMultiTexCoord2f(GL_TEXTURE0, 0.0f, 0.0f);
		glMultiTexCoord2f(GL_TEXTURE1, 0.0f, 0.0f);
		glVertex2d(-1, -1);
		glMultiTexCoord2f(GL_TEXTURE0, 1.0f, 0.0f);
		glMultiTexCoord2f(GL_TEXTURE1, 1.0f, 0.0f);
		glVertex2d(1, -1);
		glMultiTexCoord2f(GL_TEXTURE0, 1.0f, 1.0f);
		glMultiTexCoord2f(GL_TEXTURE1, 1.0f, 1.0f);
		glVertex2d(1, 1);
		glMultiTexCoord2f(GL_TEXTURE0, 0.0f, 1.0f);
		glMultiTexCoord2f(GL_TEXTURE1, 0.0f, 1.0f);
		glVertex2d(-1, 1);
	glEnd();

	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
	glXSwapBuffers(display, win);
#endif
}

GLint shadowMapTexture;
GLdouble lightProj[16], lightView[16];
GLdouble TexMat[16];
GLfloat amb_dif[4] = {0.2f, 0.2f, 0.2f, 1.0f};
GLfloat blk[4] = {0.0f, 0.0f, 0.0f, 0.0f};
GLfloat wht[4] = {1.0f, 1.0f, 1.0f, 1.0f};
static float lightPos[] = { 2.0f, 3.0f, -2.0f, 0.0f };

void invmat(mati,mato)
double mati[16];
double mato[16];
{
   int i,j;

   mato[0]  = mati[0];
   mato[5]  = mati[5];
   mato[10] = mati[10];
   mato[1]  = mati[4];
   mato[4]  = mati[1];
   mato[2]  = mati[8];
   mato[8]  = mati[2];
   mato[6]  = mati[9];
   mato[9]  = mati[6];

   mato[3]  = mati[3];
   mato[7]  = mati[7];
   mato[11] = mati[11];
   mato[15] = mati[15];

   mato[12] = -mati[12];
   mato[13] = -mati[13];
   mato[14] = -mati[14];
}

static double mView[16];
static double Lproj[16];

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} 
};

void MultInvTextMat()
{
	double mV[16];
	static double mViewi[16];
	glGetDoublev(GL_MODELVIEW_MATRIX, mV);
	invmat(mV,mViewi);
	glMatrixMode(GL_TEXTURE);
	glActiveTexture(GL_TEXTURE7);
	glLoadIdentity();	
	glMultMatrixd (Lproj);
	glMultMatrixd (mView);
	glMultMatrixd (mViewi);
	glMultMatrixd ((const GLdouble *) RR);
	glMatrixMode(GL_MODELVIEW);
}

void startTranslate(float x,float y,float z)
{
        glPushMatrix();

        glMatrixMode(GL_TEXTURE);
        glActiveTexture(GL_TEXTURE7);
	glLoadIdentity();	
	glMultMatrixd(TexMat);
        glTranslatef(x,y,z);

        glMatrixMode(GL_MODELVIEW);
        glPopMatrix();
}

void RotateShad(RR)
const GLdouble *RR;
{
	glMultMatrixd((const GLdouble *) RR);
        glPushMatrix();

        glMatrixMode(GL_TEXTURE);
        glActiveTexture(GL_TEXTURE7);
	glMultMatrixd((const GLdouble *) RR);

        glMatrixMode(GL_MODELVIEW);
        glPopMatrix();
       
}

setTextureMatrix(void)
{
	const GLdouble bias[16] = {	
		0.5, 0.0, 0.0, 0.0, 
		0.0, 0.5, 0.0, 0.0,
		0.0, 0.0, 0.5, 0.0,
		0.5, 0.5, 0.5, 1.0};
	
	glGetDoublev(GL_MODELVIEW_MATRIX, mView);
	glGetDoublev(GL_PROJECTION_MATRIX, Lproj);
	
	glMatrixMode(GL_TEXTURE);
	glActiveTexture(GL_TEXTURE7);
	
	glLoadIdentity();	
	glLoadMatrixd(bias);
	
	glMultMatrixd (Lproj);
	glMultMatrixd (mView);
	glGetDoublev(GL_TEXTURE_MATRIX, TexMat);
	
	glMatrixMode(GL_MODELVIEW);
}

#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;

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,6
};

#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 1590
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,
7,6,6,1,8,1,6,1,6,8,8,1,
7,6,6,1,8,1,6,1,6,1,6,8,8,1,
7,6,6,1,8,1,6,1,6,1,6,1,7,1,
299*0,
8,6,1,1,6,1,8,6,1,6,1,6,1,8,1,8,7,6,6,7,
6,7,6,7,6,1,7,1,1,1,8,6,1,1,6,1,8,6,1,6,
1,6,1,8,1,8,7,6,6,7,6,7,6,7,6,1,7,1,1,8,
1,8,6,1,1,6,1,8,6,1,6,1,6,1,8,1,8,7,6,7,
6,6,6,8,7,1,1,1,1,8,6,1,1,6,1,8,6,1,6,1,
6,1,8,1,8,7,6,7,6,6,6,8,1,8,1,1,8,6,1,1,
6,1,8,6,1,6,1,6,1,1,8,7,6,6,7,6,7,6,7,6,
1,7,1,1,1,8,6,1,1,6,1,8,6,1,6,1,6,1,1,8,
7,6,6,7,6,7,6,7,6,1,7,1,1,8,1,8,6,1,1,6,
1,8,6,1,6,1,6,1,1,8,7,6,7,6,6,6,8,7,1,1,
1,1,8,6,1,1,6,1,8,6,1,6,1,6,1,1,8,7,6,7,
6,6,6,8,1,8,6,1,1,15,8,8,1,8,15,8,8,1,8,15,
8,15,8,8,1,8,15,8,8,1,8,15,8,
8,6,1,1,6,1,8,6,1,6,1,6,1,8,1,8,7,6,6,7,6,7,6,7,6,1,7,1,1,6,1,
8,6,1,6,1,8,6,1,6,1,6,1,8,1,8,7,6,7,6,6,6,1,8,7,1,6,1,
8,6,1,6,1,8,6,1,6,1,6,1,8,8,7,6,8,7,6,7,1,6,1,6,1,6,1,
8,6,1,6,1,8,6,1,6,1,6,1,8,1,8,7,6,6,7,6,1,7,6,7,1,6,8,6,1,6,1,
8,6,1,6,1,8,6,1,6,1,6,1,8,1,8,7,6,6,7,6,7,6,7,6,8,1,1,7,6,1,
8,6,1,6,1,8,6,1,6,1,6,1,8,1,8,7,6,6,7,6,7,6,7,6,8,1,1,7,1,6,1,
8,6,1,6,1,8,6,1,6,1,6,1,8,8,7,6,6,7,6,7,6,7,6,8,1,1,7,1,6,1,
8,6,1,6,1,8,6,1,6,1,6,1,8,1,8,7,6,6,7,6,7,6,7,6,8,7,6,6,1,6,1,6,1,6,1,6,1,6,1,6,8,8,6,1,7,1,6,8,8,6,1,
8,6,1,6,1,8,6,1,6,1,6,1,8,1,8,7,6,7,6,6,6,8,8,1,1,1,
8,6,1,6,1,8,6,1,6,1,6,1,8,1,8,7,6,7,6,6,6,8,8,1,1,6,1,
8,6,1,6,1,8,6,1,6,1,6,1,8,1,8,6,6,7,6,7,6,8,8,1,1,1
};


#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 72
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 int ATMselp = 0;

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 int TNKup = 0;
static Window TNKwin, subTNK;
#define TNKWINW 430
#define TNKWINH 205
#define TNKOffx 15
#define TNKRESY  17
#define TNKBWIDE 30
#define TNKBROWY 165
#define NBUTTNK 11
static int ntnkb = NBUTTNK-2;
static BSTRU butTNK[NBUTTNK];
static char *TnkProgs[] = {"minimize","optimize","newton","dynamic","Xtinker","newton-ts"};
static char *AmbProgs[] = {"ambfor","ambmd","crys. opt"};
static char *grdFlags[] = {"-g","-t"};
static char *iterFlags[] = {"-c","-s"};
static char **Progs = TnkProgs;
static int nprogs = 6;
static int *tnkprg;
static double mxgrads[] = {0.01,0.01,0.01,0.0,0.01};
static double *currgrd;
static double *uscl;
static int *archfrq;
static int *arch;
static int *tnkbg;
static int AddChrg = 1;
static int Box = 0;
static int Cutoff = 1;
static int *tnkit;
static int *iqopt;
static int *ibell;
static int *natorg;
static int *irtcel;
static int *irtval;
static int *ifntcl;
#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 SLIDESTRU omapscr[6];
static int omapwn[6];
static int omapwpos[6];
static float omaprat[6];
static int omapsrf;
static BSTRU butomap[3];
static double omapt[3];
static double omapcnt1;
static double omapcnt2;
static int OMAPup = 0;
static Window OMAPwin;
static double slab[3] = {10.0,10.0,10.0};
static double EQ[3] = {0.0,0.0,0.0};
static double extnt[3] = {0.0,0.0,0.0};

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 7
static BSTRU mapbut[NBUTSM];
#define MAPWINW 513
#define MAPWINH 400
#define MAPOFFX  130
#define MAPOFFY  130
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 = 2;
static char *viropts[] = {"VRML2.0","OpenGL file","OpenGL screen"};

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 MLTup = 0;
static Window MLTwin, subMLT;
static BSTRU mltbut[1];
#define MLTWINW 350
#define MLTWINH 300
static LISTSTRU mltlist;

static int SRFup = 0;
static Window SRFwin, subSRF;
static BSTRU srfbut[6];
#define SRFWINW 310
#define SRFWINH 200
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 int CHGopt = 0;
static int CHGstat = 0;
static Window CHGwin;
static BSTRU chgbut[3];
#define CHGWINW 350
#define CHGWINH 150

static int STRup = 0;
static int STRCup = 0;
static Window STRwin, STRCwin, subSTR, subSTRC;
static BSTRU strbut[5];
#define STRCBN 13
static BSTRU strcbut[STRCBN];
#define STRWINW 250
#define STRWINH 250
#define STRSH 125
#define STRX 10
#define STRW 205

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 lnkat = 0;

static int FLRup = 0;
static Window FLRwin, subFLR;
#define NBUTSF  10
#define FRIGD   0
#define FSELR   1
#define FFLEX   2
#define FSELF   3
#define FSEL    4
#define FUSEL   5
#define FSELA   6
#define FCLOS   7
#define FBACK   8
#define FCONT   9
static BSTRU flrbut[NBUTSF];

#define FBOXWIDE 350
#define FBOXHIGH 250
#define FBOXOFFX 10
#define FBOXBLEN 100

#define FRIGCOL 12
#define FLEXCOL 9

static int bckrig = 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;
                 int *y;
                 int *index;
                 int npts;
		 int current;
		 int yelev;
		 int color;
		 int wide;
		 int high;
                } FRSTRU;

void drwgra(FRSTRU *tabptr,int yelev,Window gwin,int wide,int high,int *isav,double *fpts,int jbeg,int jend,int nents,double fmax,double fmin,double flim,int icol,int ifr,char *xstr,char *ystr,char *labstr,int isdash,int init,int notsav,int ityp);
void parse_motion(FRSTRU *tabptr);
static char *frsym[MAXFRQ];
static int nfr = 0;

static FRSTRU scfEfirst = { 0, NULL, NULL, NULL, NULL,-1,0,0,0,0,0};
static FRSTRU scfElast = { 0, NULL, NULL, NULL, NULL,-1,0,0,0,0,0};

static FRSTRU geoFmax = { 0, NULL, NULL, NULL, NULL,-1,0,0,0,0,0};
static FRSTRU geoFrms = { 0, NULL, NULL, NULL, NULL,-1,0,0,0,0,0};
static FRSTRU geoSmax = { 0, NULL, NULL, NULL, NULL,-1,0,0,0,0,0};
static FRSTRU geoSrms = { 0, NULL, NULL, NULL, NULL,-1,0,0,0,0,0};
static FRSTRU geoE = { 0, NULL, NULL, NULL, NULL,-1,0,0,0,0,0};

static FRSTRU spect = { 0, NULL, NULL, NULL, NULL,-1,0,0,0,0,0};
static FRSTRU docksco = { 0, NULL, NULL, NULL, NULL,-1,0,0,0,0,0};

static FRSTRU RamaStru = { 0, NULL, NULL, NULL, NULL,-1,0,0,0,0,0};

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

/* Spectrum variables */
#define SPBHIGH  90
static int SPECWIDE = 600;
static int SPECHIGH = 300;
#define NSBUTTS 7
static int nsbutts = 6;
static BSTRU spbut[NSBUTTS];
static char *pktyp[] = {"Gaussian", "Lorentzian"};
static char *sptyp[] = {"Infra Red", "Raman"};
static char *nmrsptyp[] = {"1H", "13C"};
static char *uvsptyp[] = {"UV spectrum"};
static double *spint;
static float *spfrq;
static int *spnfrq;
static int nspqbox = 5;
static double *out_spec = NULL;
static char *splab = NULL;
static char *forlab = "Frequency";
static char *uvlab = "Excitation Energy (nm)";
static char *nmrlab = "Shift (ppm)";
static float NMRbas = 100.0;
static int NMRnuc = 1;
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;

#define mxcpl 5
#define mxpeak 2*2*2*2*2
static float *peaks  = NULL;
static double *inten  = NULL;
static int npks = 0;
static float jcut  = 1.0;
static float nmr1Href  = 32.78;
static float nmr13Cref  = 194.47;
static float nmr1Hstep = 0.001;
static float nmr13Cstep = 0.01;
static float *nmrref  = &nmr1Href;
static int NMRup = 0;
void FRQextr();
void INTextr();

void updcallb(char *str);
void disp_map(char *str);
void srfprop();
void deletebox();

/* 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 *logo;
static int *nscnd;
static int *dolabs;
static int *forces_yes_no;
static int *ifogl;
static int *ifdogl;
static int *fullgl;
static int *icst;
static int *ibox;
static int *igfmap;
static int *iresrd;
static int srfsep;
static int srftyp;
static int *doesp;
static int *doshad;
static int *ihasex;
static int *noshad;

#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   34 
#else
#define NBUTTS   33 
#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 BGIF2    31
#define BLOCAL   32
#define BOGL     33

#define NBUTTS2  46 

#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 BJCPL    45

#define NBUTTR   5 

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


#define NQBOX   82

#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 QATOM   40
#define QPHI    41
#define QPSI    42
#define QPROT   43
#define QGRD    44
#define QARCH   45
#define QTNKJN  46
#define QMAXIT  47
#define QCUBE   48
#define QCTA    49
#define QCTB    50
#define QCTC    51
#define QNSCAL  52
#define QVFILE  53
#define QMFILE  54
#define QCNTVAL 55
#define QCOLVAL1 56
#define QCOLVAL2 57
#define QCOLVAL3 58
#define QCOLVAL4 59
#define QCOLVAL5 60
#define QPOLVAL1 61
#define QPOLVAL2 62
#define QSVFILE  63
#define QSCNT    64
#define QHW      65
#define QMINF    66
#define QMAXF    67
#define QSSCAL   68
#define QIMAX    69
#define QTMS     70
#define QFREQ    71
#define QSFIL    72
#define QDEL     73
#define QCNT     74
#define QHBMIN   75
#define QHBMAX   76
#define QHAMIN   77
#define QHAMAX   78
#define QPDB     79
#define QCNT2    80
#define QSUBSTR  81

#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 FSELSTRU fsel;
static FSELSTRU gsel;
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 LISTSTRU strlist;
static LISTSTRU str2list;
static LISTSTRU strclist;
static QBOXSTRU qboxes[NQBOX];

static int *Sinct;
static int *Sincp;

#define MAXFILELEN 1024
#define NFLS 13
static int    lpnt = 0;
static int    selfil = 0;
static int    firstreadf = 1;
static int    nfilesstart = 0;
static char   firstfile[MAXFILELEN];
static char   *pdbcode = NULL;
#define DIRX 35
#define DIRY 40
#define DIRW 255
#define DIRH 200

#define NDRS 4
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";
 
static Pixmap grayStip; 
static unsigned int  dispDEEP;

float rama_area1[16][2] = {
	{-177.5f,-180.0f},
	{-177.5f,-177.5f},
	{-172.5f,-177.5f},
	{-172.5f,-172.5f},
	{-167.5f,-172.5f},
	{-167.5f,-167.5f},
	{-127.5f,-167.5f},
	{-127.5f,-172.5f},
	{-97.5f,-172.5f},
	{-97.5f,-167.5f},
	{-77.5f,-167.5f},
	{-77.5f,-172.5f},
	{-72.5f,-172.5f},
	{-72.5f,-177.5f},
	{-67.5f,-177.5f},
	{-67.5f,-180.0f},
};

float rama_area2[25][2] = {
	{57.5f,67.5f},
	{57.5f,62.5f},
	{62.5f,62.5f},
	{62.5f,57.5f},
	{67.5f,57.5f},
	{67.5f,47.5f},
	{72.5f,47.5f},
	{72.5f,32.5f},
	{77.5f,32.5f},
	{77.5f,2.5f},
	{62.5f,2.5f},
	{62.5f,7.5f},
	{57.5f,7.5f},
	{57.5f,12.5f},
	{52.5f,12.5f},
	{52.5f,22.5f},
	{47.5f,22.5f},
	{47.5f,27.5f},
	{42.5f,27.5f},
	{42.5f,37.5f},
	{37.5f,37.5f},
	{37.5f,62.5f},
	{42.5f,62.5f},
	{42.5f,67.5f},
	{57.5f,67.5f}
};

float rama_area3[108][2] = {
	{-62.5f,180.0f},
	{-62.5f,172.5f},
	{-57.5f,172.5f},
	{-57.5f,167.5f},
	{-52.5f,167.5f},
	{-52.5f,157.5f},
	{-47.5f,157.5f},
	{-47.5f,147.5f},
	{-42.5f,147.5f},
	{-42.5f,137.5f},
	{-37.5f,137.5f},
	{-37.5f,122.5f},
	{-42.5f,122.5f},
	{-42.5f,117.5f},
	{-47.5f,117.5f},
	{-47.5f,112.5f},
	{-57.5f,112.5f},
	{-57.5f,107.5f},
	{-62.5f,107.5f},
	{-62.5f,102.5f},
	{-67.5f,102.5f},
	{-67.5f,97.5f},
	{-72.5f,97.5f},
	{-72.5f,62.5f},
	{-77.5f,62.5f},
	{-77.5f,52.5f},
	{-87.5f,52.5f},
	{-87.5f,47.5f},
	{-92.5f,47.5f},
	{-92.5f,52.5f},
	{-97.5f,52.5f},
	{-97.5f,67.5f},
	{-102.5f,67.5f},
	{-102.5f,77.5f},
	{-107.5f,77.5f},
	{-107.5f,82.5f},
	{-112.5f,82.5f},
	{-112.5f,72.5f},
	{-117.5f,72.5f},
	{-117.5f,62.5f},
	{-122.5f,62.5f},
	{-122.5f,52.5f},
	{-127.5f,52.5f},
	{-127.5f,47.5f},
	{-112.5f,47.5f},
	{-112.5f,42.5f},
	{-102.5f,42.5f},
	{-102.5f,37.5f},
	{-92.5f,37.5f},
	{-92.5f,32.5f},
	{-87.5f,32.5f},
	{-87.5f,22.5f},
	{-82.5f,22.5f},
	{-82.5f,17.5f},
	{-77.5f,17.5f},
	{-77.5f,12.5f},
	{-67.5f,12.5f},
	{-67.5f,7.5f},
	{-62.5f,7.5f},
	{-62.5f,2.5f},
	{-57.5f,2.5f},
	{-57.5f,-7.5f},
	{-52.5f,-7.5f},
	{-52.5f,-12.5f},
	{-47.5f,-12.5f},
	{-47.5f,-22.5f},
	{-42.5f,-22.5f},
	{-42.5f,-32.5f},
	{-37.5f,-32.5f},
	{-37.5f,-62.5f},
	{-42.5f,-62.5f},
	{-42.5f,-67.5f},
	{-77.5f,-67.5f},
	{-77.5f,-62.5f},
	{-117.5f,-62.5f},
	{-117.5f,-57.5f},
	{-122.5f,-57.5f},
	{-122.5f,-47.5f},
	{-127.5f,-47.5f},
	{-127.5f,-37.5f},
	{-132.5f,-37.5f},
	{-132.5f,-17.5f},
	{-137.5f,-17.5f},
	{-137.5f,2.5f},
	{-142.5f,2.5f},
	{-142.5f,32.5f},
	{-137.5f,32.5f},
	{-137.5f,52.5f},
	{-142.5f,52.5f},
	{-142.5f,57.5f},
	{-147.5f,57.5f},
	{-147.5f,67.5f},
	{-152.5f,67.5f},
	{-152.5f,77.5f},
	{-147.5f,77.5f},
	{-147.5f,87.5f},
	{-152.5f,87.5f},
	{-152.5f,97.5f},
	{-157.5f,97.5f},
	{-157.5f,112.5f},
	{-162.5f,112.5f},
	{-162.5f,122.5f},
	{-167.5f,122.5f},
	{-167.5f,132.5f},
	{-172.5f,132.5f},
	{-172.5f,142.5f},
	{-180.0f,142.5f},
	{-180.0f,180.0f}
};

float rama_area4[108][2] = {
	{-42.5f,180.0f},
	{-42.5f,172.5f},
	{-42.5f,172.5f},
	{-37.5f,172.5f},
	{-37.5f,167.5f},
	{-32.5f,167.5f},
	{-32.5f,157.5f},
	{-27.5f,157.5f},
	{-27.5f,147.5f},
	{-22.5f,147.5f},
	{-22.5f,127.5f},
	{-17.5f,127.5f},
	{-17.5f,112.5f},
	{-22.5f,112.5f},
	{-22.5f,107.5f},
	{-27.5f,107.5f},
	{-27.5f,102.5f},
	{-32.5f,102.5f},
	{-32.5f,97.5f},
	{-47.5f,97.5f},
	{-47.5f,92.5f},
	{-52.5f,92.5f},
	{-52.5f,72.5f},
	{-57.5f,72.5f},
	{-57.5f,42.5f},
	{-62.5f,42.5f},
	{-62.5f,27.5f},
	{-57.5f,27.5f},
	{-57.5f,22.5f},
	{-52.5f,22.5f},
	{-52.5f,12.5f},
	{-47.5f,12.5f},
	{-47.5f,7.5f},
	{-42.5f,7.5f},
	{-42.5f,2.5f},
	{-37.5f,2.5f},
	{-37.5f,-7.5f},
	{-32.5f,-7.5f},
	{-32.5f,-12.5f},
	{-27.5f,-12.5f},
	{-27.5f,-27.5f},
	{-22.5f,-27.5f},
	{-22.5f,-47.5f},
	{-17.5f,-47.5f},
	{-17.5f,-67.5f},
	{-22.5f,-67.5f},
	{-22.5f,-77.5f},
	{-27.5f,-77.5f},
	{-27.5f,-82.5f},
	{-47.5f,-82.5f},
	{-47.5f,-87.5f},
	{-77.5f,-87.5f},
	{-77.5f,-92.5f},
	{-87.5f,-92.5f},
	{-87.5f,-112.5f},
	{-92.5f,-112.5f},
	{-92.5f,-122.5f},
	{-97.5f,-122.5f},
	{-97.5f,-137.5f},
	{-92.5f,-137.5f},
	{-92.5f,-142.5f},
	{-82.5f,-142.5f},
	{-82.5f,-147.5f},
	{-72.5f,-147.5f},
	{-72.5f,-152.5f},
	{-67.5f,-152.5f},
	{-67.5f,-157.5f},
	{-62.5f,-157.5f},
	{-62.5f,-162.5f},
	{-57.5f,-162.5f},
	{-57.5f,-167.5f},
	{-52.5f,-167.5f},
	{-52.5f,-172.5f},
	{-47.5f,-172.5f},
	{-47.5f,-177.5f},
	{-42.5f,-177.5f},
	{-42.5f,-180.0f},
	{-180.0f,-180.0f},
	{-180.0f,-147.5f},
	{-177.5f,-147.5f},
	{-167.5f,-147.5f},
	{-167.5f,-142.5f},
	{-157.5f,-142.5f},
	{-157.5f,-137.5f},
	{-147.5f,-137.5f},
	{-147.5f,-132.5f},
	{-142.5f,-132.5f},
	{-142.5f,-127.5f},
	{-147.5f,-127.5f},
	{-147.5f,-97.5f},
	{-152.5f,-97.5f},
	{-152.5f,-92.5f},
	{-157.5f,-92.5f},
	{-157.5f,-82.5f},
	{-162.5f,-82.5f},
	{-162.5f,-52.5f},
	{-157.5f,-52.5f},
	{-157.5f,-37.5f},
	{-162.5f,-37.5f},
	{-162.5f,-7.5f},
	{-167.5f,-7.5f},
	{-167.5f,32.5f},
	{-172.5f,32.5f},
	{-172.5f,52.5f},
	{-177.5f,52.5f},
	{-177.5f,77.5f},
	{-180.0f,77.5f},
	{-180.0f,180.0f}
};

float rama_area5[67][2] = {
	{82.5f,57.5f},
	{87.5f,57.5f},
	{87.5f,42.5f},
	{92.5f,42.5f},
	{92.5f,22.5f},
	{97.5f,22.5f},
	{97.5f,-17.5f},
	{92.5f,-17.5f},
	{92.5f,-22.5f},
	{87.5f,-22.5f},
	{87.5f,-27.5f},
	{82.5f,-27.5f},
	{82.5f,-37.5f},
	{87.5f,-37.5f},
	{87.5f,-47.5f},
	{92.5f,-47.5f},
	{92.5f,-57.5f},
	{87.5f,-57.5f},
	{87.5f,-67.5f},
	{82.5f,-67.5f},
	{82.5f,-72.5f},
	{77.5f,-72.5f},
	{77.5f,-77.5f},
	{62.5f,-77.5f},
	{62.5f,-72.5f},
	{57.5f,-72.5f},
	{57.5f,-67.5f},
	{52.5f,-67.5f},
	{52.5f,-37.5f},
	{57.5f,-37.5f},
	{57.5f,-27.5f},
	{62.5f,-27.5f},
	{62.5f,-22.5f},
	{57.5f,-22.5f},
	{57.5f,-12.5f},
	{52.5f,-12.5f},
	{52.5f,-7.5f},
	{47.5f,-7.5f},
	{47.5f,-2.5f},
	{42.5f,-2.5f},
	{42.5f,2.5f},
	{37.5f,2.5f},
	{37.5f,12.5f},
	{32.5f,12.5f},
	{32.5f,22.5f},
	{27.5f,22.5f},
	{27.5f,32.5f},
	{22.5f,32.5f},
	{22.5f,47.5f},
	{17.5f,47.5f},
	{17.5f,67.5f},
	{22.5f,67.5f},
	{22.5f,77.5f},
	{27.5f,77.5f},
	{27.5f,82.5f},
	{32.5f,82.5f},
	{32.5f,87.5f},
	{47.5f,87.5f},
	{47.5f,92.5f},
	{67.5f,92.5f},
	{67.5f,87.5f},
	{72.5f,87.5f},
	{72.5f,82.5f},
	{77.5f,82.5f},
	{77.5f,77.5f},
	{82.5f,77.5f},
	{82.5f,57.5f},
};

float rama_area6[10][2] = {
	{77.5f,180.0f},
	{77.5f,162.5f},
	{82.5f,162.5f},
	{82.5f,147.5f},
	{72.5f,147.5f},
	{72.5f,157.5f},
	{67.5f,157.5f},
	{67.5f,167.5f},
	{62.5f,167.5f},
	{62.5f,180.0f} 
};

float rama_area7[28][2] = {
	{57.5f,-180.0f},
	{57.5f,-167.5f},
	{52.5f,-167.5f},
	{52.5f,-162.5f},
	{47.5f,-162.5f},
	{47.5f,-157.5f},
	{42.5f,-157.5f},
	{42.5f,-152.5f},
	{37.5f,-152.5f},
	{37.5f,-142.5f},
	{32.5f,-142.5f},
	{32.5f,-107.5f},
	{37.5f,-107.5f},
	{37.5f,-102.5f},
	{42.5f,-102.5f},
	{42.5f,-97.5f},
	{52.5f,-97.5f},
	{52.5f,-92.5f},
	{62.5f,-92.5f},
	{62.5f,-97.5f},
	{67.5f,-97.5f},
	{67.5f,-102.5f},
	{72.5f,-102.5f},
	{72.5f,-112.5f},
	{77.5f,-112.5f},
	{77.5f,-157.5f},
	{72.5f,-157.5f},
	{72.5f,-180.0f}
};

float rama_area8[10][2] = {
	{162.5f,180.0f},
	{162.5f,147.5f},
	{167.5f,147.5f},
	{167.5f,132.5f},
	{172.5f,132.5f},
	{172.5f,117.5f},
	{177.5f,117.5f},
	{177.5f,77.5f},
	{180.0f,77.5f},
	{180.0f,180.0f}
};

float rama_area9[10][2] = {
	{162.5f,-180.0f},
	{162.5f,-177.5f},
	{167.5f,-177.5f},
	{167.5f,-167.5f},
	{172.5f,-167.5f},
	{172.5f,-157.5f},
	{177.5f,-157.5f},
	{177.5f,-147.5f},
	{180.0f,-147.5f},
	{180.0f,-180.0f}
};

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, when the time is activated */
   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);
  }
}

void 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 = vfork();
    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 (xison) {
    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);
    }
   } else {
	dos2u(strname);
   }
}

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

 result = *(zmptrp->iz + (i*4) + j);

 return(result);

}

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

 result = (zmptrp->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
	zmptrp->bl,zmptrp->alph,zmptrp->bet,zmptrp->ibl,zmptrp->ialph,
	zmptrp->ibet,zmptrp->imap,zmptrp->ianz,zmptrp->iz,
	xyzp->lwrit,xyzp->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
	zmptrp->bl,zmptrp->alph,zmptrp->bet,zmptrp->ibl,zmptrp->ialph,
	zmptrp->ibet,zmptrp->imap,zmptrp->ianz,zmptrp->iz,
	xyzp->lwrit,xyzp->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
	zmptrp->bl,zmptrp->alph,zmptrp->bet,zmptrp->ibl,zmptrp->ialph,
	zmptrp->ibet,zmptrp->imap,zmptrp->ianz,zmptrp->iz,
	xyzp->iconn,xyzp->ianz,xyzp->ityp,xyzp->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
	zmptrp->bl,zmptrp->alph,zmptrp->bet,zmptrp->ibl,zmptrp->ialph,
	zmptrp->ibet,zmptrp->imap,zmptrp->ianz,zmptrp->iz,
	geop->epoints,xyzp->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
	zmptrp->bl,zmptrp->alph,zmptrp->bet,zmptrp->ibl,zmptrp->ialph,
	zmptrp->ibet,zmptrp->imap,zmptrp->ianz,zmptrp->iz,xyzp->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,zmptrp->imap);
#else
#ifdef CRAY
	FNDMZZ(ixyz,istat,zmptrp->imap);
#else
	fndmzz_(ixyz,istat,zmptrp->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
	xyzp->qat,xyzp->rzp,zmptrp->ianz,zmptrp->imap,
	xyzp->ianz,xyzp->lring,xyzp->ityp,xyzp->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
	zmptrp->bl,zmptrp->alph,zmptrp->bet,zmptrp->ibl,zmptrp->ialph,
	zmptrp->ibet,zmptrp->imap,zmptrp->ianz,zmptrp->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
	zmptrp->bl,zmptrp->alph,zmptrp->bet,zmptrp->ibl,zmptrp->ialph,
	zmptrp->ibet,zmptrp->imap,zmptrp->ianz,zmptrp->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;
{
	int part;

	part = zmpart->ipart;

#if defined(VMS) || defined(UNDERSC)
	dumzz(cc,ianc,nnatoms,
#else
#ifdef CRAY
	DUMZZ(cc,ianc,nnatoms,
#else
	dumzz_(cc,ianc,nnatoms,
#endif
#endif
	zmptrp->bl,zmptrp->alph,zmptrp->bet,zmptrp->ibl,zmptrp->ialph,
	zmptrp->ibet, zmptrp->imap,zmptrp->ianz,zmptrp->iz,
	stocp->cstoc,stocp->czstoc,stocp->astoc,stocp->bstoc,stocp->ianstc,
	xyzp->coo,xyzp->iresid,&calfptr->issdon);

}

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

#if defined(VMS) || defined(UNDERSC)
	convzmzz(cc,ianc,nnatoms,igo,ico,ido,
#else
#ifdef CRAY
	CONVZMZZ(cc,ianc,nnatoms,igo,ico,ido,
#else
	convzmzz_(cc,ianc,nnatoms,igo,ico,ido,
#endif
#endif
	zmptrp->bl,zmptrp->alph,zmptrp->bet,zmptrp->ibl,zmptrp->ialph,
	zmptrp->ibet,zmptrp->imap,zmptrp->ianz,zmptrp->iz,
	stocp->cstoc,stocp->czstoc,stocp->astoc,stocp->bstoc,stocp->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
        xyzp->coo,xyzp->ianz,
	zmptrp->bl,zmptrp->alph,zmptrp->bet,zmptrp->ibl,zmptrp->ialph,
	zmptrp->ibet,zmptrp->imap,zmptrp->ianz,zmptrp->iz,
	stocp->cstoc,stocp->czstoc,stocp->astoc,stocp->bstoc,stocp->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
	xyzp->coo,xyzp->ianz,
	zmptrp->bl,zmptrp->alph,zmptrp->bet,zmptrp->ibl,zmptrp->ialph,
	zmptrp->ibet,zmptrp->imap,zmptrp->ianz,zmptrp->iz,
	stocp->cstoc,stocp->czstoc,stocp->astoc,stocp->bstoc,stocp->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
	dorbp->stoalfa,dorbp->stobnorm,dorbp->istos,dorbp->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
	dorbp->p,dorbp->paa,orbp->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
	dorbp->vectrs,dorbp->vectrb,dorbp->focc,dorbp->focb,dorbp->p,dorbp->paa,
	dorbp->averag,orbp->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
	dorbp->vectrs,dorbp->vectrb,dorbp->focc,dorbp->focb,dorbp->p,dorbp->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
	dorbp->vectrs,dorbp->focc,dorbp->p,dorbp->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
	dorbp->p);

}

#if defined(VMS) || defined(UNDERSC)
espgrd(npts1,npts2,npts3,idebug)
#else
#ifdef CRAY
ESPGRD(npts1,npts2,npts3,idebug)
#else
espgrd_(npts1,npts2,npts3,idebug)
#endif
#endif
int *npts1;
int *npts2;
int *npts3;
int *idebug;
{
   int ZSize,memstat;
   double d;

   ZSize = *sgrd.mx3d;
   memstat = 1;

   if (fsgrd.xden == NULL) {
       if ((fsgrd.xden = (double *) malloc((sizeof d)*ZSize*ZSize*ZSize)) 
		== NULL) {
		memstat = 0;
       }
       if ((fsgrd.yden = (double *) malloc((sizeof d)*ZSize*ZSize*ZSize)) 
		== NULL) {
		memstat = 0;
       }
       if ((fsgrd.zden = (double *) malloc((sizeof d)*ZSize*ZSize*ZSize)) 
		== NULL) {
		memstat = 0;
       }
   }

#if defined(VMS) || defined(UNDERSC)
	espgrdd(npts1,npts2,npts3,idebug,
#else
#ifdef CRAY
	ESPGRDD(npts1,npts2,npts3,idebug,
#else
	espgrdd_(npts1,npts2,npts3,idebug,
#endif
#endif
	sgrd.denn,dorbp->p,fsgrd.xden,fsgrd.yden,fsgrd.zden);

}

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

#if defined(VMS) || defined(UNDERSC)
	newdenmad(dorbp->p,orbp->qd);
#else
#ifdef CRAY
	NEWDENMAD(dorbp->p,orbp->qd);
#else
	newdenmad_(dorbp->p,orbp->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
	dorbp->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
	dorbp->p,dorbp->paa,orbp->pd,orbp->gd,orbp->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
	dorbp->vectrs,dorbp->vectrb,dorbp->eiga,dorbp->eigb,
	dorbp->ncols,dorbp->ncolb);

}

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

#if defined(VMS) || defined(UNDERSC)
	stind(dorbp->p,xyzp->qat);
#else
#ifdef CRAY
	STIND(dorbp->p,xyzp->qat);
#else
	stind_(dorbp->p,xyzp->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
	dorbp->p,xyzp->qat,xyzp->iconn);

}

#if defined(VMS) || defined(UNDERSC)
dipole()
#else
#ifdef CRAY
DIPOLE()
#else
dipole_()
#endif
#endif
{
   int ZSize,ntt,i;
   double d;

   ZSize = *dorbp->mxorb;
   if ((dmao = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	fprintf(stderr,"Out of memory\n");
   }
   if ((nor = (int *) malloc((sizeof i)*ZSize*ZSize)) == NULL) {
	fprintf(stderr,"Out of memory\n");
   }

   ntt = NAT->norbs*(NAT->norbs+1)/2;


#if defined(VMS) || defined(UNDERSC)
	dipold(
#else
#ifdef CRAY
	DIPOLD(
#else
	dipold_(
#endif
#endif
	&ntt,nor,dmao,dorbp->focc,dorbp->focb,dorbp->vectrs,dorbp->vectrb,dorbp->p);

}

#if defined(VMS) || defined(UNDERSC)
boys(norb,nor,dmao,vecs)
#else
#ifdef CRAY
BOYS(norb,nor,dmao,vecs)
#else
boys_(norb,nor,dmao,vecs)
#endif
#endif
int *norb;
int *nor;
double *dmao;
double *vecs;
{
   int i,ZSize,ntt,memstat,nbasis;
   double d;
   double *cl,*rij,*qpix,*qpjx;
   int *iord,*iir;

   memstat = 1;
   nbasis = NAT->norbs;
   ntt = nbasis*(nbasis+1)/2;

   boy.dmao = dmao;
   boy.nor = nor;

   if ((cl = (double *) malloc((sizeof d)*nbasis*nbasis)) == NULL) {
        memstat = 0;
	fprintf(stderr,"cl Out of memory\n");
   }
   boy.cl = cl;

   if ((rij = (double *) malloc((sizeof d)*ntt*3)) == NULL) {
        memstat = 0;
	fprintf(stderr,"rij Out of memory\n");
   }
   boy.rij = rij;

   if ((qpix = (double *) malloc((sizeof d)*nbasis)) == NULL) {
        memstat = 0;
	fprintf(stderr,"qpix Out of memory\n");
   }
   boy.qpix = qpix;

   if ((qpjx = (double *) malloc((sizeof d)*nbasis)) == NULL) {
        memstat = 0;
	fprintf(stderr,"qpjx Out of memory\n");
   }
   boy.qpjx = qpjx;

   if ((iord = (int *) malloc((sizeof i)*nbasis)) == NULL) {
        memstat = 0;
	fprintf(stderr,"iord Out of memory\n");
   }
   boy.iord = iord;

   if ((iir = (int *) malloc((sizeof i)*nbasis)) == NULL) {
        memstat = 0;
	fprintf(stderr,"irr Out of memory\n");
   }
   boy.iir = iir;

#if defined(VMS) || defined(UNDERSC)
	boyd(norb,nor,dmao,vecs,
#else
#ifdef CRAY
	BOYS(norb,nor,dmao,vecs,
#else
	boyd_(norb,nor,dmao,vecs,
#endif
#endif
	&nbasis,&ntt,cl,iord,iir,rij,qpix,qpjx);

}

#if defined(VMS) || defined(UNDERSC)
int mseed()
#else
#ifdef CRAY
int MSEED()
#else
int mseed_()
#endif
#endif
{
  return (int)(((long)time(NULL)+(long)getpid()) % (long)1000000);
}

#if defined(VMS) || defined(UNDERSC)
mopin(istat,ibin,impas)
#else
#ifdef CRAY
MOPIN(istat,ibin,impas)
#else
mopin_(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
	dorbp->vectrs,dorbp->averag,dorbp->p,dorbp->focc,dorbp->eiga,
	orbp->qd,orbp->pd,dorbp->nocc,dorbp->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
	dorbp->vectrs,dorbp->vectrb,dorbp->focc,dorbp->focb,dorbp->eiga,
	dorbp->eigb,dorbp->nocc,dorbp->nocb,dorbp->ncols,dorbp->ncolb,
	xyzp->coo,xyzp->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
	dorbp->vectrs,dorbp->vectrb,dorbp->focc,dorbp->focb,dorbp->eiga,
	dorbp->eigb,dorbp->nocc,dorbp->nocb,dorbp->ncols,dorbp->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
	dorbp->focc,dorbp->focb,dorbp->nocc,dorbp->nocb,dorbp->ncols,
	dorbp->ncolb,xyzp->coo,xyzp->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
	dorbp->focc,dorbp->focb,dorbp->nocc,dorbp->nocb,
	dorbp->ncols,dorbp->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
	xyzp->ianz,xyzp->iatoms,
	dorbp->focc,dorbp->focb,dorbp->nocc,dorbp->nocb,
	dorbp->ncols,dorbp->ncolb);

}

#if defined(VMS) || defined(UNDERSC)
rdnwch(idebug,irtype,istats)
#else
#ifdef CRAY
RDNWCH(idebug,irtype,istats)
#else
rdnwch_(idebug,irtype,istats)
#endif
#endif
int *idebug;
int *irtype;
int *istats;
{

#if defined(VMS) || defined(UNDERSC)
	rdnwcd(idebug,irtype,istats,
#else
#ifdef CRAY
	RDNWCD(idebug,irtype,istats,
#else
	rdnwcd_(idebug,irtype,istats,
#endif
#endif
	xyzp->ianz,xyzp->iatoms,
	dorbp->focc,dorbp->focb,dorbp->nocc,dorbp->nocb,
	dorbp->ncols,dorbp->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
	dorbp->vectrs,dorbp->vectrb,dorbp->focc,dorbp->focb,dorbp->eiga,
	dorbp->eigb,dorbp->averag,dorbp->p,orbp->qd,orbp->pd,
	dorbp->nocc,dorbp->nocb,dorbp->ncols,dorbp->ncolb,
	geop->formax,geop->forrms,geop->dismax,geop->disrms,
	geop->epoints,geop->isav,xyzp->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
	dorbp->vectrs,dorbp->vectrb,dorbp->focc,dorbp->focb,dorbp->eiga,
	dorbp->eigb,dorbp->nocc,dorbp->nocb,dorbp->ncols,dorbp->ncolb,
	dorbp->stoalfa,dorbp->stobnorm,dorbp->istos,dorbp->naorbs,
	geop->formax,geop->forrms,geop->dismax,geop->disrms,
	geop->epoints,geop->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
	dorbp->vectrs,dorbp->vectrb,dorbp->focc,dorbp->focb,dorbp->eiga,
	dorbp->eigb,dorbp->nocc,dorbp->nocb,dorbp->ncols,dorbp->ncolb,
	dorbp->stoalfa,dorbp->stobnorm,dorbp->istos,dorbp->naorbs,
	geop->formax,geop->forrms,geop->dismax,geop->disrms,
	geop->epoints,geop->isav,xyzp->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
	dorbp->vectrs,dorbp->vectrb,dorbp->focc,dorbp->eiga,dorbp->eigb,
	dorbp->ncols,dorbp->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
	dorbp->vectrs,dorbp->vectrb,dorbp->eiga,dorbp->eigb,
	dorbp->ncols,dorbp->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
	dorbp->vectrs,dorbp->vectrb,dorbp->focc,dorbp->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
	dorbp->ncols,dorbp->ncolb,dorbp->focc,dorbp->focb,dorbp->eiga,dorbp->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
	dorbp->focc,dorbp->focb,dorbp->eiga,dorbp->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
	dorbp->focc,dorbp->focb,dorbp->eiga,dorbp->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
	dorbp->focc,dorbp->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,xyzp->coo,
			xyzp->lwrit,xyzp->ityp,xyzp->icont,xyzp->ncont);
       else mapsrf(sgrd.denn,mgrd.fmap,&mapit);
#else
#ifdef CRAY
       if (*idomap) ALMGRD();
       if (*idocal) SRFCAL(idomap,sgrd.denn,mgrd.fmap,xyzp->coo,
			xyzp->lwrit,xyzp->ityp,xyzp->icont,xyzp->ncont);
       else MAPSRF(sgrd.denn,mgrd.fmap,&mapit);
#else
       if (*idomap) almgrd_();
       if (*idocal) srfcal_(idomap,sgrd.denn,mgrd.fmap,xyzp->coo,
			xyzp->lwrit,xyzp->ityp,xyzp->icont,xyzp->ncont);
       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,&cell->ichx);

}

#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,&cell->ichx);

}

void disp_map(char *str)
{
	int i,idopn,srft;

	srft = NSurf[istruct];
	NSurf[istruct] = omapsrf;
	*vlcnt = omapcnt1;
	idopn = 0;
	if (omapPandN && !(*rng1 >= 0.0) ) {
	   idopn = 1;
	   *vlcnt2 = omapcnt2;
	} else {
	   *vlcnt2 = -omapcnt1;
	}
#if defined(VMS) || defined(UNDERSC)
	dpomap(&idopn);
#else
#ifdef CRAY
	DPOMAP(&idopn);
#else
	dpomap_(&idopn);
#endif
#endif
#ifdef DOGL
	srfprop();
	if (srft > omapsrf) NSurf[istruct] = srft;
	ogbox();
#endif
	update_struct();
}

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

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

}

getcval()
{
	omapcnt1 = *rng2 / 2.0;
	sprintf(stemp,"%5.2f",omapcnt1);
	qboxstr(&qboxes[QCNT],&OMAPwin,1,0,-1,20,180,
	   50,QBOXHIGH, 0,NULL,stemp,
	   0,3,2000,disp_map);
	qboxes[QCNT].dflt = &omapcnt1;


	if (omapPandN && !(*rng1 >= 0.0) ) {
	   omapcnt2 = *rng1 / 2.0;
	   sprintf(stemp,"%5.2f",omapcnt2);
	   qboxstr(&qboxes[QCNT2],&OMAPwin,0,0,-1,20,210,
	   50,QBOXHIGH, 0,NULL,stemp,
	   0,3,2000,disp_map);
	   qboxes[QCNT2].dflt = &omapcnt2;
	}
}

int omap()
{
    if (!*ipdbon) {
	DoCan(event.xbutton.x_root, event.xbutton.y_root,
	"Electron density maps are only available for PDB files.",0);
	return(1);
    } else {
	if (pdbcode == NULL) {
	     qboxstr(&qboxes[QSRFW],NULL,1,0,-1,
			DEFQX,DEFQY,QBOXWIDE,QBOXHIGH,0,
			"Omap/DSN6 Filename ? ",NULL,0,0,
			584,dummyproc);
			return(1);
	} else {
	     if (omapr == 1) {
		 if (!OMAPup) InitOmap(0);
	     } else {
		 if (OMAPup) DeleteOMAP();
		 if (!CheckWGET()) 
		      if (!GetOMAPWWW(pdbcode,strname)) return(1);
	     }
	}
   }
   return(0);
}

res_dens(Ca)
int Ca;
{
   int l;
   double x,y,z;

   if (Ca >= 0) l = calfptr->icalf[Ca][0]-1;
   omapCa = l;
   x = xyzp->coo[l*3];
   y = xyzp->coo[l*3+1];
   z = xyzp->coo[l*3+2];
   omaprat[0] = (z - comsrfptr->vo[2] + 0.5*comsrfptr->r[2]*omaprat[1])  
		/ comsrfptr->r[2];
   omaprat[2] = (x - comsrfptr->vo[0] + 0.5*comsrfptr->r[0]*omaprat[3])  
		/ comsrfptr->r[0];
   omaprat[4] = (y - comsrfptr->vo[1] + 0.5*comsrfptr->r[1]*omaprat[5]) 
		/ comsrfptr->r[1];

   omapwpos[0] = (int) ((float) omapwn[0]*omaprat[0]);
   omapwpos[2] = (int) ((float) omapwn[2]*omaprat[2]);
   omapwpos[4] = (int) ((float) omapwn[4]*omaprat[4]);

   RedrawSlide(&omapscr[0]);
   RedrawSlide(&omapscr[2]);
   RedrawSlide(&omapscr[4]);
   UpdateOMAP1();
   UpdateOMAP2();
   UpdateOMAP3();
   update_struct();
}

UpdateOMAP1()
{

   EQ[0] = comsrfptr->vo[2] + extnt[2]*omaprat[0];

   update_struct();
   
}

UpdateSLAB1()
{

   slab[0] = extnt[2]*omaprat[1];

   update_struct();
   
}

UpdateOMAP2()
{

   EQ[1] = comsrfptr->vo[0] + extnt[0]*omaprat[2];

   update_struct();
   
}

UpdateSLAB2()
{

   slab[1] = extnt[0]*omaprat[3];

   update_struct();
   
}

UpdateOMAP3()
{

   EQ[2] = comsrfptr->vo[1] + extnt[1]*omaprat[4];

   update_struct();
   
}

UpdateSLAB3()
{

   slab[2] = extnt[1]*omaprat[5];

   update_struct();
   
}

void InitOmap(iopt)
int iopt;
{
   int i;
   
   OMAPup = 1;

   omapPandN = iopt;

   OMAPwin = CreateWindow("OMAP display","-30+30",230,280,
	 		 infobg,infofg,(Window)0);

   XSelectInput(display, OMAPwin, 
	KeyPressMask | ExposureMask | ButtonPressMask | ButtonReleaseMask 
		| ButtonMotionMask | LeaveWindowMask);
   XMapWindow(display,OMAPwin);

   getcval();

   DefBut(&butomap[0], OMAPwin, 100, 245, 50, 23,
	"Close", infobg, -15);

   DefBut(&butomap[1], OMAPwin, 75, 180, 50, 23,
	"Apply", infobg, -15);

   DefBut(&butomap[2], OMAPwin, 155, 185, 15, 15,
	"", infobg, -15);

   omapwn[0] = 100; omapwpos[0] = 100;
   DefSlide(&omapscr[0],OMAPwin,20,50,20,100,10,&omapwn[0],&omapwpos[0],
	&omaprat[0], UpdateOMAP1);

   omapwn[1] = 100; omapwpos[1] = 100;
   DefSlide(&omapscr[1],OMAPwin,140,50,20,100,10,&omapwn[1],&omapwpos[1],
	&omaprat[1], UpdateSLAB1);

   omapwn[2] = 100; omapwpos[2] = 100;
   DefSlide(&omapscr[2],OMAPwin,50,50,20,100,10,&omapwn[2],&omapwpos[2],
	&omaprat[2], UpdateOMAP2);

   omapwn[3] = 100; omapwpos[3] = 100;
   DefSlide(&omapscr[3],OMAPwin,170,50,20,100,10,&omapwn[3],&omapwpos[3],
	&omaprat[3], UpdateSLAB2);

   omapwn[4] = 100; omapwpos[4] = 100;
   DefSlide(&omapscr[4],OMAPwin,80,50,20,100,10,&omapwn[4],&omapwpos[4],
	&omaprat[4], UpdateOMAP3);

   omapwn[5] = 100; omapwpos[5] = 100;
   DefSlide(&omapscr[5],OMAPwin,200,50,20,100,10,&omapwn[5],&omapwpos[5],
	&omaprat[5], UpdateSLAB3);

   extnt[0] = 0.0;
   for (i=0; i<3; i++) extnt[0] += comsrfptr->v1[i]*comsrfptr->r[i];
   extnt[1] = 0.0;
   for (i=0; i<3; i++) extnt[1] += comsrfptr->v2[i]*comsrfptr->r[i];
   extnt[2] = 0.0;
   for (i=0; i<3; i++) extnt[2] += comsrfptr->v3[i]*comsrfptr->r[i];

   slab[0] = extnt[2];
   EQ[0] = comsrfptr->vo[2] + slab[0];
   slab[1] = extnt[0];
   EQ[1] = comsrfptr->vo[0] + slab[1];
   slab[2] = extnt[1];
   EQ[2] = comsrfptr->vo[1] + slab[2];

   omapsrf = NSurf[istruct];
   NSurf[istruct]++;
   if (omapPandN && !(*rng1 >= 0.0) ) NSurf[istruct]++;

}

void RedrawOMAP()
{
   int i;

   if (!OMAPup) return;

   butje(OMAPwin,0,0,230,280,4,0,-15,1,None,0,0,0);
   ULineString(OMAPwin,"Clip Planes:",20,20);
   LineString(OMAPwin,"Position",20,35);
   LineString(OMAPwin,"Separation",140,35);

   LineString(OMAPwin,"Z",25,48);
   LineString(OMAPwin,"X",55,48);
   LineString(OMAPwin,"Y",85,48);

   LineString(OMAPwin,"Z",145,48);
   LineString(OMAPwin,"X",175,48);
   LineString(OMAPwin,"Y",205,48);

   sprintf(atemp,"Contour Value [ 0.0 - %5.2f]:",*rng2);
   ULineString(OMAPwin,atemp,20,170);

   LineString(OMAPwin,"Residue",180,195);
   LineString(OMAPwin,"Follow",180,205);

   for (i=0; i<6; i++) RedrawSlide(&omapscr[i]);

   PromptBox(&qboxes[QCNT]);
   if (omapPandN) PromptBox(&qboxes[QCNT2]);

   for (i=0; i<3; i++) DrwBut(&butomap[i]);

}

DeleteOMAP()
{
   int i;

   XSync(display, False);
   XDestroyWindow(display,OMAPwin);
   XSync(display, False);
   omapfol = 0;
   omapCa = -1;
   if (omaplck) {
  	for (i=0; i<3; i++) rotptr->t[i] = omapt[i];
	omaplck = 0;
   }
   OMAPup = 0;
#ifdef DOGL
   DeleteSurface(omapsrf);
   deletebox();
#endif
   update_struct();
}

#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,
	xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,
	&cell->natc,&cell->norg,&cell->icent,&cell->inorm,
	&cell->ncon,&cell->nspg,&cell->ichx,
	&cell->nopr,cell->ir,cell->it,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

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

#if defined(VMS) || defined(UNDERSC)
	rdinfd(npts1,npts2,isubtr,istat,
#else
#ifdef CRAY
	RDINFD(npts1,npts2,isubtr,istat,
#else
	rdinfd_(npts1,npts2,isubtr,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, int *iorb, double *dens);

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

#if defined(VMS) || defined(UNDERSC)
        oginid(r,adjus,natoms,nat,icol,xsym,ysym,zsym,vdwr,cnst,npts1,
		npts2,iorb,sgrd.dens);
#else
#ifdef CRAY
        OGINID(r,adjus,natoms,nat,icol,xsym,ysym,zsym,vdwr,cnst,npts1,
		npts2,iorb,sgrd.dens);
#else
        oginid_(r,adjus,natoms,nat,icol,xsym,ysym,zsym,vdwr,cnst,npts1,
		npts2,iorb,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
	dorbp->vectrs,dorbp->vectrb,dorbp->focc,dorbp->focb,dorbp->eiga,
	dorbp->eigb,dorbp->nocc,dorbp->nocb,dorbp->ncols,dorbp->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(xyzp->coo,xyzp->ianz);
#else
#ifdef CRAY
	ANID(xyzp->coo,xyzp->ianz);
#else
	anid_(xyzp->coo,xyzp->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
	xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->isurf,
	calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino,
	calfptr->ihet,calfptr->iclhet,calfptr->reson,calfptr->iams,
	calfptr->isal);

}

#if defined(VMS) || defined(UNDERSC)
actexp(que,lque,ikleur,idosrf)
#else
#ifdef CRAY
ACTEXP(que,lque,ikleur,idosrf)
#else
actexp_(que,lque,ikleur,idosrf)
#endif
#endif
int *que;
int *lque;
int *ikleur;
int *idosrf;
{

#if defined(VMS) || defined(UNDERSC)
	actexd(que,lque,ikleur,idosrf,
#else
#ifdef CRAY
	ACTEXD(que,lque,ikleur,idosrf,
#else
	actexd_(que,lque,ikleur,idosrf,
#endif
#endif
	&calfptr->ncalf,calfptr->iamino);

}

#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
	xyzp->qat,xyzp->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
	xyzp->iresid,xyzp->isurf,
        &calfptr->ncalf,calfptr->ianf,calfptr->islu,
        &calfptr->nchain,calfptr->iamino,calfptr->ihet,calfptr->reson,
	calfptr->isal,calfptr->irsnr,calfptr->achain);

}

#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
	xyzp->iaton,xyzp->iatclr,xyzp->iresid,
	calfptr->icalf,calfptr->ianf,calfptr->islu,&calfptr->nchain,
	calfptr->iamino,calfptr->ibck);

}

#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
	xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->iconn,
	calfptr->icalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino,calfptr->ihet,calfptr->reson,
	calfptr->isal,calfptr->ibck);

}

#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
	xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->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
	xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->ityp,
	&calfptr->ncalf,calfptr->iamino);

}

#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
	xyzp->ityp,
	&calfptr->ncalf,calfptr->iamino);

}

#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
	xyzp->coo,
	&calfptr->ncalf,calfptr->icalf);

}

#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
	xyzp->coo,
	calfptr->icalf,&calfptr->ncalf,calfptr->iamino);

}

#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
	xyzp->coo,xyzp->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
	xyzp->coo,xyzp->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
	xyzp->coo,xyzp->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
	xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->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
	xyzp->coo,xyzp->ianz,xyzp->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
	xyzp->ianz,xyzp->iconn,xyzp->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
	xyzp->coo,xyzp->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
	xyzp->coo,xyzp->qat,xyzp->icont,xyzp->ncont);
}

#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
	xyzp->ianz,xyzp->iconn,xyzp->ityp,
        calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino,
	calfptr->isal,calfptr->irsnr,&calfptr->ihashb,
	calfptr->rphi,calfptr->rpsi);

}

#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
	xyzp->coo,xyzp->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
	rotptr->t,xyzp->coo,xyzp->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
	xyzp->ianz,xyzp->iresid,xyzp->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
	xyzp->ianz,xyzp->coo,xyzp->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
	xyzp->coo);

}

#if defined(VMS) || defined(UNDERSC)
calgas(iasel,istat)
#else
#ifdef CRAY
CALGAS(iasel,istat)
#else
calgas_(iasel,istat)
#endif
#endif
int *iasel;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	calgad(iasel,istat,
#else
#ifdef CRAY
	CALGAD(iasel,istat,
#else
	calgad_(iasel,istat,
#endif
#endif
	xyzp->qat,xyzp->ianz,xyzp->iconn,xyzp->iresid,xyzp->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
	xyzp->coo,xyzp->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
	xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->iconn,xyzp->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
	xyzp->isurf,xyzp->iaton,xyzp->ianz,xyzp->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
	xyzp->iresid,xyzp->isurf,calfptr->iams,calfptr->ihets);

}

#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
	xyzp->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
	xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->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
	xyzp->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
	xyzp->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
	xyzp->coo,xyzp->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
	xyzp->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
	xyzp->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
	rotptr->t,xyzp->coo,
	&scalptr->scal,&scalptr->scali,&scalptr->smag);

}

#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
	xyzp->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
	xyzp->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
	xyzp->ianz);

}

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

#if defined(VMS) || defined(UNDERSC)
	gampod(ipoint,istat,ioxyz,
#else
#ifdef CRAY
	GAMPOD(ipoint,istat,ioxyz,
#else
	gampod_(ipoint,istat,ioxyz,
#endif
#endif
	xyzp->coo,xyzp->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
	xyzp->coo,xyzp->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 *iff;
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
	xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iconn,
	&scalptr->scal,&scalptr->scali,&scalptr->smag,
	&cell->natc,&cell->ichx,&cell->icrtp);

}

#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
	xyzp->coo,xyzp->iconn,xyzp->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
	xyzp->coo,xyzp->ianz,xyzp->iconn,xyzp->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
	xyzp->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
	rotptr->t,xyzp->coo,&posptr->zv,&posptr->pincr,
	&scalptr->scal,&scalptr->scali,&scalptr->smag,&scalptr->iscupd);

}

#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
	xyzp->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,&monmode,
#else
#ifdef CRAY
	DOMCOD(ipt,idoall,&monmode,
#else
	domcod_(ipt,idoall,&monmode,
#endif
#endif
	xyzp->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
	xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iconn,xyzp->qat,
	&cell->natc,&cell->norg,&cell->icent,&cell->nspg,
	&cell->ichx,&cell->nopr,cell->ir,cell->it,
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);


	if (*igetxy == -1) {
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat,&ZERO);
	   getxyd(igetxy,heat,iaddprv,
#else
#ifdef CRAY
	   ALLCOO(&addat,&ZERO);
	   GETXYD(igetxy,heat,iaddprv,
#else
	   allcoo_(&addat,&ZERO);
	   getxyd_(igetxy,heat,iaddprv,
#endif
#endif
	   xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iconn,xyzp->qat,
	   &cell->natc,&cell->norg,&cell->icent,&cell->nspg,
	   &cell->ichx,&cell->nopr,cell->ir,cell->it,
	   &cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	   &cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

        }
}

#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
	xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->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
	xyzp->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
	xyzp->iresid,xyzp->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
	xyzp->coo,xyzp->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
	xyzp->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
	xyzp->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
	xyzp->coo,xyzp->qat,xyzp->ianz,xyzp->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
	xyzp->coo,xyzp->ianz,xyzp->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
	xyzp->ianz,xyzp->iatclr,xyzp->iconn,xyzp->coo,xyzp->qat,
	&cell->natc,&cell->icent,&cell->nspg,
	&cell->ichx,&cell->nopr,cell->ir,cell->it,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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
	xyzp->coo,&scalptr->fscal);

}

#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
	xyzp->coo,xyzp->qat,xyzp->rzp,xyzp->ixp,xyzp->iyp,xyzp->iconn,
	xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->inat,
	&posptr->xv,&posptr->yv,calfptr->icalf,&calfptr->ncalf,
	calfptr->icxp,calfptr->icyp,&scalptr->scal,&scalptr->scali);

}

#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
	xyzp->coo,xyzp->qat,xyzp->rzp,xyzp->ixp,xyzp->iyp,xyzp->iconn,xyzp->ianz,
	xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->inat,
	&posptr->xv,&posptr->yv,&posptr->zv,&posptr->c0,
	calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino,calfptr->reson,
	calfptr->icxp,calfptr->icyp,calfptr->irsnr,calfptr->achain,
	&scalptr->scali);

}

#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
	xyzp->coo,xyzp->rzp,xyzp->ixp,xyzp->iyp,
	&posptr->xv,&posptr->yv,&scalptr->scal,&scalptr->scali);

}

#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
	xyzp->coo,xyzp->rzp,xyzp->ixp,xyzp->iyp,
	&posptr->xv,&posptr->yv,&posptr->zv,&posptr->c0,
	&scalptr->scali);

}

#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
	xyzp->coo,xyzp->rzp,xyzp->ixp,xyzp->iyp,xyzp->iatclr,
	&scalptr->scali);

}

#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
	xyzp->coo,xyzp->rzp,xyzp->ixp,xyzp->iyp,xyzp->iatclr,
	&posptr->zv,&scalptr->scali);

}

#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
	xyzp->coo,xyzp->ixp,xyzp->iyp,xyzp->iaton,xyzp->iconn,
	&posptr->xv,&posptr->yv,&scalptr->scal);

}

#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
	xyzp->coo,xyzp->rzp,xyzp->ixp,xyzp->iyp,xyzp->ianz,xyzp->iatclr,
	&posptr->xv,&posptr->yv,&scalptr->scal,&scalptr->scali);

}

#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
	xyzp->coo,xyzp->rzp,xyzp->ixp,xyzp->iyp,xyzp->ianz,xyzp->iatclr,
	&posptr->xv,&posptr->yv,&posptr->zv,&posptr->c0,&scalptr->scali);

}

#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
	xyzp->coo,xyzp->rzp,xyzp->ixp,xyzp->iyp,xyzp->ianz,xyzp->iatclr,
	&posptr->xv,&posptr->yv,&posptr->zv,&posptr->c0,
	&scalptr->scal,&scalptr->scali);

}

#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
	xyzp->coo,xyzp->rzp,xyzp->ianz,xyzp->iatclr,
	&posptr->xv,&posptr->yv,&scalptr->scal,&scalptr->scali);

}

#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
	xyzp->coo,xyzp->rzp,xyzp->ianz,xyzp->iatclr,
	&posptr->xv,&posptr->yv,&posptr->zv,&posptr->c0,&scalptr->scali);

}

#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
	xyzp->ixp,xyzp->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
	xyzp->rzp,xyzp->ixp,xyzp->iyp,
	calfptr->icalf,calfptr->ianf,calfptr->islu,&calfptr->nchain,
	calfptr->iamino,calfptr->reson,calfptr->irsnr,calfptr->achain,
	&scalptr->scali);

}

#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
	xyzp->ixp,xyzp->iyp,
	calfptr->icalf,calfptr->iamino,calfptr->irsnr);

}

#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
	xyzp->ityp,xyzp->ipdbt,
	calfptr->iamino,calfptr->reson);

}

#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
	xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iresid,xyzp->iatclr,xyzp->iconn,
	xyzp->ixp,xyzp->iyp,xyzp->rzp,xyzp->inat,xyzp->qat,
	&posptr->xv,&posptr->yv,&posptr->zv,
	calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino,calfptr->reson,&scalptr->scal);

}

#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
	rotptr->rz,rotptr->t,
	xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->iconn,
	calfptr->icalf,calfptr->ianf,calfptr->islu,&calfptr->nchain,
	calfptr->iamino,calfptr->reson,&scalptr->scal,&scalptr->scali);

}

#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
	xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->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
	xyzp->ipdbt,xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iresid,xyzp->iconn,
	calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino);


	if (!istat) {
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat,&ZERO);
	   hcoodd(&istat,ioatms,nstrt,
#else
#ifdef CRAY
	   ALLCOO(&addat,&ZERO);
	   HCOODD(&istat,ioatms,nstrt,
#else
	   allcoo_(&addat,&ZERO);
	   hcoodd_(&istat,ioatms,nstrt,
#endif
#endif
	   xyzp->ipdbt,xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iresid,
	   xyzp->iconn,
	   calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	   &calfptr->nchain,calfptr->iamino);
        }
}

#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
	xyzp->coo,xyzp->ianz,xyzp->iconn,
	calfptr->icalf);

}

#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
	xyzp->coo,xyzp->ianz,xyzp->iconn,
	calfptr->icalf,&calfptr->ncalf,calfptr->iamino);

}

#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
	xyzp->coo,xyzp->iconn,xyzp->ianz,
	calfptr->icalf,&calfptr->ncalf);

}

#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
	xyzp->ianz,xyzp->iaton,xyzp->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
	xyzp->ianz,xyzp->iatclr,xyzp->iaton,xyzp->iconn);

}

#if defined(VMS) || defined(UNDERSC)
getchn(ires,ichain)
#else
#ifdef CRAY
GETCHN(ires,ichain)
#else
getchn_(ires,ichain)
#endif
#endif
int *ires;
int *ichain;
{
#if defined(VMS) || defined(UNDERSC)
	getcdh(ires,ichain,
#else
#ifdef CRAY
	GETCDH(ires,ichain,
#else
	getcdh_(ires,ichain,
#endif
#endif
	calfptr->ianf,calfptr->islu,&calfptr->nchain);
}

#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
	&calfptr->issdon);
}

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

#if defined(VMS) || defined(UNDERSC)
	ribbod(&istat,iscnd,dogl,nr,iungl,ipart,ist,ichain,rotptr->t,
#else
#ifdef CRAY
	RIBBOD(&istat,iscnd,dogl,nr,iungl,ipart,ist,ichain,rotptr->t,
#else
	ribbod_(&istat,iscnd,dogl,nr,iungl,ipart,ist,ichain,rotptr->t,
#endif
#endif
	xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,
	xyzp->iconn,
	calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino,calfptr->isal,&calfptr->ihashb);

	if (!istat) {
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat,&ZERO);
	   ribbod(&istat,iscnd,dogl,nr,iungl,ipart,ist,ichain,rotptr->t,
#else
#ifdef CRAY
	   ALLCOO(&addat,&ZERO);
	   RIBBOD(&istat,iscnd,dogl,nr,iungl,ipart,ist,ichain,rotptr->t,
#else
	   allcoo_(&addat,&ZERO);
	   ribbod_(&istat,iscnd,dogl,nr,iungl,ipart,ist,ichain,rotptr->t,
#endif
#endif
	   xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,
	   xyzp->iconn,
	   calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	   &calfptr->nchain,calfptr->iamino,calfptr->isal,&calfptr->ihashb);
        }
}

#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
	xyzp->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
	xyzp->coo,xyzp->iresid,&calfptr->ishoh);

}

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

#if defined(VMS) || defined(UNDERSC)
	proxd(itarg,backb,adds,idocom,thresh,
#else
#ifdef CRAY
	PROXD(itarg,backb,adds,idocom,thresh,
#else
	proxd_(itarg,backb,adds,idocom,thresh,
#endif
#endif
	xyzp->coo,xyzp->iresid,xyzp->iaton,xyzp->iconn,
	calfptr->iams,&calfptr->ishoh);

}

#if defined(VMS) || defined(UNDERSC)
setchn(iopt)
#else
#ifdef CRAY
SETCHN(iopt)
#else
setchn_(iopt)
#endif
#endif
int *iopt;
{

#if defined(VMS) || defined(UNDERSC)
	setcdd(iopt,
#else
#ifdef CRAY
	SETCDD(iopt,
#else
	setcdd_(iopt,
#endif
#endif
	&calfptr->nchain,calfptr->ianf,calfptr->islu,calfptr->irsnr,
	calfptr->achain);

}

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

#if defined(VMS) || defined(UNDERSC)
	rdchd(idebug,iop,istdbd,useab,moddma,istat,icssr,
#else
#ifdef CRAY
	RDCHD(idebug,iop,istdbd,useab,moddma,istat,icssr,
#else
	rdchd_(idebug,iop,istdbd,useab,moddma,istat,icssr,
#endif
#endif
	xyzp->coo,xyzp->iconn,xyzp->ianz,xyzp->iatclr,xyzp->ityp,xyzp->qat,
	&cell->natc,&cell->icent,&cell->inorm,&cell->ncon,&cell->nspg,
	&cell->kz,&cell->ichx,&cell->icrtp,&cell->nopr,cell->ir,cell->it,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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
	xyzp->coo,xyzp->qat,xyzp->ianz,xyzp->iatclr,xyzp->iconn,
	&cell->natc,&cell->norg,&cell->icent,&cell->inorm,&cell->ncon,
	&cell->nspg,&cell->kz,&cell->nopr,cell->ir,cell->it,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

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

#if defined(VMS) || defined(UNDERSC)
	getxdd(ipnt,nat,istat,
#else
#ifdef CRAY
	GETXDD(ipnt,nat,istat,
#else
	getxdd_(ipnt,nat,istat,
#endif
#endif
	xyzp->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
	xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,
	&cell->natc,&cell->norg,&cell->icent,&cell->inorm,
	&cell->ncon,&cell->nspg,&cell->kz,
	&cell->nopr,cell->ir,cell->it,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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
	xyzp->coo,xyzp->qat,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,
	xyzp->iconn,xyzp->lwrit,xyzp->lring,xyzp->ityp,
	&scalptr->scal,&scalptr->scali,&scalptr->smag,
	&cell->natc,&cell->norg,&cell->icent,&cell->inorm,
	&cell->ncon,&cell->nspg,
	&cell->nopr,cell->ir,cell->it,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2]);

}

#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
	xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->qat,xyzp->ityp);

}

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

#if defined(VMS) || defined(UNDERSC)
	pold(nat,ipolh,iatom,
#else
#ifdef CRAY
	POLD(nat,ipolh,iatom,
#else
	pold_(nat,ipolh,iatom,
#endif
#endif
	xyzp->ianz,xyzp->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
	xyzp->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
	xyzp->coo,xyzp->qat,xyzp->ianz,xyzp->iatclr,xyzp->iresid,xyzp->iconn,
	xyzp->ityp,xyzp->ipdbt,
	calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino,calfptr->reson,
	calfptr->isal,calfptr->irsnr,&calfptr->ishoh);

	if (*istat == -1) {
           NHetAtm = 0;
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat,&ZERO);
	   rdgrod(idebug,istat,
#else
#ifdef CRAY
	   ALLCOO(&addat,&ZERO);
	   RDGROD(idebug,istat,
#else
	   allcoo_(&addat,&ZERO);
	   rdgrod_(idebug,istat,
#endif
#endif
	   xyzp->coo,xyzp->qat,xyzp->ianz,xyzp->iatclr,xyzp->iresid,xyzp->iconn,
	   xyzp->ityp,xyzp->ipdbt,
	   calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	   &calfptr->nchain,calfptr->iamino,calfptr->reson,
	   calfptr->isal,calfptr->irsnr,&calfptr->ishoh);
        }
}

#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
	xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn);

}

#if defined(VMS) || defined(UNDERSC)
addtbx(v1,v2,v3)
#else
#ifdef CRAY
ADDTBX(v1,v2,v3)
#else
addtbx_(v1,v2,v3)
#endif
#endif
double *v1;
double *v2;
double *v3;
{

#if defined(VMS) || defined(UNDERSC)
	addtbd(v1,v2,v3,
#else
#ifdef CRAY
	ADDTBD(v1,v2,v3,
#else
	addtbd_(v1,v2,v3,
#endif
#endif
	xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,xyzp->iaton,
	xyzp->iresid);

}

#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
	xyzp->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
	xyzp->coo,xyzp->qat,xyzp->ianz,xyzp->iatclr,xyzp->iresid,xyzp->iconn,
	xyzp->ityp,xyzp->ipdbt,
	calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino,calfptr->reson,
	calfptr->isal,&calfptr->ishoh,&calfptr->ihashb,
	&cell->natc,&cell->norg,&cell->icent,&cell->ncon,&cell->nspg,
	&cell->kz,&cell->ichx,&cell->nopr,cell->ir,cell->it,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

	if (*istat == -1) {
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat,&ZERO);
	   rdmod(idebug,ipdbon,ioadd,istat,
#else
#ifdef CRAY
	   ALLCOO(&addat,&ZERO);
	   RDMOD(idebug,ipdbon,ioadd,istat,
#else
	   allcoo_(&addat,&ZERO);
	   rdmod_(idebug,ipdbon,ioadd,istat,
#endif
#endif
	   xyzp->coo,xyzp->qat,xyzp->ianz,xyzp->iatclr,xyzp->iresid,xyzp->iconn,
   	   xyzp->ityp,xyzp->ipdbt,
	   calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
   	   &calfptr->nchain,calfptr->iamino,calfptr->reson,
	   calfptr->isal,&calfptr->ishoh,&calfptr->ihashb,
	   &cell->natc,&cell->norg,&cell->icent,&cell->ncon,&cell->nspg,
	   &cell->kz,&cell->ichx,&cell->nopr,cell->ir,cell->it,
	   &cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	   &cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	   &cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	   &cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);
        }
}

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

#if defined(VMS) || defined(UNDERSC)
	wrmod(iun,
#else
#ifdef CRAY
	WRMOD(iun,
#else
	wrmod_(iun,
#endif
#endif
	xyzp->coo,xyzp->qat,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iconn,
	xyzp->iresid,xyzp->lring,xyzp->inat,xyzp->ityp,xyzp->ipdbt,
	calfptr->icalf,&calfptr->ncalf,calfptr->iamino,&calfptr->ishoh,
	&cell->natc,&cell->nspg,&cell->ichx,
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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)
	ispnd(ispn,iat,irng,idochg,ifive,
#else
#ifdef CRAY
	ISPND(ispn,iat,irng,idochg,ifive,
#else
	ispnd_(ispn,iat,irng,idochg,ifive,
#endif
#endif
	xyzp->qat,xyzp->ianz,xyzp->iaton,xyzp->iconn,xyzp->lwrit,xyzp->lring);

}

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

#if defined(VMS) || defined(UNDERSC)
	wrcryd(iun,
#else
#ifdef CRAY
	WRCRYD(iun,
#else
	wrcryd_(iun,
#endif
#endif
	xyzp->ianz,xyzp->coo,
	&cell->natc,&cell->nspg,&cell->ichx,
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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
	xyzp->coo,xyzp->ianz,xyzp->iconn,xyzp->iatclr,
	&cell->natc,&cell->icent,&cell->ncon,&cell->nspg,
	&cell->kz,&cell->nopr,cell->ir,cell->it,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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
	xyzp->coo,xyzp->ianz,xyzp->iconn,xyzp->iatclr,
	&cell->natc,&cell->icent,&cell->ncon,&cell->nspg,
	&cell->nopr,cell->ir,cell->it,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

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

#if defined(VMS) || defined(UNDERSC)
	wrshld(iun,idospf,
#else
#ifdef CRAY
	WRSHLD(iun,idospf,
#else
	wrshld_(iun,idospf,
#endif
#endif
	xyzp->coo,xyzp->ianz,
	&cell->natc,&cell->icent,&cell->nspg,
	&cell->kz,&cell->ichx,&cell->nopr,cell->ir,cell->it,
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

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

#if defined(VMS) || defined(UNDERSC)
	wrcifd(iun,
#else
#ifdef CRAY
	WRCIFD(iun,
#else
	wrcifd_(iun,
#endif
#endif
	xyzp->coo,xyzp->ianz,
	&cell->natc,&cell->nspg,&cell->ichx,
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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
	xyzp->coo,xyzp->ianz,
	&cell->natc,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5]);

}

#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
	xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,
	&cell->natc,&cell->ichx,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5]);

}

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

#if defined(VMS) || defined(UNDERSC)
	wrchd(iun,
#else
#ifdef CRAY
	WRCHD(iun,
#else
	wrchd_(iun,
#endif
#endif
	xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,xyzp->qat,xyzp->ityp,
	&cell->natc,&cell->inorm,&cell->nspg,&cell->ichx,
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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
	xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,xyzp->qat,
	&cell->natc,&cell->icent,&cell->ncon,&cell->nspg,
	&cell->ichx,&cell->nopr,cell->ir,cell->it,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

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

#if defined(VMS) || defined(UNDERSC)
	wrmsd(iun,
#else
#ifdef CRAY
	WRMSD(iun,
#else
	wrmsd_(iun,
#endif
#endif
	xyzp->coo,xyzp->ianz,xyzp->iconn,xyzp->qat,
	&cell->natc,&cell->nspg,&cell->ichx,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5]);

}

#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
	xyzp->coo,xyzp->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
	xyzp->coo,xyzp->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
	xyzp->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
	xyzp->coo);

}

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

#if defined(VMS) || defined(UNDERSC)
	wrcpdd(iun,
#else
#ifdef CRAY
	WRCPDD(iun,
#else
	wrcpdd_(iun,
#endif
#endif
	xyzp->ianz,xyzp->coo,&cell->natc,&cell->ichx,
        &cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
        &cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#if defined(VMS) || defined(UNDERSC)
cpmdcell()
#else
#ifdef CRAY
CPMDCELL()
#else
cpmdcell_()
#endif
#endif
{

#if defined(VMS) || defined(UNDERSC)
	cpmdceld(
#else
#ifdef CRAY
	CPMDCELD(
#else
	cpmdceld_(
#endif
#endif
	&cell->nspg,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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
	xyzp->coo,xyzp->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
	xyzp->coo,xyzp->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
	xyzp->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
	xyzp->coo,xyzp->ianz,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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
	xyzp->coo,xyzp->ianz,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5]);

}

#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
	xyzp->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
	xyzp->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
	xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,xyzp->qat,xyzp->ityp,
	&cell->natc,&cell->norg,&cell->icent,&cell->inorm,
	&cell->ncon,&cell->nspg,&cell->kz,&cell->ichx,
	&cell->nopr,cell->ir,cell->it,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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
	xyzp->coo,xyzp->ianz,&calfptr->ihashb);

}

#if defined(VMS) || defined(UNDERSC)
evwat()
#else
#ifdef CRAY
EVWAT()
#else
evwat_()
#endif
#endif
{
	int nwat;

#if defined(VMS) || defined(UNDERSC)
	quwat(&nwat);
	nwat = nwat*3;
	if (nwat + *xyzp->iatoms > *xyzp->mxnat) allcoo(&nwat,&ZERO);
	evwad(
#else
#ifdef CRAY
	QUWAT(&nwat);
	nwat = nwat*3;
	if (nwat + *xyzp->iatoms > *xyzp->mxnat) ALLCOO(&nwat,&ZERO);
	EVWAD(
#else
	quwat_(&nwat);
	nwat = nwat*3;
	if (nwat + *xyzp->iatoms > *xyzp->mxnat) allcoo_(&nwat,&ZERO);
	evwad_(
#endif
#endif

	xyzp->coo,xyzp->qat,xyzp->iresid,calfptr->irsnr,xyzp->iatclr,
	xyzp->iaton,xyzp->iconn,xyzp->ianz,&calfptr->ncalf,calfptr->icalf,
	xyzp->ityp,xyzp->ipdbt);

}

#if defined(VMS) || defined(UNDERSC)
quwat(nwat)
#else
#ifdef CRAY
QUWAT(nwat)
#else
quwat_(nwat)
#endif
#endif
int *nwat;
{

#if defined(VMS) || defined(UNDERSC)
	quwad(nwat,
#else
#ifdef CRAY
	QUWAD(nwat,
#else
	quwad_(nwat,
#endif
#endif
	xyzp->iresid,xyzp->iconn,xyzp->ianz);

}

#if defined(VMS) || defined(UNDERSC)
fndoh(itar,ang,ires,copt,istat)
#else
#ifdef CRAY
FNDOH(itar,ang,ires,copt,istat)
#else
fndoh_(itar,ang,ires,copt,istat)
#endif
#endif
int *itar;
double *ang;
int *ires;
double *copt;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	fndod(itar,ang,ires,copt,istat,
#else
#ifdef CRAY
	FNDOD(itar,ang,ires,copt,istat,
#else
	fndod_(itar,ang,ires,copt,istat,
#endif
#endif
	xyzp->coo,xyzp->qat,xyzp->iconn,xyzp->ityp,xyzp->iresid,
	calfptr->irsnr,&calfptr->ncalf,calfptr->icalf);

}

#if defined(VMS) || defined(UNDERSC)
opthyd()
#else
#ifdef CRAY
OPTHYD()
#else
opthyd_()
#endif
#endif
{
	int i;

	LigandHydroQ(1,1,1,0);

        update_model=0;
	if (*fftyp != 7) typit(7,0);

#if defined(VMS) || defined(UNDERSC)
	opthdd(
#else
#ifdef CRAY
	OPTHDD(
#else
	opthdd_(
#endif
#endif
	iupres,&nupres,calfptr->irsnr,&calfptr->ncalf, calfptr->icalf,xyzp->coo,
	xyzp->qat,xyzp->iconn,xyzp->ianz,xyzp->iresid,calfptr->iamino,
	xyzp->ityp,xyzp->ipdbt);

#ifdef DOGL
	for (i=0; i < nupres; i++ ) {
	   ogres(iupres[i],0,0);
	}
	if (*fancy) {
	   oghet(0);
	} else {
	   oglines();
	}
	update_model = 0;
#endif
	update_struct();

}

#if defined(VMS) || defined(UNDERSC)
nmrcpl(idebug)
#else
#ifdef CRAY
NMRCPL(idebug)
#else
nmrcpl_(idebug)
#endif
#endif
int *idebug;
{
   double d;
   int size;

   size = NAT->natoms;

   if ((jcoupl = (double *) malloc((sizeof d)*size*size)) != NULL) {
#if defined(VMS) || defined(UNDERSC)
	nmrcpd(idebug,
#else
#ifdef CRAY
	NMRCPD(idebug,
#else
	nmrcpd_(idebug,
#endif
#endif
	jcoupl);
   } else {
	fprintf(stderr,"Failed to allocate memory for J-coupling !\n");
	nmrptr->ihsnmr = 1;
   }
}

#if defined(VMS) || defined(UNDERSC)
nmcshl()
#else
#ifdef CRAY
NMCSHL()
#else
nmcshl_()
#endif
#endif
{
   double d;
   int size;

   size = NAT->natoms;

   if ((jcoupl = (double *) malloc((sizeof d)*size*size)) != NULL) {
#if defined(VMS) || defined(UNDERSC)
	nmcshd(
#else
#ifdef CRAY
	NMCSHD(
#else
	nmcshd_(
#endif
#endif
	jcoupl);
   } else {
	fprintf(stderr,"Failed to allocate memory for J-coupling !\n");
	nmrptr->ihsnmr = 1;
   }
}

#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;
{
  int iszhnt;

#if defined(VMS) || defined(UNDERSC)
	pdbsiz(&iszhnt);
	if (*ioadd) {
	   if (iszhnt + *xyzp->iatoms > *xyzp->mxnat) allcoo(&iszhnt,&ZERO);
	} else {
	   if (iszhnt > *xyzp->mxnat) allcoo(&iszhnt,&ZERO);
           setid(&FOUR,&ZERO,xyzp->isurf,xyzp->iresid,xyzp->ipdbt);
	}
	pdbsdd(istat,doscnd,ioadd,
#else
#ifdef CRAY
	PDBSIZ(&iszhnt);
	if (*ioadd) {
	   if (iszhnt + *xyzp->iatoms > *xyzp->mxnat) ALLCOO(&iszhnt,&ZERO);
	} else {
	   if (iszhnt > *xyzp->mxnat) ALLCOO(&iszhnt,&ZERO);
           SETID(&FOUR,&ZERO,xyzp->isurf,xyzp->iresid,xyzp->ipdbt);
	}
	PDBSDD(istat,doscnd,ioadd,
#else
	pdbsiz_(&iszhnt);
	if (*ioadd) {
	   if (iszhnt + *xyzp->iatoms > *xyzp->mxnat) allcoo_(&iszhnt,&ZERO);
	} else {
	   if (iszhnt > *xyzp->mxnat) allcoo_(&iszhnt,&ZERO);
           setid_(&FOUR,&ZERO,xyzp->isurf,xyzp->iresid,xyzp->ipdbt);
	}
	pdbsdd_(istat,doscnd,ioadd,
#endif
#endif
	xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iresid,xyzp->iconn,xyzp->ityp,
        &calfptr->ncalf,calfptr->ianf,calfptr->islu,
        &calfptr->nchain,calfptr->iamino,calfptr->ihet,
        calfptr->isal,calfptr->irsnr,calfptr->achain,
	&calfptr->ihashb,&calfptr->ishoh);


	if (*istat == -1) {
	   NHetAtm = 0;
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat,&ZERO);
	   pdbsdd(istat,doscnd,ioadd,
#else
#ifdef CRAY
	   ALLCOO(&addat,&ZERO);
	   PDBSDD(istat,doscnd,ioadd,
#else
	   allcoo_(&addat,&ZERO);
	   pdbsdd_(istat,doscnd,ioadd,
#endif
#endif
	   xyzp->coo,xyzp->ianz,xyzp->iaton,xyzp->iresid,xyzp->iconn,
	   xyzp->ityp,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
           &calfptr->nchain,calfptr->iamino,calfptr->ihet,
           calfptr->isal,calfptr->irsnr,calfptr->achain,
	   &calfptr->ihashb,&calfptr->ishoh);
        }
}

#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
	xyzp->ianz,xyzp->iconn,xyzp->iresid,
	&calfptr->ncalf,calfptr->iamino);

}

#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
	xyzp->ianz,xyzp->iconn,xyzp->iresid,
	&calfptr->ncalf,calfptr->iamino);

}

#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
	xyzp->iconn,xyzp->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
	xyzp->iconn,xyzp->ianz,xyzp->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
	xyzp->qat,xyzp->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
	xyzp->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
	xyzp->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
	xyzp->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
	xyzp->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
	xyzp->ianz,xyzp->iconn,xyzp->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
	xyzp->ianz,xyzp->iconn,xyzp->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
	xyzp->ianz,xyzp->iconn,xyzp->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
	xyzp->iconn,xyzp->coo,
        calfptr->icalf,calfptr->ianf,calfptr->islu,
        &calfptr->nchain,calfptr->iamino);

}

#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
	xyzp->iconn,xyzp->coo,
        calfptr->icalf,calfptr->ianf,calfptr->islu,
        &calfptr->nchain,calfptr->iamino);

}

#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
	xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->iconn,
	xyzp->isurf,xyzp->ipdbt,xyzp->ityp,&calfptr->ncalf,calfptr->icalf,
	xyzp->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
	xyzp->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
	xyzp->ianz,xyzp->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
	xyzp->ianz,xyzp->coo);

}

#if defined(VMS) || defined(UNDERSC)
nwxyz(idebug,ipnt,istat)
#else
#ifdef CRAY
NWXYZ(idebug,ipnt,istat)
#else
nwxyz_(idebug,ipnt,istat)
#endif
#endif
int *idebug;
int *ipnt;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	nwxyd(idebug,ipnt,istat,
#else
#ifdef CRAY
	NWXYD(idebug,ipnt,istat,
#else
	nwxyd_(idebug,ipnt,istat,
#endif
#endif
	xyzp->ianz,xyzp->coo);

}

#if defined(VMS) || defined(UNDERSC)
fnwxyz(idebug,istat)
#else
#ifdef CRAY
FNWXYZ(idebug,istat)
#else
fnwxyz_(idebug,istat)
#endif
#endif
int *idebug;
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	fnwxyd(idebug,istat,
#else
#ifdef CRAY
	FNWXYD(idebug,istat,
#else
	fnwxyd_(idebug,istat,
#endif
#endif
	xyzp->ianz,xyzp->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
	xyzp->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
	xyzp->coo);

}

#if defined(VMS) || defined(UNDERSC)
getnfr(istat)
#else
#ifdef CRAY
GETNFR(istat)
#else
getnfr_(istat)
#endif
#endif
int *istat;
{

#if defined(VMS) || defined(UNDERSC)
	getnfd(istat,
#else
#ifdef CRAY
	GETNFD(istat,
#else
	getnfd_(istat,
#endif
#endif
	xyzp->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
	xyzp->coo);

}

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

#if defined(VMS) || defined(UNDERSC)
	rotmod(ipoint,ifav,
#else
#ifdef CRAY
	ROTMOD(ipoint,ifav,
#else
	rotmod_(ipoint,ifav,
#endif
#endif
	xyzp->coo);

}

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

#if defined(VMS) || defined(UNDERSC)
	rotfid(ioxyz,
#else
#ifdef CRAY
	ROTFID(ioxyz,
#else
	rotfid_(ioxyz,
#endif
#endif
	xyzp->ianz,xyzp->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
	rotptr->t,xyzp->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
	xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->ipdbt,
	calfptr->icalf,&calfptr->ncalf,calfptr->iamino);

}

#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
	xyzp->ianz,xyzp->iresid,xyzp->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
	xyzp->ianz,xyzp->iresid,xyzp->ipdbt,
	calfptr->iamino);

}

#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
	xyzp->ianz,xyzp->iatclr,xyzp->iconn,xyzp->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
	xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->iconn,xyzp->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
	xyzp->ianz,xyzp->isurf,xyzp->coo,xyzp->icont,xyzp->ncont);

}

#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
	xyzp->isurf,xyzp->ianz,xyzp->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
	xyzp->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
	xyzp->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
	xyzp->ianz,xyzp->coo);

}

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

#if defined(VMS) || defined(UNDERSC)
	wrmsfd(iun,
#else
#ifdef CRAY
	WRMSFD(iun,
#else
	wrmsfd_(iun,
#endif
#endif
	xyzp->coo,xyzp->qat,xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,
	xyzp->iconn,xyzp->lring,xyzp->ityp,&cell->natc,&cell->nspg,&cell->ichx,
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);


}

#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
	xyzp->ianz,xyzp->iaton,xyzp->iconn,xyzp->lring,xyzp->ityp,xyzp->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
	xyzp->ianz,xyzp->iaton,xyzp->iconn,xyzp->isurf,xyzp->lring,
	xyzp->lwrit,&calfptr->ncalf,&calfptr->ishoh,
	xyzp->iresid,xyzp->ityp,xyzp->coo,xyzp->qat,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#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
	rotptr->rx,rotptr->ry,rotptr->rz,
	xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->iconn,
	xyzp->lring,xyzp->coo,xyzp->rzp,calfptr->reson,
	calfptr->ianf,&calfptr->nchain,&calfptr->ncalf);

}

#if defined(VMS) || defined(UNDERSC)
getnat(natoms)
#else
#ifdef CRAY
GETNAT(natoms)
#else
getnat_(natoms)
#endif
#endif
int *natoms;
{
   int i;

/*
   *natoms = 0;
   for (i=0; i < *xyzp->iatoms; i++ ) 
	if (xyzp->ianz[i] < 100 && xyzp->ianz[i] > 0) (*natoms)++;
*/

   *natoms = *xyzp->iatoms;
   for (i=*xyzp->iatoms-1; i >= 0; i-- ) 
	if (xyzp->ianz[i] < 100 && xyzp->ianz[i] > 0) {
	    *natoms = i;
            (*natoms)++;
	    break;
	}
}

#if defined(VMS) || defined(UNDERSC)
allon(nwramb,newat)
#else
#ifdef CRAY
ALLON(nwramb,newat)
#else
allon_(nwramb,newat)
#endif
#endif
int *nwramb;
int *newat;
{
   int i,j,iwat,nwat,iall;

   nwat = (*newat - *nwramb);
   iall = nwat + 8;

   if (*newat > *xyzp->mxnat)  {
#if defined(VMS) || defined(UNDERSC)
	allcoo(&iall,&ZERO);
#else
#ifdef CRAY
	ALLCOO(&iall,&ZERO);
#else
	allcoo_(&iall,&ZERO);
#endif
#endif
   }

   nwat = nwat/3;
   *xyzp->iatoms = *newat;
   if (NHetAtm < 4) NHetAtm = 4;

   cellpnt->iclon = 1;

   HetAtm[NHetAtm] = "Water";

   for (i=0; i < nwat; i++ ) {
        iwat = *nwramb + 3*i;

	xyzp->ianz[iwat] = 8;
	xyzp->ityp[iwat] = 649;
	xyzp->qat[iwat] = -0.834;
	xyzp->iaton[iwat] = 1;
	xyzp->iatclr[iwat] = 1;
	xyzp->iresid[iwat] = -NHetAtm;
	xyzp->iconn[iwat*(MXCON+1)] = 2;
	xyzp->iconn[iwat*(MXCON+1)+1] = (iwat+1)+1;
	xyzp->iconn[iwat*(MXCON+1)+2] = (iwat+2)+1;

	xyzp->ianz[iwat+1] = 1;
	xyzp->ityp[iwat+1] = 650;
	xyzp->qat[iwat+1] = 0.471;
	xyzp->iaton[iwat+1] = 1;
	xyzp->iatclr[iwat+1] = 1;
	xyzp->iresid[iwat+1] = -NHetAtm;
	xyzp->iconn[(iwat+1)*(MXCON+1)] = 1;
	xyzp->iconn[(iwat+1)*(MXCON+1)+1] = (iwat)+1;

	xyzp->ianz[iwat+2] = 1;
	xyzp->ityp[iwat+2] = 650;
	xyzp->qat[iwat+2] = 0.471;
	xyzp->iaton[iwat+2] = 1;
	xyzp->iatclr[iwat+2] = 1;
	xyzp->iresid[iwat+2] = -NHetAtm;
	xyzp->iconn[(iwat+2)*(MXCON+1)] = 1;
	xyzp->iconn[(iwat+2)*(MXCON+1)+1] = (iwat)+1;

   }

   *xyzp->iatoms = *newat;

   for (i=0; i < 8; i++ ) {
	iwat = *newat + i;
	xyzp->iaton[iwat] = 1;
   }

   NHetAtm++;
}

#if defined(VMS) || defined(UNDERSC)
upajob()
#else
#ifdef CRAY
UPAJOB()
#else
upajob_()
#endif
#endif
{
   if (ATMup) RedrawATM();
   if (TNKup) RedrawTNK();
   RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
}

#if defined(VMS) || defined(UNDERSC)
rdbin(iun,heat)
#else
#ifdef CRAY
RDBIN(iun,heat)
#else
rdbin_(iun,heat)
#endif
#endif
int *iun;
double *heat;
{
#if defined(VMS) || defined(UNDERSC)
	rdbid(iun,heat,
#else
#ifdef CRAY
	RDBID(iun,heat,
#else
	rdbid_(iun,heat,
#endif
#endif
	xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,
	xyzp->lring, &cell->natc,&cell->norg,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);
}

#if defined(VMS) || defined(UNDERSC)
gettyp(ires,iat1,iat2)
#else
#ifdef CRAY
GETTYP(ires,iat1,iat2)
#else
gettyp_(ires,iat1,iat2)
#endif
#endif
int *ires;
int *iat1;
int *iat2;
{
#if defined(VMS) || defined(UNDERSC)
	gettyd(ires,iat1,iat2,
#else
#ifdef CRAY
	GETTYD(ires,iat1,iat2,
#else
	gettyd_(ires,iat1,iat2,
#endif
#endif
	xyzp->ityp,xyzp->ipdbt,xyzp->ianz,xyzp->iresid,
	calfptr->iamino,calfptr->icalf,&calfptr->ncalf);
}

#if defined(VMS) || defined(UNDERSC)
chkbrk()
#else
#ifdef CRAY
CHKBRK()
#else
chkbrk_()
#endif
#endif
{
#if defined(VMS) || defined(UNDERSC)
	chkbrd(
#else
#ifdef CRAY
	CHKBRD(
#else
	chkbrd_(
#endif
#endif
	xyzp->iconn,calfptr->icalf,calfptr->ianf,calfptr->islu,
	calfptr->iamino,calfptr->isal,calfptr->reson,
	&calfptr->ncalf,&calfptr->nchain);
}

#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
	xyzp->ianz,xyzp->iconn,xyzp->iatclr,xyzp->ityp,xyzp->coo,xyzp->qat,
	xyzp->isurf,&calfptr->issdon,&cellpnt->iclon,&cell->ichx,
	&calfptr->ishoh,&cell->nspg,&cell->natc,&cell->norg,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

	if (*igttnk == -1) {
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat,&ZERO);
	   gettnd(igttnk,idebug,ipdbon,iffset,iheat,heat,
#else
#ifdef CRAY
	   ALLCOO(&addat,&ZERO);
	   GETTND(igttnk,idebug,ipdbon,iffset,iheat,heat,
#else
	   allcoo_(&addat,&ZERO);
	   gettnd_(igttnk,idebug,ipdbon,iffset,iheat,heat,
#endif
#endif
	   xyzp->ianz,xyzp->iconn,xyzp->iatclr,xyzp->ityp,xyzp->coo,xyzp->qat,
	   xyzp->isurf,&calfptr->issdon,&cellpnt->iclon,&cell->ichx,
	   &calfptr->ishoh,&cell->nspg,&cell->natc,&cell->norg,
	   &cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	   &cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	   &cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	   &cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);
        }
}

#if defined(VMS) || defined(UNDERSC)
tnkfst(igttnk,idebug)
#else
#ifdef CRAY
TNKFST(igttnk,idebug)
#else
tnkfst_(igttnk,idebug)
#endif
#endif
int *igttnk;
int *idebug;
{

#if defined(VMS) || defined(UNDERSC)
	tnkfsd(igttnk,idebug,
#else
#ifdef CRAY
	TNKFSD(igttnk,idebug,
#else
	tnkfsd_(igttnk,idebug,
#endif
#endif
	xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,
	xyzp->lring,&cell->ichx,
	&cell->natc,&cell->norg,
	&cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	&cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

	if (*igttnk == -1) {
#if defined(VMS) || defined(UNDERSC)
	   allcoo(&addat,&ZERO);
	   tnkfsd(igttnk,idebug,
#else
#ifdef CRAY
	   ALLCOO(&addat,&ZERO);
	   TNKFSD(igttnk,idebug,
#else
	   allcoo_(&addat,&ZERO);
	   tnkfsd_(igttnk,idebug,
#endif
#endif
	   xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,
	   xyzp->lring,&cell->ichx,
	   &cell->natc,&cell->norg,
	   &cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	   &cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	   &cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	   &cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);
        }
}

#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
	xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iconn,xyzp->iresid,
	xyzp->lwrit,xyzp->lring,xyzp->ityp,xyzp->coo,xyzp->qat,xyzp->icont,
	calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino,&calfptr->ishoh,
	&cell->natc,
	&cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	&cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

}

#if defined(VMS) || defined(UNDERSC)
chkcoo(kcoo,kcooh)
#else
#ifdef CRAY
CHKCOO(kcoo,kcooh)
#else
chkcoo_(kcoo,kcooh)
#endif
#endif
int *kcoo;
int *kcooh;
{

#if defined(VMS) || defined(UNDERSC)
	chkcod(kcoo,kcooh,
#else
#ifdef CRAY
	CHKCOD(kcoo,kcooh,
#else
	chkcod_(kcoo,kcooh,
#endif
#endif
	xyzp->ianz,xyzp->iconn);
}

#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
	xyzp->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
	xyzp->ianz,xyzp->iaton,xyzp->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
	xyzp->ianz,xyzp->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
	xyzp->ianz,xyzp->iaton,xyzp->iresid,xyzp->iconn);

}

#if defined(VMS) || defined(UNDERSC)
haswat(ino)
#else
#ifdef CRAY
HASWAT(ino)
#else
haswat_(ino)
#endif
#endif
int *ino;
{

#if defined(VMS) || defined(UNDERSC)
	haswad(ino,
#else
#ifdef CRAY
	HASWAD(ino,
#else
	haswad_(ino,
#endif
#endif
	xyzp->ianz,xyzp->iaton,xyzp->iresid,xyzp->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
	xyzp->ianz,xyzp->iaton,xyzp->iresid,xyzp->iconn,
	xyzp->lwrit,xyzp->lring,
	calfptr->icalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino);

}

#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
	xyzp->ianz,xyzp->iaton,xyzp->iconn,xyzp->lwrit,xyzp->coo,
	calfptr->icalf,&calfptr->ncalf);

}

#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
	xyzp->ianz,xyzp->iaton,xyzp->iconn,xyzp->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
	xyzp->ianz,xyzp->iaton,xyzp->iresid,xyzp->iconn,xyzp->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
	xyzp->ianz,xyzp->iaton,xyzp->iresid,xyzp->iconn,xyzp->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
	xyzp->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
	xyzp->isurf,xyzp->iresid,xyzp->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
	xyzp->iresid,xyzp->coo,
	calfptr->icalf,&calfptr->ncalf,calfptr->reson);

}

#if defined(VMS) || defined(UNDERSC)
newfil(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls,iof)
#else
#ifdef CRAY
NEWFIL(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls,iof)
#else
newfil_(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls,iof)
#endif
#endif
int *idebug;
int *istat;
int *inc;
int *ioadd;
int *ioatms;
int *nstrt;
int *namols;
int *nxtmf;
int *ipdbon;
int *namls;
int *iof;
{

#if defined(VMS) || defined(UNDERSC)
	newfid(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls,iof,
#else
#ifdef CRAY
	NEWFID(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls,iof,
#else
	newfid_(idebug,istat,inc,ioadd,ioatms,nstrt,namols,nxtmf,ipdbon,namls,iof,
#endif
#endif
	xyzp->iaton,xyzp->iatclr,xyzp->iresid,
	&calfptr->ncalf);

}

#if defined(VMS) || defined(UNDERSC)
acthlp(iop1,iop2,iop3)
#else
#ifdef CRAY
ACTHLP(iop1,iop2,iop3)
#else
acthlp_(iop1,iop2,iop3)
#endif
#endif
int *iop1;
int *iop2;
int *iop3;
{

#if defined(VMS) || defined(UNDERSC)
	acthld(iop1,iop2,iop3,
#else
#ifdef CRAY
	ACTHLD(iop1,iop2,iop3,
#else
	acthld_(iop1,iop2,iop3,
#endif
#endif
	calfptr->ihet);

}

#if defined(VMS) || defined(UNDERSC)
acttog(iop1,iop2,iop3)
#else
#ifdef CRAY
ACTTOG(iop1,iop2,iop3)
#else
acttog_(iop1,iop2,iop3)
#endif
#endif
int *iop1;
int *iop2;
int *iop3;
{

#if defined(VMS) || defined(UNDERSC)
	acttod(iop1,iop2,iop3,
#else
#ifdef CRAY
	ACTTOD(iop1,iop2,iop3,
#else
	acttod_(iop1,iop2,iop3,
#endif
#endif
	calfptr->ihet);

}

#if defined(VMS) || defined(UNDERSC)
acttag(iop1,iop2,iop3)
#else
#ifdef CRAY
ACTTAG(iop1,iop2,iop3)
#else
acttag_(iop1,iop2,iop3)
#endif
#endif
int *iop1;
int *iop2;
int *iop3;
{

#if defined(VMS) || defined(UNDERSC)
	acttad(iop1,iop2,iop3,
#else
#ifdef CRAY
	ACTTAD(iop1,iop2,iop3,
#else
	acttad_(iop1,iop2,iop3,
#endif
#endif
	calfptr->ihet);

}

#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
	xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iresid,xyzp->iconn,xyzp->qat,
	calfptr->ihet,calfptr->iclhet,calfptr->reson,calfptr->iams,
	calfptr->ihets,calfptr->irsnr,&calfptr->ncalf,&calfptr->issdon,
	&scalptr->scal,&scalptr->scali,&scalptr->fscal,&scalptr->smag,
	&posptr->xv,&posptr->yv,&posptr->zv,&posptr->pincr,
	&cell->natc,&cell->ichx,&cell->icrtp,
	&pnt->ipoints,&geo1ptr->ngeoms);

}

#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
	xyzp->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
	xyzp->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
	xyzp->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
	geop->formax,geop->forrms,geop->dismax,geop->disrms,
	geop->epoints,geop->isav,xyzp->coo,xyzp->ianz,
	&cell->icrtp);

}

#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
	geop->epoints,
	xyzp->coo,xyzp->qat,xyzp->ianz,xyzp->iaton,xyzp->iresid,
	xyzp->iconn,xyzp->ityp,
	&calfptr->ncalf,calfptr->ianf,calfptr->islu,&calfptr->nchain,
	calfptr->iamino,calfptr->reson,calfptr->irsnr,calfptr->achain);

}

#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
	geop->isav,geop->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
	geop->epoints,&scalptr->scal);

}

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

/* shadow C routines for Fortran routines to rotation pointers */

#if defined(VMS) || defined(UNDERSC)
xyzrot(inct,theang)
#else
#ifdef CRAY
XYZROT(inct,theang)
#else
xyzrot_(inct,theang)
#endif
#endif
int *inct;
double *theang;
{
#if defined(VMS) || defined(UNDERSC)
	xyzrod(inct,theang,
#else
#ifdef CRAY
	XYZROD(inct,theang,
#else
	xyzrod_(inct,theang,
#endif
#endif
	rotptr->rx,rotptr->ry,rotptr->rz);
}

#if defined(VMS) || defined(UNDERSC)
rotts(x,y,z,xc,yc,zc,itran)
#else
#ifdef CRAY
ROTTS(x,y,z,xc,yc,zc,itran)
#else
rotts_(x,y,z,xc,yc,zc,itran)
#endif
#endif
float *x;
float *y;
float *z;
double *xc;
double *yc;
double *zc;
int *itran;
{
#if defined(VMS) || defined(UNDERSC)
	rottd(x,y,z,xc,yc,zc,itran,
#else
#ifdef CRAY
	ROTTD(x,y,z,xc,yc,zc,itran,
#else
	rottd_(x,y,z,xc,yc,zc,itran,
#endif
#endif
	rotptr->rx,rotptr->ry,rotptr->rz,rotptr->t);
}

#if defined(VMS) || defined(UNDERSC)
rott(x,y,z,xc,yc,zc,itran)
#else
#ifdef CRAY
ROTT(x,y,z,xc,yc,zc,itran)
#else
rott_(x,y,z,xc,yc,zc,itran)
#endif
#endif
double *x;
double *y;
double *z;
double *xc;
double *yc;
double *zc;
int *itran;
{
#if defined(VMS) || defined(UNDERSC)
	rotd(x,y,z,xc,yc,zc,itran,
#else
#ifdef CRAY
	ROTD(x,y,z,xc,yc,zc,itran,
#else
	rotd_(x,y,z,xc,yc,zc,itran,
#endif
#endif
	rotptr->rx,rotptr->ry,rotptr->rz,rotptr->t);
}

#if defined(VMS) || defined(UNDERSC)
inirot()
#else
#ifdef CRAY
INIROT()
#else
inirot_()
#endif
#endif
{
#if defined(VMS) || defined(UNDERSC)
	inirod(
#else
#ifdef CRAY
	INIROD(
#else
	inirod_(
#endif
#endif
	rotptr->rx,rotptr->ry,rotptr->rz,rotptr->t);
}

#if defined(VMS) || defined(UNDERSC)
mtinv3()
#else
#ifdef CRAY
MTINV3()
#else
mtinv3_()
#endif
#endif
{
#if defined(VMS) || defined(UNDERSC)
	mtind3(
#else
#ifdef CRAY
	MTIND3(
#else
	mtind3_(
#endif
#endif
	rotptr->rx,rotptr->ry,rotptr->rz);
}

#if defined(VMS) || defined(UNDERSC)
mktrn(inct,incp)
#else
#ifdef CRAY
MKTRN(inct,incp)
#else
mktrn_(inct,incp)
#endif
#endif
int *inct;
int *incp;
{
#if defined(VMS) || defined(UNDERSC)
	mktrd(inct,incp,
#else
#ifdef CRAY
	MKTRD(inct,incp,
#else
	mktrd_(inct,incp,
#endif
#endif
	&posptr->xv,&posptr->yv,&posptr->zv,
	&posptr->pincr,&scalptr->scal,&scalptr->scali,&scalptr->smag);
}

#if defined(VMS) || defined(UNDERSC)
setxyv()
#else
#ifdef CRAY
SETXYV()
#else
setxyv_()
#endif
#endif
{
#if defined(VMS) || defined(UNDERSC)
	setxyd(
#else
#ifdef CRAY
	SETXYD(
#else
	setxyd_(
#endif
#endif
	&posptr->xv,&posptr->yv);
}

#if defined(VMS) || defined(UNDERSC)
chkbck(upogl)
#else
#ifdef CRAY
CHKBCK(upogl)
#else
chkbck_(upogl)
#endif
#endif
int *upogl;
{
	if (*upogl) SSdone[istruct] = 0;
#if defined(VMS) || defined(UNDERSC)
	chkbcd(
#else
#ifdef CRAY
	CHKBCD(
#else
	chkbcd_(
#endif
#endif
	&calfptr->ncalf,calfptr->ihet,calfptr->reson);
}

/* END shadow C routines for Fortran routines to rotation pointers */

#if defined(VMS) || defined(UNDERSC)
qupd()
{
    int oglon;

    rsold = RESUND;
    oglon = (*fancy || *fullgl);
    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) {
	doclr();
	if (*persp) {
	   plmolp();
	} else {
	   plmol();
	}
      }
      if (*logo) dlogo();
      doexp();
#ifdef DOGL
    }
#endif

}
#else
#ifdef CRAY
QUPD()
{
    int oglon;

    oglon = (*fancy || *fullgl);
    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) {
	doclr();
	if (*persp) {
	   PLMOLP();
	} else {
	   PLMOL();
	}
      }
      if (*logo) DLOGO();
      DOEXP();
#ifdef DOGL
    }
#endif
}

#else
qupd_()
{
    int oglon;

    oglon = (*fancy || *fullgl);
    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) {
	doclr();
	if (*persp) {
	   plmolp_();
	} else {
	   plmol_();
	}
      }
      if (!*fullgl) {
	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
}

void SetSurfColor(is,j)
int is;
int j;
{
   int i;

   if (is >= MAXSURF || j >= MAX_COLORS) return;

#ifdef DOGL
   diffuseColor[istruct][is][0] = ((GLfloat) colorr[j]) / 65535.0 ;
   diffuseColor[istruct][is][1] = ((GLfloat) colorg[j]) / 65535.0 ;
   diffuseColor[istruct][is][2] = ((GLfloat) colorb[j]) / 65535.0 ;
   diffuseColor[istruct][is][3] = 1.0;
   for (i=0; i<3; i++) {
	specularColor[is][i] = specColor[i];
   }
#endif
}

void CopySurfColor(is1,is2)
int is1;
int is2;
{
   int i;

   if (is2 >= MAXSURF) return;

   fprintf(stderr,"copysurfcolor is1 %d is2 %d\n",is1,is2);
#ifdef DOGL
   diffuseColor[istruct][is2][0] = diffuseColor[istruct][is1][0];
   diffuseColor[istruct][is2][1] = diffuseColor[istruct][is1][1];
   diffuseColor[istruct][is2][2] = diffuseColor[istruct][is1][2];
   for (i=0; i<3; i++) {
	specularColor[is2][i] = specularColor[is1][i];
   }
#endif
}

sizz(i,j,iset)
int i;
int j;
int iset;
{

 *(zmptrp->iz + (i*4) + j) = iset;

}


static int *Snstr;
#ifdef VMS
static struct dsc$descriptor_s *Sstr;
#else
#ifdef CRAY
static _fcd Sstr;
#else
static char *Sstr;
#endif
#endif


ColorByStruct()
{
    int i,k,ilow;

    for (k=0; k < alnptr->nalign; k++) {
	if (k == 0) {
	   ilow = 0;
        } else {
	   ilow = alnptr->istch[k-1];
	}
	for (i=ilow; i < alnptr->istch[k]; i++)
	   chncol(i,alnptr->istcol[k],0);
    }
}

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,&clfhptr->isndcl[iop],&ZERO);
#else
#ifdef CRAY
                ACTHEL(&ONE,&iop,&clfhptr->isndcl[iop],&ZERO);
#else
                acthel_(&ONE,&iop,&clfhptr->isndcl[iop],&ZERO);
#endif
#endif
		}
	    }
	}
}

void sndon(iop,set,color)
int iop;
int set;
int color;
{
   int i;

   if (iop > 3) return;

   if (*ipdbon && SSdone[istruct] == -1) {
       if (!OMAPup) NSurf[istruct] = 0;
#if defined(VMS) || defined(UNDERSC)
       ribgl(calfptr->ianf,&calfptr->nchain,&calfptr->ncalf,xyzp->iatoms);
#else
#ifdef CRAY
       RIBGL(calfptr->ianf,&calfptr->nchain,&calfptr->ncalf,xyzp->iatoms);
#else
       ribgl_(calfptr->ianf,&calfptr->nchain,&calfptr->ncalf,xyzp->iatoms);
#endif
#endif
       SSdone[istruct] = 1;
   }

   for (i=RIBindex[istruct].start[iop]; 
	i <= RIBindex[istruct].end[iop]; i++) {
	SSon[istruct][i] = 1;
	if (set) {
	   SetSurfColor(i,color);
	} else {
	   SetSurfColor(i,clfhptr->isndcl[iop]);
	}
   }

   RedrawSTRC();
}

void sndoff(iop)
int iop;
{
   int i;

   if (iop > 3) return;

   for (i=RIBindex[istruct].start[iop]; 
	i <= RIBindex[istruct].end[iop]; i++) {
	SSon[istruct][i] = 0;
   }

   RedrawSTRC();
}

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 < *xyzp->iatoms; i++ ) xyzp->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,&clfhptr->isndcl[iop],&ZERO);
#else
#ifdef CRAY
                ACTHEL(&ONE,&iop,&clfhptr->isndcl[iop],&ZERO);
#else
                acthel_(&ONE,&iop,&clfhptr->isndcl[iop],&ZERO);
#endif
#endif
		sndon(iop,0,0);
	    }
	    if (alnptr->nalign) ColorByStruct();
	}
}

DebugStructure()
{
   int i;

   for (i=0; i<nstruct; i++) {
	   fprintf(stderr,"str %d file %s\n",i,COO[i]->fname);
	   fprintf(stderr," iatoms %d\n",COO[i]->iatoms);
	   fprintf(stderr," natoms %d\n",COO[i]->NAT.natoms);
	   fprintf(stderr," ipoints %d\n",COO[i]->ipoints);
	   fprintf(stderr," iftyp %d\n",COO[i]->iftyp);
	   fprintf(stderr," iconv %d\n",COO[i]->poi.iconv);
	   fprintf(stderr," mxzorg %d\n",COO[i]->zmt.mxzorg);
   }
}

void SaveFirstStruct()
{
    int j;
    char* p;


    COO[0]->coo   = *xyzp;
    COO[0]->geop  = *geop;
    COO[0]->zmt   = *zmptrp;
    COO[0]->stoc  = *stocp;
    COO[0]->dorb  = *dorbp;
    COO[0]->orb   = *orbp;

    COO[0]->fname = (char *) malloc(strlen(firstfile) + 3);
    strcpy(COO[0]->fname, firstfile);

    if ((p = strrchr(firstfile, '/'))) p++; 
    strfiles[0] = (char *) malloc(strlen(p) + 3);
    strcpy(strfiles[0], p);

    if (pdbcode == NULL) {
	COO[0]->pdbcode = NULL;
    } else {
	COO[0]->pdbcode = (char *) malloc(5);
	strncpy(COO[0]->pdbcode, pdbcode,4);
	COO[0]->pdbcode[4] = '\0';
    }

}

void SaveActiveStruct()
{
    int j;
    char* p;

/* 
   These are the data with general pointers that are copied to the
   COO structures when a new structure becomes active

   For Data structures that use dynamic memory allocation, we only
   keep a pointer in the COO structure. The pointer is assigned in
   the memory allocation rotines (allcoo, allgeo) when a new file 
   is read.
*/

    COO[istruct]->IANZbox = IANZbox;
    COO[istruct]->BLbox   = BLbox;
    COO[istruct]->ALPHbox = ALPHbox;
    COO[istruct]->BETbox  = BETbox;
    COO[istruct]->IZbox   = IZbox;

    COO[istruct]->iatoms = *xyzp->iatoms;
    COO[istruct]->mxnat = *xyzp->mxnat;
    COO[istruct]->natorg = *natorg;
    COO[istruct]->pdb = *ipdbon;
    COO[istruct]->backb = *backb;
    COO[istruct]->iftyp = *iftyp;
    COO[istruct]->rot = *rotptr;
    COO[istruct]->pos = *posptr;
    COO[istruct]->scal = *scalptr;
    COO[istruct]->cell = *cell;
    COO[istruct]->cellpnt = *cellpnt;
    COO[istruct]->geo = *geo1ptr;
    COO[istruct]->cnv = *cnvptr;
    COO[istruct]->poi = poi;
    COO[istruct]->ipoints = pnt->ipoints;
    COO[istruct]->calf = *calfptr;
    COO[istruct]->strx = strx;
    COO[istruct]->XYZ = *XYZ;
    COO[istruct]->NAT = *NAT;
    COO[istruct]->bas = *BAS;
    COO[istruct]->gau = *slagau;
    COO[istruct]->mop = *MOP;
    COO[istruct]->frq = *FRQ;
    COO[istruct]->pseud = *PSEUD;
    COO[istruct]->plane = *plane;
    COO[istruct]->eul = *eul;
    COO[istruct]->proj = *proj;
    COO[istruct]->mfdata = *mfdata;
    COO[istruct]->potcom = *potcom;
    COO[istruct]->zmpart = *zmpart;
    COO[istruct]->jobcom = *jobcom;
    COO[istruct]->qdpptr = *qdpptr;
    COO[istruct]->hlpsrf = *hlpsrf;
    COO[istruct]->hetlab = hetlab;
    COO[istruct]->nmr = *nmrptr;
    COO[istruct]->jcoupl = jcoupl;
    COO[istruct]->nz = *zmptrp->nz;
    COO[istruct]->ihaszm = *zmptrp->ihaszm;
    COO[istruct]->mxzat = *zmptrp->mxzat;
    COO[istruct]->ncols = *dorbp->ncols;
    COO[istruct]->ncolb = *dorbp->ncolb;
    COO[istruct]->nocc = *dorbp->nocc;
    COO[istruct]->nocb = *dorbp->nocb;
    COO[istruct]->naorbs = *dorbp->naorbs;
    COO[istruct]->mxorb = *dorbp->mxorb;
    COO[istruct]->uhf = *iuhf;
    COO[istruct]->spd = *ispd;
    COO[istruct]->ipsi = *ipsi;
    COO[istruct]->inact = inactMC;
    COO[istruct]->inaf = inafMC;
    COO[istruct]->uscl = *uscl;
    COO[istruct]->adjus = *adjuss;
    COO[istruct]->atcol = *atcol;
    COO[istruct]->ZMEAA = ZMEAA;
    COO[istruct]->doesp = *doesp;
    COO[istruct]->fftyp = *fftyp;
    COO[istruct]->irtcel = *irtcel;
    COO[istruct]->normc = *normc;
    COO[istruct]->icst = *icst;
    COO[istruct]->ibox = *ibox;
    COO[istruct]->igfmap = *igfmap;
    COO[istruct]->iresrd = *iresrd;
    COO[istruct]->clfstr = *clfstrptr;
    COO[istruct]->fancy = *fancy;
    COO[istruct]->alnstr = *alnptr;
    COO[istruct]->ihasex = *ihasex;

    for (j=0; j<FRQ->nfreq; j++) 
       COO[istruct]->frsym[j] = frsym[j];

    for (j=0; j<NHetAtm; j++) 
       COO[istruct]->HetAtm[j] = HetAtm[j];
    COO[istruct]->NHetAtm = NHetAtm;

    for (j=0; j<ntits; j++) 
       COO[istruct]->mlftit[j] = mlftit[j];
    COO[istruct]->ntits = ntits;

    if (pdbcode == NULL) {
	COO[istruct]->pdbcode = NULL;
    } else {
	COO[istruct]->pdbcode = (char *) malloc(5);
	strncpy(COO[istruct]->pdbcode, pdbcode,4);
	COO[istruct]->pdbcode[4] = '\0';
    }
}

AllocateStructure(newstr)
STRUSTRU **newstr;
{
  *newstr = (STRUSTRU *) malloc((sizeof **newstr)*1); 
}

AllocateSubStructures(file)
char *file;
{
	NHetAtm = 0;
	Ngrostr = 0;
	omapr = 0;

	xyzp   = &COO[nstruct]->coo;
	geop   = &COO[nstruct]->geop;
	zmptrp = &COO[nstruct]->zmt;
	stocp  = &COO[nstruct]->stoc;
	dorbp  = &COO[nstruct]->dorb;
	orbp   = &COO[nstruct]->orb;


	strfiles[nstruct] = (char *) malloc(strlen(file) + 3);
	COO[nstruct]->fname = (char *) malloc(strlen(strname) + 3);
	strcpy(strfiles[nstruct], file);
	strcpy(COO[nstruct]->fname, strname);

	if (strx.fpos != NULL) strx.fpos = NULL;
	if (strx.fptr) strx.fptr = NULL;

	nstruct++; 
	istruct = nstruct - 1;

#if defined(VMS) || defined(UNDERSC)
	allcoo(&addat,&ONE);
	allgeo(&addat,&ONE);
	allorb(&addat,&ONE);
#else
#ifdef CRAY
	ALLCOO(&addat,&ONE);
	ALLGEO(&addat,&ONE);
	ALLORB(&addat,&ONE);
#else
	allcoo_(&addat,&ONE);
	allgeo_(&addat,&ONE);
	allorb_(&addat,&ONE);
#endif
#endif

	*xyzp->iatoms = 0;

	AllocZMat(*xyzp->mxnat,ONE);


	strlist.select = istruct;
	if (!STRup) inistr();
	else RedrawSTR();
}

void NewActiveStruct()
{
    int i,j,j1,nstr, HasZMtmp;
#ifdef VMS
    struct dsc$descriptor_s ztr;
#else
#ifdef CRAY
    _fcd ztr;
#else
    char ztr[4];
#endif
#endif

    xyzp   = &COO[istruct]->coo;
    geop   = &COO[istruct]->geop;
    zmptrp = &COO[istruct]->zmt;
    stocp  = &COO[istruct]->stoc;
    dorbp  = &COO[istruct]->dorb;
    orbp   = &COO[istruct]->orb;

    IANZbox = COO[istruct]->IANZbox;
    BLbox   = COO[istruct]->BLbox;
    ALPHbox = COO[istruct]->ALPHbox;
    BETbox  = COO[istruct]->BETbox;
    IZbox   = COO[istruct]->IZbox;

    *xyzp->iatoms   = COO[istruct]->iatoms;
    *xyzp->mxnat    = COO[istruct]->mxnat;
    *natorg         = COO[istruct]->natorg;
    *ipdbon         = COO[istruct]->pdb;
    *iftyp          = COO[istruct]->iftyp;
    *rotptr         = COO[istruct]->rot;
    *posptr         = COO[istruct]->pos;
    *scalptr        = COO[istruct]->scal;
    *cell           = COO[istruct]->cell;
    *cellpnt        = COO[istruct]->cellpnt;
    *geo1ptr        = COO[istruct]->geo;
    *cnvptr         = COO[istruct]->cnv;
    bckpoi(istruct);
    pnt->ipoints    = COO[istruct]->ipoints;
    *calfptr        = COO[istruct]->calf;
    strx            = COO[istruct]->strx;
    *XYZ            = COO[istruct]->XYZ;
    *NAT            = COO[istruct]->NAT;
    *BAS            = COO[istruct]->bas;
    *slagau         = COO[istruct]->gau;
    *MOP            = COO[istruct]->mop;
    *FRQ            = COO[istruct]->frq;
    *PSEUD          = COO[istruct]->pseud;
    *plane          = COO[istruct]->plane;
    *eul            = COO[istruct]->eul;
    *proj           = COO[istruct]->proj;
    *mfdata         = COO[istruct]->mfdata;
    *potcom         = COO[istruct]->potcom;
    *zmpart         = COO[istruct]->zmpart;
    *jobcom         = COO[istruct]->jobcom;
    *qdpptr         = COO[istruct]->qdpptr;
    *hlpsrf         = COO[istruct]->hlpsrf;
    hetlab          = COO[istruct]->hetlab;
    *nmrptr         = COO[istruct]->nmr;
    jcoupl          = COO[istruct]->jcoupl;
    *zmptrp->nz     = COO[istruct]->nz;
    *zmptrp->ihaszm = COO[istruct]->ihaszm;
    *zmptrp->mxzat  = COO[istruct]->mxzat;
    *dorbp->ncols   = COO[istruct]->ncols;
    *dorbp->ncolb   = COO[istruct]->ncolb;
    *dorbp->nocc    = COO[istruct]->nocc;
    *dorbp->nocb    = COO[istruct]->nocb;
    *dorbp->naorbs  = COO[istruct]->naorbs;
    *dorbp->mxorb   = COO[istruct]->mxorb;
    *iuhf           = COO[istruct]->uhf;
    *ispd           = COO[istruct]->spd;
    *ipsi           = COO[istruct]->ipsi;
    *uscl           = COO[istruct]->uscl;
    *adjuss         = COO[istruct]->adjus;
    *atcol          = COO[istruct]->atcol;
    *doesp          = COO[istruct]->doesp;
    *fftyp          = COO[istruct]->fftyp;
    *irtcel         = COO[istruct]->irtcel;
    *normc          = COO[istruct]->normc;
    *icst           = COO[istruct]->icst;
    *ibox           = COO[istruct]->ibox;
    *igfmap         = COO[istruct]->igfmap;
    *iresrd         = COO[istruct]->iresrd;
    *clfstrptr      = COO[istruct]->clfstr;
    *fancy          = COO[istruct]->fancy;
    *alnptr         = COO[istruct]->alnstr;
    *ihasex         = COO[istruct]->ihasex;
    pdbcode	    = COO[istruct]->pdbcode;

    NHetAtm         = COO[istruct]->NHetAtm;
    for (j=0; j<NHetAtm; j++) 
	HetAtm[j] = COO[istruct]->HetAtm[j];

    for (j=0; j<NHetAtm; j++) {
	j1 = j + 1;
#if defined(VMS) || defined(UNDERSC)
/*
	for (i=0; i<strlen(HetAtm[j]); i++)
	    ztr.dsc$a_pointer[i] = HetAtm[j][i];
	parhet(&j1,&ztr);
*/
	clfstrptr->ihashz = 0;
#else
#ifdef CRAY
/*
	strncpy(_fcdtocp(ztr),HetAtm[j],strlen(HetAtm[j]));
	PARHET(&j1,ztr);
*/
	clfstrptr->ihashz = 0;
#else
	if (HetAtm[j] != NULL) {
	   strncpy(ztr,HetAtm[j],3);
	   parhet_(&j1,ztr);
	}
#endif
#endif
    }

    ntits         = COO[istruct]->ntits;
    for (j=0; j<ntits; j++) 
	mlftit[j] = COO[istruct]->mlftit[j];

    for (j=0; j<FRQ->nfreq; j++) 
        frsym[j]  = COO[istruct]->frsym[j];

    pnt->ipnt = 1;

    HasZMtmp = *zmptrp->ihaszm;

    actde(COO[istruct]->inact,COO[istruct]->inaf,0);

    *backb           = COO[istruct]->backb;
    if (*backb) {
	TogDown(&cbut[BBACKB]);
	ActBut(&cbut[BFORC],1);
	ActBut(&cbut[BINCRF],1);
	ActBut(&cbut[BHBOND],1);
	ActBut(&cbut[BDECRF],1);
	ActBut(&cbut[BUNSC],1);
    } else {
	TogUp(&cbut[BBACKB]);
    }

    if (*fancy) {
	TogDown(&cbut[BSOLID]);
    } else {
	TogUp(&cbut[BSOLID]);
    }

    if (*atcol) {
	TogDown(&cbut[BATCOL]);
    } else {
	TogUp(&cbut[BATCOL]);
    }

    if (HasZMtmp) {
	ZMEAA           = COO[istruct]->ZMEAA;
	if (ZMEAA) EXPbox[0].fake = 0;
	else EXPbox[0].fake = 1;
    }

/* Now update open windows */

    if (ZMEup) {
	
	if (pdb && !*zmptrp->ihaszm) { 
	   if (DoPDB()) i = 1;
	} else {
#if defined(VMS) || defined(UNDERSC)
	   upzme();
#else
#ifdef CRAY
	   UPZME();
#else
	   upzme_();
#endif
#endif
	}
	RedrawZME();
    }

    if (cnvup) {
	drwcnv();
    }

    if (specup) {
	createspec(0);
	drwspec();
    }

    if (FRup) {
	createfr(0);
	RedrawList(&frlist);
    }

    if (geoup) {
	XClearWindow(display,wingeo);

#if defined(VMS) || defined(UNDERSC)
	drwgeo();
#else
#ifdef CRAY
	DRWGEO();
#else
	drwgeo_();
#endif
#endif
    }

/* close old iun2 unit and open file associated with new active structure */

    nstr = strlen(COO[istruct]->fname);

#ifdef VMS
    for (i=0; i<strlen(COO[istruct]->fname); i++)
	{Sstr->dsc$a_pointer[i] = COO[istruct]->fname[i];}
    nwfil(Sstr,&nstr);
#else
#ifdef CRAY
    strncpy(_fcdtocp(Sstr),COO[istruct]->fname,
	strlen(COO[istruct]->fname));
    NWFIL(Sstr,&nstr);
#else
    strcpy(Sstr,COO[istruct]->fname);
#if defined(UNDERSC)
    nwfil(Sstr,&nstr);
#else
    nwfil_(Sstr,&nstr);
#endif
#endif
#endif

    WinName(win,COO[istruct]->fname);
    omapr = 0;

}

void GetFirstFile()
{
char* p;
char* q;

	nfilesstart = fsel.nfiles;
	firstreadf = 0;
	if (nfilesstart) {
	   strcpy(firstfile,fsel.files[0]);
	   if (firstfile[0] != '/') {
		if (getcwd(firstfile,MAXFILELEN) == NULL) 
		   strcpy(firstfile,"./");
		if (firstfile[strlen(firstfile)-1] == '/') 
		   firstfile[strlen(firstfile)-1] = '\0';

		p = fsel.files[0];
		while (p[0] == '.' && p[1] == '.') {
		   q = firstfile;
		   if ((q = strrchr(firstfile, '/'))) q[0] = '\0';
		   p++; p++; p++;
		}
		if (p[0] == '.') p++;
		if (p[0] == '/') p++;
		if (firstfile[strlen(firstfile)-1] != '/') 
		   strcat(firstfile,"/");
		strcat(firstfile,p);
	   }
	}
}

void NewDir(fs)
FSELSTRU *fs;
{
char* p;
char  tmpdir[MAXDIRLEN];

	seldir = fs->dirlist.select;
	if (seldir > fs->ndirs - 1) seldir = fs->ndirs - 1;

	if (strcmp(fs->dirs[seldir],"..") == 0) {
	    strcpy(tmpdir,fs->lastdir);
	    if (fs->lastdir[0] != '/') {

		if (getcwd(fs->lastdir,MAXDIRLEN) == NULL) 
		   strcpy(fs->lastdir,"./");
		if (fs->lastdir[strlen(fs->lastdir)-1] != '/') 
		   strcat(fs->lastdir,"/");

		p = tmpdir;
		if (p[0] == '.') p++;
		if (p[0] == '/') p++;
		strcat(fs->lastdir,p);
	    }

	    if (fs->lastdir[strlen(fs->lastdir)-1] == '/') 
		fs->lastdir[strlen(fs->lastdir)-1] = '\0';

	    if ((p = strrchr(fs->lastdir, '/'))) {
		p++; *p = '\0';
	    }

	} else {
	    if (strcmp(fs->dirs[seldir],".") != 0) {
		strcat(fs->lastdir,fs->dirs[seldir]);
		strcat(fs->lastdir,"/");
	    }
	}
}

int palette()
{
    int iii, clopt, ich, doret;
    LSSTRU List;

#ifdef DOGL
    GLint loc;
    List.list = palopt; List.nents = 9;
#ifdef GL_COLOR_ATTACHMENT0_EXT
    if (has_shader && has_fbo) List.nents = 12;
#endif
#else
    List.list = palopt; List.nents = 7;
#endif

    doret = 1;

    if (DoPopUp(winMC, cbut[BPAL].x+1,cbut[BPAL].y+BUTTH,
	&List,&clopt,0) == -1) {
   	update_model = 0;
	return(0);
    }

    RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);

    switch (clopt) {
	case 0:
		List.list = bgopt; List.nents = 2;
		if (DoPopUp(winMC,cbut[BPAL].x+1,cbut[BPAL].y+BUTTH,
			    &List,&BGmode,0) == -1) return(0);
		WriteRes();
		break;

	case 1:
	case 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) return(0);
			colt = iii;
		    } else {
			if (has_opengl && (*fancy || *fullgl)) {
				colt = 13; BGmode = 1;
			} else colt = 0;
		    }

		    if (has_opengl && (*fancy || *fullgl) ) {
			OBGcolor = colt;
		    } else {
			IBGcolor = colt;
		    }

		    XSetBackground(display, gc, colors[IBGcolor]);

#ifdef DOGL
		    if (has_opengl) setobg();
#endif
		    WriteRes();
		}
		break;

	case 3:
		doret = 0;
		update_model = 0;
		if (!COLup) InitCOL();
		else XMapRaised(display,COLwin);
		break;

	case 4:
		doret = 0;
		if (!monoscr) {
			if (DoPopUp(winMC,cbut[BPAL].x-8,cbut[BPAL].y+BUTTH,
				    NULL,&iii,0) == -1) return(0);
			if (iii) {
			   activecolor = iii;
			   update_model = 0;
			   if (!ECOLup) EditCOL();
			   else XMapRaised(display,ECOLwin);
			}
		}
		break;

	case 5:
		ResetColors();
		break;

	case 6:
		doret = 0;
		update_model = 0;
		if (!DPTup) InitDPT();
		else XMapRaised(display,DPTwin);
		break;

	case 7:
		doret = 0;
		update_model = 0;
		if (!STRCup) inistrc();
		break;

	case 8:
		List.list = Chains; 
		List.nents = calfptr->nchain;

		doret = 0;

		if (DoPopUp(winMC,cbut[BPAL].x-8,cbut[BPAL].y+8*BUTTH,
			     &List,&ich,0) == -1) return(0);

		RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);

		if (DoPopUp(winMC,cbut[BPAL].x-8,cbut[BPAL].y+8*BUTTH,
			     NULL,&iii,0) == -1) return(0);

		chncol(ich,iii-1,1);
		break;
	case 9:
		DoSSAO = 0;
		DoShad = 0;
		DoShadow = 0;
		if (DoBlur) {
		   DoBlur = 0;
		} else {
		   DoBlur = 1;
		}
		break;
	case 10:
		List.list = occlopt; List.nents = 2;

		DoBlur = 0;
		DoShad = 0;
		DoShadow = 0;
		if (DoSSAO) {
		   DoSSAO = 0;
		} else {
		   if (DoPopUp(winMC,cbut[BPAL].x+1,cbut[BPAL].y+10*BUTTH,
			    &List,&SSAO_type,0) == -1) return(0);
		   DoSSAO = 1;
		}
#ifdef DOGL
#ifdef GL_ARB_shader_objects
		glUseProgramObjectARB(program[1]);
		loc    = glGetUniformLocationARB(program[1], "ssaotyp");
		glUniform1iARB(loc, SSAO_type);
#endif
#endif
		break;
	case 11:
		if (DoShad) DoShad = 0;
		else {
		   DoShad = 1;
		   DoShadow = 1;
		   DoSSAO = 0;
		   DoBlur = 0;
		}
		break;
       }

       return(doret);
}

void ScrollWheel(inct,incp,iop)
int *inct;
int *incp;
int iop;
{
        update_model = 0;
	*inct = 417; 

	*incp = 5;
	if (iop) *incp = -5;

#if defined(VMS) || defined(UNDERSC)
	mktrn(inct,incp);
	qupd();
#else
#ifdef CRAY
 	MKTRN(inct,incp);
	QUPD();
#else
       	mktrn_(inct,incp);
	qupd_();
#endif
#endif

}

void setgif(iopt)
int iopt;
{

  if (dogif) {
	dogif = 0;
	if (iopt) {
	   TogBut(&cbut[BGIF]);
	} else {
	   TogBut(&dbut[BGIF2]);
	}
  } else {
	if (DisplayCells(display, screen) > 256) {;
	   strcpy(molwstr,"GIF file only for 8-bits screen");
	   StatusStr(0,1);
	} else {
	   dogif = 1;
	   if (iopt) {
#ifdef DOGL
	     if (has_opengl && (*fancy || *fullgl)) {
		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 {
#endif
	 	strcpy(molwstr,"a GIF file per screen update");
		StatusStr(0,1);
#if defined(VMS) || defined(UNDERSC)
		doexp();
#else
#ifdef CRAY
		DOEXP();
#else
		doexp_();
#endif
#endif
#ifdef DOGL
	     }
#endif
	     TogBut(&cbut[BGIF]);
	   } else {
	     TogBut(&dbut[BGIF2]);
	   }
	}
  }
  update_model = 0;
}

void FileSelect(fs)
FSELSTRU *fs;
{

    fs->win = CreateWindow("Molden File Select","-80-80",QBOXWIDE,QBOXRFD,
                            infobg,infofg,(Window)0);
    XSelectInput(display, fs->win, ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask);

    DefBut(&fs->rbut[BDIR],  fs->win, 325, 275            , 110, BUTTH, 
        	   "Update Directory", infobg, CNTCOL);

    if (fs->parse) {
	DefBut(&fs->rbut[BCAN],  fs->win, 325, 275+BUTTN      , 50, BUTTH, 
        	   "Close", infobg, CNTCOL);

	DefBut(&fs->rbut[BREP],  fs->win, 325, 75            , 15, 15, 
        	   " ", infobg, CNTCOL);
	DefBut(&fs->rbut[BADD],  fs->win, 325, 100            ,15, 15, 
        	   " ", infobg, CNTCOL);
	DefBut(&fs->rbut[BPDB],  fs->win, 325, 190            ,60, BUTTH, 
        	   "Get PDB", infobg, CNTCOL);
	ActBut(&fs->rbut[Fwinopt],-1);
	TogDown(&fs->rbut[Fwinopt]);
    } else {
	DefBut(&fs->rbut[BCAN],  fs->win, 325, 275+BUTTN      , 50, BUTTH, 
        	   "OK", infobg, CNTCOL);
    }


    if (fs->nfiles == 0) {
	  getfiles(fs,fs->lastdir);
    } else {
	if (fs->parse) {
	  if (firstreadf) GetFirstFile();
	}
    }
}

void FileSelectList(fs)
FSELSTRU *fs;
{
   DefList(&fs->flist,fs->win,DIRX,DIRY,DIRW,DIRH,NULL,
		NFLS,fs->files,NULL,NULL,NULL,&fs->nfiles);
   fs->flist.select = selfil;
   fs->flist.lpnt = lpnt;
   DefList(&fs->dirlist,fs->win,DDIRX,DDIRY,DDIRW,
		DDIRH,NULL,NDRS,fs->dirs,NULL,NULL,NULL,&fs->ndirs);
   fs->dirlist.select = seldir;
   fs->dirlist.lpnt = 0;
   XMapWindow(display,fs->win);

   if (fs->parse) {
   	qboxstr(&qboxes[QREADF],&fs->win,1,0,-1,DEFQX,
		DEFQY,QBOXWIDE,QBOXHIGH,0,
		"Directory: ",fs->lastdir,0,
		0,fs->inct,fwincall);

   	qboxstr(&qboxes[QSUBSTR],&fs->win,0,0,190,322,
		155,60,35,0,
		"","",0,0,fs->inct,substrcall);

	qboxstr(&qboxes[QPDB],&fs->win,0,0,190,322,
		215,60,35,0,
		"","",4,0,fs->inct,getpdbcall);
   } else {
   	qboxstr(&qboxes[QREADF],&fs->win,1,0,-1,DEFQX,
		DEFQY,QBOXWIDE,QBOXHIGH,0,
		fs->label,fs->pntr,0,
		0,fs->inct,filecall);

   }
}

int FileSelectBP(fs)
FSELSTRU *fs;
{
    int i;

#ifndef VMS

    if (PressList(&fs->dirlist,event.xbutton.x, event.xbutton.y)) {
	 if (fs->ndirs > 0) {
	     NewDir(fs);
	     getfiles(fs,fs->lastdir);
	     RedrawFwin(fs);
	     update_model = 0;
	 }
    }

#endif

    if (PressList(&fs->flist,event.xbutton.x, event.xbutton.y)) {

	 selfil = fs->flist.select;
	 if (selfil > fs->nfiles - 1) selfil = fs->nfiles - 1;
	 lpnt = fs->flist.lpnt;
         XFlush(display);
         XSync(display, True);
         RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
         XSync(display, True);
   
	 if (fs->parse) {

	    if (fs->files[selfil][0] != '/') {
		strcpy(strname,fs->lastdir);
#ifndef VMS
		if (strname[strlen(strname)-1] != '/') strcat(strname,"/");
#endif
		strcat(strname,fs->files[selfil]);
	    } else strcpy(strname,fs->files[selfil]);

	    if (strstr(strname,".ogl")) {
		if (!has_opengl) {
		   lViewer(strname);
		   return(1);
		}
	    }

	    if (ParseFile(strname,fs->files[selfil])) return(1);

	 } else {
	    strcpy(qboxes[QREADF].str,fs->files[selfil]);
	    PromptBox(&qboxes[QREADF]);
	    if (fs->subopt == 1) {
		strcpy(qboxes[QMFILE].str,fs->files[selfil]);
	        PromptBox(&qboxes[QMFILE]);
	    }
	 }
    } else {

	update_model = 0;

	i = ClickBox(&qboxes[QREADF],1,event.xbutton.x,event.xbutton.y);
	if (i>=0) {
	    qboxes[QREADF].active = 1;
	    qboxes[QPDB].active = 0;
	    qboxes[QSUBSTR].active = 0;
	}
	PromptBox(&qboxes[QREADF]);


	if (fs->parse) {
	   i = ClickBox(&qboxes[QSUBSTR],1,event.xbutton.x,event.xbutton.y);
	   if (i>=0) {
	       qboxes[QSUBSTR].active = 1;
	       qboxes[QREADF].active = 0;
	       qboxes[QPDB].active = 0;
	   }
	   PromptBox(&qboxes[QSUBSTR]);
	   i = ClickBox(&qboxes[QPDB],1,event.xbutton.x,event.xbutton.y);
	   if (i>=0) {
	       qboxes[QPDB].active = 1;
	       qboxes[QSUBSTR].active = 0;
	       qboxes[QREADF].active = 0;
	   }
	   PromptBox(&qboxes[QPDB]);
	   i=Clickwin(fs->rbut,NBUTTR,event.xbutton.x, event.xbutton.y,1);
	} else {
	   i=Clickwin(fs->rbut,2,event.xbutton.x, event.xbutton.y,1);
	}

	if (i>=0) {
        	switch (i) {
                    case BDIR : if (fs->parse) {
				   getfiles(fs,qboxes[QREADF].str);
				} else {
				   getfiles(fs,fs->lastdir);
				}
				RedrawFwin(fs);
				break;
                    case BCAN : XUnmapWindow(display,fs->win);
				TogUp(&cbut[BREADF]);
                                fs->qbrfile = 0;
				if (!fs->parse && !fs->subopt) {
				   cpstr(qboxes[QREADF].str,gfile,SUBLEN1);
	    			   *Sinct = fs->inct;
	    			   return(1);
				}
                                break;
                    case BREP : TogBut(&fs->rbut[Fwinopt]);
				ActBut(&fs->rbut[Fwinopt],1);
				Fwinopt = BREP;
				TogBut(&fs->rbut[Fwinopt]);
				ActBut(&fs->rbut[Fwinopt],-1);
				addfile = 0;
				break;
                    case BADD : TogBut(&fs->rbut[Fwinopt]);
				ActBut(&fs->rbut[Fwinopt],1);
				Fwinopt = BADD;
				TogBut(&fs->rbut[Fwinopt]);
				ActBut(&fs->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;
                    case BPDB : 
				if (!CheckWGET()) {
				    strcpy(strname,"");
				    GetPDBWWW(qboxes[QPDB].str,strname);
				    if (ParseFile(strname,qboxes[QPDB].str)) return(1);
				}
				break;
		}
	}

    }
}

#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 || Command == OpenWindow) {
     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) {
	   gl2DEnd();
	   *inct = holdt;
	   *incp = holdp;
	   count = 0; scount = 0;
	   gl2DInit();
	   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:

    gl2DEnd();

    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 != fsel.win) {
				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]=='t') {
                   { sprintf(stemp,"Orbital number (1-%d)? ",NAT->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;
		 }
		 gl2DInit();
                 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;
		   gl2DInit();
                   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 == win 
		&& event.xbutton.button == 4)  ScrollWheel(inct,incp,1);

              if (event.xbutton.window == win 
		&& event.xbutton.button == 5)  ScrollWheel(inct,incp,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],10,
				event.xbutton.x,event.xbutton.y);
			if (i>=0) {
				for (j=0; j<10; 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 == STRCwin) {
	         update_model = 0;
		 i = Clickwin(strcbut,STRCBN,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsSTRC(i)) return(0);
		 } else {
			if (PressList(&strclist,
				event.xbutton.x, event.xbutton.y)) {

				dispsf();
			}
		 }
	      }

              if (event.xbutton.window == gsel.win ) {

		if (FileSelectBP(&gsel) == 1) return(0);

              }

              if (event.xbutton.window == winC) {
		 int doret = 1;
		 *ivtwo = -1;
                 i=Clickwin(dbut,NBUTTS,event.xbutton.x, event.xbutton.y,1);

		 update_model = 1;
		 gl2DInit();

                 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,dorbp->eiga,dorbp->focc,
				NULL,dorbp->ncols);

			   if (*iuhf && ibeta) 
      				DefList(&elist,EBox,DIRX,DIRY,DIRW,DIRH,
				" Nr.        Eigenvalue   Occupation",
				NFLS,NULL,dorbp->eigb,dorbp->focb,NULL,
				dorbp->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,
				"Postscript is not supported for 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(istruct,1);
				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;
				}
		 		if (STRCup) {
				    XDestroyWindow(display,STRCwin);
				    STRCup = 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) {
				doret = 0;
				InitMAP();
			     } else {
				if (i == BVRML2) 
				   InitVIR();
				else if (i == BSPACE && 
				(NAT->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)) {
		          FreeAll(1);
                          XFreeGC(display, gc);
                          XCloseDisplay(display);
                          *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 = 3;
			    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 BGIF2: 
			setgif(0);
			doret = 0;
			break;
                 case BLOCAL: 
#if defined(VMS) || defined(UNDERSC)
			dipole();
#else
#ifdef CRAY
			DIPOLE();
#else
			dipole_();
#endif
#endif
			doret = 0;
			break;
                 case BOGL: 
#ifdef DOGL
			if (*ifdogl) {
			   *ifdogl = 0;
			   TogUp(&dbut[BOGL]);
			   gl2DInit();
			} else {
			   if (has_opengl) {
			      *ifdogl = 1;
			      TogDown(&dbut[BOGL]);
			      if (!do3dx && !*do3d && !*dospa) *do3d = 1;
			      dispsf();
			      inistrc();
			   }
			}
			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;
/*				}*/
				gsel.qbrfile = 1;
				gsel.subopt = 0;
				FileSelectList(&gsel);
				doret = 0;
				*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++;

#ifdef DOGL
		 rubber(0);
#else
                 XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);
#endif
   
                 /* 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);

#ifdef DOGL
		 rubber(0);
#else
                 XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);
#endif

              } /* 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;
		    if (*fullgl && !*ifdogl) {
			yoff = 1.0 - yoff - 1.0/scale;
		    }

                    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;

	      while(XCheckTypedWindowEvent(display,win,Expose,&report)) {
	           if (event.xexpose.count == 0) break;
	      }

              if (event.xexpose.window == win && !ZoomSelection && !*ifdogl) {
                   if (!CheckForConfig()) {
                       if (!*fullgl && molback == molcur) {
                          XCopyArea(display,molcur,win,gc,0,0,width,height,0,0);
                       }
                       else {
                          RedrawWin();
                       }
                   }
              } else {
                   if (event.xexpose.window == winC) {
			while(XCheckTypedWindowEvent(display,win,
				Expose,&report));
                   	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();
	      if (event.xexpose.window == STRwin) RedrawSTR();
	      if (event.xexpose.window == STRCwin) RedrawSTRC();
	      if (event.xexpose.window == gsel.win) RedrawFwin(&gsel);
           }
           break;

	   case MapNotify: {
	      if (event.xmap.window == expldat.win && 
		event.xmap.send_event == True) 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) {

		   while(XCheckTypedWindowEvent(display, win, 
			ConfigureNotify,&event));

                   if (event.xconfigure.width == width &&
                       event.xconfigure.height == height) {
			if (has_opengl && *ifdogl) {
#ifdef DOGL
			    glXSwapBuffers(display, win);
#endif
			} else {
			    if ( !*fullgl && 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;}

		   Aspect = (float) width / (float) height;
		   if (has_opengl && *ifdogl) Reshape(1);
		   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 (DoactMC) {
#if defined(VMS) || defined(UNDERSC)
	curs(&ZERO);
#else
#ifdef CRAY
	CURS(&ZERO);
#else
	curs_(&ZERO);
#endif
#endif
	actde(*inct,*incp,0); 
	DoactMC = 0;
	if (ntits > 1 && !MLTup) initMLT();
    }

    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) zmpart->ipart = animptr.part;
	anim();
       }
     }
ALOOP:

    while (!done) {
  
	XFlush(display);
	if (XPending(display) == 0  && DoFreq ) {
		XSync(display,False) ;return (0);
	}
	if (aflag && !cflag && !dflag) {
	   if (! ((*fancy || *fullgl) && has_opengl) ) {
              XSetForeground(display, gc, colors[2]);
              for (i = 0; i <acnt-1; i++) {
		   XDrawLine(display,win,gc,
			xyzp->iyp[asel[i]-1],xyzp->ixp[asel[i]-1],
			xyzp->iyp[asel[i+1]-1],xyzp->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 == ATMwin && i == QATOM) {
				if (ATMselp <= *xyzp->iatoms) {
	    			    update_sel = 1;
	    			    update_model = 0;
				    if (xyzp->iaton[ATMsel] == 2) 
					xyzp->iaton[ATMsel] = 1;
				    ATMsel = ATMselp - 1;
				    xyzp->iaton[ATMsel] = 2;
				    UpdateATM();
				    RedrawATM();
				    update_struct();
				} else {
				    if (DoCan(width/2, height/2,
					"Number greater than total number of atoms",0)) {
				    }
				}
			}
		       if (!(key_event->window == fsel.win && 
			     (i == QREADF || i == QSUBSTR))) {
				return(0);
			}
		   }
		}
	      }

              if (key_event->window == ZMEwin) {
		int isl;

		istat = 0; isl = 0;
		for (i=0; i<*zmptrp->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 (ks==XK_space)
                   { if (omaplck) omaplck = 0;
		     else {
			omaplck = 1;
			for (i=0; i<3; i++) 
			   rotptr->t[i] = xyzp->coo[omapCa*3+i];
			update_struct();
		     }
		   }
                 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]=='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 < *xyzp->iatoms; i++ ) {
				if (xyzp->iaton[i] >= 2) xyzp->iaton[i] = 1;
			}
	    		update_sel = 1;
			XUndefineCursor(display,win);
			RedrawZME();
*/
			XUndefineCursor(display,win);
			if (*ialtyp == 1) {
                           for (i=0; i<*iscst; i++) xyzp->iaton[i] = 1;
                           for (i=*iscst; i<(*iscst)+(*nscnd); i++) 
				xyzp->iaton[i] = 2;
			} else {
                           for (i=0; i<*xyzp->iatoms; i++) xyzp->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 || *fullgl) && 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;

/* blag set: single atom selection */

                 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(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,
					*xyzp->iatoms,curx,cury,MINDIFF);

		    if (bretval == 321) {
			*inct = 530;
			idum1 = DelAmino(xyzp->iresid[*incp-1]);
		    }

		    if (bretval == 322) {
			*inct = 530;
			InsertAmino = xyzp->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 < *xyzp->iatoms; i++ ) xyzp->iaton[i] = 1;
			xyzp->iaton[*incp-1] = 2;
	    		update_sel = 1;
		    }
		    if (bretval == 565) {
			int ir;

			ir = xyzp->iresid[*incp-1];
			for (i=0; i < *xyzp->iatoms; i++ ) {
			   if (xyzp->iresid[i] == ir) xyzp->iaton[i] = 2;
			}
	    		update_sel = 1;
		    }

		    if (bretval == 566) {

#if defined(VMS) || defined(UNDERSC)
			proxic(incp,backb,&ONE,&ZERO,&THRESH);
#else
#ifdef CRAY
			PROXIC(incp,backb,&ONE,&ZERO,&THRESH);
#else
			proxic_(incp,backb,&ONE,&ZERO,&THRESH);
#endif
#endif
			ressel();
	    		update_sel = 1;
		    }
		    return(0);
                 }

/* aflag set: select multiple atoms */

                 if (aflag && ! bflag && !(event.xbutton.state & ControlMask)) {
                    int ia,ib,floke,low,up;

		    up = *xyzp->iatoms;
		    low = 0;

		    if (cflag) {
			if (acnt == 0 || acnt == 2 || acnt == 4) {
			   low = 0; up = *iscst;
			} else {
			   low = *iscst; up = *xyzp->iatoms;
			}
		    }


		    ib = FindSel(xyzp->iaton,xyzp->iyp,xyzp->ixp,low,up,
				curx,cury,MINDIFF);

		    if (ib < 0) ib = -2;
                    floke = 1;

                    for (ia = 0; ia <acnt; ia++) {
			if (dflag) {
			   if (ia < *xyzp->mxnat) 
				if (jring[ia] == ib+1 ) floke = 0;
			} else {
                           if (asel[ia] == ib+1 ) floke = 0;
			}
		    }

/*
		    if (cflag) {
			if (acnt == 0 || acnt == 2 || acnt == 4) {
			   if (ib >= *iscst) floke = 0;
			} else {
			   if (ib < *iscst) floke = 0;
			}
		    }
*/

                    if (floke && ib >= 0) {

		       if (dflag) {
			  if (acnt < *xyzp->mxnat) jring[acnt] = ib+1;
		       } else {
			  asel[acnt] = ib+1;
		       }
			
		       if (aflag && (*fancy || *fullgl) && has_opengl) {
			  xyzp->iaton[ib] = 3;
		          update_model = 0;
	    		  update_sel = 1;
#ifdef DOGL
			  dispsf();
#endif
		       }

                       aflag--;
                       acnt++;

                       if (*ibell) XBell(display,0);

		       if (cflag) {
			xyzp->iaton[ib] = 3 + (acnt-1)/2;
	    		update_sel = 1;
			if (aflag) return(0);
		       }

		       if (dflag) {
			xyzp->iaton[ib] = 3;
			sprintf(stemp,"%d Atoms to go",aflag);
			strcpy(ZMEerr,stemp);
			RedrawStatus();
	    		update_sel = 1;
			if (aflag) {
		           update_model = 0;
			   return(0);
			}
		       }
                    }

		    if (!cflag && !dflag) {
			if (! ((*fancy || *fullgl) && has_opengl) ) {
			   XSetForeground(display, gc, colors[2]);
			   for (i = 0; i <acnt-1; i++) {
				XDrawLine(display,win,gc,
				xyzp->iyp[asel[i]-1]  ,xyzp->ixp[asel[i]-1], 
				xyzp->iyp[asel[i+1]-1],xyzp->ixp[asel[i+1]-1]);
			   }
			}
		    }

                    if (!aflag) {

/* done multiple atom selecting, now parse selection */

	               update_model = 1;
                       XUndefineCursor(display,win);

		       if (cflag) {
			  for (i=0; i<*xyzp->iatoms; i++) xyzp->iaton[i] = 1;
	    		  update_sel = 1;
			  if (cflag == 1) {

/* align two molecules, 3 atoms of each molecule selected */

#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,xyzp->coo);
#else
#ifdef CRAY
				CLLVEC(asel,&anum,xyzp->coo);
#else
				cllvec_(asel,&anum,xyzp->coo);
#endif
#endif
			  }
			  cflag = 0;
			  return(0);

		       } else if (dflag) {
/* reorder zmatrix */
			  dflag = 0; Selecting = 0; ZMEsel = 0;
			  for (i=0; i<*xyzp->iatoms; i++) xyzp->iaton[i] = 2;
	    		  update_sel = 1;
			  *isimpl = 4;
			  ApplSel(0);
			  return(0);

		       } else if (SelZME(asel)) {

/* add zmat line, parse new structure */

			  return(0);

		       } else {

/* calculate distance, angle, or dihedral */

#ifdef DOGL
			  if ((*fancy || *fullgl) && has_opengl) {
			      ogunsel();
			  }
#endif

			  if (eflag) {
			     if (asel[1] > asel[0]) {
				eflag = asel[0];
				asel[0] = asel[1];
				asel[1] = eflag;
			     }
			     eflag = 0;
			     aret = jcoupl[(asel[0]-1)*NAT->natoms + asel[1]-1];
			     anum = 6;
			  } 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 && *zmptrp->ihaszm) {
			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 (hlpsrf->itsrf) {
			if (has_opengl && (*fancy || *fullgl)) {
			   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(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,
			*xyzp->iatoms,curx,cury,MINDIFF);
		    if (k != -1) {
			if (xyzp->iaton[ATMsel] == 2) xyzp->iaton[ATMsel] = 1;
	    		update_sel = 1;
			ATMsel = k;
			ATMselp = ATMsel + 1;
			xyzp->iaton[ATMsel] = 2;
			fprintf(stderr,"Coordinates (Ang) %#9.3f,%#9.3f,%#9.3f\n",
			   xyzp->coo[ATMsel*3]*toangs,
			   xyzp->coo[ATMsel*3+1]*toangs,
			   xyzp->coo[ATMsel*3+2]*toangs);
			if (ATMup) {
			   UpdateATM();
			   XMapRaised(display,ATMwin);
			   RedrawATM();
			} else {
			   InitATM(event.xbutton.x_root,event.xbutton.y_root);
			   qdpptr->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 || *fullgl) && 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);
		 if (! (has_opengl && (*fancy || *fullgl)) ) {
                    XSetFunction(display, gc, GXxor);
                    XSetForeground(display, gc, colors[11]);
		 }

                 ZoomX1 = event.xbutton.x;
                 ZoomY1 = event.xbutton.y;
                 ZoomW = 1;
                 ZoomH = 1;

		 if (has_opengl && (*fancy || *fullgl)) {
#ifdef DOGL
		    rubber(1);
#endif
		 } else {
                    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 == win && event.xbutton.button == 4)  {
	        update_model = 0;
		*inct = 417; *incp = -5;
#if defined(VMS) || defined(UNDERSC)
		mktrn(inct,incp);
		qupd();
#else
#ifdef CRAY
 		MKTRN(inct,incp);
		QUPD();
#else
       		mktrn_(inct,incp);
		qupd_();
#endif
#endif
	      }

              if (event.xbutton.window == win && event.xbutton.button == 5)  {
	        update_model = 0;
		*inct = 417; *incp = 5;
#if defined(VMS) || defined(UNDERSC)
		mktrn(inct,incp);
		qupd();
#else
#ifdef CRAY
 		MKTRN(inct,incp);
		QUPD();
#else
       		mktrn_(inct,incp);
		qupd_();
#endif
#endif
	      }

              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 && FRQ->ihasi) RedrawList(&frlist);
			}
			if (*incp) {
			   if (FRQ->ihasi) {
				drwspec();
				return (0);
			   } else if (nmrptr->ihsnmr) {
				click_nmr_spec(spect.current);
			   }
			} 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 (geo1ptr->ifmxav && geoFmax.current != -1) {
				*incp = 1 + geoFmax.index[geoFmax.current];
			}
			if (geo1ptr->ifrmav && geoFrms.current != -1) {
				*incp = 1 + geoFrms.index[geoFrms.current];
			}
			if (geo1ptr->idmxav && geoSmax.current != -1) {
				*incp = 1 + geoSmax.index[geoSmax.current];
			}
			if (geo1ptr->idrmav && geoSrms.current != -1) {
				*incp = 1 + geoSrms.index[geoSrms.current];
			}
			if (geo1ptr->ieav && geoE.current != -1) {
				*incp = 1 + geoE.index[geoE.current];
			}
			if (*incp) {
			   pnt->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 == winrama && ramaup) {
		 if (event.xbutton.button == 1 || event.xbutton.button == 2) {
		    int i,j,itmp,ftmp,rtmp;
		    i = FindSel(NULL,RamaStru.x,RamaStru.y,0,RamaStru.npts,
			event.xbutton.x,event.xbutton.y,GLTOL);
		    if (i >= 0 && i < calfptr->ncalf) {
			j = (calfptr->iamino[i])-1;
			if (j >= 0 && j < MXRES) {
			   sprintf(pchgtmp,"%s %d\0",
				AminoAcids[j],calfptr->irsnr[i]);
			   XSetBackground(display, gc, colors[15]);
			   XSetForeground(display, gc, colors[0]);
			   XDrawImageString(display, winrama, gc, 
				rwi-100, rhi-10, pchgtmp, strlen(pchgtmp));

			   itmp = *ivdwpl;
			   ftmp = *fancy;
			   *ivdwpl = 1;
			   *fancy = 1;
			   calfptr->reson[i] = 1;
			   rtmp = i+1;
			   if (*backb) actami_(&rtmp,&ZERO,&ONE,&ZERO);
#ifdef DOGL
			   ogres(i+1,1,0);
#endif
			   *ivdwpl = itmp;
			   *fancy = ftmp;
			   if (RamaStru.current != -1) {
				j = RamaStru.current;
				rtmp = j+1;
				if (*backb) {
					calfptr->reson[j] = 0;
					actami_(&rtmp,&ZERO,&ZERO,&ZERO);
				}
#ifdef DOGL
				ogres(j+1,1,0);
#endif
				if (calfptr->iamino[j] == 1) {
				   DrawTriangle(0.0,0.0,
				   RamaStru.x[j],RamaStru.y[j],
				   6,3,1,0);
				} else if (calfptr->iamino[j] == 15) {
				   DrawTriangle(0.0,0.0,
				   RamaStru.x[j],RamaStru.y[j],
				   6,4,1,0);
				} else {
				   DrawBox(0.0,0.0,
				   RamaStru.x[j],RamaStru.y[j],
				   6,3,1,0);
				}
			   }
			   dispsf();
			   if (calfptr->iamino[i] == 1) {
				DrawTriangle(0.0,0.0,
				RamaStru.x[i],RamaStru.y[i],
				6,0,0,0);
			   } else if (calfptr->iamino[i] == 15) {
				DrawTriangle(0.0,0.0,
				RamaStru.x[i],RamaStru.y[i],
				6,0,0,0);
			   } else {
				DrawBox(0.0,0.0,
				RamaStru.x[i],RamaStru.y[i],
				6,0,0,0);
			   }
			   RamaStru.current = i;
			}
#ifndef DOGL
			return(0);
#endif
		    }
		 }
	      }

              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) {
			xyzp->ityp[ATMsel] = ffsgn[*fftyp]*(fftlist.select + 1);
		    } else {
			if (xyzp->ianz[ATMsel] == 
				ffatnr[*fftyp][fftlist.select]) {
			   xyzp->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 (xyzp->ianz[ATMsel] == 
				ffatnr[*fftyp][fftlist.select]) {
			   xyzp->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 (xyzp->iaton[pmfat1] == 1) xyzp->iaton[pmfat1] = 3;
		 else xyzp->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 (xyzp->iaton[pmfat2] == 1) xyzp->iaton[pmfat2] = 4;
		 else xyzp->iaton[pmfat2] = 1;
	    	 update_sel = 1;
                 return(0);
	       }
	      }

              if (event.xbutton.window == MLTwin ) {

	       if (PressList(&mltlist,event.xbutton.x, event.xbutton.y)) {
		 mfdata->imol = mltlist.select + 1;
		 if (mfdata->imol > ntits) mfdata->imol = ntits;
		 WinName(win,mlftit[mltlist.select]);
		 DowinC = 1; DoactC = 1; DoactMC = 1;
#if defined(VMS) || defined(UNDERSC)
		 curs(&ONE);
#else
#ifdef CRAY
	 	 CURS(&ONE);
#else
		 curs_(&ONE);
#endif
#endif
		 *inct = 481;
		 *incp = addfile;
                 return(0);

	       }

	      }

              if (event.xbutton.window == fsel.win ) {

		if (FileSelectBP(&fsel) == 1) return(0);

              }

	      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,ntnkb,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],3,
                                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[QATOM].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],nspqbox,
                                event.xbutton.x,event.xbutton.y);
                        if (i>=0) {
			    int j;
			    for (j=0; j<nspqbox; 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 == FLRwin) {
		 i = Clickwin(flrbut,NBUTSF,event.xbutton.x, event.xbutton.y,1);
                 if (i>=0) {
			if (ButtonsFLR(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;
			}
		    }
		    if (ScrollPage(NULL,&dptscr[0],event.xbutton.x,
			event.xbutton.y)) {
		    }
	      }

	      if (event.xbutton.window == OMAPwin) {
		    update_model = 0;
		    i = Clickwin(butomap,3,event.xbutton.x, event.xbutton.y,1); 
		    if (i>=0) {
                        switch (i) {
			case 0:
			   XSync(display, False);
			   XDestroyWindow(display,OMAPwin);
			   XSync(display, False);
			   omapfol = 0;
			   omapCa = -1;
			   if (omaplck) {
		   		for (i=0; i<3; i++) rotptr->t[i] = omapt[i];
				omaplck = 0;
			   }
			   OMAPup = 0;
#ifdef DOGL
			   DeleteSurface(omapsrf);
			   deletebox();
#endif
			   update_struct();
			   break;
			case 1: 
			   omapcnt1 = atof(qboxes[QCNT].str);
			   if (omapPandN) omapcnt2 = atof(qboxes[QCNT2].str);
			   disp_map(NULL);
			   break;
			case 2: 
			   TogBut(&butomap[2]);
			   if (omapfol) {
				omapfol = 0;
		   		for (i=0; i<3; i++) rotptr->t[i] = omapt[i];
				update_struct();
			   } else {
				if (!omaphlp) {
			           if (DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
				"Use space bar to lock/unlock\nDensity volume",0)) {}
				   omaphlp = 1;
				   RedrawOMAP();
				}
				omapfol = 1;
		   		for (i=0; i<3; i++) {
				   int i2;
				   omapt[i] = rotptr->t[i];
				   i2 = 1 + 2*i;
				   omaprat[i2] = 25.0/(float) comsrfptr->r[i];
				   omapwpos[i2] = 
					(int) ((float) omapwn[i2]*omaprat[i2]);
				   RedrawSlide(&omapscr[i2]);
				}
			   }
		   	   UpdateSLAB1();
		   	   UpdateSLAB2();
		   	   UpdateSLAB3();
			   update_struct();
			   break;
			}
		    } else {
			if (ClickBox(&qboxes[QCNT],1, 
				event.xbutton.x,event.xbutton.y) >= 0) {
				qboxes[QCNT].active = 1;
				qboxes[QCNT2].active = 0;
				RedrawOMAP();
			}
			if (ClickBox(&qboxes[QCNT2],1, 
				event.xbutton.x,event.xbutton.y) >= 0) {
				qboxes[QCNT2].active = 1;
				qboxes[QCNT].active = 0;
				RedrawOMAP();
			}
		    }
		    for (i=0; i<6; i++) {
			if (SlideScroll(&omapscr[i],event.xbutton.x,
				event.xbutton.y)) {
			}
		    }
	      }

	      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,6,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsSRF(i)) idum1 = 0;
		 }
	      }

              if (event.xbutton.window == MLTwin) {
	         update_model = 0;
		 i = Clickwin(mltbut,1,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsMLT(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,3,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsCHG(i)) return(0);
		 }
	      }

              if (event.xbutton.window == STRwin) {
	         update_model = 0;
		 i = Clickwin(strbut,5,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsSTR(i)) return(0);
		 } else {
			if (PressList(&strlist,
				event.xbutton.x, event.xbutton.y)) {

			    if (istruct > -1) SaveActiveStruct();

			    if (strlist.select < nstruct) {
				istruct = strlist.select;
				NewActiveStruct();

				/*DebugStructure();*/

  				update_sel = 1;
				doclr();
				if (NMols[istruct] == -1) update_model = 1;
				update_struct();
				if (ntits > 1) {
				   initMLT();
				} else {
				   if (MLTup) {
		    			XDestroyWindow(display,MLTwin);
					MLTup = 0;
				   }
				}
			    }
			}
			if (PressList(&str2list,
				event.xbutton.x, event.xbutton.y)) {

			    if (str2list.select < nstruct) {
				sstruct = str2list.select;
			    }
			}
		 }
	      }

              if (event.xbutton.window == STRCwin) {
	         update_model = 0;
		 i = Clickwin(strcbut,STRCBN,event.xbutton.x, event.xbutton.y,1);
		 if (i>=0) {
			if (ButtonsSTRC(i)) return(0);
		 } else {
			if (PressList(&strclist,
				event.xbutton.x, event.xbutton.y)) {

				dispsf();
			}
		 }
	      }

              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,
					&mfdata->imol,0) == -1) break;
				 WinName(win,mlftit[mfdata->imol]);
				 mfdata->imol++;
				 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;
				}
*/
				if (!MLTup) initMLT();
				break;
                 case BSOLID: 
			      update_sel = 1;
			      if (!TogBut(&cbut[BSOLID])){
				LSSTRU List;
				List.list = vdwstr ; List.nents = 3;
				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;
				   *fancy = 1;
				   ndmtmp = monptr->ndm;
				   if (*fancy || *fullgl) {
#if defined(VMS) || defined(UNDERSC)
					ogmon();
#else
#ifdef CRAY
					OGMON();
#else
					ogmon_();
#endif
#endif
				   }
/*
 clrmon clears created connections, and sets ndm zero
 it DOES NOT clear the monitor array
*/

#if defined(VMS) || defined(UNDERSC)
					clrmon();
#else
#ifdef CRAY
					CLRMON();
#else
					clrmon_();
#endif
#endif
				   monptr->ndm = ndmtmp;
				   ResetRes();
				}
			      } else {
				*incp = 1;
				*ivdwpl = 0;
				if (has_opengl) {
				   if (*fullgl) {
					*ifogl = 1;
				   } else {
					*ifogl = 0;
				   }
				} else {
				   *ifogl = 0;
				}
				*fancy = 0;
				if (has_opengl) {
				   if (*fullgl) {
#if defined(VMS) || defined(UNDERSC)
				      ogmon();
#else
#ifdef CRAY
				      OGMON();
#else
				      ogmon_();
#endif
#endif
				   } else {
/*
 domcon creates connections for ifogl!=1 and calls ogmon
*/

#if defined(VMS) || defined(UNDERSC)
				      domcon(&ONE,&ONE);
#else
#ifdef CRAY
				      DOMCON(&ONE,&ONE);
#else
				      domcon_(&ONE,&ONE);
#endif
#endif
				   }
				   ResetRes();
				}
			      }
			      *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<*xyzp->iatoms; i++) 
				   if (xyzp->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;
				*shade  = 0;
				*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(istruct,1);
				if (fsel.qbrfile) {
				   TogUp(&cbut[BREADF]);
				   fsel.qbrfile = 0;
				   XUnmapWindow(display,fsel.win);
				}
				if (ZMEup) UnMapZME();
				if (frfor && FRup) {
				   TogUp(&cbut[BFORC]);
				   XDestroyWindow(display,FrBox);
				   DoFreq = 0;
				   FRup = 0;
				   NMRup = 0;
				}
				if (frfor && specup) {
				   XDestroyWindow(display,winspec);
				   specup = 0;
				}
				if (distup) {
				   distup = 0;
				   XUnmapWindow(display,DISTwin);
				}
		 		if (STRCup) {
				    XDestroyWindow(display,STRCwin);
				    STRCup = 0;
				}
		 		if (OMAPup) {
				    XDestroyWindow(display,OMAPwin);
				    OMAPup = 0;
				    omapr = 0;
#ifdef DOGL
				    deletebox();
#endif
				}
				gl2DInit();
				break;

                 case BQUITT: 
				update_model = 0;
				if (!DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
					" Are you sure to quit?  ",1)) {
				   FreeAll(1);
#ifdef DOGL
#ifdef GL_ARB_shader_objects
				   if (has_shader) del_shader();
#endif
#ifdef GL_COLOR_ATTACHMENT0_EXT
				   if (has_fbo) del_fbo(&fbo);
#endif
#endif
				   XFreeGC(display, gc);
				   XCloseDisplay(display);
				   exit(0);
				   *inct = 15;
				}
				break;

                 case BSURF: {
				int itmp;
				LSSTRU List;
				if (ISOup) break;
#ifdef MPFIT
				List.list = pots; List.nents = 19;
#else
				List.list = pots; List.nents = 18;
#endif
				if (DoPopUp(winMC,
				   cbut[BSURF].x+1,cbut[BSURF].y-20,
				   &List,&itmp,0) == -1) break;
				RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
				if (itmp == 7) {
				   if (DoCan(event.xbutton.x_root,
					event.xbutton.y_root,
					"This will take a while",1)) {
					break;
				   }
				}
				if (itmp == 0 || itmp == 1 || itmp == 7 || itmp == 8) {
				   List.list = surftyp; List.nents = 2;
		   		   if (itmp == 1) List.nents = 3;
				   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 == 7 || itmp == 8) {
						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();
					   }
					}
				   }
		   		   if (surface->istyp == 2) {
				   	   int kcoo,kcooh;
#if defined(VMS) || defined(UNDERSC)
					   chkcoo(&kcoo,&kcooh);
#else
#ifdef CRAY
					   CHKCOO(&kcoo,&kcooh);
#else
					   chkcoo_(&kcoo,&kcooh);
#endif
#endif
					   *pol  =  0.085;
					   *pol2 = -0.07;
					   *ipsa = 1;

					   if (kcooh) {
#if defined (_WIN32) || defined(_WIN64)
			   		   if (DoCan(XX,YY,
#else
			   		   if (DoCan(event.xbutton.x_root,
						   	event.xbutton.y_root,
#endif
				"Molecule contains -COOH group !\nThis should be deprotonated",0)) {}
					   }
		   		   }
				   RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
				}
				if (itmp == 3) {
				    double tsa,psa;

#if defined(VMS) || defined(UNDERSC)
				    tpsa();
#else
#ifdef CRAY
				    TPSA();
#else
				    tpsa_();
#endif
#endif
				    doret = 0;
				    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 == 5) {
				   qboxstr(&qboxes[QSRFW],NULL,1,0,-1,
				    DEFQX,DEFQY,QBOXWIDE,QBOXHIGH,0,
				    "Surface Filename ? ",NULL,0,0,
				    575,dummyproc);
				    break;
				}
				if (itmp == 11) {
				   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(1);
				   break;
				}
				if (itmp == 12) {
#if defined(VMS) || defined(UNDERSC)
				   clqgas(&calfptr->ishoh);
#else
#ifdef CRAY
				   CLQGAS(&calfptr->ishoh);
#else
				   clqgas_(&calfptr->ishoh);
#endif
#endif
				   break;
				}
				if (itmp == 14) {
				    List.list = srfopt; List.nents = 2; int iii;
				    if (DoPopUp(winMC,cbut[BSURF].x-8,
					cbut[BSURF].y+14*LINEHIGH,&List,&iii,0) == -1) break;
				    if (iii) {
					molsrf(iii,0,1);
				    } else {
					if (DoPopUp(winMC,
					      cbut[BSURF].x-8,cbut[BSURF].y+BUTTH,
					      NULL,&iii,0) == -1) break;
					molsrf(iii,0,0);
				    }
				    break;
				}
				if (itmp == 15) {
				    if (omap()) break;
				    break;
				}
				if (itmp == 16) {
				   if (OMAPup) DeleteOMAP();
				   qboxstr(&qboxes[QSRFW],NULL,1,0,-1,
					DEFQX,DEFQY,QBOXWIDE,QBOXHIGH,0,
					"GRID kont Filename ? ",NULL,0,0,
					586,dummyproc);
				    break;
				}
				if (itmp == 17) {
			   	   createRama();ramaup=1;
				}
#ifdef DOGL
				*incp = 0;
				if (itmp == 6) {
#if defined(VMS) || defined(UNDERSC)
				   srfclr();
#else

#ifdef CRAY
				   SRFCLR();
#else
				   srfclr_();
#endif

#endif
				   dispsf();
				}
#endif
				if (itmp == 13) {
				   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 == 18) {
				    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 = 5;
					if (DoPopUp(winMC,
					     cbut[BHYD].x+1,cbut[BHYD].y+BUTTH,
					     &List,&itmp,0) == -1) break;
					if (itmp != 2 && itmp != 3 && 
					    itmp != 4) TogDown(&cbut[BHYD]);

					if (itmp == 3) InitPar();
					else if (itmp == 4) {
#if defined(VMS) || defined(UNDERSC)
					   curs(&ONE);
					   opthyd();
					   curs(&ZERO);
#else
#ifdef CRAY
					   CURS(&ONE);
					   OPTHYD();
					   CURS(&ZERO);
#else
					   curs_(&ONE);
					   opthyd_();
					   curs_(&ZERO);
#endif
#endif
					   doret = 0;
					}
					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,
					589,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 (! cell->ichx) {
#if defined(VMS) || defined(UNDERSC)
					mkcell(xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,
#else
#ifdef CRAY
					MKCELL(xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,
#else
					mkcell_(xyzp->coo,xyzp->ianz,xyzp->iatclr,xyzp->iconn,
#endif
#endif
				   &cell->natc,&cell->icent,&cell->inorm,&cell->nspg,
				   &cell->nopr,cell->ir,cell->it,
				   &cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
				   &cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
				   &cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
				   &cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);
					cell->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 { 
				update_model = 0;
				if (frfor) {
				   if (FRup) {
                                           XDestroyWindow(display,FrBox);
					   if (specup) {
					      XDestroyWindow(display,winspec);
					      specup = 0;					
					   }
					   *inct = 520;
					   DoFreq = 0;
					   FRup = 0;
				           TogUp(&cbut[BFORC]);
				   } else {
					   if (FRQ->nfreq) createfr(1);
					   createspec(1);
					   DoFreq = 1;
					   if (FRQ->nfreq) FRup = 1;
				           TogDown(&cbut[BFORC]);
				   }
				} else {
				   *incp = TogBut(&cbut[BFORC]);
				   *inct = 130;
				   if (*fancy || *fullgl) ogforces();
				   update_struct();
				}
			      }
                              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 {
				doret = 0;
				scalptr->fscal = scalptr->fscal*1.5;
				scalptr->fscal = MAXI(scalptr->fscal,0.01);
#if defined(VMS) || defined(UNDERSC)
				parfc();
#else
#ifdef CRAY
				PARFC();
#else
				parfc_();
#endif
#endif
				update_model = 0;
				if (*fancy || *fullgl) ogforces();
				update_struct();
			      }
                              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;

					sndon(iop,1,*Snstr);

				 } else {

/* switch OFF helix/strand/.. or hetatm */

					*Snstr = 1;
					sndoff(iop);
#ifdef DOGL
					ogbck(iop);
#endif
				 }
				 *inct = 330; 
				}
			      }
                              else {
				doret = 0;
				scalptr->fscal = scalptr->fscal/1.5;
				scalptr->fscal = MAXI(scalptr->fscal,0.01);
#if defined(VMS) || defined(UNDERSC)
				parfc();
#else
#ifdef CRAY
				PARFC();
#else
				parfc_();
#endif
#endif
				update_model = 0;
				if (*fancy || *fullgl) ogforces();
				update_struct();
			      }
			      break; 

                 case BUNSC:  if (pdb) {*inct = 340;
					TogBut(&cbut[BUNSC]);}
                              else {
				doret = 0;
				scalptr->fscal = 1.0;
#if defined(VMS) || defined(UNDERSC)
				parfc();
#else
#ifdef CRAY
				PARFC();
#else
				parfc_();
#endif
#endif
				update_model = 0;
				if (*fancy || *fullgl) ogforces();
				update_struct();
			      }
                              break;

                 case BHBOND: if (pdb) {
                                int ict;

			        TogBut(&cbut[BHBOND]);
				if (!hbon) { 
				   hbon = 1;
				   ict = 490;
				   if (*ipdbon && *zmptrp->ihaszm) ict = 626;
				   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 && *zmptrp->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 == 14 && cell->ichx) {
				   List.list = ambwopts; List.nents = 2;
				   if (DoPopUp(winMC,
					cbut[BWRITF].x+1,cbut[BWRITF].y+BUTTH,
					&List,&pbc->icell,0) == -1) break;
				   if (pbc->icell == 1) {
#if defined(VMS) || defined(UNDERSC)
				fdat(&EIGHTEEN,&ZERO,&ZERO,&ZERO,&ZERO,&ZERO);
#else
#ifdef CRAY
				FDAT(&EIGHTEEN,&ZERO,&ZERO,&ZERO,&ZERO,&ZERO);
#else
				fdat_(&EIGHTEEN,&ZERO,&ZERO,&ZERO,&ZERO,&ZERO);
#endif
#endif
		   		   }
			      }
			      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: 
				doret = 0;
				if (fsel.qbrfile) {
				   TogUp(&cbut[BREADF]);
				   fsel.qbrfile = 0;
				   XUnmapWindow(display,fsel.win);
				}
				else {
				   TogDown(&cbut[BREADF]);
				   fsel.qbrfile = 1;
				   FileSelectList(&fsel);

				   TogDown(&dbut[BMOL]);
				   TogDown(&dbut[BCONT]);
				   TogUp(&dbut[BFILL]);
				   TogUp(&dbut[BORI]);
				}
			        update_model = 0;
				break;

                 case BZMAT:    if (ZMEup) {
				   UnMapZME();
				}
				else {
				   if (pdb && !*zmptrp->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:
				doret = palette();
				break;

                 case BGIF:
                              { setgif(1);
				doret = 0;
				break;}
                 case BLABEL:  
				if (cbut[BLABEL].toggle) {
				   LSSTRU List;
				   List.list = labels; 
				   List.nents = 6;
				   if (nmrptr->ihsnmr) {
					List.nents = 7;
					if (DoPopUp(winMC,
					cbut[BLABEL].x+1,cbut[BLABEL].y-20,
					&List,&qdpptr->iqon,0) == -1) break;
				   } else {

					if (DoPopUp(winMC,
					cbut[BLABEL].x+1,cbut[BLABEL].y,
					&List,&qdpptr->iqon,0) == -1) break;
				   }
				   if (qdpptr->iqon == 3 && !qdpptr->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) {
				   cellpnt->iclon = 0;
                                   *backb = 1; 
                                   ActBut(&cbut[BFORC],1);
                                   ActBut(&cbut[BINCRF],1);
                                   ActBut(&cbut[BHBOND],1);
                                   ActBut(&cbut[BDECRF],1);
                                   ActBut(&cbut[BUNSC],1);
			           preset();
                               }
                               else {
                                   *backb = 0;
                                   ActBut(&cbut[BFORC],0);
                                   ActBut(&cbut[BINCRF],0);
                                   ActBut(&cbut[BDECRF],0);
                                   ActBut(&cbut[BUNSC],0);
                                   ActBut(&cbut[BHBOND],0);
				   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 < *xyzp->iatoms; i++ ) 
					xyzp->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 (geo1ptr->gcvav) {
				        TogDown(&cbut[BGEOM]);
					creategeom();
					geoup = 1;
				    }
			       }
                               else {
				    TogUp(&cbut[BGEOM]);
                                    XDestroyWindow(display,wingeo);geoup = 0;}
                               break;}
                 case BJCPL:  
			        update_model = 0;
                                if (!Selecting && !cflag && !dflag) {
				   *inct = 170;*incp = 1; 
				   aflag = 2;anum = 2;acnt = 0; eflag = 1;
				   XDefineCursor(display,win,AtomCursor);
				}
                                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 (geo1ptr->gcvav) {
			if (geo1ptr->ifmxav) parse_motion(&geoFmax);
      			if (geo1ptr->ifrmav) parse_motion(&geoFrms);
			if (geo1ptr->idmxav) parse_motion(&geoSmax);
			if (geo1ptr->idrmav) parse_motion(&geoSrms);
			if (geo1ptr->ieav) parse_motion(&geoE);
		}
	      }

              if(event.xmotion.window == win && ZoomSelection) {


                 while(XCheckTypedWindowEvent(display, win, MotionNotify,
                                        &event));
		 if ( !(has_opengl && (*fancy || *fullgl))) {
                    XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);
		 }

                 MotionCount++;

                 /* 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);
		 if (has_opengl && (*fancy || *fullgl)) {
#ifdef DOGL
		    rubber(1);
#endif
		 } else {
                    XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);
		 }

              } /* end ZoomSelection */

                                                                                
           } /* end MotionNotify */
           break;


           case ButtonRelease: {

              if (!((*fancy || *fullgl) && 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;

		 if (has_opengl && (*fancy || *fullgl)) {
		    dispsf();
		 } else {
                    XDrawRectangle(display, win, gc,
                                ZoomX1, ZoomY1, ZoomW, ZoomH);
                    XSetFunction(display, gc, GXcopy);
		 }
                 XUndefineCursor(display, win);

                 if (MotionCount >=3 ) {
                    for ( i = 0; i < *xyzp->iatoms; i++ ) {
                      if (xyzp->iaton[i] >= 1 && 
                      VIERKANT(xyzp->iyp[i], xyzp->ixp[i], 
				ZoomX1, ZoomY1, ZoomW, ZoomH)) {
                         if (Select && xyzp->ianz[i] != 100) xyzp->iaton[i] = 2;
                         else xyzp->iaton[i] = 1;
                      }
                    }
		    if (SelRes != -3) {
			for ( i = 0; i < *xyzp->iatoms; i++ ) {
			   if (xyzp->iaton[i] > 1) {
				xyzp->iresid[i] = SelRes;
	   			xyzp->iatclr[i] = xyzp->iatclr[ATMsel];
				xyzp->iaton[i] = 1;
			   }
			}
			SelRes = -3;
		    }
	    	    update_model = 0;
	    	    update_sel = 1;
                    return(0);
                 }

              } /* end zoom */

              if (( (*fancy || *fullgl) && 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 || *fullgl) && has_opengl) 
			&& event.xexpose.window == win) {
                 if ( molback == molcur ) {
                    XCopyArea(display,molcur,win,gc,0,0,width,height,0,0);
                 }
              }

              if (((*fancy || *fullgl)  && 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 == FLRwin) RedrawFLR();
	      if (event.xexpose.window == RESwin) RedrawRESwin();
	      if (event.xexpose.window == fsel.win) RedrawFwin(&fsel);
	      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 == OMAPwin) RedrawOMAP();
              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 == MLTwin) RedrawMLT();
	      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 == STRwin && STRup)
		   RedrawSTR();

              if (event.xexpose.window == STRCwin && STRCup)
		   RedrawSTRC();

              if (event.xexpose.window == winrama && ramaup) {
		   if ( rwiold != rwi || rhiold != rwi) {
	              if (event.xexpose.count == 0) {
			  XResizeWindow(display, winrama, rwi, rwi);
			  rwiold = rwi; rhiold = rhi;
		      }
		   }
		   DrawRama();
	      }

              if (event.xexpose.window == wingeo && geoup) {

		   while(XCheckTypedWindowEvent(display,wingeo,
				Expose,&report));
		   XClearWindow(display,wingeo);

#if defined(VMS) || defined(UNDERSC)
                   drwgeo();
#else
#ifdef CRAY
                   DRWGEO();
#else
                   drwgeo_();
#endif
#endif
	      }

           }
           break;

	   case MapNotify: {
	      if (event.xmap.window == expldat.win && 
		event.xmap.send_event == True) 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 == fsel.win) {
			if (fsel.qbrfile) {
			    TogUp(&cbut[BREADF]);
			    fsel.qbrfile = 0;
			    XUnmapWindow(display,fsel.win);
			}
		    } 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;
#if defined(VMS) || defined(UNDERSC)
			    resfr();
			    doconn();
#else
#ifdef CRAY
			    RESFR();
			    DOCONN();
#else
			    resfr_();
			    doconn_();
#endif
#endif
       		      	    *normc = 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 == winrama) {
			if (ramaup) {
			    XDestroyWindow(display,winrama);
			    ramaup = 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 == SRFwin) {
			if (SRFup) {
			    XDestroyWindow(display,SRFwin);
			    SRFup = 0;
			}
		    } else if (client_event->window == MLTwin) {
			if (MLTup) {
			    XDestroyWindow(display,MLTwin);
			    MLTup = 0;
			}
		    } else if (client_event->window == winau) {
			if (gijsup) {
			    XFreePixmap(display,gijs);
			    XDestroyWindow(display,winau);
			    gijsup = 0;
			}
		    } else if (client_event->window == STRwin) {
			if (DoCan(width/2, height/2,
				"This window is essential",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*/

	      while(XCheckTypedWindowEvent(display, 
		event.xconfigure.window, ConfigureNotify,&event));

              if (event.xconfigure.window == win) {

		   /* check for real resize */

                   if (event.xconfigure.width == width &&
                       event.xconfigure.height == height) {
			if (has_opengl && (*fancy || *fullgl)) {
#ifdef DOGL
			    /*glXSwapBuffers(display, win);*/
dispsf();
#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 || *fullgl)) Reshape(1);
                   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);
			if (i >= 2) 
			    spbut[i].x = SPECWIDE + (spbut[i].x - spoldw);
		   }
		   for (i=0; i<nspqbox; i++) 
			qboxes[QHW+i].y = SPECHIGH + (qboxes[QHW+i].y - spold);
		   drwspec();
              }

              if (event.xconfigure.window == wingeo) {

		   nhframes = 1;
		   if (geo1ptr->ifmxav || geo1ptr->ifrmav) nhframes = 2;
		   nwframes = 1;
		   if (geo1ptr->idmxav || geo1ptr->idrmav) nwframes = 2;

		   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);
              }

              if (event.xconfigure.window == winrama) {

		   rwi = event.xconfigure.width;
		   rhi = event.xconfigure.height;

		   if (rwi < rhi) {
			rhi = rwi;
		   } else {
			rwi = rhi;
		   }

		   if (rwi > DisplayWidth(display,screen) ||
		       rhi > DisplayHeight(display,screen)) {
			if (DisplayWidth(display,screen) > 
			    DisplayHeight(display,screen)) {
				rwi = rhi = DisplayHeight(display,screen);
			} else {
				rwi = rhi = DisplayWidth(display,screen);
			}
		   }

                   size_hints.flags  = PSize;
                   size_hints.width  =  rwi;
                   size_hints.height  =  rwi;
                   XSetNormalHints(display, winrama, &size_hints);
              }
           }
           break;

           case UnmapNotify:         break;

           default: break;		/* ignore unexpected events */

        }  /* end switch event type*/


    }/* end while */

#ifdef DOGL
    if ((has_opengl && (
	(!(*fancy || *fullgl) && !moving ) || 
	( (*fancy || *fullgl) && !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");
*/
    if (getenv("DISPLAY") == NULL) putenv("DISPLAY=127.0.0.1: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")) {
	if (*istaro) {
	   StarNetOld = 1;
	} else {
	   StarNet = 1;
	   fprintf(stderr,"\nWith older versions of StarNet X-Win32\n");
	   fprintf(stderr,"(6.1 and older) use the -Q commandline flag\n\n");
	}
    }

    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

    Aspect = (float) width / (float) height;

    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))== NULL) {
       mfinfo = XQueryFont(display,XGContextFromGC(gc));}
    else {

       XSetFont(display,gc,mfinfo->fid);
    }

    labinfo = XLoadQueryFont(display,LFONT);

    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) ;

    initnthe();

#ifdef DOGL
    if (has_opengl) {
       if (strstr(ServerVendor(display),"StarNet") && !(*istaro)) 
	   *fullgl = 1;
       if (*fullgl) *ifogl = 1;
       glXMakeCurrent(display,win,cx);
       Reshape(0);
       const char *glExtensions = 
		(const GLubyte *) glGetString(GL_EXTENSIONS);
       if (strstr(glGetString(GL_VENDOR),"Tungsten")) DoMIPMAP = 0;
#ifdef GL_ARB_shader_objects
       if (! *noshad) {
	if (*doshad) has_shader = check_shader(glExtensions);
       }
#endif
#ifdef GL_COLOR_ATTACHMENT0_EXT
       if (! *noshad) {
	   has_fbo = init_fbo(&fbo,fbo_type,glExtensions);
	   if (!has_fbo) {
	      fbo_type = 4;
	      has_fbo = init_fbo(&fbo,fbo_type,glExtensions);
	   }
       }
#endif
       glClear(GL_COLOR_BUFFER_BIT);
       makeRasterFont(display);
       initOpengl();
       initthe();
       ogelem();
    }
#else
    *fullgl = 0;
#endif

    CreatewinC(DEFWINCGEOM);
    XSelectInput(display, winC, SubstructureNotifyMask | ExposureMask | 
				ButtonPressMask | 
				KeyPressMask | PointerMotionMask | 
				PointerMotionMask  |
				EnterWindowMask | LeaveWindowMask);
    CreatewinMC(DEFWINMCGEOM);
    XSelectInput(display, winMC, StructureNotifyMask | SubstructureNotifyMask |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);

    gsel.parse = 0;
    gsel.inct = 280;
#ifdef VMS
    strcpy(gsel.lastdir,"[]");
#else
    strcpy(gsel.lastdir,"./");
#endif
    strcpy(gsel.label,"Grid file:");
    gsel.pntr = gfile;

    FileSelect(&gsel);

    fsel.parse = 1;
    fsel.inct = 480;
#ifdef VMS
    strcpy(fsel.lastdir,"[]");
#else
    strcpy(fsel.lastdir,"./");
#endif

    FileSelect(&fsel);

    ZMEwin = CreateWindow("Zmatrix Editor","-0+0",ZMEWINW,ZMEWINH,infobg,infofg,(Window)0);
    XSelectInput(display, ZMEwin, 
		SubstructureNotifyMask | ExposureMask | KeyPressMask | 
		ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | 
		LeaveWindowMask | PointerMotionMask | EnterWindowMask);
    subZM = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],ZMEwin);

    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;
   }
   XDestroyImage(img);
}

static int isdraw = 0;

movexy(xval,yval)
float xval;
float yval;
{
#ifdef DOGL
  gstart_xlx = (xval-xoff)*scale*2.0 - 1.0;
  gstart_yly = (yval-yoff)*scale*2.0 - 1.0;

  if (*fullgl && !*ifdogl) {
	if (isdraw) glEnd();
	isdraw = 1;
	glBegin(GL_LINES);
  }
#endif

  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;

#ifdef DOGL

  gxlx = (xval-xoff)*scale*2.0 - 1.0;
  gyly = (yval-yoff)*scale*2.0 - 1.0;

  if (*fullgl && !*ifdogl) {
	if (isdraw) {
	   glVertex2f(gstart_xlx, gstart_yly);     
	   glVertex2f(gxlx,gyly);
	}
	gstart_xlx = gxlx;
	gstart_yly = gyly;
  } else {
#endif
	XDrawLine(display, molcur, gc, xlx, yly, start_xlx, start_yly);
#ifdef DOGL
  }
#endif

  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;
#ifdef DOGL
/*
  if (*fullgl && !*ifdogl) {
	gxlx = (xval-xoff)*scale*2.0 -1.0;
	gyly = (yval-yoff)*scale*2.0 -1.0;
	if (isdraw) {
	   glEnd();
	   isdraw = 0;
        }
#if defined(VMS) || defined(UNDERSC)
	drwstr(&gxlx,&gyly,strval,&nval);
#else
#ifdef CRAY
	DRWSTR(&gxlx,&gyly,strval,&nval);
#else
	drwstr_(&gxlx,&gyly,strval,&nval);
#endif
#endif
  } else {
*/
#endif
	XDrawString(display, molcur, gc, xlx, yly, strval, nval);
#ifdef DOGL
/*
  } 
*/
#endif

}

#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;
#ifdef DOGL
  if (*fullgl && !*ifdogl) {
	if (isdraw) {
	   glEnd();
	   isdraw = 0;
        }
	glLineWidth(*linpass);
   }
#endif
}

changepen(pen)

float pen;
{
  foreground_pixel = colors[(int)pen];

#ifdef DOGL
  if (*fullgl && !*ifdogl) {
	if (isdraw) {
	   glEnd();
	   isdraw = 0;
        }
	glColor3f(((GLfloat) colorr[(int) pen]) / 65535.0,
		  ((GLfloat) colorg[(int) pen]) / 65535.0,
		  ((GLfloat) colorb[(int) pen]) / 65535.0);
  } else {
#endif
	XSetForeground(display, gc, foreground_pixel);
#ifdef DOGL
  } 
#endif

}

#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;
}

static int v2d;

gl2DInit()
{

#ifdef DOGL
    if (*fullgl && !*ifdogl && !isgl2D) {
	v2d = width;
	if (v2d > height) v2d = height;
	glViewport(0,0,v2d,v2d);
        glXMakeCurrent(display,win,cx);
	glClearColor(0.0,0.0,0.0,1.0);
	glDisable(GL_LIGHTING);           
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLineWidth(1.0);
	glMatrixMode (GL_MODELVIEW);
	glLoadIdentity ();
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity ();
	gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
        glEnable(GL_COLOR_MATERIAL);
	glRasterPos2f(-1.0,-1.0);
	isdraw = 0;
	isgl2D = 1;
	if (StarNet) {
	   if (!glIsList(theDens)) {
		theDens = glGenLists(1);
		glNewList(theDens, GL_COMPILE_AND_EXECUTE);
	   }
	}
    }
#endif
}

gl2DEnd()
{
#ifdef DOGL
    if (*fullgl && !*ifdogl && isgl2D) {
	glEnd();
        glXSwapBuffers(display, win);
	if (StarNet) glDeleteLists(theDens,1);
        glDisable(GL_COLOR_MATERIAL);
        if (dogif && count > 0) {
           picnum++;
           if (picnum < *picmax) {
		glXWaitGL();
		sprintf(stemp, "%s%03d.gif",GifFile,picnum);
		WOGLGIF(stemp);
	   }
	}
	isgl2D = 0;
    }
#endif
}

void RedrawWin()
{
     int cnt = 0;
     int i;

     if (count <= 0) return;

#ifdef DOGL
     if (*fullgl) {
	gl2DInit();
     } else {
#endif
	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);
	}
#ifdef DOGL
     }
#endif

     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 */

#ifdef DOGL
     if (*fullgl) {
	gl2DEnd();
     } else {
#endif
        if ( molback == molcur ) 
		XCopyArea(display,molcur,win,gc,0,0,width,height,0,0);
#ifdef DOGL
     }
#endif

} /* 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)
void drawseg(segments,npoints,iinv)
#else
#ifdef CRAY
void DRAWSEG(segments,npoints,iinv)
#else
void 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)
void drwpol(points,npoints,icol,icon,isgrey)
#else
#ifdef CRAY
void DRWPOL(points,npoints,icol,icon,isgrey)
#else
void drwpol_(points,npoints,icol,icon,isgrey)
#endif
#endif

XPoint *points;
int *npoints;
int *icol;
int *icon;
int *isgrey;
{
/*  XPoint *tempp;*/

  if (!xison) return;

  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)
void plsph(xori,yori,fwidth,ia)
#else
#ifdef CRAY
void PLSPH(xori,yori,fwidth,ia)
#else
void 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);
	}
     }
}

void 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;
		if (qp->win == QBox) qboxup = 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) qdpptr->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 = 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);
}

void 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 (jobcom->ibatch) {
	TogUp(&sbut[SBATC]);
  } else {
	TogDown(&sbut[SBATC]);
  }

  if (jobcom->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: 
		jobcom->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;

		  lnkat = 0;

		  /* Counting the number of Link atoms between H and lower 
		     levels*/

		  ism = isl = 0;
		  for (j=0;j<*xyzp->iatoms;j++) {
	   	     if (xyzp->ityp[j] >= 20000) isl = 1;
	   	     if (xyzp->ityp[j] >= 10000 && xyzp->ityp[j] < 20000) ism = 1;
		     ionij = xyzp->ityp[j] / 10000;
		     if (ionij != 0) continue;
		     nconn = xyzp->iconn[j*(MXCON+1)];
		     for (k=1;k<=nconn;k++) {
		       if (xyzp->ityp[xyzp->iconn[j*(MXCON+1)+k]-1]/10000 > 0) lnkat++;
		     }
		  }
		  lnkat += 20000;
		  jobcom->itotc = jobcom->icopth;
		  jobcom->imult = jobcom->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 = jobcom->icoptm+3;
		  ispopt = jobcom->ispoptm-1;
		  if (ism == 0 && isl == 1) {
		     icopt = jobcom->icoptl+3;
		     ispopt = jobcom->ispoptl-1;
		  }

		}  else if (ioniom == 2) {

	          lnkat = 0;

		  /* Counting the number of Link atoms between H and 
		       lower levels*/

		 for (j=0;j<*xyzp->iatoms;j++) {
		         ionij = xyzp->ityp[j] / 10000;
			 if(ionij != 0) continue;
		         nconn = xyzp->iconn[j*(MXCON+1)];
		         for (k=1;k<=nconn;k++) {
		           if (xyzp->ityp[xyzp->iconn[j*(MXCON+1)+k]-1]/10000 > 0) lnkat++;
		         }
		  }
		  lnkat += 20000;
		  jobcom->itotc = jobcom->icopth;
		  jobcom->imult = jobcom->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;
*/
		  }
	          lnkat = 0;

		  /* Counting the number of Link atoms between H+M and 
		     lower levels*/

		  for (j=0;j<*xyzp->iatoms;j++) {
			ionij = xyzp->ityp[j] / 10000;
			if (ionij == 2) continue;
			nconn = xyzp->iconn[j*(MXCON+1)];
			for (k=1;k<=nconn;k++) {
			   if (xyzp->ityp[xyzp->iconn[j*(MXCON+1)+k]-1]/10000 == 2) lnkat++;
			}
		  }
		  lnkat += 20000;
		  jobcom->itotc = jobcom->icoptm;
		  jobcom->imult = jobcom->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 = jobcom->icoptl+3;
		  ispopt = jobcom->ispoptl-1;
		}
		lnkat = 0;
		jobcom->itotc = icopt - 3;
		jobcom->imult = ispopt + 1;
		jobcom->ito = itopt[jmode] + 1;
		jobcom->imo = imopt[jmode] + 1;
		jobcom->ibo = ibopt[jmode] + 1;
		jobcom->ihs = ihess;
#ifdef DOQUEUE
		jobcom->itm = quetims[qopt];
#else
		jobcom->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: 
		jobcom->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<*xyzp->iatoms;i++) {
	   if (xyzp->ityp[i] >= 20000) isl = 1;
	   if (xyzp->ityp[i] >= 10000 && xyzp->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 (jobcom->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 - (lnkat / 10000);
     lnkat -= (lnkat / 10000) * 10000;
   } else {
     lnkat = 0;
   }

   if (*zmptrp->ihaszm) {
	for (i=0; i<*zmptrp->nz; i++) {
	   if (ioniom && (xyzp->ityp[i]/10000 >= ionil)) continue;
	   if (zmptrp->ianz[i] >= 0 && zmptrp->ianz[i] < 99) {
		ne = ne + zmptrp->ianz[i];
	   }
	}
   } else {
      if (jobcom->iwxyz) {
	for (i=0; i<*xyzp->iatoms; i++) {
	   if (ioniom && (xyzp->ityp[i]/10000 >= ionil)) continue;
	   if (xyzp->ianz[i] >= 0 && xyzp->ianz[i] < 99) {
		ne = ne + xyzp->ianz[i];
	   }
	}
      } else {
	return(0);
      }
   }
/*
   fprintf(stderr,"ionil %d ne %d itotc %d lnkat %d mult %d\n",
                   ionil,ne,jobcom->itotc,lnkat,jobcom->imult);
*/
   ne = ne - jobcom->itotc + lnkat;
   if (ne % 2 == jobcom->imult % 2) return(1);
   return(0);
}

RedrawLBox(lp)
LISTSTRU *lp;
{
      int i,nen,isel;
      char drawstrc[44];

      drawstrc[43] = '\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);

      nen = MINI(lp->mxents,*lp->list.nents);
      if (lp->lpnt > *lp->list.nents - lp->mxents) {
	 lp->lpnt = *lp->list.nents - lp->mxents;
	 if (lp->lpnt < 0) lp->lpnt = 0;
      }

      for (i=0; i<nen; i++) {
	 isel = 0;
	 if (lp->list.slst != NULL) {
	   if (lp->list.slst[i+lp->lpnt]) isel = 1;
	 } else {
	   if (i+lp->lpnt == lp->select) isel = 1;
	 }
         if (isel) {
              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.2f",lp->lpnt+i+1,
			lp->list.flst[lp->lpnt+i]);
		  else
		  	sprintf(drawstrc,"%4d      %11.6f      %3.2f",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 && lp->list.flst == NULL) 
		  	   sprintf(drawstrc,"%4d      %11.6f      %s",
				lp->lpnt+i+1,lp->list.rlst[lp->lpnt+i],
				lp->list.list[lp->lpnt+i]);
		  	if (lp->list.rlst != NULL && lp->list.flst != NULL) 
		  	   sprintf(drawstrc,"%4d   %11.3f        %6.2f   %s",
				lp->lpnt+i+1,lp->list.rlst[lp->lpnt+i],
				lp->list.flst[lp->lpnt+i],
				lp->list.list[lp->lpnt+i]);
			else if (lp->list.rlst == NULL && 
				 lp->list.flst == NULL) {
			   if (lp->list.list[lp->lpnt+i] != NULL) 
			   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.2f",lp->lpnt+i+1,
			lp->list.flst[lp->lpnt+i]);
		  }
		  else {
		  	sprintf(drawstrc,"%4d      %11.6f      %3.2f",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 && lp->list.flst == NULL) 
		  	   sprintf(drawstrc,"%4d      %11.6f      %s",
				lp->lpnt+i+1,lp->list.rlst[lp->lpnt+i],
				lp->list.list[lp->lpnt+i]);
		  	if (lp->list.rlst != NULL && lp->list.flst != NULL) 
		  	   sprintf(drawstrc,"%4d   %11.3f        %6.2f   %s",
				lp->lpnt+i+1,lp->list.rlst[lp->lpnt+i],
				lp->list.flst[lp->lpnt+i],
				lp->list.list[lp->lpnt+i]);
			else if (lp->list.rlst == NULL && 
				 lp->list.flst == NULL) {
			   if (lp->list.list[lp->lpnt+i] != NULL) 
			   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,slist,nentries)
LISTSTRU	*lp;
Window		win;
int		x,y;
unsigned int	w,h;
int		mx;
char		*label;
char         **lstr;
float		*rlist;
double		*flst;
int		*slist;
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.slst = slist;
  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,NULL);

  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;
      if (lp->list.slst != NULL) {
	   if (lp->list.slst[lp->select]) {
		lp->list.slst[lp->select] = 0;
	   } else {
		lp->list.slst[lp->select] = 1;
	   }
      }
      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);
}

/**********************************************/
void 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;
  if (animptr.on || *movie) 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)));
}

void 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);
    XFillPolygon(display, bwin, gc, butc, 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 postscript 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";

  DefBut(&dbut[BGIF2],  winC, MSOFFX+BOFFX+90, MSOFFY+24+BUTTN*2, 22, 22, 
	   "Quit", infobg, CNTCOL);
  dbut[BGIF2].explstr = "Make a gif file of each screen update.";

  DefBut(&dbut[BLOCAL], winC, PLOFFX+BOFFX+65, PLOFFY+24, 60, BUTTH, 
	   "Local", infobg, CNTCOL);
  dbut[BLOCAL].explstr = "Boys localization of orbitals";

#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;

  dbut[BGIF2].pix = FotoPix;
  dbut[BGIF2].pw  = foto_width;
  dbut[BGIF2].ph  = foto_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";

  DefBut(&cbut[BJCPL],  winMC, CLOFFX+BOFFX+70, CLOFFY+5, 15, 15, 
	   "J", infobg, CNTCOL);
  cbut[BJCPL].explstr = "Calculate J coupling two atoms";

  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) || 
	        (i == BJCPL && nmrptr->ihsnmr != 2) ) )
	   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, "SulfurBridge",      FOFFX+BOFFX+20, FOFFY+38+BUTTN*3);
	LineString(winMC, "H-bonds",           FOFFX+BOFFX+20, FOFFY+38+BUTTN*4);
  } else {
	if (frfor) {
	   if (nmrptr->ihsnmr) {
		ULineString(winMC, "Spectrum:", FOFFX+BOFFX , FOFFY+15);
		LineString(winMC, "NMR Spectr."         , 
			FOFFX+BOFFX+20 , FOFFY+38);
	   } else if (*ihasex) {
		ULineString(winMC, "Spectrum:", FOFFX+BOFFX , FOFFY+15);
		LineString(winMC, "UV spectrum"         , 
			FOFFX+BOFFX+20 , FOFFY+38);
	   } else {
		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] [surf] 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 filecall(char *str)
{
	cpstr(str,gfile,SUBLEN1);
}

void fwincall(char *str)
{
	getfiles(&fsel,str);
	RedrawFwin(&fsel);
}

void substrcall(char *str)
{
	getfiles(&fsel,fsel.lastdir);
	RedrawFwin(&fsel);
}

void getpdbcall(char *str)
{
	if (!CheckWGET()) {
	    GetPDBWWW(qboxes[QPDB].str,strname);
	    if (ParseFile(strname,qboxes[QPDB].str)) return;
	}
}

RedrawFwin(fs)
FSELSTRU *fs;
{
  int i;

  XSetForeground(display, gc, infobg);
  if (fs->parse) {
	strncpy(qboxes[QREADF].str,fs->lastdir,MAXSTRLEN);
  } else {
	strncpy(qboxes[QREADF].str,fs->pntr,MAXSTRLEN);
  }
  PromptBox(&qboxes[QREADF]); 

  RedrawList(&fs->flist);
  RedrawList(&fs->dirlist);

  if (fs->parse) {
	for (i=0; i<NBUTTR; i++) DrwBut(&fs->rbut[i]);
	PromptBox(&qboxes[QPDB]); 
	PromptBox(&qboxes[QSUBSTR]); 
  } else {
	for (i=0; i<2; i++) DrwBut(&fs->rbut[i]);
  }

  ULineString(fs->win, "Files", 325, 55);
  ULineString(fs->win, "Directories", 325, 265);
  if (fs->parse) {
	LineString(fs->win, "Filter:", 322, 145);
	LineString(fs->win, "Replace", 350, 85);
	LineString(fs->win, "Add", 350, 110);
  }

}

#if defined(VMS) || defined(UNDERSC)
void prsogl()
#else
#ifdef CRAY
void PRSOGL()
#else
void prsogl_()
#endif
#endif
{
    selfil = 0;

    if (fsel.files[selfil][0] != '/') {
	strcpy(strname,fsel.lastdir);
#ifndef VMS
	if (strname[strlen(strname)-1] != '/') strcat(strname,"/");
#endif
	strcat(strname,fsel.files[selfil]);
    } else strcpy(strname,fsel.files[selfil]);

    ParseFile(strname,fsel.files[selfil]);
}

int ParseFile(strname,shortname)
char *strname;
char *shortname;
{
   int i;

#ifdef VMS
   for (i=0; i<strlen(strname); i++)
	Sstr->dsc$a_pointer[i] = strname[i];
#else
#ifdef CRAY
   strncpy(_fcdtocp(Sstr),strname,strlen(strname));
#else
   if (Sstr != NULL) strcpy(Sstr,strname);
#endif
#endif

   *Snstr = strlen(strname);
   *Sinct = qboxes[QREADF].qbinct;
   *Sincp = addfile;

   doalign = 0;
   *irtcel = 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;
        *normc = 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;
   }

   if (MLTup) {
	XDestroyWindow(display,MLTwin);
	MLTup = 0;
   }

   ZMEswitch[0].toggle = 1; ZMEAA = 0; EXPbox[0].fake = 1; 
   RedrawZME(); XSync(display,False);
   pdb = 0; oqlen = 0; oqpos = 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;
   FRQ->ihasi = 0;

   if (!addfile && *multstruct) {

	if (nstruct == MAXSTRUCT) {

	    if (!DoCan(event.xbutton.x_root,event.xbutton.y_root,
		"Reached maximum number supported structures",0)) {}

	} else {

	    if (nstruct == 0 && nfilesstart != 0) {
		AllocateStructure(&COO[0]);
		SaveFirstStruct();
		nstruct++;
	    }

	    AllocateStructure(&COO[nstruct]);

	    if (nstruct != 0) SaveActiveStruct();

	    if (COO[nstruct] == NULL) {
		   if (!DoCan(event.xbutton.x_root,event.xbutton.y_root,
			     "Failed to allocate memory for structure",0)) {}
	    } else {
		   AllocateSubStructures(shortname);
	    }
	}
   }

   ntits = 0;

   if (!addfile) {
	*backb = 0;
	empty_model(istruct,1);
   }

#if defined(VMS) || defined(UNDERSC)
   curs(&ONE);
#else
#ifdef CRAY
   CURS(&ONE);
#else
   curs_(&ONE);
#endif
#endif

   if (strstr(strname,".ogl")) {
	if (has_opengl) {
	    if (rdoglfile(strname)) return(0);
	}
#if defined(VMS) || defined(UNDERSC)
	curs(&ZERO);
#else
#ifdef CRAY
	CURS(&ZERO);
#else
	curs_(&ZERO);
#endif
#endif
	*Sinct = 0;
        return(0);

   } else {

  	update_sel = 1;
  	update_model = 1;
	RedrawFwin(&fsel);
        return(1);
   }

}

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);
}

DrawTriangle(x,y,xt,yt,r,icol,ifill,iconv)
double x;
double y;
int xt;
int yt;
int r;
int icol;
int ifill;
int iconv;
{
   int r2,r3,r6;
   XPoint box_Xpoint[5];

   r2 = 0.5 * r;
   r6 = 0.25*sqrt(6.0)*r;
   r3 = sqrt(3.0)*r/3.0;

   if (iconv) {
	glpnt(rwi,rhi,x,y,&xt,&yt,0);
   }

   box_Xpoint[0].x = xt;
   box_Xpoint[0].y = yt+r3;
   
   box_Xpoint[1].x = xt+r2;
   box_Xpoint[1].y = yt-r6;
   
   box_Xpoint[2].x = xt-r2;
   box_Xpoint[2].y = yt-r6;
   
   box_Xpoint[3].x = box_Xpoint[0].x;
   box_Xpoint[3].y = box_Xpoint[0].y;
   
   XSetForeground(display, gc, colors[icol]);
   if (ifill) {
	XFillPolygon(display,winrama,gc,box_Xpoint,3,
		Nonconvex,CoordModeOrigin);
   } else {
	XDrawLines(display,winrama,gc,box_Xpoint,4,CoordModeOrigin);
   }
}

DrawBox(x,y,xt,yt,r,icol,ifill,iconv)
double x;
double y;
int xt;
int yt;
int r;
int icol;
int ifill;
int iconv;
{
   int r2;
   XPoint box_Xpoint[5];

   r2 = 0.5 * r;

   if (iconv) glpnt(rwi,rhi,x,y,&xt,&yt,0);

   box_Xpoint[0].x = xt-r2;
   box_Xpoint[0].y = yt-r2;
   
   box_Xpoint[1].x = xt-r2;
   box_Xpoint[1].y = yt+r2;
   
   box_Xpoint[2].x = xt+r2;
   box_Xpoint[2].y = yt+r2;
   
   box_Xpoint[3].x = xt+r2;
   box_Xpoint[3].y = yt-r2;
   
   box_Xpoint[4].x = box_Xpoint[0].x;
   box_Xpoint[4].y = box_Xpoint[0].y;
   
   XSetForeground(display, gc, colors[icol]);
   if (ifill) {
	XFillPolygon(display,winrama,gc,box_Xpoint,5,
		Nonconvex,CoordModeOrigin);
   } else {
	XDrawLines(display,winrama,gc,box_Xpoint,5,CoordModeOrigin);
   }
}

createRama()
{
      rwi = 600; rhi = 600;
      winrama = CreateWindow("Ramachandran Plot",DEFCNV2GEOM,
              rwi,rhi, infobg, infofg,(Window)0);
      XSelectInput(display, winrama, ExposureMask | 
              ButtonPressMask | PointerMotionMask | StructureNotifyMask);
      XMapWindow(display, winrama);
      RamaStru.current = -1;

}

DrawRama()
{
      char *tmpptr;
      int xt,yt,qlen;
      int dum0,i,n,x1t,y1t,ioff;
      double scx,scy,x1,y1,x2,y2;
      XPoint rama_Xpoint1[150];

      n = calfptr->ncalf;

      if (RamaStru.npts < n && RamaStru.x != NULL) {
	free(RamaStru.x);
	free(RamaStru.y);
	free(RamaStru.index);
      }
      
      if (RamaStru.x == NULL || RamaStru.npts < n) {
	RamaStru.x = (int *) malloc((sizeof i)*n);
	RamaStru.y = (int *) malloc((sizeof i)*n);
	RamaStru.index =  (int *) malloc((sizeof i)*n);
      }
      RamaStru.npts = n;

	 butje(winrama,0,0, rwi,rhi,3,0,0,0,None,0,0,0);

         XSetForeground(display, gc, BlackPixel(display,screen));


         XDrawString(display,winrama,gc,rwi/2-13,rhi-10,
		"PHI (degrees)",13);

         XDrawString(display,winrama,gc,10,rhi/2,   "P",1);
         XDrawString(display,winrama,gc,10,rhi/2+10,"S",1);
         XDrawString(display,winrama,gc,10,rhi/2+20,"I",1);

	 glpnt(rwi,rhi,0.0,0.0,&xt,&yt,0);
	 rama_Xpoint1[0].x = xt;
	 rama_Xpoint1[0].y = yt;
	 glpnt(rwi,rhi,0.0,1.0,&xt,&yt,0);
	 rama_Xpoint1[1].x = xt;
	 rama_Xpoint1[1].y = yt;
	 glpnt(rwi,rhi,1.0,1.0,&xt,&yt,0);
	 rama_Xpoint1[2].x = xt;
	 rama_Xpoint1[2].y = yt;
	 glpnt(rwi,rhi,1.0,0.0,&xt,&yt,0);
	 rama_Xpoint1[3].x = xt;
	 rama_Xpoint1[3].y = yt;
	 glpnt(rwi,rhi,0.0,0.0,&xt,&yt,0);
	 rama_Xpoint1[4].x = xt;
	 rama_Xpoint1[4].y = yt;

	 XSetForeground(display, gc, colors[15]);
	 XFillPolygon(display,winrama,gc,rama_Xpoint1,5,
		Nonconvex,CoordModeOrigin);


	 for (i=0; i<108; i++) {
		x1 = (rama_area4[i][0]/360.0 + 0.5);
		y1 = (rama_area4[i][1]/360.0 + 0.5);
		glpnt(rwi,rhi,x1,y1,&x1t,&y1t,0);
		rama_Xpoint1[i].x = x1t;
		rama_Xpoint1[i].y = y1t;
	 }
	 rama_Xpoint1[108].x = rama_Xpoint1[0].x;
	 rama_Xpoint1[108].y = rama_Xpoint1[0].y;

	 XSetForeground(display, gc, colors[2]);
	 XFillPolygon(display,winrama,gc,rama_Xpoint1,108,
		Nonconvex,CoordModeOrigin);

	 for (i=0; i<67; i++) {
		x1 = (rama_area5[i][0]/360.0 + 0.5);
		y1 = (rama_area5[i][1]/360.0 + 0.5);
		glpnt(rwi,rhi,x1,y1,&x1t,&y1t,0);
		rama_Xpoint1[i].x = x1t;
		rama_Xpoint1[i].y = y1t;
	 }

	 rama_Xpoint1[67].x = rama_Xpoint1[0].x;
	 rama_Xpoint1[67].y = rama_Xpoint1[0].y;

	 XFillPolygon(display,winrama,gc,rama_Xpoint1,67,
		Nonconvex,CoordModeOrigin);

	 for (i=0; i<10; i++) {
		x1 = (rama_area6[i][0]/360.0 + 0.5);
		y1 = (rama_area6[i][1]/360.0 + 0.5);
		glpnt(rwi,rhi,x1,y1,&x1t,&y1t,0);
		rama_Xpoint1[i].x = x1t;
		rama_Xpoint1[i].y = y1t;
	 }

	 rama_Xpoint1[10].x = rama_Xpoint1[0].x;
	 rama_Xpoint1[10].y = rama_Xpoint1[0].y;

	 XFillPolygon(display,winrama,gc,rama_Xpoint1,10,
		Nonconvex,CoordModeOrigin);

	 for (i=0; i<28; i++) {
		x1 = (rama_area7[i][0]/360.0 + 0.5);
		y1 = (rama_area7[i][1]/360.0 + 0.5);
		glpnt(rwi,rhi,x1,y1,&x1t,&y1t,0);
		rama_Xpoint1[i].x = x1t;
		rama_Xpoint1[i].y = y1t;
	 }

	 rama_Xpoint1[28].x = rama_Xpoint1[0].x;
	 rama_Xpoint1[28].y = rama_Xpoint1[0].y;

	 XFillPolygon(display,winrama,gc,rama_Xpoint1,28,
		Nonconvex,CoordModeOrigin);

	 for (i=0; i<10; i++) {
		x1 = (rama_area8[i][0]/360.0 + 0.5);
		y1 = (rama_area8[i][1]/360.0 + 0.5);
		glpnt(rwi,rhi,x1,y1,&x1t,&y1t,0);
		rama_Xpoint1[i].x = x1t;
		rama_Xpoint1[i].y = y1t;
	 }

	 rama_Xpoint1[10].x = rama_Xpoint1[0].x;
	 rama_Xpoint1[10].y = rama_Xpoint1[0].y;

	 XFillPolygon(display,winrama,gc,rama_Xpoint1,10,
		Nonconvex,CoordModeOrigin);

	 for (i=0; i<10; i++) {
		x1 = (rama_area9[i][0]/360.0 + 0.5);
		y1 = (rama_area9[i][1]/360.0 + 0.5);
		glpnt(rwi,rhi,x1,y1,&x1t,&y1t,0);
		rama_Xpoint1[i].x = x1t;
		rama_Xpoint1[i].y = y1t;
	 }

	 rama_Xpoint1[10].x = rama_Xpoint1[0].x;
	 rama_Xpoint1[10].y = rama_Xpoint1[0].y;

	 XFillPolygon(display,winrama,gc,rama_Xpoint1,10,
		Nonconvex,CoordModeOrigin);

	 for (i=0; i<16; i++) {
		x1 = (rama_area1[i][0]/360.0 + 0.5);
		y1 = (rama_area1[i][1]/360.0 + 0.5);
		glpnt(rwi,rhi,x1,y1,&x1t,&y1t,0);
		rama_Xpoint1[i].x = x1t;
		rama_Xpoint1[i].y = y1t;
	 }
	 rama_Xpoint1[16].x = rama_Xpoint1[0].x;
	 rama_Xpoint1[16].y = rama_Xpoint1[0].y;

	 XSetForeground(display, gc, colors[1]);
	 XFillPolygon(display,winrama,gc,rama_Xpoint1,17,
		Nonconvex,CoordModeOrigin);

	 for (i=0; i<25; i++) {
		x1 = (rama_area2[i][0]/360.0 + 0.5);
		y1 = (rama_area2[i][1]/360.0 + 0.5);
		glpnt(rwi,rhi,x1,y1,&x1t,&y1t,0);
		rama_Xpoint1[i].x = x1t;
		rama_Xpoint1[i].y = y1t;
	 }
	 rama_Xpoint1[25].x = rama_Xpoint1[0].x;
	 rama_Xpoint1[25].y = rama_Xpoint1[0].y;

	 XFillPolygon(display,winrama,gc,rama_Xpoint1,25,
		Nonconvex,CoordModeOrigin);

	 for (i=0; i<108; i++) {
		x1 = (rama_area3[i][0]/360.0 + 0.5);
		y1 = (rama_area3[i][1]/360.0 + 0.5);
		glpnt(rwi,rhi,x1,y1,&x1t,&y1t,0);
		rama_Xpoint1[i].x = x1t;
		rama_Xpoint1[i].y = y1t;
	 }
	 rama_Xpoint1[108].x = rama_Xpoint1[0].x;
	 rama_Xpoint1[108].y = rama_Xpoint1[0].y;

	 XFillPolygon(display,winrama,gc,rama_Xpoint1,108,
		Nonconvex,CoordModeOrigin);

         XSetForeground(display, gc, BlackPixel(display,screen));
	 dum0 = 0;
         drwgl(winrama,rwi,rhi,0.0,0.0,1.0,0.0,dum0,dum0,0,0);
         drwgl(winrama,rwi,rhi,0.0,0.0,0.0,1.0,dum0,dum0,0,0);
         drwgl(winrama,rwi,rhi,0.0,1.0,1.0,1.0,dum0,dum0,0,0);
         drwgl(winrama,rwi,rhi,1.0,1.0,1.0,0.0,dum0,dum0,0,0);
         drwgl(winrama,rwi,rhi,0.0,0.5,1.0,0.5,dum0,dum0,0,0);
         drwgl(winrama,rwi,rhi,0.5,0.0,0.5,1.0,dum0,dum0,0,0);

	 scx = 12.0;
	 for (i=0; i<13; i++) {
		  x1 = ((double) i)/scx;
		  y1 = 0.0;
		  y2 = -0.02;
		  drwgl(winrama,rwi,rhi,x1,y1,x1,y2,dum0,dum0,0,0);
		  drwgl(winrama,rwi,rhi,y1,x1,y2,x1,dum0,dum0,0,0);
	 }

	 ioff = CHIGH/2;

	 glpnt(rwi,rhi,0.0,-0.04,&xt,&yt,0);
	 sprintf(stemp,"%d",-180);
	 qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
	 XDrawString(display,winrama,gc,xt-qlen/2,yt,stemp,strlen(stemp));

	 glpnt(rwi,rhi,0.25,-0.04,&xt,&yt,0);
	 sprintf(stemp,"%d",-90);
	 qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
	 XDrawString(display,winrama,gc,xt-qlen/2,yt,stemp,strlen(stemp));

	 glpnt(rwi,rhi,0.5,-0.04,&xt,&yt,0);
	 sprintf(stemp,"%d",0);
	 qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
	 XDrawString(display,winrama,gc,xt-qlen/2,yt,stemp,strlen(stemp));

	 glpnt(rwi,rhi,0.75,-0.04,&xt,&yt,0);
	 sprintf(stemp,"%d",90);
	 qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
	 XDrawString(display,winrama,gc,xt-qlen/2,yt,stemp,strlen(stemp));

	 glpnt(rwi,rhi,1.0,-0.04,&xt,&yt,0);
	 sprintf(stemp,"%d",180);
	 qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
	 XDrawString(display,winrama,gc,xt-qlen/2,yt,stemp,strlen(stemp));

	 glpnt(rwi,rhi,-0.04,0.0,&xt,&yt,0);
	 sprintf(stemp,"%d",-180);
	 qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
	 XDrawString(display,winrama,gc,xt-qlen/2,yt+ioff,stemp,strlen(stemp));

	 glpnt(rwi,rhi,-0.04,0.25,&xt,&yt,0);
	 sprintf(stemp,"%d",-90);
	 qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
	 XDrawString(display,winrama,gc,xt-qlen/2,yt+ioff,stemp,strlen(stemp));

	 glpnt(rwi,rhi,-0.04,0.5,&xt,&yt,0);
	 sprintf(stemp,"%d",0);
	 qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
	 XDrawString(display,winrama,gc,xt-qlen/2,yt+ioff,stemp,strlen(stemp));

	 glpnt(rwi,rhi,-0.04,0.75,&xt,&yt,0);
	 sprintf(stemp,"%d",90);
	 qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
	 XDrawString(display,winrama,gc,xt-qlen/2,yt+ioff,stemp,strlen(stemp));

	 glpnt(rwi,rhi,-0.04,1.0,&xt,&yt,0);
	 sprintf(stemp,"%d",180);
	 qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
	 XDrawString(display,winrama,gc,xt-qlen/2,yt+ioff,stemp,strlen(stemp));

	 for (i=0; i<calfptr->ncalf; i++) {
	   x1 = calfptr->rphi[i]/360.0 + 0.5;
	   y1 = calfptr->rpsi[i]/360.0 + 0.5;
           if (calfptr->iamino[i] == 1) {
		DrawTriangle(x1,y1,0,0,6,3,1,1);
	   } else if (calfptr->iamino[i] == 15) {
		DrawTriangle(x1,y1,0,0,6,4,1,1);
	   } else {
		DrawBox(x1,y1,0,0,6,3,1,1);
	   }
	   glpnt(rwi,rhi,x1,y1,&xt,&yt,0);
	   RamaStru.x[i] = xt;
	   RamaStru.y[i] = yt;
	   RamaStru.index[i] = i;
	 }

	 if (RamaStru.current != -1) {
	   i = RamaStru.current;
	   if (calfptr->iamino[i] == 1) {
		DrawTriangle(0.0,0.0,
			RamaStru.x[i],RamaStru.y[i],
			6,0,0,0);
	   } else if (calfptr->iamino[i] == 15) {
		DrawTriangle(0.0,0.0,
			RamaStru.x[i],RamaStru.y[i],
			6,0,0,0);
	   } else {
		DrawBox(0.0,0.0,
			RamaStru.x[i],RamaStru.y[i],
			6,0,0,0);
	   }
	 }
}

createconv()
{
      wincnv = CreateWindow("SCF Convergence",DEFCNVGEOM,
              CNVWIDE,CNVHIGH, infobg, infofg,(Window)0);
      XSelectInput(display, wincnv, ExposureMask | 
              ButtonPressMask | PointerMotionMask);
      XMapWindow(display, wincnv);
}

createfr(dowin)
int dowin;
{

   if (dowin) {
	FrBox = CreateWindow("Molden Frequency Select","-80-80",QBOXWIDE,310,
	   infobg,infofg,(Window)0);
	XSelectInput(display, FrBox, ExposureMask | KeyPressMask | 
	   ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | 
	   LeaveWindowMask);
   }

   if (FRQ->ihasi < 0) {
	if (*ihasex) {
	   DefList(&frlist,FrBox,DIRX,DIRY,DIRW,DIRH,
	   "  Nr.     Excitation (nm)   Int.  Mult-Irrep.",
	   NFLS,frsym,FRQ->freq,FRQ->frint,NULL,&FRQ->nfreq);
	} else {
	   DefList(&frlist,FrBox,DIRX,DIRY,DIRW,DIRH,
	   "  Nr.     Frequency (cm-1)  Int.  Irrep.",
	   NFLS,frsym,FRQ->freq,FRQ->frint,NULL,&FRQ->nfreq);
	}
   } else {
      	DefList(&frlist,FrBox,DIRX,DIRY,DIRW,DIRH,"  Nr.     Frequency    (cm-1)",
	NFLS,NULL,FRQ->freq,NULL,NULL,&FRQ->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";
   if (dowin) XMapWindow(display,FrBox);
}

void INTextr() {
      int i;

      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];
        }
      }
}

init_spec()
{
  int i,frtmp;
      if (FRQ->ihasi) {

	spint = FRQ->frint;
	spfrq = FRQ->freq;
	spnfrq = &FRQ->nfreq;
	min_freq = 0;
	max_freq = 0;
	for (i=0; i < FRQ->nfreq; i++) {
	   frtmp = (int) (spfrq[i]*freq_scale);
	   if (frtmp > max_freq) max_freq = frtmp;
	}
	i = max_freq / 500;
	max_freq = (i+1)*500;
	freq_step = 1.0;
	hwhm = 20.0;
	if (*ihasex) {
	   splab = uvlab;
        } else {
	   splab = forlab;
	}
	nspqbox = 5;
	nsbutts = 5;

      } else if (nmrptr->ihsnmr) {

	prep_nmr();
	spint = inten;
	spfrq = peaks;
	spnfrq = &npks;
	FRQextr();
	if (spmode) {
	   freq_step = nmr13Cstep;
	} else {
	   freq_step = nmr1Hstep;
	}
	hwhm = 0.01;
	splab = nmrlab;
	nspqbox = 7;
	nsbutts = 7;
      }
}

#if defined(VMS) || defined(UNDERSC)
gtfcor(int *ifrq,int *x1,int *y1,int *x2,int *y2)
#else
#ifdef CRAY
GTFCOR(int *ifrq,int *x1,int *y1,int *x2,int *y2)
#else
gtfcor_(int *ifrq,int *x1,int *y1,int *x2,int *y2)
#endif
#endif
{
  int lb,rb,frqrng,iw,x,imagx,imagy;
  double p;

  lb = 34; rb = 57; iw = 4;
  imagx = 1000; imagy = 500;
 
  frqrng = (max_freq - min_freq);

  p = (double) (imagx-lb-rb) / (double) frqrng;

  x =  lb + (int) (p*FRQ->freq[*ifrq-1]);
  *x1 = x - iw; *x2 = x + iw;
  *y1 = 0; *y2 = imagy;
  
}

#if defined(VMS) || defined(UNDERSC)
pltspec(int *opt)
#else
#ifdef CRAY
PLTSPEC(int *opt)
#else
pltspec_(int *opt)
#endif
#endif
{
   init_spec();
   if (nmrptr->ihsnmr) {
	avch3();
	prep_nmr();
   }
   calc_spectrum(0);
   write_spectrum("spec.ps",0,*opt);
   
}

void createspec(dowin)
int dowin;
{
      int i;

      if (!FRQ->ihasi && !nmrptr->ihsnmr) return;

      if (dowin) {
	winspec = CreateWindow("Spectrum",DEFCNVGEOM,
              SPECWIDE,SPECHIGH+SPBHIGH, infobg, infofg,(Window)0);
	XSelectInput(display, winspec, SubstructureNotifyMask | ExposureMask | 
		ButtonPressMask | ButtonReleaseMask | PointerMotionMask | 
		StructureNotifyMask | KeyPressMask | 
		EnterWindowMask | LeaveWindowMask); 
	subSPEC = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],winspec);
	XMapWindow(display, winspec);
      }

      init_spec();

      calc_spectrum(0);

      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);
      if (FRQ->ihasi) {
	  if (*ihasex) {
             spbut[1].str = *uvsptyp;
	     spbut[1].explstr = "UV spectrum";
	  } else {
             spbut[1].str = sptyp[spmode];
	     spbut[1].explstr = "Type of spectrum: Infrared, Raman\nSome QM programs calculate both intensities";
	  }
      } else if (nmrptr->ihsnmr) {
          spbut[1].str = nmrsptyp[spmode];
	  spbut[1].explstr = "Type of NMR spectrum: 1H, 13C";
	  if (spmode) {
		nmrref  = &nmr13Cref;
	  } else {
		nmrref  = &nmr1Href;
	  }
      }


      DefBut(&spbut[2], winspec, SPECWIDE-85, SPECHIGH+15 + 2*BUTTN, 75, 23, 
	"Close", infobg, ZMBCOL);
      spbut[2].explstr = "Close window";

      DefBut(&spbut[3], winspec, SPECWIDE-85, SPECHIGH+15, 75, 23, 
	"Postscript", infobg, ZMBCOL);
      spbut[3].explstr = "Export spectrum as Postscript file";

      DefBut(&spbut[4], winspec, SPECWIDE-85, SPECHIGH+15 + BUTTN,35, 23, 
	"Xmgr", infobg, ZMBCOL);
      spbut[4].explstr = "Export spectrum as input file for Xmgr";

      DefBut(&spbut[5], winspec, SPECWIDE-40, SPECHIGH+15 + BUTTN,30, 23,
        "jdx", infobg, ZMBCOL);
      spbut[5].explstr = "Export spectrum as jdx file";

      DefBut(&spbut[6], winspec, SPECWIDE-85, SPECHIGH+15 - BUTTN,75, 23, 
	"Aver. CH3", infobg, ZMBCOL);
      spbut[6].explstr = "Average shielding and J-coupling\nof rotational equivalent Hydrogens on CH3";

      qboxstr(&qboxes[QHW],&winspec,1,0,190,200,SPECHIGH,
	150,QBOXHIGH-5,2,"Half-Width"," ",10,QREAL,2000,updcallb);
      if (FRQ->ihasi) {
	sprintf(qboxes[QHW].str,"%-4.1f",hwhm);
      } else if (nmrptr->ihsnmr) {
	sprintf(qboxes[QHW].str,"%-8.4f",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 = "Apply intensity scale factor\nInstrumental in comparing spectra";

      if (nmrptr->ihsnmr) {

	qboxstr(&qboxes[QTMS],&winspec,0,0,190,200,SPECHIGH+15+2*BUTTN,
	150,QBOXHIGH-5,2,"TMS ref.  "," ",10,QREAL,2000,updcallb);
	sprintf(qboxes[QTMS].str,"%6.2f",*nmrref);
	qboxes[QTMS].qflt = nmrref;
	qboxes[QTMS].explstr = "The TMS reference.\nIsotropic Magnetic shielding (ppm)";

	qboxstr(&qboxes[QFREQ],&winspec,0,0,190,10,SPECHIGH+15+2*BUTTN,
	170,QBOXHIGH-5,2,"Carrier Freq. (MHz)"," ",10,QREAL,2000,updcallb);
	sprintf(qboxes[QFREQ].str,"%5.1f",NMRbas);
	qboxes[QFREQ].qflt = &NMRbas;
	qboxes[QFREQ].explstr = "Carrier frequency\nInfluences the size of the peak splitting";
      }

      specup = 1;
}

creategeom()
{

      gwi = CNVWIDE*2; ghi = CNVHIGH*2;
      if (!geo1ptr->idmxav && !geo1ptr->idrmav) gwi = CNVWIDE;
      if (!geo1ptr->ifmxav && !geo1ptr->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,NULL,pmfmn,npmfmx);

      DefList(&pmflistmx,winpmf,DIRX,160,DIRW,80,
	"Top Positive Interactions",5,NULL,NULL,NULL,pmfmx,npmfmx);
*/
      DefList(&pmflistmn,winpmf,DIRX,DIRY,DIRW,80,
	NULL,5,NULL,NULL,pmfmn,NULL,npmfmx);

      DefList(&pmflistmx,winpmf,DIRX,160,DIRW,80,
	NULL,5,NULL,NULL,pmfmx,NULL,npmfmx);

}

#if defined(VMS) || defined(UNDERSC)
crsco()
#else
#ifdef CRAY
CRSCO()
#else
crsco_()
#endif
#endif
{
   if (!scoup) 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)
void errzme(str, nstr, icard, ivar)
#else
#ifdef CRAY
void ERRZME(str, nstr, icard, ivar)
#else
void 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<*xyzp->iatoms; i++) xyzp->iaton[i] = 1;
	DeActZME();
	xyzp->iaton[zmptrp->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;

}

#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 || *fullgl)) {
	if (StarNetOld) {
	   XDrawString(display, win, gc, *yvl, *xvl, strvl->dsc$a_pointer, *sl);
	} else {
	   if (strvl[*sl]  != '\0') 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 || *fullgl)) {
	if (StarNetOld) {
	   XDrawString(display, win, gc, *yvl, *xvl, _fcdtocp(strvl), *sl);
	} else {
	   if (strvl[*sl]  != '\0') 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 || *fullgl) ) {
	if (StarNetOld) {
	   XDrawString(display, win, gc, *yvl, *xvl, strvl, *sl);
	} else {
	   if (strvl[*sl]  != '\0') 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 || *fullgl)) {
	if (StarNetOld) {
	   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)));
}

static int dsort(f1,f2)
float f1, f2;
{
    int iret;

    iret = -1;
    if (f1 == f2) iret = 0;
    if (f1 > f2) iret = 1;
    return (iret);
}

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);
  }
}

void getfiles(fs,dirname)
FSELSTRU *fs;
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,"/");
  if (fs->lastdir != dirname) strcpy(fs->lastdir,dirname);
  strcpy(fs->substr,qboxes[QSUBSTR].str);

  for (i=0; i<fs->nfiles; i++) free(fs->files[i]);
  fs->nfiles = 0;
  lpnt = 0;

  for (i=0; i<fs->ndirs; i++) free(fs->dirs[i]);
  fs->ndirs = 0;

  dir = opendir(dirname);
  if (!dir) {
    fs->ndirs = 1;
    fs->dirs[0] = (char *) malloc(6);
    strcpy(fs->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 {
		fs->dirs[j] = (char *) malloc(strlen(dp->d_name) + 3);
		if (!fs->dirs[j]) fprintf(stderr,"getfiles: malloc error\n");
		strcpy(fs->dirs[j], dp->d_name); j++;
	   }
	} else {
	   if (i >= MAXNAMES) {
		ifstat = 1;
	   } else {
		if (strstr(dp->d_name,fs->substr)) {
		fs->files[i] = (char *) malloc(strlen(dp->d_name) + 3);
		if (!fs->files[i]) fprintf(stderr,"getfiles: malloc error\n");
		strcpy(fs->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);
  }

  fs->nfiles = i;
  fs->flist.lpnt = 0;
  fs->flist.select = 0;

  qsort((char *) fs->files, fs->nfiles, sizeof(char *), dosort);

  fs->ndirs = j;
  fs->dirlist.lpnt = 0;
  fs->dirlist.select = 0;

  if (fs->ndirs == 0) {
    fs->ndirs = 1;
    fs->dirs[j] = (char *) malloc(6);
    strcpy(fs->dirs[j], "..");
  } else {
    qsort((char *) fs->dirs, fs->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 {
	 inactMC = inact; inafMC = inaf;
	 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 (FRQ->ihasi) {
	        if (specup) drwspec();
	    } else {
	        if (specup) {
		   XDestroyWindow(display,winspec);
		   specup = 0;
		}
	    }
	    if (FRQ->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 (!mfdata->imol) {
            ActBut(&cbut[BMOLF],-1);
	 } else {
            ActBut(&cbut[BMOLF],1);
	 }

	 if (*fullgl) {
	    *persp = 1;
	    TogDown(&cbut[BPERSP]); 
	 }
    
     }

     if (iwin) RedrawwinC(0,0,WINCWIDE,WINCHIGH);
     else      RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
     ATMsel = 0;
     ATMselp = ATMsel + 1;
     if (ATMup) {
	UpdateATM();
	RedrawATM();
     }
     if (CPup) {
	UpdateCP();
	RedrawCP();
     }
     if (CTup) {
	RedrawCT();
     }
     if (STRCup) {
	UpdateSTRC();
	RedrawSTRC();
     }


     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
	xyzp->ianz,xyzp->ityp);

}

#if defined(VMS) || defined(UNDERSC)
void prslab(str, nstr, iopt)
#else
#ifdef CRAY
void PRSLAB(str, nstr, iopt)
#else
void prslab_(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;
{

       if (hetlab.NHetLab >= MXHETLAB) return;
       
       hetlab.iat[hetlab.NHetLab]    = *iopt;

       hetlab.HetLab[hetlab.NHetLab] = (char *) malloc(*nstr+1);
       if (!hetlab.HetLab[hetlab.NHetLab]) 
		fprintf(stderr,"prslab: malloc error\n");

       strcp(str,hetlab.HetLab[hetlab.NHetLab],*nstr);

#ifndef CRAY
       hetlab.HetLab[hetlab.NHetLab][*nstr] = '\0';
#endif
       hetlab.NHetLab++;

}

#if defined(VMS) || defined(UNDERSC)
sftlab(iopt)
#else
#ifdef CRAY
SFTLAB(iopt)
#else
sftlab_(iopt)
#endif
#endif
int *iopt;
{
   int i;

   for (i=0; i<hetlab.NHetLab; i++)
	if (hetlab.iat[i] == *iopt) hetlab.iat[i] = *iopt + 1;
}

#if defined(VMS) || defined(UNDERSC)
void parsfn(str, nstr, iopt)
#else
#ifdef CRAY
void PARSFN(str, nstr, iopt)
#else
void 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 = fsel.files;
	  nstrings = &fsel.nfiles;
	  room = *nstr + 3;
	  break;
       case 1: 
	  strarr = HetAtm;
	  nstrings = &NHetAtm;
	  if (NHetAtm >= MXHETA) 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;
	  if (ntits >= MXTITL) return;
	  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;
       case 11: 
	  pdbcode = str;
	  break;
       case 12: 
	  gfile = 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;
{
/* ostr (C) -> str (Fortran) */
  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+1; 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;
{
/* str (fortran) -> ostr (C) */
  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);
}

#if defined(VMS) || defined(UNDERSC)
parfns(str, nstr)
#else
#ifdef CRAY
PARFNS(str, nstr)
#else
parfns_(str, nstr)
#endif
#endif

#ifdef VMS
struct dsc$descriptor_s *str;
#else
#ifdef CRAY
_fcd str;
#else
char *str;
#endif
#endif
int *nstr;
{

   if (*nstr < MAXSTRLEN) {
       strcp(str,strname,*nstr);
#ifndef CRAY
       strname[*nstr] = '\0';
#endif
   }

}

volatile sig_atomic_t pdone;

static void handle_child()
{
/*  fprintf(stderr,"handle_child %d\n",tnkpid);*/
  sigprocmask(SIG_BLOCK,&base_mask,NULL);
  pdone = 1;
  fndfile = 1;
  tnkupf = 1;
  if (tnkloop) send_expose();
  sigprocmask(SIG_UNBLOCK,&base_mask,NULL);
}

static int tdone;

static void handle_alarm()
{
  tdone = 1;
}

static void handle_explalarm()
{
   XMapEvent expe;
   Window win;

   expe.type = MapNotify;
   expe.display = display;
   if (expldat.borq) {
	win = expldat.qarr[expldat.button].win;
   } else {
	win = expldat.barr[expldat.button].win;
   }
   expe.window = expldat.win;
   if (expldat.winup != NULL) if (! *expldat.winup) return;

   if (!expldat.active && !animptr.on && !*movie) {
	XFlush(display);
	XSendEvent(display, win, 
		False, SubstructureNotifyMask, (XEvent *) &expe);
	XFlush(display);
   }
}

static int escopt = 0;

static void handle_tnk()
{
   sigprocmask(SIG_BLOCK,&base_mask,NULL);
   tnkupf = 1;
   sigprocmask(SIG_UNBLOCK,&base_mask,NULL);
}

static void update_tnk()
{
   int phlp,iret,i;
   char cmdcyc[MAXCMD];
   struct stat st;
   struct timeval tv,tvn;
   long tvs,tvu, tottv;

   if (uping) return;
 
   uping = 1;
   if (opttim) gettimeofday(&tv,NULL);

   phlp = pdone;
   sprintf(cmdcyc,"%s.%03d",cmdstr,cycle);
/*fprintf(stderr,"TNKPNT %s\n",cmdcyc);*/
   fndfile = 1;
   st.st_mode = 0;
   if (!stat(cmdcyc, &st)) {
/*fprintf(stderr,"Found file %s\n",cmdcyc);*/
	signal(SIGALRM,SIG_IGN);
#if defined(VMS) || defined(UNDERSC)
       	tnkpnt(&cycle,&iret);
#else
#ifdef CRAY
       	TNKPNT(&cycle,&iret);
#else
       	tnkpnt_(&cycle,&iret);
#endif
#endif
	if (iret) {
	   tnkupd = 1;
	   if (tnkloop) send_expose();
           if (delcyclefile) unlink(cmdcyc);
	   cycle++;
	} else {
	   fprintf(stderr,"found file ERROR\n");
	}
	
   } else {
/*fprintf(stderr,"NOT Found file %s\n",cmdcyc);*/
	if (phlp == pdone) {
	   fndfile = 0;
	   if (tnkloop) send_expose();
	}
   }

   if (opttim) {
	gettimeofday(&tvn,NULL);
	tvs = tvn.tv_sec - tv.tv_sec;
	tvu = (tvn.tv_usec - tv.tv_usec) / 1000L;
	timo[icyco] = tvu;
	icyco++;
	if (icyco >= NCYCO) {
	   tottv = 0L;
	   for (i=0; i<NCYCO; i++)  {
		tottv = tottv + timo[i];
	   }
	   TIMi = 2*((int) tottv) / NCYCO;
	   if (TIMi < 5) TIMi = 5;
	   opttim = 0;
	}
   }

   uping = 0;
}

static void handle_tnkesc()
{
   tnkesc = 1;
}

static void esctnk()
{
   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();
	}
   }

   escopt = 0;

#ifdef HASTIMER
   Timer(100,1);
#endif

}

int escox()
{
   char cmdtmp[MAXCMD];
   struct stat st;

   sprintf(cmdtmp,"%s_opt.xyz",cmdstr);
   st.st_mode = 0;
   if (!stat(cmdtmp, &st)) {
	if (st.st_size) return(1);
   }
   return(0);
}

void spaesc(fname)
char *fname;
{
   char tmpf[MAXCMD], *p, *q;

   strcpy(tmpf,fname);

   while (p = strchr(fname,' ')) {
      q = strchr(tmpf,' ');
      p[0] = '\\';
      p[1] = '\0';
      strcat(fname,q);
      p[1] = '\n';
      strcpy(tmpf,fname);
   }

   while (p = strchr(fname,'\n')) p[0] = ' ';
}

setlck(i)
int *i;
{
        FILE *out;
        char lckfile[80];
	struct stat st;

        sprintf(lckfile,"%d.ambforw",*i);

	st.st_mode = 0;
	if (stat(lckfile, &st)) {
           out = fopen(lckfile,"w");
           fprintf(out,"lock\n");
           fclose(out);
	}
}

#if defined(VMS) || defined(UNDERSC)
int islck(i)
#else
#ifdef CRAY
int ISLCK(i)
#else
int islck_(i)
#endif
#endif
int *i;
{
        FILE *out;
        char lckfile[80];
	struct stat st;

        sprintf(lckfile,"%d.ambforw",*i);

	st.st_mode = 0;

	if (!stat(lckfile, &st)) {
	   return 1;
	} else {
	   return 0;
	}
}

int getexe(iprg,mpi,cmdfil)
int iprg;
int mpi;
char *cmdfil;
{

#ifdef __CYGWIN__
   sprintf(cmdfil,"%s%s.exe",exepath[0],AmbProgs[iprg]);
#else
   if (mpi) {
	sprintf(cmdfil,"%s%s.mpi",exepath[0],AmbProgs[iprg]);
   } else {
	sprintf(cmdfil,"%s%s",exepath[0],AmbProgs[iprg]);
   }
#endif

   if (! (access(cmdfil,F_OK) == 0 && !isdir(cmdfil))) {
#ifdef __CYGWIN__
	sprintf(cmdfil,"%sambfor/%s.exe",exepath[0],AmbProgs[iprg]);
#else
	if (mpi) {
	   sprintf(cmdfil,"%sambfor/%s.mpi",exepath[0],AmbProgs[iprg]);
	} else {
	   sprintf(cmdfil,"%sambfor/%s",exepath[0],AmbProgs[iprg]);
	}
#endif
	if (! (access(cmdfil,F_OK) == 0)) {
	   if (mpi) {
		sprintf(cmdfil,"%s.mpi",AmbProgs[iprg]);
	   } else {
		sprintf(cmdfil,"%s",AmbProgs[iprg]);
	   }
	} else {
	   return(1);
	}
   } else {
	return(1);
   }
   return(0);
}

void doamb(jobstr)
char *jobstr;
{
   char cmdfil[MAXCMD];
   char cmdopt[MAXCMD];
   char cmdtmp[MAXCMD] = "ambfor ";
   char **argv;
   char *p;
   char *ambfor = "ambfor";
   char *spntr;
   char gtolstr[20];
   char iterstr[20];
   int iprg;
   FILE *out;

   if (hasmpi && usempi) {
	domamb(jobstr);
	return;
   }

   iprg = *tnkprg;
   if (iprg == 2) iprg = 0;

   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);

   getexe(iprg,0,cmdfil);

   strcpy(cmdtmp,cmdfil);
#ifdef __CYGWIN__
   spaesc(cmdtmp);
   if (p = strstr(cmdfil,".exe")) p[0] = '\0';
#endif
   strcat(cmdtmp," ");

   if (tnk_single) {
	strcat(cmdtmp,"-n -s ");
   } else {
	if (*tnkbg) {
	   strcat(cmdtmp,"-n ");
	} else {
	   strcat(cmdtmp,"-M ");
	}

	if (*arch) {
	   strcat(cmdtmp," -a ");
	}

	if (Box) {
	   strcat(cmdtmp," -b ");
	}

	if (Cutoff) {
	   strcat(cmdtmp," -N ");
	}

	strcat(cmdtmp,grdFlags[iprg]);
	strcat(cmdtmp," ");
	strcat(cmdtmp,gtolstr);

	strcat(cmdtmp," ");
	strcat(cmdtmp,iterFlags[iprg]);
	strcat(cmdtmp," ");
	strcat(cmdtmp,iterstr);

	strcat(cmdtmp," ");
   }

   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 %f\n",newen);
*/
		}
	   }
	   fclose(out);
	}
   } else {
     if (*tnkbg) {
	if (*arch) {
	   if (Box) {
	      if (Cutoff) {
		if (execlp(cmdfil,AmbProgs[iprg],"-n","-a","-b","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(cmdfil,AmbProgs[iprg],"-n","-a","-b",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   } else {
	      if (Cutoff) {
		if (execlp(cmdfil,AmbProgs[iprg],"-n","-a","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(cmdfil,AmbProgs[iprg],"-n","-a",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   }
	} else {

	   if (Box) {
	      if (Cutoff) {
		if (execlp(cmdfil,AmbProgs[iprg],"-n","-b","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(cmdfil,AmbProgs[iprg],"-n","-b",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   } else {
	      if (Cutoff) {
		if (execlp(cmdfil,AmbProgs[iprg],"-n","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(cmdfil,AmbProgs[iprg],"-n",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   }

	}
     } else {
	if (*arch) {
	   if (Box) {
	      if (Cutoff) {
		if (execlp(cmdfil,AmbProgs[iprg],"-M","-a","-b","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(cmdfil,AmbProgs[iprg],"-M","-a","-b",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   } else {
	      if (Cutoff) {
		if (execlp(cmdfil,AmbProgs[iprg],"-M","-a","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(cmdfil,AmbProgs[iprg],"-M","-a",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   }
	} else {
	   if (Box) {
	      if (Cutoff) {
		if (execlp(cmdfil,AmbProgs[iprg],"-M","-b","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr,
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(cmdfil,AmbProgs[iprg],"-M","-b",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr,
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   } else {
	      if (Cutoff) {
		if (execlp(cmdfil,AmbProgs[iprg],"-M","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr,
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(cmdfil,AmbProgs[iprg],"-M",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr,
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   }
	}
     }
   }
}

domamb(jobstr)
char *jobstr;
{
   char cmdfil[MAXCMD];
   char cmdopt[MAXCMD];
   char cmdtmp[MAXCMD] = "ambfor ";
   char **argv;
   char *p;
   char *ambfor = "ambfor";
   char *spntr;
   char gtolstr[20];
   char iterstr[20];
   char procstr[20];
   int iprg;
   FILE *out;

   iprg = *tnkprg;
   if (iprg == 2) iprg = 0;

   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(procstr,"%d",useproc);

   getexe(iprg,1,cmdfil);

   strcpy(cmdtmp,mpicmd);
   strcat(cmdtmp," -mca btl tcp,self -np ");
   strcat(cmdtmp,procstr);
   strcat(cmdtmp," ");
   strcat(cmdtmp,cmdfil);

#ifdef __CYGWIN__
   spaesc(cmdtmp);
   if (p = strstr(cmdfil,".exe")) p[0] = '\0';
#endif

   strcat(cmdtmp," ");

   if (tnk_single) {
	strcat(cmdtmp,"-n -s ");
   } else {
	if (*tnkbg) {
	   strcat(cmdtmp,"-n ");
	} else {
	   strcat(cmdtmp,"-M ");
	}

	if (*arch) {
	   strcat(cmdtmp," -a ");
	}

	if (Box) {
	   strcat(cmdtmp," -b ");
	}

	if (Cutoff) {
	   strcat(cmdtmp," -N ");
	}

	strcat(cmdtmp,grdFlags[iprg]);
	strcat(cmdtmp," ");
	strcat(cmdtmp,gtolstr);

	strcat(cmdtmp," ");
	strcat(cmdtmp,iterFlags[iprg]);
	strcat(cmdtmp," ");
	strcat(cmdtmp,iterstr);

	strcat(cmdtmp," ");
   }

   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 %f\n",newen);
*/
		}
	   }
	   fclose(out);
	}
   } else {
     if (*tnkbg) {
	if (*arch) {
	   if (Box) {
	      if (Cutoff) {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-n","-a","-b","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-n","-a","-b",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   } else {
	      if (Cutoff) {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-n","-a","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-n","-a",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   }
	} else {

	   if (Box) {
	      if (Cutoff) {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-n","-b","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-n","-b",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   } else {
	      if (Cutoff) {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-n","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-n",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   }

	}
     } else {
	if (*arch) {
	   if (Box) {
	      if (Cutoff) {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-M","-a","-b","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-M","-a","-b",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   } else {
	      if (Cutoff) {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-M","-a","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-M","-a",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr, 
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   }
	} else {
	   if (Box) {
	      if (Cutoff) {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-M","-b","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr,
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-M","-b",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr,
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   } else {
	      if (Cutoff) {
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-M","-N",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr,
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      } else {
/*yoyyoyo*/
		if (execlp(mpicmd,"mpirun",
		    "-mca","btl","tcp,self","-np",procstr,
		    cmdfil,"-M",
		    grdFlags[iprg],gtolstr,
		    iterFlags[iprg],iterstr,
		    DOSpath(jobstr),NULL) == -1) {
		    system(cmdtmp);
		}
	      }
	   }
	}
     }
   }
}

mloop(iopt)
int *iopt;
{
   int i;
   int ptmp,ctmp;

   sigprocmask(SIG_BLOCK,&base_mask,NULL);
   XFlush(display);

   tnkloop = 1;

   if (XPending(display)>0) {

	if (XCheckTypedWindowEvent(display, winMC, ButtonPress,&event)) {
	   event.xbutton.window = winMC;
	} else { 
	   if (XCheckTypedWindowEvent(display, win, ButtonPress,&event)) {
		event.xbutton.window = win;
	   } else {
		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,SIGINT);
		  escopt = 1; pdone = 1;
		  if (!escox()) *iopt = -1;
 		  Timer(TIMi,1);
		  /*fndfile = 0;*/
		  break;
		}
	   }

	}
	break;
	case ButtonPress:
		if (event.xbutton.window == win) {
		   if (event.xbutton.button == 3) OnTop();
		   else if (event.xbutton.button == 4)  
			ScrollWheel(&ctmp,&ptmp,1);
		   else if (event.xbutton.button == 5)  
			ScrollWheel(&ctmp,&ptmp,0);
		   else {
		      if (*ball) {
			gmoving = 1;
			moving = 1;
			tnkupd = 1;
			hold = 0;
			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 || *fullgl) && 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,SIGINT);
				/*fndfile = 0;*/
				pdone = 1;
				escopt = 1;
				if (!escox()) *iopt = -1;
 		  		Timer(TIMi,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;
				    if (has_opengl) {
					if (*fullgl) {
					   *ifogl = 1;
					} else {
					   *ifogl = 0;
					}
				    } else {
					*ifogl = 0;
				    }
				} else {
				    *fancy = 1;
				    if (has_opengl) {
					*ifogl = 1;
				    } else {
					*ifogl = 0;
				    }
				}
				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 || *fullgl) && has_opengl) 
					&& event.xbutton.window == win) {
		   moving = 0;
		   gmoving = 0;
		   hold = 0;
		   holdt = 0; holdp = 0;
		}

		if (event.xbutton.window == win && 
			   (event.xbutton.button == 1 || 
			    event.xbutton.button == 2) && !ZoomSelection ) 
		   moving = 0;

		if (((*fancy || *fullgl) && has_opengl) && 
				event.xbutton.window == win) {
		   gmoving = 0;
		   moving = 0;
		   hold = 0;
		   holdt = 0; holdp = 0;
		   dispsf();
		}
		break;

	case MotionNotify:
		event.xmotion.window = win;
		motion_screen(&ctmp,&ptmp);
		break;

	case Expose:
		if (event.xexpose.window == win) {
		   if ((*fancy || *fullgl) && 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 == SEQwin) RedrawSEQ();
              	if (event.xexpose.window == ATMwin) RedrawATM();
		if (event.xexpose.window == winMC)
				RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
		break;

	default: break;
	}
   }

   sigprocmask(SIG_UNBLOCK,&base_mask,NULL);
}

#if defined(VMS) || defined(UNDERSC)
sysstr(str,nstr)
#else
#ifdef CRAY
SYSSTR(str,nstr)
#else
sysstr_(str,nstr)
#endif
#endif

#ifdef VMS
struct dsc$descriptor_s *str;
#else
#ifdef CRAY
_fcd str;
#else
char *str;
#endif
#endif
int *nstr;

{
	int i,ns;
	char cmdfil[MAXCMD];

        ns = *nstr;
        if (*nstr > MAXCMD ) ns = MAXCMD;
        for (i=0; i<MAXCMD; i++) cmdstr[i] = ' ';
	strcp(str,cmdstr,ns);
	cmdstr[ns] = '\0';

	system(cmdstr);
}

#if defined(VMS) || defined(UNDERSC)
void exstr(str,nstr,iopt)
#else
#ifdef CRAY
void EXSTR(str,nstr,iopt)
#else
void 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;
        int ptmp,ctmp;
	char cmdfil[MAXCMD];

	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 = vfork();
	  switch(pid) {
	  case -1:
		fprintf(stderr,"Couldnt Fork\n");
		break;
	  case 0:	/*child */
/* iopt is always 1 since this is case 1: so it will nver do doamb here ?*/
                if (*iopt == 1) {
		   execlp(cmdstr," ",(char *)0);
		} else {
		   doamb(cmdstr);
		}
		_exit(0);
		break;
	  default:	/*parent*/
		return;
		break;
	  }
	  break;

	case 3:
	case 2:

	  if (*iopt == 3 && ! *tnkbg) setlck(&ONE);

	  signal(SIGCHLD,handle_child);
	  tnkpid = vfork();
	  tnkfrk = 1;

	  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,(char *)0);

		} else if (*iopt == 3) {

		   setenv("LD_LIBRARY_PATH",npth,1);
		   doamb(cmdstr);
		}
		_exit(0);
		break;
	  default:	/*parent*/
	  	pdone = 0;
	  	cycle = 1;
		fndfile = 1;
		escopt = 0;
		tnkesc = 0;
#ifdef HASTIMER
		hold = 0;
		holdt = 0; holdp = 0;
		update_model = 0;
		if (*iopt == 3) delcyclefile = 1;
		opttim = 1;
		icyco = 0;
	  	signal(SIGCHLD,handle_child);
		sigemptyset(&base_mask);
		sigaddset(&base_mask,SIGALRM);
		sigaddset(&base_mask,SIGCHLD);
   		Timer(TIMi,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 || tnkupf || tnkupd || tnkesc) {
			 while (1){
			   XSync(display, False);
			   if (XCheckMaskEvent(display,
				ButtonReleaseMask, &event)) {
				hold = 0;
				holdt = 0; holdp = 0;
				moving = 0;
				gmoving = 0;
				break;
			   }

			   if (tnkesc) {
				esctnk();
			   } else {
				sigprocmask(SIG_BLOCK,&base_mask,NULL);
		   		if (tnkupf) {
				   update_tnk();
	/* set new alarm */
				   Timer(TIMi,1);
				   tnkupf = 0;
				   if ((*fancy || *fullgl) && has_opengl) 
					update_model = 1;
				}
				sigprocmask(SIG_UNBLOCK,&base_mask,NULL);
			   }

		   	   if (tnkupd || tnkesc) {
				if ((*fancy || *fullgl) && has_opengl) 
				update_model = 1;
				tnkupd = 0;
			   }

			   doclr();

#if defined(VMS) || defined(UNDERSC)
			   mktrn(&holdt,&holdp);
			   qupd();
#else
#ifdef CRAY
			   MKTRN(&holdt,&holdp);
			   QUPD();
#else
			   mktrn_(&holdt,&holdp);
			   qupd_();
#endif
#endif
			   update_model = 0;

			   if (!hold) break;

			   if (tnkesc) break;

			 }
		   }

		   if (tnkesc) break;

		   mloop(iopt);
#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);
		break;
	  }
	  break;
	}

	signal(SIGCHLD,SIG_IGN);
	signal(SIGALRM,SIG_IGN);

	esctnk();
	update_model = 1;
	doclr();

#if defined(VMS) || defined(UNDERSC)
	qupd();
#else
#ifdef CRAY
	QUPD();
#else
	qupd_();
#endif
#endif

	handle = 0;
	tnkfrk = 0;
}

#if defined(VMS) || defined(UNDERSC)
void tomap(imap,iambfor)
#else
#ifdef CRAY
void TOMAP(imap,iambfor)
#else
void tomap_(imap,iambfor)
#endif
#endif
int *imap;
int *iambfor;
{
  *imap = 1;
  *iambfor = 0;
  if (Progs == AmbProgs && *tnkprg == 1) *imap = 0;
  if (Progs == AmbProgs) *iambfor = 1;
}

int typchk(silent)
int silent;
{
   int i,j;

   j = 0;
   for ( i = 0; i < *xyzp->iatoms; i++ ) 
	   if (xyzp->ianz[i] < 99 &&  xyzp->ityp[i] == 0) {
		if (!silent) {
		   if (xyzp->iresid[i] > 0) {
			fprintf(stderr,"AtomNr. %d %s %s untyped\n",i+1,
			elements[xyzp->ianz[i]],
			AminoAcids[calfptr->iamino[xyzp->iresid[i]-1]-1]);
		   } else if (xyzp->iresid[i] < -3) {
			fprintf(stderr,"AtomNr. %d %s %s untyped\n",i+1,
			elements[xyzp->ianz[i]],
			HetAtm[ABS(xyzp->iresid[i])]);
		   }
		}
		j++;
	   }

   return(j);

}

int typit(ff,silent)
int ff;
int silent;
{
   int iretval,retype;
   char mess[64];

   iretval = 0;
   retype = 0; 

   if (*fftyp != ff) {
	*fftyp = ff;
	retype = 1;
   } else {
	if (typchk(silent)) retype = 1;
   }
   
   if (retype) {
#if defined(VMS) || defined(UNDERSC)
	dotyp(&cell->ichx);
#else
#ifdef CRAY
	DOTYP(&cell->ichx);
#else
	dotyp_(&cell->ichx);
#endif
#endif
	iretval = typchk(silent);

	if (ATMup) {
	   UpdateATM();
	   XMapRaised(display,ATMwin);
	   RedrawATM();
	}
	if (!silent) {
	   sprintf(mess,"(Re)typing %s",ForceFields[*fftyp]);
	   if (DoCan(event.xbutton.x_root,event.xbutton.y_root,mess,0)) {}
	}
   }
   return(iretval);
}

#define NUMCOL 16

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;
	PopUpChunk = -1;
  } 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 0;

  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]);

#ifdef DOGL
  if ( (*fancy || *fullgl) && has_opengl && !StarNetOld) {
	dispsf();
	glXWaitGL();
  }
#endif

  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 / PopUpEntryH;
		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;
		    if (List != NULL) if (*iopt >= List->nents) 
			*iopt = List->nents - 1;
		    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)) / ((PopUpNum+1)*PopUpEntryH);
           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 */

   XSetFunction(display, gc, GXcopy);
   XSetPlaneMask(display, gc, (unsigned long) ~0L);
   XDestroyWindow(display,PopUp);

#ifdef DOGL
   if ( (*fancy || *fullgl) && has_opengl && !StarNetOld) {
	dispsf();
	glXWaitGL();
   }
#endif

   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]);
          XFillRectangle(display, PopUp, gc, 0,
               (i * PopUpHeight)/PopUpNum, PopUpWidth,PopUpEntryH);
      }
  }
  else {
      XSetForeground(display, gc, colors[190]);
      XFillRectangle(display, PopUp, gc, 0,0,
		          PopUpWidth,PopUpHeight);
      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)
void confrm(iop,istat)
#else
#ifdef CRAY
void CONFRM(iop,istat)
#else
void 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. \n\n Hit esc to abort calculation.");
		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)
void plsph3(xori,yori,diameter,ia,ioffs,icfac)
#else
#ifdef CRAY
void PLSPH3(xori,yori,diameter,ia,ioffs,icfac)
#else
void 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)
void plrod3(xori,yori,diameter1,diameter2,diameter3,rodlen,ioffs,icfac,cosa,sina)
#else
#ifdef CRAY
void PLROD3(xori,yori,diameter1,diameter2,diameter3,rodlen,ioffs,icfac,cosa,sina)
#else
void 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)
void plrodx(xori,yori,rada,radb,radc,rodlen,ioffs,cosa,sina)
#else
#ifdef CRAY
void PLRODX(xori,yori,rada,radb,radc,rodlen,ioffs,cosa,sina)
#else
void 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


void 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;

  if (handle == 1 && (timopt == 0 || timopt == 2)) return;
  if (msec <= 0) return;
  usec = (long) msec * 1000;

  it[timopt].it_value.tv_sec = 0L;
  it[timopt].it_value.tv_usec = 0L;
  it[timopt].it_interval.tv_sec = 0L;
  it[timopt].it_interval.tv_usec = 0L;

  if (usec>=1000000L) {  
    it[timopt].it_value.tv_sec = usec / 1000000L;
    usec %= 1000000L;
  }

  it[timopt].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[timopt], NULL);
  if (!timopt) pause();
#endif 
}
#endif

#if defined(VMS) || defined(UNDERSC)
parpoi(
#else
#ifdef CRAY
PARPOI(
#else
parpoi_(
#endif
#endif
	nzm,nso,nio,nzo,ioropt,ifor,ixyz98,iopr,isymm,irc,
	imp2,icntp,msucc,ioni,mopopt,isbin,irtype,
	ipdbgro,ifav,ioxyz,iconv,ircus,nscnd,iscst,ialtyp)

int *nzm;
int *nso;
int *nio;
int *nzo;
int *ioropt;
int *ifor;
int *ixyz98;
int *iopr;
int *isymm;
int *irc;
int *imp2;
int *icntp;
int *msucc;
int *ioni;
int *mopopt;
int *isbin;
int *irtype;
int *ipdbgro;
int *ifav;
int *ioxyz;
int *iconv;
int *ircus;
int *nscnd;
int *iscst;
int *ialtyp;
{
   
 poi.nzm = *nzm;
 poi.nso = *nso;
 poi.nio = *nio;
 poi.nzo = *nzo;
 poi.ioropt = *ioropt;
 poi.ifor = *ifor;
 poi.ixyz98 = *ixyz98;
 poi.iopr = *iopr;
 poi.isymm = *isymm;
 poi.irc = *irc;
 poi.imp2 = *imp2;
 poi.icntp = *icntp;
 poi.msucc = *msucc;
 poi.ioni = *ioni;
 poi.mopopt = *mopopt;
 poi.isbin = *isbin;
 poi.irtype = *irtype;
 poi.ipdbgro = *ipdbgro;
 poi.ifav = *ifav;
 poi.ioxyz = *ioxyz;
 poi.iconv = *iconv;
 poi.ircus = *ircus;
 poi.nscnd = *nscnd;
 poi.iscst = *iscst;
 poi.ialtyp = *ialtyp;

 ptrpoi.nzm = nzm;
 ptrpoi.nso = nso;
 ptrpoi.nio = nio;
 ptrpoi.nzo = nzo;
 ptrpoi.ioropt = ioropt;
 ptrpoi.ifor = ifor;
 ptrpoi.ixyz98 = ixyz98;
 ptrpoi.iopr = iopr;
 ptrpoi.isymm = isymm;
 ptrpoi.irc = irc;
 ptrpoi.imp2 = imp2;
 ptrpoi.icntp = icntp;
 ptrpoi.msucc = msucc;
 ptrpoi.ioni = ioni;
 ptrpoi.mopopt = mopopt;
 ptrpoi.isbin = isbin;
 ptrpoi.irtype = irtype;
 ptrpoi.ipdbgro = ipdbgro;
 ptrpoi.ifav = ifav;
 ptrpoi.ioxyz = ioxyz;
 ptrpoi.iconv = iconv;
 ptrpoi.ircus = ircus;
 ptrpoi.nscnd = nscnd;
 ptrpoi.iscst = iscst;
 ptrpoi.ialtyp = ialtyp;
}

bckpoi(istruct)
int istruct;
{

 poi = COO[istruct]->poi;

 *ptrpoi.nzm     = poi.nzm;
 *ptrpoi.nso     = poi.nso;
 *ptrpoi.nio     = poi.nio;
 *ptrpoi.nzo     = poi.nzo;
 *ptrpoi.ioropt  = poi.ioropt;
 *ptrpoi.ifor    = poi.ifor;
 *ptrpoi.ixyz98  = poi.ixyz98;
 *ptrpoi.iopr    = poi.iopr;
 *ptrpoi.isymm   = poi.isymm;
 *ptrpoi.irc     = poi.irc;
 *ptrpoi.imp2    = poi.imp2;
 *ptrpoi.icntp   = poi.icntp;
 *ptrpoi.msucc   = poi.msucc;
 *ptrpoi.ioni    = poi.ioni;
 *ptrpoi.mopopt  = poi.mopopt;
 *ptrpoi.isbin   = poi.isbin;
 *ptrpoi.irtype  = poi.irtype;
 *ptrpoi.ipdbgro = poi.ipdbgro;
 *ptrpoi.ifav    = poi.ifav;
 *ptrpoi.ioxyz   = poi.ioxyz;
 *ptrpoi.iconv   = poi.iconv;
 *ptrpoi.ircus   = poi.ircus;
 *ptrpoi.nscnd   = poi.nscnd;
 *ptrpoi.iscst   = poi.iscst;
 *ptrpoi.ialtyp  = poi.ialtyp;

}

#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: FRQ = (FRQSTRU *) fptr; break;
    case 2: dorb.eiga = fptr; dorb.focc = (double *) ffptr; dorb.ncols = nitem;
	    dorb.mxorg = 0;
	    break;
    case 3: geo1ptr = (GEO1STRU *) fptr; 
	    geopntr.mxorg = 0;
	    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: pnt = (PNTSTRU *) 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: elmptr = (ELMSTRU *) fptr; break;
    case 9: zmptr.nz = nitem;
	    zmptr.mxzorg = 0;
	    break;
    case 10: dorb.eigb = fptr; dorb.focb = (double *) ffptr; dorb.ncolb = nitem;
	     break;
    case 11: iuhf = nitem; break;
    case 12: xyz.icont = nitem; break;
    case 13: xyz.ncont = nitem; break;
    case 15: xyz.iatoms = nitem;
	     xyz.mxorg = 0;
	     break;
    case 16: DoFreq = 0; break;
    case 129: DoFreq = 1; break;
    case 17: iftyp = nitem; break;
    case 18: esp = (double *) fptr; break;
    case 19: doesp = nitem; break;
    case 20: potcom = (POTSTRU *) fptr; break;
    case 21: irtval = nitem; break;
    case 22: ifntcl = 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: jobcom = (JOBSTRU *) nitem; break;
    case 37: espvdw = (double *) fptr; break;
    case 38: ispd = nitem; break;
    case 39: ibgcol = nitem; break;
    case 40: cell= (CELLSTRU *) nitem; break;
    case 41: jring = nitem; break;
    case 42: isimpl = nitem; break;
    case 43: surface = (SRFSTRU *) fptr; break;
    case 44: ivdwpl = nitem;break;
    case 45: NAT = (NATSTRU *) nitem; break;
    case 46: dospa = nitem; break;
    case 47: xyz.qat = (double *) fptr; 
	     break;
    case 48: fftyp = nitem; break;
    case 49: xyz.ityp = (short int *) nitem; 
	     break;
    case 50: xyz.ipdbt = (short int *) nitem; 
	     break;
    case 51: calfptr = (CALFSTRU *) fptr; break;
    case 52: istaro = 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: normc = 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 = 0; 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 = 0;
	     break;
    case 99: mapit = nitem; break;
    case 100: ipsi = nitem; break;
    case 101: mapval = (double *) fptr; break;
    case 102: imapopt = nitem; break;
    case 110: ipdbwh = nitem; break;
    case 113: ideltm = 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: zmpart = (ZMPARTSTRU *) 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: hlpsrf = (HSRFSTRU *) nitem; break;
    case 139: backb = nitem; break;
    case 142: XYZ = (XYZSTRU *) fptr; break;
    case 143: BAS = (BASSTRU *) fptr; 
	      slagau = (GAUSTRU *) nitem;
	      break;
    case 144: comsrfptr = (COMSRFSTRU *) fptr; break;
    case 145: scle = (double *) fptr; break;
    case 146: ipsa = nitem; break;
    case 148: ifdogl = nitem; break;
    case 149: xyz.isurf = nitem; 
	      break;
    case 150: mapcol = (RGB *) fptr; valcol = (double *) ffptr; break;
/* already declared above
    case 151: (GEO2STRU *) fptr; break;
*/
    case 153: pmfrot = (PMFROTSTRU *) fptr; break;
    case 154: adjuss = (double *) 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; vlcnt2 = (double *) ffptr; break;
    case 167: scalptr = (SCALSTRU *) fptr; break;
    case 168: clfhptr = (CLFHSTR *) 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;
    case 175: MOP = (MOPSTRU *) nitem; break;
    case 176: PSEUD = (PSEUDSTRU *) nitem; break;
    case 177: plane = (PLANESTRU *) fptr; break;
    case 178: eul = (EULSTRU *) fptr; break;
    case 179: proj = (PROJSTRU *) fptr; break;
    case 180: multstruct = nitem; break;
    case 181: mfdata = (MFSTRU *) nitem; break;
    case 182: pol = (double *) fptr; break;
    case 183: pol2 = (double *) fptr; break;
    case 184: icpsa = (int *) nitem; break;
    case 185: idtpsa = (int *) nitem; break;
    case 186: movie = (int *) nitem; break;
    case 187: fullgl = (int *) nitem; break;
    case 188: icst = (int *) nitem; break;
    case 189: ibox = (int *) nitem; break;
    case 190: igfmap = (int *) nitem; break;
    case 191: clfstrptr = (CLFSTRU *) nitem; break;
    case 192: nmrptr = (NMRSTRU *) fptr; break;
    case 193: iresrd = (int *) nitem; break;
    case 194: alnptr = (ALNSTRU *) nitem; break;
    case 195: pbc = (PBCSTRUC *) fptr; break;
    case 196: doshad = (int *) nitem; break;
    case 197: ihasex = (int *) nitem; break;
    case 198: noshad = (int *) 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);
}

void 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,splab,"Intensity","",0,1,0,1);

      if (!specps) {
	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 < *spnfrq; i++) {
	intensity = 0.0;
	frq = ((double) spfrq[i])*freq_scale;
	for (j=0; j < *spnfrq; j++) {
	   center = ((double) spfrq[j])*freq_scale ;
	   rel_offset = (frq - center) / hwhm;
	   intensity += spint[j] * lineshape(rel_offset);
	}
        
	x1 = ((((double) spfrq[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 *) spfrq;

      if (!specps) {
	for (i=0; i<nsbutts; i++) DrwBut(&spbut[i]);
	for (i=0; i<nspqbox; i++) {
	   PromptBox(&qboxes[QHW+i]);
	}

	ULineString(winspec,"Spectrum:",CNVBORD, SPECHIGH+15);
	ULineString(winspec,"Lineshape:",CNVBORD, SPECHIGH+BUTTN+15);
      }

}

void 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)
void drwgeo()
#else
#ifdef CRAY
void DRWGEO()
#else
void drwgeo_()
#endif
#endif
{
      int nitems;

      if (!geo1ptr->gcvav || !geoup) return;

      nhframes = 1;
      if (geo1ptr->ifmxav || geo1ptr->ifrmav) nhframes = 2;
      nwframes = 1;
      if (geo1ptr->idmxav || geo1ptr->idrmav) nwframes = 2;

      if (geo1ptr->ieav) {
	   nitems = geo1ptr->nepnts;
	   if (nitems > geo1ptr->mxpnt) nitems = geo1ptr->mxpnt;
	   drwgra(&geoE,-5,wingeo,CNVWIDE,CNVHIGH,geop->isav,
	   geop->epoints,0,0,nitems,geo1ptr->enmax,geo1ptr->enmin,
	   0.0e0,9,1,"Point","Energy",NULL,0,1,1,0);
      }

      nitems = geo1ptr->ngeoms;
      if (nitems > geo1ptr->mxpnt) nitems = geo1ptr->mxpnt;

      if (geo1ptr->ifmxav)
	   drwgra(&geoFmax,-5,wingeo,CNVWIDE,CNVHIGH,geop->isav,
	   geop->formax,0,0,nitems,geo1ptr->fgmax,geo1ptr->fgmin,
	   geo1ptr->fmaxt,5,2,"Point","Force","Max. Force",0,1,0,0);

      if (geo1ptr->ifrmav) 
	   drwgra(&geoFrms,10,wingeo,CNVWIDE,CNVHIGH,geop->isav,
	   geop->forrms,0,0,nitems,geo1ptr->fgmax,geo1ptr->fgmin,
	   geo1ptr->frmst,6,2,"Point","Force","Aver. Force",1,0,0,0);

      if (geo1ptr->idmxav)
	   drwgra(&geoSmax,-5,wingeo,CNVWIDE,CNVHIGH,geop->isav,
	   geop->dismax,0,0,nitems,geo1ptr->dgmax,geo1ptr->dgmin,
	   geo1ptr->dmaxt,1,3,"Point","Step","Max. Step",0,1,0,0);

      if (geo1ptr->idrmav)
	   drwgra(&geoSrms,10,wingeo,CNVWIDE,CNVHIGH,geop->isav,
           geop->disrms,0,0,nitems,geo1ptr->dgmax,geo1ptr->dgmin,
	   geo1ptr->drmst,11,3,"Point","Step","Aver. Step",1,0,0,0);

      XSetLineAttributes(display, gc, 1, LineSolid, CapButt, JoinMiter);


}

void 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,xoff;
      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;

      if (tabptr->npts < nents && tabptr->x != NULL) {
	free(tabptr->x);
	free(tabptr->y);
	free(tabptr->index);
      }
      
      if (tabptr->x == NULL || tabptr->npts < nents) {
	tabptr->x = (int *) malloc((sizeof i)*nents);
	tabptr->y = (int *) malloc((sizeof i)*nents);
	tabptr->index =  (int *) malloc((sizeof i)*nents);
      }

      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) {

       if (!specps) {
         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,None,0,0,0);
         XSetForeground(display, gc, BlackPixel(display,screen));
	 xoff = strlen(xstr)*10;
         XDrawString(display,gwin,gc,(tabptr->wide-CNVBORD-xoff)+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));
       
	} else {
	   glpnt(tabptr->wide,tabptr->high,0.85,-0.10,&xt,&yt,ifr);
	   qlen = strlen(xstr);
	   fprintf(spout,"%d %d m 4 0 (%s) ashow\n",
		600*(xt-qlen/2)/SPECWIDE,-300*yt/SPECHIGH,xstr);
	   qlen = strlen(ystr);
	   for (i=0; i < strlen(ystr); i++,tmpptr++) {
		glpnt(tabptr->wide,tabptr->high,-0.02,1.0-i*0.05,&xt,&yt,ifr);
		fprintf(spout,"%d %d m 4 0 (%c) ashow\n",
		600*(xt)/SPECWIDE,-300*yt/SPECHIGH,ystr[i]);
	   }
        }

         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);

	 if (freq_step == 1.0) {
		tick = 5;
		if (nents > 50) tick = 10;
		if (nents > 500) tick = 100;
		if (nents > 1000) tick = 500;
		if (nents > 10000) tick = 1000;
		if (nents > 100000) tick = 10000;
	 } else if (freq_step == nmr1Hstep) {
		tick = 1;
	 } else if (freq_step == nmr13Cstep) {
		tick = 10;
	 }

	 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);

		  if (specps) {
			qlen = strlen(stemp);
			fprintf(spout,"%d %d m 4 0 (%s) ashow\n",
			  600*(xt-qlen/2)/SPECWIDE,-300*yt/SPECHIGH,stemp);
		  } else {
			qlen = XTextWidth(mfinfo,stemp, strlen(stemp));
			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 (!specps) {

         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));

	} else {
		qlen = strlen(labstr);
		xt = 0; yt = 0;
		fprintf(spout,"%d %d m 4 0 (%s) ashow\n",
		600*(xt-qlen/2)/SPECWIDE,-300*yt/SPECHIGH,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 == pnt->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 == pnt->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 && !specps) {
	    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);
      }

}

void 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 (!specps) {
	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);
	}
	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);
	}
  } else {
     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");
  }
}

void 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);

}

void 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,0,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 *) spfrq) {
	   sprintf(stemp,"%f",freq_scale*spfrq[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 *) spfrq) {
           sprintf(stemp,"%f",freq_scale*spfrq[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 || *fullgl) && has_opengl && !StarNetOld) ) {
           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 %-6d ",AminoAcids[calfptr->iamino[Ca]-1],
					 calfptr->irsnr[Ca]);
		atemp[12] = '\0';
	   } else {
		sprintf(atemp,"%3s     ",HetAtm[abs(Ca)]);
		atemp[9] = '\0';
	   }

	   if ((*fancy || *fullgl) && has_opengl && !StarNetOld) {
#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 || *fullgl) && has_opengl && !StarNetOld) 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 || *fullgl) && has_opengl)) 
	|| (Ca <= -4 && Ca != rsold) || 
	   (Ca == RESUND && rsold != RESUND)) {

	 if ( !( (*fancy || *fullgl) && has_opengl && !StarNetOld) ) {
           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 = calfptr->icyp[Ca];
		y = calfptr->icxp[Ca];
	   } else {
		x = iy[l];
		y = ix[l]-20;
	   }

	   if (Ca >= 0) {
		sprintf(atemp,"%3s %3d ",AminoAcids[calfptr->iamino[Ca]-1],
					 calfptr->irsnr[Ca]);
	   } else {
		int aca;
		
		aca = abs(Ca+1);
		if (aca < MXHETA) {
		   sprintf(atemp,"%3s     ",HetAtm[abs(Ca)]);
		   sprintf(atemp,"%3s     ",HetAtm[abs(Ca+1)]);
		}
	   }

	   if ( (*fancy || *fullgl) && has_opengl && !StarNetOld) {
#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 || *fullgl) && has_opengl && !StarNetOld) dispsf();
#endif
	 }
	 rsold = Ca;
      }
}

int FindSel(onoff,x,y,ist,num_items,cursorx,cursory,mindiff)
int *onoff;
int *x;
int *y;
int ist;
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 = ist; i < ist+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 && xyzp->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 || *fullgl)) {
	dzmin = 1000000;
    } else {
	dzmin = -1000000;
    }
    for ( i = 0; i < calfptr->ncalf; i++ ) {
     for ( j = 0; j < 4; j++ ) {
      l = calfptr->icalf[i][j]-1;
      if (l < 0 || l > *xyzp->mxnat) continue;
      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 = xyzp->rzp[l];
	  dsqr = dx*dx + dy*dy;
          if (dx < mindiff && dy < mindiff && dsqr < dsq_min) {
	     if (has_opengl && (*fancy || *fullgl)) {
		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 - calfptr->icyp[i]);
	dy = ABS(cursory - calfptr->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&&*zmptrp->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, -elmptr->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, -elmptr->icol[i]);
   }

   SetQZME();

   DefScroll(&zscroll,ZMEwin,ZMEZOffx+ZMEZWIDE+ZMESCR,ZMEZOffy+22,22,
             ZME_window_high*ZMEQHIGH+ZMEBord-2*22,zmptrp->nz,
	    &ZME_window_pos,ZME_window_high,NULL);

   strcpy(ZMEerr,"Use Mouse Button 2 to change the status of a variable");

   if (ZMEAA) make_aa();
}

UnMapZME()
{
	int nw;

	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);

#if defined(VMS) || defined(UNDERSC)
        haswat(&nw);
#else
#ifdef CRAY
        HASWAT(&nw);
#else
        haswat_(&nw);
#endif
#endif
	if (nw != nwater[istruct])  {
	   reswat();
#ifdef DOGL
	   if (*fancy) {
	      oghet(0);
	   } else {
	      oglines();
	   }
#endif
	}
}

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<*zmptrp->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, 
		   -clfhptr->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, 
		   -clfhptr->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 = zmptrp->nz;

   if (ZME_window_pos > *zmptrp->nz-1-ZME_window_high) {
	if (*zmptrp->nz-1-ZME_window_high >= 0) {
	    ZME_window_pos = *zmptrp->nz-ZME_window_high;
        } 
	else ZME_window_pos = 0;
   }

   for (i=0; i<*zmptrp->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<*zmptrp->nz; i++) {
		zmptrp->ibl[i] = iop; 
		BLbox[i].col = icol; 
		BLbox[i].changed = 1;
		zmptrp->ialph[i] = iop; 
		ALPHbox[i].col = icol; 
		ALPHbox[i].changed = 1; 
		zmptrp->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 (!*zmptrp->ihaszm) return;

   strcpy(ZMEerr," ");
   for (i=0; i<*zmptrp->nz; i++) {
	   if (zmptrp->ianz[i] >= 0 && zmptrp->ianz[i] < 100) 
		sprintf(stemp,"%s",elements[zmptrp->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],zmptrp->bl[i]);
	   	   qboxstr(&BLbox[i],&ZMEwin,0,fake,196,0,0,ZMEvarW,ZMEQHIGH,
		     ZC_DEF,NULL,stemp,11,2,0,dummyproc);
		   QPcol(&BLbox[i],zmptrp->ibl[i]);
		   BLbox[i].explstr = BLstr;
		}
		else if (j == 1) {
	   	   sprintf(stemp,zmeform[ZMEAA],zmptrp->alph[i]);
	   	   qboxstr(&ALPHbox[i],&ZMEwin,0,fake,196,0,0,ZMEvarW,ZMEQHIGH,
		     ZC_DEF,NULL,stemp,11,2,0,dummyproc);
		   QPcol(&ALPHbox[i],zmptrp->ialph[i]);
		   ALPHbox[i].explstr = ALPHstr;
		}
		else if (j == 2) {
		   zvw = ZMEvarW; zvwn = 11;
                   if (ZMEAA) {
			zvw = ZMEvarWs;
			zvwn = 8;
		   }
	   	   sprintf(stemp,zmeform[ZMEAA],zmptrp->bet[i]);
	   	   qboxstr(&BETbox[i],&ZMEwin,0,fake,196,0,0,zvw,ZMEQHIGH,
		     ZC_DEF,NULL,stemp,zvwn,3,0,dummyproc);
		   QPcol(&BETbox[i],zmptrp->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 */


  if (!xison) return;

	SetQZME();
	if (ZME_window_pos >= *zmptrp->nz) ZME_window_pos = 0;
	if (*zmptrp->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<*zmptrp->nz; i++) {

	   found = 0;
	   for (j=0; j<100; j++) {
		if (strcasecmp(IANZbox[i].str,elements[j]) == 0) {
		    found = 1;
		    zmptrp->ianz[i] = j;
		}
	   }
	   if (strcasecmp(IANZbox[i].str,"XX") == 0) {
		found = 1;
		zmptrp->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 (zmptrp->ibl[i] > 1) {
			zmptrp->bl[i] = zmptrp->bl[zmptrp->ibl[i] - 1];
			strcpy(BLbox[i].str,BLbox[zmptrp->ibl[i] - 1].str);
		    } else {
			if (BLbox[i].changed) {
	   		    if (strlen(BLbox[i].str)) 
				sscanf(BLbox[i].str,"%lf",&zmptrp->bl[i]);
			    else {
				ActOnErr(i,1,"ZMAT NOT parsed: Empty string !");
				return;
			    }
			    BLbox[i].changed = 0;
			}
		    }
		    break;
		case 1:

		    if (zmptrp->ialph[i] > 1) {
			zmptrp->alph[i] = zmptrp->alph[zmptrp->ialph[i] - 1];
			strcpy(ALPHbox[i].str,ALPHbox[zmptrp->ialph[i] - 1].str);
		    } else {
			if (ALPHbox[i].changed) {
	   		    if (strlen(ALPHbox[i].str)) 
				sscanf(ALPHbox[i].str,"%lf",&zmptrp->alph[i]);
			    else {
				ActOnErr(i,2,"ZMAT NOT parsed: Empty string !");
				return;
			    }
			    ALPHbox[i].changed = 0;
			}
		    }
		    break;
		case 2:
		    if (ABS(zmptrp->ibet[i]) > 1) {
			if (zmptrp->ibet[i] > 0) {
			    zmptrp->bet[i] = zmptrp->bet[zmptrp->ibet[i] - 1];
			    strcpy(BETbox[i].str,BETbox[zmptrp->ibet[i] - 1].str);
			} else {
			    zmptrp->bet[i] = -zmptrp->bet[ABS(zmptrp->ibet[i]) - 1];
			    sprintf(stemp,"%f",zmptrp->bet[i]);
			    strcpy(BETbox[i].str,stemp);
			}
		    } else {
			if (BETbox[i].changed) {
	   		    if (strlen(BETbox[i].str)) 
				sscanf(BETbox[i].str,"%lf",&zmptrp->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<*zmptrp->nz; j++) {
	if (jxyz == zmptrp->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 = (elmptr->vdwr[atomnr1-1] + elmptr->vdwr[atomnr2-1])*0.98;
	strcpy(ZMEerr,"Bondlength estimated from Van der Waals Radii");
    }
    return BL;

}

FirstLine()
{

	*zmptrp->nz = 1;
	xyzp->ianz[0] = zmptrp->ianz[0];
	zmptrp->imap[0] = 1;
	*xyzp->iatoms = 1;
	xyzp->coo[0] = 0.0;
	xyzp->coo[1] = 0.0;
	xyzp->coo[2] = 0.0;
	xyzp->iconn[0] = 0;
	xyzp->iaton[0] = 1;
	scalptr->scali = 3.5;
	scalptr->scal = 2.5*scalptr->scali;
	ZME_window_pos = 0;
#if defined(VMS) || defined(UNDERSC)
	strot(rotptr->rx,rotptr->ry,rotptr->rz);
#else
#ifdef CRAY
	STROT(rotptr->rx,rotptr->ry,rotptr->rz);
#else
	strot_(rotptr->rx,rotptr->ry,rotptr->rz);
#endif
#endif
	update_sel = 1;
}

int GetRes(atomnr,iph,Asel)
int atomnr;
short int *iph;
int Asel;
{
  int irt,irtt,n,i,ii,nt,nh[3];
  short int ipt;

  *iph = 0; irt = NHETRES;

  if (*ipdbon && !*ialtyp) {

#if defined(VMS) || defined(UNDERSC)
	numhed(&irt,xyzp->iresid);
#else
#ifdef CRAY
	NUMHED(&irt,xyzp->iresid);
#else
	numhed_(&irt,xyzp->iresid);
#endif
#endif
	irt++;
	irt = -irt;

	irtt = xyzp->iresid[Asel];

	if (irtt > 0) {

/* attach to residue atom */

		if (atomnr == 1) {

		/* attach H to residue atom */

		   ipt = xyzp->ipdbt[Asel];
		   switch (calfptr->iamino[irtt-1]) {
		   case 3:
		   /* serine */
			switch (ipt) {
			case 1:
			   *iph = 1;
			   irt = irtt;
			   break;
			case 31:
			   *iph = 10;
			   irt = irtt;
			   break;
			}
			break;
		   case 5:
		   /* threonine */
			switch (ipt) {
			case 1:
			   *iph = 1;
			   irt = irtt;
			   break;
			case 31:
			   *iph = 10;
			   irt = irtt;
			   break;
			case 32:
			   *iph = 13;
			   irt = irtt;
			   break;
			}
			break;
		   case 4:
		   /* cysteine */
			switch (ipt) {
			case 1:
			   *iph = 1;
			   irt = irtt;
			   break;
			case 37:
			   *iph = 10;
			   irt = irtt;
			   break;
			}
			break;
		   case 9:
		   /* asparate */
			switch (ipt) {
			case 1:
			   *iph = 1;
			   irt = irtt;
			   break;
			case 29:
			   *iph = 22;
			   irt = irtt;
			   break;
			case 30:
			   *iph = 25;
			   irt = irtt;
			   break;
			}
			break;
		   case 13:
		   /* glutamate */
			switch (ipt) {
			case 1:
			   *iph = 1;
			   irt = irtt;
			   break;
			case 34:
			   *iph = 31;
			   irt = irtt;
			   break;
			case 35:
			   *iph = 34;
			   irt = irtt;
			   break;
			}
			break;
		   case 17:
		   /* histidine */
			switch (ipt) {
			case 1:
			   *iph = 1;
			   irt = irtt;
			   break;
			case 20:
			   *iph = 22;
			   irt = irtt;
			   break;
			case 24:
			   *iph = 34;
			   irt = irtt;
			   break;
			}
			break;
		   case 19:
		   /* tyrosine */
			switch (ipt) {
			case 33:
			   *iph = 52;
			   irt = irtt;
			   break;
			}
			break;
		   default:
			switch (ipt) {
			case 1:
			   *iph = 1;
			   irt = irtt;
			   break;
			}
			break;
		   }
		}
		if (*iph == 1) {
		   for (i=0; i < 3; i++) nh[i] = 0;
		   n = xyzp->iconn[Asel*(MXCON+1)];
		   for (i=0; i < n; i++) {
			ii = xyzp->iconn[Asel*(MXCON+1)+i+1];
			if (ii > 0) {
			    if (xyzp->ianz[ii-1] == 1) {
				nt = (int) xyzp->ipdbt[ii-1];
				if (nt >= 1 && nt <= 3) {
				   nh[nt-1] = 1;
				}
			    }
			}
		   }
		   for (i=0; i < 3; i++) {
			if (nh[i] == 0) {
			   *iph = i+1;
			   break;
			}
		   }
		}

	} else {

/* attach to NON residue atom */

		irt = irtt;
	}
	if (irt != irtt) {
	   int airt;
	   airt = ABS(irt);

	   if (airt < MXHETA) {
		NHetAtm == airt+1;
		calfptr->ihet[airt] = 1;
		HetAtm[airt] = "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 (*zmptrp->nz >= *zmptrp->mxzat - 1) {
	ioke = 0;
	if (AllocZMat(*xyzp->mxnat,ZERO)) ioke = 1;
  }
  if (!ioke) return;

  if (!mapchk()) map_prop();

  izptr = *zmptrp->nz;

  if (Asel != NULL) {
	irt = GetRes(atomnr,&iph,Asel[0]);
  } else {
	irt = NHETRES;
  }

  if (iph) {
	int imxt,imnt,ipartt;

	imxt = zmpart->imx; imnt = zmpart->imn; ipartt = zmpart->ipart;
	FindZRange(irt);
	row = zmpart->imx;
	zmpart->imx = imxt; zmpart->imn = imnt; zmpart->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);
	zmptrp->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 <4; i++) {
	    if (i == 3) {
		sizz(izptr,3,0);
	    } else {
		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,zmptrp->ianz[izptr],zmptrp->ianz[Asel[0]]);
	} else dis = *dist;

	sprintf(BLbox[izptr].str,"%f",dis);
	zmptrp->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(zmptrp->alph[Asel[1]]-120.0) <=
		    ABS(zmptrp->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(zmptrp->alph[i]-120.0) <=
			   ABS(zmptrp->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);
	zmptrp->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] = zmptrp->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);
	zmptrp->bet[izptr] = (double) dihtmp;
	BETbox[izptr].changed = 1;

        zmptrp->ibl[izptr] = 1;
        zmptrp->ialph[izptr] = 1;
        zmptrp->ibet[izptr] = 1;
        zmptrp->imap[izptr] = izptr+1;

        iptr1 = izptr;
	if (*ialtyp) iptr1 = iptr1 + *iscst;
        
	xyzp->ipdbt[iptr1] = iph;
	xyzp->iresid[iptr1] = irt;
	xyzp->ityp[iptr1] = 0;
	xyzp->iaton[iptr1] = 1;
	xyzp->iatclr[iptr1] = 1;

	(*zmptrp->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 = *zmptrp->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 (!*zmptrp->nz) isfirst = 1;
    
    row = GetRow(1);
    if (row == -1) {
	if (isfirst) {
           AddLine(1,0,selMap,NULL,NULL,NULL,0);
           *zmptrp->nz = 1;
	   row = 0;
	   zmptr.ianz[0] = atnr;
	} else {
	   return;
	}
    }

    irt = NHETRES;
    rest = zmptrp->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);
    zmptrp->alph[1] = 0.0;
    zmptrp->bet[1] = 0.0;
    zmptrp->bet[2] = 0.0;

    *zmptrp->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;

    xyzp->ipdbt[iptr1] = 0;
    xyzp->ityp[iptr1] = 0;
    xyzp->iresid[iptr1] = irt;
    xyzp->iatclr[iptr1] = 1;
    xyzp->iaton[iptr1] = 1;
    update_sel = 1;

    if (*zmptrp->nz >1) {
	sprintf(BLbox[row].str,"%f",
	    CalcBL(0,atnr,zmptrp->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] = *zmptrp->nz-1;

    switch(atnr) {
    case 6:	AddLine(1,0,selMap,NULL,NULL,NULL,0);
	        if (*zmptrp->nz == 3) selMap[2] = *zmptrp->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 = *zmptrp->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 = *zmptrp->nz - frglen;
    *zmptrp->nz = *zmptrp->nz - frglen;

    if (!frglen) return;

    frag = (ZLINESTRU *) malloc((sizeof *frag)*frglen);

    for (i=0; i < frglen; i++) {
	offset = *zmptrp->nz + i;
	frag[i].ianz = zmptrp->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 = zmptrp->bl[offset];
	frag[i].alph = zmptrp->alph[offset];
	frag[i].bet = zmptrp->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)*(*zmptrp->mxzat))) == NULL) 
	return;

    for (j=0; j<*zmptrp->nz; j++) {
	if (zmptrp->imap[j] > 0) {
	   arr[j] = xyzp->qat[zmptrp->imap[j]-1];
	} else {
	   arr[j] = 0.0;
	}
    }
    for (j=0; j<*zmptrp->nz; j++) xyzp->qat[j] = arr[j];

    if (ScrewNotTrans) {
	scangle = 180.0;
    } else {
	scangle = 0.0;
    }

    frglen = *zmptrp->nz;
    *zmptrp->nz = 0;

    if (!frglen) return;

    frag = (ZLINESTRU *) malloc((sizeof *frag)*frglen);


    for (i=0; i < frglen; i++) {
	offset = *zmptrp->nz + i;
	frag[i].ianz = zmptrp->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 = zmptrp->bl[offset];
	frag[i].alph = zmptrp->alph[offset];
	frag[i].bet = zmptrp->bet[offset];
    }
    *zmptrp->nz = 0;
    CopyFrag(SCREW,2,-1);
    CopyFrag(frag,frglen,-1);

    sizz(2,0,2);
    sizz(2,1,1);
    sizz(2,2,0);
    zmptrp->bl[2] = 1.08;
    if (!ScrewNotTrans) zmptrp->ibl[2] = 0;
    zmptrp->alph[2] = 90.0;
    zmptrp->ialph[2] = 0;
    zmptrp->bet[2] = 0.0;

    sizz(3,1,2);
    sizz(3,2,1);
    zmptrp->alph[3] = 120.0;
    zmptrp->bet[3] = 120.0;
    
    sizz(4,2,2);
    zmptrp->bet[4] = 120.0;

    for (j=0; j < *zmptrp->nz; j++) xyzp->iatclr[j] = 12;

    xyzp->qat[0] = 0.0;
    xyzp->qat[1] = 0.0;
    for (j=frglen-1; j >= 0; j--) {
	xyzp->iresid[j+2] = 1;
	xyzp->qat[j+2] = xyzp->qat[j];
    }

    xxprev = 1;
    xprev = 2;

    for (i=0; i < nfrg; i++) {

	offset = *zmptrp->nz;
	offhlp = offset;
	*zmptrp->nz = *zmptrp->nz + 1;
	zmptrp->ianz[offset] = 99;
	sizz(offset,0,xprev);
	sizz(offset,1,xprev + 1);
	sizz(offset,2,xxprev);
	zmptrp->bl[offset] = zmptrp->bl[1];
	zmptrp->ibl[offset] = 2;
	zmptrp->alph[offset] = 90.0;
	zmptrp->ialph[offset] = 0;
	zmptrp->bet[offset] = 180.0;
	zmptrp->ibet[offset] = 0;
        xyzp->qat[offset] = 0.0;

	offset++;

	CopyFrag(frag,frglen,3);

	sizz(offset,0,offset);
	sizz(offset,1,xprev);
	sizz(offset,2,xprev + 1);
	zmptrp->bl[offset] = zmptrp->bl[2];
	zmptrp->ibl[offset] = 3;
	zmptrp->alph[offset] = 90.0;
	zmptrp->ialph[offset] = 0;
	zmptrp->bet[offset] = scangle;
	if (i == 0) {
	   zmptrp->ibet[offset] = 0;
	   iscangle = offset + 1;
	} else {
	   zmptrp->ibet[offset] = iscangle;
	}
   
	offset++;

	sizz(offset,1,offset - 1);
	sizz(offset,2,xprev);
	zmptrp->alph[offset] = zmptrp->alph[3];
	zmptrp->ialph[offset] = 4;
	zmptrp->bet[offset] = zmptrp->bet[3];
	zmptrp->ibet[offset] = 4;
    
	offset++;
	sizz(offset,2,offset - 2);
	zmptrp->bet[offset] = zmptrp->bet[4];
	zmptrp->ibet[offset] = 5;

	xxprev = xprev;
	xprev = 2 + (1+frglen)*(i+1);

	for (j=offhlp; j < *zmptrp->nz; j++) xyzp->iatclr[j] = i + 1;

	for (j=frglen-1; j >= 0 ; j--) {
	   xyzp->iresid[j+offhlp+1] = i+1;
	   xyzp->qat[j+offhlp+1] =arr[j];
	}
    }

    for (j=0; j < *zmptrp->nz; j++) xyzp->iaton[j] = 1;
    update_sel = 1;

    DeActZME(); 

    *zmptrp->ihaszm = 1;

    SetQZME(); 

    ZME_window_pos = 0;

    if (*zmptrp->nz < ZME_window_high) RedrawZME();
    else UpdateZME();

#if defined(VMS) || defined(UNDERSC)
    dumzm(xyzp->coo,xyzp->ianz,xyzp->iatoms);
    doconn();docent();doclr();qupd();
#else
#ifdef CRAY
    DUMZM(xyzp->coo,xyzp->ianz,xyzp->iatoms);
    DOCONN();DOCENT();doclr();QUPD();
#else
    dumzm_(xyzp->coo,xyzp->ianz,xyzp->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 < *xyzp->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 < *xyzp->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 = *zmptrp->nz;

    iret = 1;
    if (nz > *zmptrp->mxzat-28) {
	iret = 0;
	if (AllocZMat(*xyzp->mxnat,ZERO)) 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 (!*zmptrp->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 (zmptrp->ianz[row] == 8) {
		if (zmptrp->ianz[izz(row,0)-1] == 6) {
		   co = izz(row,0)-1;
		   if (izz(row,2) == row) {
			if (zmptrp->ianz[row-1] == 8) {
			    row--;
			    if (update) {
				DeActZME();
				IANZbox[row].active = 1;
			    }
			}
		   }
		   nn = row;
		   if (zmptrp->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;
    calfptr->isal[calfptr->ncalf] = iconf;
    calfptr->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(xyzp->ipdbt,BACK_TYP,frglen-1,nz);
    if (isfirst) {
	xyzp->ipdbt[0] = 1;
	xyzp->iresid[0] = calfptr->ncalf;
	xyzp->iatclr[0] = 12;
    } else {
	xyzp->ipdbt[row] = 1;
	xyzp->iresid[row] = calfptr->ncalf;
	xyzp->iatclr[row] = 12;
    }

    MoveFrag(aminozmt[iamin].zmat,AMINO,aminozmt[iamin].zlines,frglen);
    CopyPDBTyp(xyzp->ipdbt,aminozmt[iamin].ipdbt,aminozmt[iamin].zlines,
		nz+frglen-1);
    frglen = frglen + aminozmt[iamin].zlines;

    if (isfirst) {
	MoveFrag(BACKHS,AMINO,2,frglen);
	CopyPDBTyp(xyzp->ipdbt,BACKHS_TYP,2,nz+frglen-1);
	frglen = frglen + 2;
    }
    AddFrag(AMINO,frglen,109.471,180.0,row,0,0);
    SetPDBArray(xyzp->iresid,frglen-1,calfptr->ncalf,nz);
    SetPDBArray(xyzp->iatclr,frglen-1,12,nz);

    if (isfirst) {
	zmptrp->bet[nz+2] = apsi;
    } else if (amiami) {
	if (iamin != 14) {
	    sizz(nz+4,2,co + 1);
	    zmptrp->bet[nz+4] = 180.0;
	}
	zmptrp->bl[nn] = 1.340;
	zmptrp->alph[nn] = 112.7;
	sizz(nz,1,co + 1);
	sizz(nz,2,ca + 1);
	zmptrp->alph[nz] = 121.0;
	if (omega != NULL) zmptrp->bet[nz] = *omega;
	else zmptrp->bet[nz] = 180.0;
	sizz(nz+1,2,co + 1);
	zmptrp->bet[nz+1] = aphi;
	zmptrp->bet[nz+2] = apsi;
    }

    sidechainstart = nz+5;
    if (iamin == 14) sidechainstart = nz+4;
    if (chi1 != NULL && aminozmt[iamin].chis[0] != -1) 
	zmptrp->bet[sidechainstart-1+aminozmt[iamin].chis[0]] = *chi1;
    if (chi2 != NULL && aminozmt[iamin].chis[1] != -1) 
	zmptrp->bet[sidechainstart-1+aminozmt[iamin].chis[1]] = *chi2;
    if (chi3 != NULL && aminozmt[iamin].chis[2] != -1) 
	zmptrp->bet[sidechainstart-1+aminozmt[iamin].chis[2]] = *chi3;
    if (chi4 != NULL && aminozmt[iamin].chis[3] != -1) 
	zmptrp->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 = *zmptrp->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=*zmptrp->nz-1; j >= row; j--) {
	zmptrp->bl[j+nlines] = zmptrp->bl[j];
	zmptrp->alph[j+nlines] = zmptrp->alph[j];
	zmptrp->bet[j+nlines] = zmptrp->bet[j];
	zmptrp->ianz[j+nlines] = zmptrp->ianz[j];
	zmptrp->imap[j+nlines] = zmptrp->imap[j] + nlines;
	for (k=0; k < 4; k++) {
	   prot = 0;
	   for (l=0; l < nprot; l++) {
		if ((izz(j,k) == iprot[l]) && xyzp->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(zmptrp->ibl[j]) < row+1) 
	   zmptrp->ibl[j+nlines] = zmptrp->ibl[j];
	else zmptrp->ibl[j+nlines] = zmptrp->ibl[j]-SIGN(zmptrp->ibl[j]);

	if (ABS(zmptrp->ialph[j]) < row+1)
	   zmptrp->ialph[j+nlines] = zmptrp->ialph[j];
	else zmptrp->ialph[j+nlines] = zmptrp->ialph[j]-SIGN(zmptrp->ialph[j]);

	if (ABS(zmptrp->ibet[j]) < row+1) 
	   zmptrp->ibet[j+nlines] = zmptrp->ibet[j];
	else zmptrp->ibet[j+nlines] = zmptrp->ibet[j]-SIGN(zmptrp->ibet[j]);
    }

    for (j=*xyzp->iatoms-1; j >= row; j--) {
	xyzp->iatclr[j+nlines] = xyzp->iatclr[j];
	if (xyzp->iresid[j] >= ires) {
	   xyzp->iresid[j+nlines] = xyzp->iresid[j] + seq_len;
        } else {
	   xyzp->iresid[j+nlines] = xyzp->iresid[j];
	}
	xyzp->iaton[j+nlines] = xyzp->iaton[j];
	xyzp->ianz[j+nlines] = xyzp->ianz[j];
	stocp->ianstc[j+nlines] = xyzp->ianz[j];
	xyzp->ipdbt[j+nlines] = xyzp->ipdbt[j];
	xyzp->ityp[j+nlines] = xyzp->ityp[j];
	if (qdpptr->ihasq) xyzp->qat[j+nlines] = xyzp->qat[j];
	for (k=0; k < 3; k++) {
	   xyzp->coo[(j+nlines)*3+k] = xyzp->coo[j*3+k];
	   stocp->cstoc[(j+nlines)*3+k] = xyzp->coo[j*3+k];
	   stocp->czstoc[(j+nlines)*3+k] = xyzp->coo[j*3+k];
	}
	kcon = 0;
	for (k=0; k < xyzp->iconn[j*(MXCON+1)]; k++) {
	   noab = xyzp->iconn[j*(MXCON+1)+k+1];
	   ab = ABS(noab);
	   prot = 0;
	   for (l=0; l < nprot; l++) {
		if ((ab == iprot[l]) && xyzp->iresid[j] <= 0) prot = 1;
	   }
	   if (ab > row && !prot) {
		if (noab > 0) {
		   xyzp->iconn[(j+nlines)*(MXCON+1)+kcon+1] = noab + nlines;
		} else {
		   xyzp->iconn[(j+nlines)*(MXCON+1)+kcon+1] = noab - nlines;
		}
		kcon++;
	   } else {
		xyzp->iconn[(j+nlines)*(MXCON+1)+kcon+1] = noab;
		kcon++;
	   }
	}
	xyzp->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 = *zmptrp->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;
	zmptrp->ianz[addrow] = 8;
    } else {
	row = -1;
	ica = calfptr->icalf[ires-2][0] - 1;
	for (i=ica; i < *zmptrp->nz; i++) {
	    if (xyzp->iresid[i] != ires-1) {
		row = i; break;
	    }
	}
	if (row == -1) row = *zmptrp->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];
	   calfptr->isal[j+seq_len] = calfptr->isal[j];
	   calfptr->irsnr[j+seq_len] = calfptr->irsnr[j]+seq_len;
	   strcpy(achain[j+seq_len],achain[j]);
	}
    }

    *zmptrp->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;
	zmptrp->ianz[in-1] = 7;
	xyzp->ipdbt[in-1] = 1;
	xyzp->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 (zmptrp->ianz[ica+4] == 1 && zmptrp->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 (zmptrp->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 (zmptrp->ianz[ica+3] == 8 && zmptrp->ianz[ica+4] == 6) {
/* regular pro */
	   sizz(ica+4,0,ica+1);
	   sizz(ica+4,2,in);
	} else if (zmptrp->ianz[ica+2] == 8 && zmptrp->ianz[ica+3] == 6) {
/* end pro */
	   sizz(ica+3,0,ica+1);
	   sizz(ica+3,2,in);
	}


	xyzp->iatclr[in-1] = xyzp->iatclr[ica];

    }
    if (ires == 1) {
	zmptrp->alph[ica] = 121.0;
	zmptrp->bet[ica] = 180.0;
	zmptrp->bet[ica+1] = phi_angle;
	zmptrp->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);
	     }
	}
    }


    *zmptrp->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 > *zmptrp->nz-1-ZME_window_high) {
	   if (*zmptrp->nz-1-ZME_window_high >= 0) {
	    ZME_window_pos = *zmptrp->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 = zmptrp->bet[icap+1];
	for (i=0; i < 3; i++) {
	   refa1[i] = stocp->czstoc[ina*3+i];
	   refa2[i] = stocp->czstoc[ica*3+i];
	   refa3[i] = stocp->czstoc[ico*3+i];
	}
   }

   if (ires >= calfptr->ncalf) {
	for (i=ica; i < *zmptrp->nz; i++) {
	    if (xyzp->iresid[i] != ires) {
		ica2 = i; break;
	    }
	}
	if (ica2 == -1) ica2 = *zmptrp->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 = zmptrp->bet[ica+1];

/* if list2: psi_angle != zmptrp->bet[ica+2]; */
	psi_angle = zmptrp->bet[ica+2];

	omeg = zmptrp->bet[ica];
	for (i=0; i < 4; i++) {
           bl1[i] = zmptrp->bl[ica+i];
           alph1[i] = zmptrp->alph[ica+i];
           bet1[i] = zmptrp->bet[ica+i];
	}
	if (zmptrp->ianz[ica+2] == 7) {
	   ilst1 = 0;
	} else if (zmptrp->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 = zmptrp->bet[ica2];
	}

	for (i=0; i < 3; i++) {
           bl2[i] = zmptrp->bl[ica2+i];
           alph2[i] = zmptrp->alph[ica2+i];
	}
	bl3[0] = zmptrp->bl[ica0];
	alph3[0] = zmptrp->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 < *zmptrp->nz; i++) {
	ktyp = 0;
	if (xyzp->iresid[i] <= 0) ktyp = 1;
	if ((xyzp->iresid[i] == ires) && (xyzp->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) zmptrp->bet[ica+1] = phi_angle;
	if (ilst2) {
	   zmptrp->bet[ica+2] = psi_angle;
	   zmptrp->bet[ica+3] = bet1[2];
	}
	if (ires == 1) {
	   icap = calfptr->icalf[1][0] - 1;
	   zmptrp->bet[ica+2] = psi_angle;
	   zmptrp->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++) {
           zmptrp->bl[ica+i] = bl1[i];
           zmptrp->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) {
           zmptrp->bl[ica+2] = bl2[0];
           zmptrp->alph[ica+2] = alph2[0];
           zmptrp->bl[ica+3] = bl1[3];
           zmptrp->alph[ica+3] = alph1[3];
	}
	zmptrp->bl[ica0] = bl3[0];
	zmptrp->alph[ica0] = alph3[0];
	zmptrp->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) xyzp->iresid[i+nefflin] = ires;
   }

   if (ires == 1) {
	for (i=0; i < 3; i++) {
	   xyzp->coo[i]   = refa1[i];
	   xyzp->coo[3+i] = refa2[i];
	   xyzp->coo[6+i] = refa3[i];
	}
   }

}

prtzmt(ibeg)
int ibeg;
{
   int i;

   fprintf(stderr,"Zmatrix\n");
   fprintf(stderr,"zmptrp->nz %d\n",*zmptrp->nz);
   for (i=ibeg; i < *zmptrp->nz; i++) {
	fprintf(stderr,"zmt %d ianz %d iz0 %d iz1 %d iz2 %d\n",i,zmptrp->ianz[i],izz(i,0),izz(i,1),izz(i,2));
	fprintf(stderr,"atm iresid %d ipdbt %d ityp %d iaton %d \n",xyzp->iresid[i],xyzp->ipdbt[i],xyzp->ityp[i],xyzp->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],calfptr->isal[i],calfptr->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 = *zmptrp->nz + i;
	if (linkoffset != -1) {
	   variablestatus = linkoffset + i;
	} else {
	   variablestatus = 1;
	}
	zmptrp->ianz[offset] = frag[i].ianz;
	for (j=0; j < 3; j++) {
	    sizz(offset,j, frag[i].iz[j] + *zmptrp->nz);
	}
	sizz(offset,3,0);
	zmptrp->bl[offset] = frag[i].bl;
	zmptrp->ibl[offset] = variablestatus;
	zmptrp->alph[offset] = frag[i].alph;
	zmptrp->ialph[offset] = variablestatus;
	zmptrp->bet[offset] = frag[i].bet;
	zmptrp->ibet[offset] = variablestatus;
    }
    *zmptrp->nz = *zmptrp->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 (!*zmptrp->nz) isfirst = 1;

    if (DEBUG) {
	fprintf(stderr,"nz %d\n",*zmptrp->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;
		*zmptrp->nz = 1;
	   } else {
		return;
	   }
	}
    } else row = addrow;

    atnr = 6;
    irt = NHETRES;
    rest = zmptrp->imap[row]-1;
    if (rest >= 0) irt = GetRes(atnr,&iph,rest);

    if (*zmptrp->nz >1) {
	zmptrp->ianz[row] = frag[0].ianz;
	zmptrp->bl[row] = 
		CalcBL(0,frag[0].ianz,zmptrp->ianz[izz(row,0)-1]);
	if (pdbt) {

	   iptr1 = row;
	   if (*ialtyp) iptr1 = iptr1 + *iscst;

	   xyzp->ipdbt[iptr1] = 0;
	   xyzp->ityp[iptr1] = 0;
	   xyzp->iresid[iptr1] = irt;
	   xyzp->iatclr[iptr1] = 1;
	   xyzp->iaton[iptr1] = 1;
	}
    }

    if (*zmptrp->nz == 1) {
	row = 0;
        zmptrp->ianz[0] = frag[0].ianz;
    }

    for (i=1; i < fraglen; i++) {
	offset = *zmptrp->nz + i - 1;
	zmptrp->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] + *zmptrp->nz - 1);
	    }
	}
	sizz(offset,3, frag[i].iz[3]);
	zmptrp->bl[offset] = frag[i].bl;
	zmptrp->ibl[offset] = 1;
	zmptrp->alph[offset] = frag[i].alph;
	zmptrp->ialph[offset] = 1;
	zmptrp->bet[offset] = frag[i].bet;
	zmptrp->ibet[offset] = 1;
	zmptrp->imap[offset] = offset+1;
	xyzp->iatclr[offset] = 12;
	if (pdbt) {

	    iptr1 = offset;
	    if (*ialtyp) iptr1 = iptr1 + *iscst;

	    xyzp->ipdbt[iptr1] = 0;
	    xyzp->iresid[iptr1] = irt;
	    xyzp->iatclr[iptr1] = 1;
	    xyzp->ityp[iptr1] = 0;
	    xyzp->iaton[iptr1] = 1;
	}
    }


    sizz(1,1,0);
    sizz(1,2,0);
    sizz(1,3,0);
    sizz(2,2,0);
    sizz(2,3,0);
    zmptrp->alph[1] = 0.0;
    zmptrp->bet[1] = 0.0;
    zmptrp->bet[2] = 0.0;

    if (*zmptrp->nz > 1) {
	offset = *zmptrp->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));
	}
	zmptrp->alph[offset] = covang;
	zmptrp->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));
	}
	if (frag == cyclopentane) {
	   zmptrp->bet[offset] = 200.0;
	} else {
	   zmptrp->bet[offset] = 180.0;
	}
    }

    update_sel = 1;
    if (update) DeActZME(); 

    *zmptrp->nz = *zmptrp->nz + fraglen - 1;

    *zmptrp->ihaszm = 1;

    if (update) {

	SetQZME(); 

	ZME_window_pos = *zmptrp->nz-ZME_window_high;
	if (ZME_window_pos < 0) ZME_window_pos = 0;

	if (*zmptrp->nz < ZME_window_high) RedrawZME();
	else UpdateZME();

	*Sinct = 530;
    }
}

AddCycloHexane() {

    AddXH3(6,0);
    (*zmptrp->nz)--;
    DeActZME();
    IANZbox[*zmptrp->nz-2].active = 1;
    AddXH3(6,0);
    DeActZME();
    IANZbox[*zmptrp->nz-3].active = 1;
    AddXH3(6,0);
    strcpy(BETbox[*zmptrp->nz-3].str,"60.0");
    BETbox[*zmptrp->nz-3].changed = 1;
    GetQZME();
    DeActZME();
    IANZbox[*zmptrp->nz-3].active = 1;
    AddXH3(6,0);
    strcpy(BETbox[*zmptrp->nz-3].str,"300.0");
    BETbox[*zmptrp->nz-3].changed = 1;
    DeActZME();
    GetQZME();
    IANZbox[*zmptrp->nz-3].active = 1;
    AddXH3(6,0);
    strcpy(BETbox[*zmptrp->nz-3].str,"60.0");
    BETbox[*zmptrp->nz-3].changed = 1;
    GetQZME();
    DeActZME();
    IANZbox[*zmptrp->nz-3].active = 1;
    AddXH3(6,0);
    strcpy(BETbox[*zmptrp->nz-3].str,"60.0");
    BETbox[*zmptrp->nz-3].changed = 1;
    DeActZME();
    GetQZME();
    (*zmptrp->nz)--;

    ZME_window_pos = *zmptrp->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(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,*xyzp->iatoms,
			cursorx,cursory,MINDIFF);

	if (i >= 0) {
    		update_sel = 1;
		for (j=0; j<*zmptrp->nz; j++) {
			if (i == zmptrp->imap[j]-1) {
				for (k=0; k<*xyzp->iatoms; k++) 
				   if (xyzp->iaton[k] >= 1) xyzp->iaton[k] = 1;
				DeActZME();
				xyzp->iaton[i] = 3;
                                if (ZMEAA) {
				   ires = xyzp->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,zmptrp->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 || *fullgl) {
                iat = FindSel(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,
			*xyzp->iatoms,cursorx,cursory,MINDIFF);
	   } else {
                iat = FindSel(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,
			*xyzp->iatoms,cursorx,cursory,MINDIFF);
                if (iat < 0) ires = FindCaP(cursorx,cursory,MINDIFF);
	   }
	}
   } else {
	if (*ipdbon) {
           iat = FindSel(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,
			*xyzp->iatoms,cursorx,cursory,MINDIFF);
	   if (iat < 0) ires = FindCaP(cursorx,cursory,MINDIFF);
	}
   }

   if ((iat >= 0 || ires >= 0) && *ipdbon) {
	if (iat >= 0) {
	   CurAmino = xyzp->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 (!*zmptrp->ihaszm) return;

  if (qdpptr->ihasq) maparr(NULL,xyzp->qat,NULL,NULL,1);
  maparr(NULL,NULL,NULL,xyzp->ityp,3);
  maparr(NULL,NULL,NULL,xyzp->ipdbt,3);
  maparr(NULL,NULL,xyzp->iatclr,NULL,2);
  maparr(NULL,NULL,xyzp->iresid,NULL,2);

  if ((iarr = (int *) malloc((sizeof j)*(*zmptrp->mxzat))) != NULL) {
    if ((imarr = (int *) malloc((sizeof j)*(*zmptrp->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 = zmptrp->imap[row];

   map_prop();

   for (j=row; j < *zmptrp->nz-nlines; j++) {
	zmptrp->bl[j] = zmptrp->bl[j+nlines];
	zmptrp->alph[j] = zmptrp->alph[j+nlines];
	zmptrp->bet[j] = zmptrp->bet[j+nlines];
	zmptrp->ianz[j] = zmptrp->ianz[j+nlines];
	for (k=0; k < 4; k++) {
	   prot = 0;
	   for (l=0; l < nprot; l++) {
		if ((izz(j+nlines,k) == iprot[l]) && xyzp->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(zmptrp->ibl[j+nlines]) < row+1) 
	   zmptrp->ibl[j] = zmptrp->ibl[j+nlines];
	else zmptrp->ibl[j] = zmptrp->ibl[j+nlines]-SIGN(zmptrp->ibl[j+nlines]);

	if (ABS(zmptrp->ialph[j+nlines]) < row+1)
	   zmptrp->ialph[j] = zmptrp->ialph[j+nlines];
	else zmptrp->ialph[j] = zmptrp->ialph[j+nlines]-SIGN(zmptrp->ialph[j+nlines]);

	if (ABS(zmptrp->ibet[j+nlines]) < row+1) 
	   zmptrp->ibet[j] = zmptrp->ibet[j+nlines];
	else zmptrp->ibet[j] = zmptrp->ibet[j+nlines]-SIGN(zmptrp->ibet[j+nlines]);

	xyzp->iatclr[j]  = xyzp->iatclr[j+nlines];
	xyzp->iresid[j]  = xyzp->iresid[j+nlines];
	xyzp->iaton[j]   = xyzp->iaton[j+nlines];
	xyzp->ianz[j]    = xyzp->ianz[j+nlines];
	stocp->ianstc[j] = xyzp->ianz[j+nlines];
	xyzp->ipdbt[j]   = xyzp->ipdbt[j+nlines];
	xyzp->ityp[j]    = xyzp->ityp[j+nlines];
	if (qdpptr->ihasq) xyzp->qat[j] = xyzp->qat[j+nlines];
	for (k=0; k < 3; k++) {
	   xyzp->coo[j*3+k] = xyzp->coo[(j+nlines)*3+k];
	   stocp->cstoc[j*3+k] = xyzp->coo[(j+nlines)*3+k];
	   stocp->czstoc[j*3+k] = xyzp->coo[(j+nlines)*3+k];
	}
	kcon = 0;
	for (k=0; k < xyzp->iconn[(j+nlines)*(MXCON+1)]; k++) {
	   noab = xyzp->iconn[(j+nlines)*(MXCON+1)+k+1];
	   ab = ABS(noab);
	   prot = 0;
	   for (l=0; l < nprot; l++) {
		if ((ab == iprot[l]) && xyzp->iresid[j+nlines] <= 0) prot = 1;
	   }
	   if (ab > row && !prot) {
		if (noab > 0) {
		   xyzp->iconn[j*(MXCON+1)+kcon+1] = noab - nlines;
		} else {
		   xyzp->iconn[j*(MXCON+1)+kcon+1] = noab + nlines;
		}
		kcon++;
	   } else {
		xyzp->iconn[j*(MXCON+1)+kcon+1] = noab;
		kcon++;
	   }
	}
	xyzp->iconn[j*(MXCON+1)] = kcon;

   }

   for (j=0; j < *zmptrp->nz; j++) {
	zmptrp->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;
   }

   *zmptrp->nz = *zmptrp->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 < xyzp->iconn[(ica+1)*(MXCON+1)]; i++)
	if (xyzp->ianz[xyzp->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 < xyzp->iconn[in*(MXCON+1)]; i++)
	iatje = xyzp->iconn[in*(MXCON+1)+1+i]-1;
	if (xyzp->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 = *zmptrp->nz - ica;
	   for (i=ica; i < *zmptrp->nz; i++) {
		if (xyzp->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 (zmptrp->ianz[ica+2] == 7) {

	   sizz(ica+2,2,in);
	   sizz(ica+4,0,in);
	   sizz(ica+4,2,icop);

	} else {

	   if (zmptrp->ianz[ica+2] == 8) {

		if (zmptrp->ianz[ica+3] == 1) {
		   sizz(ica+3,0,in);
		   sizz(ica+3,2,icop);
		   n = 4;
		}
		if (zmptrp->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
*/
	zmptrp->ianz[in-1] = 8;
	xyzp->iresid[in-1] = xyzp->iresid[in-1] - 1;
	xyzp->ipdbt[in-1] = 38;
   } else {
	xyzp->iatclr[in-1] = xyzp->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 < *zmptrp->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 < *zmptrp->nz; i++) {
	   if (izz(i,0) == inn) sizz(i,0,in);
	}
   }

   for (i=0; i < *zmptrp->nz; i++) {
	if (xyzp->iresid[i] > ires) 
	   xyzp->iresid[i] = xyzp->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];
	calfptr->irsnr[j] = calfptr->irsnr[j+1] - 1;
	calfptr->isal[j] = calfptr->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 >= *zmptrp->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;

   zmpart->imx = -1;
   for (i=ica; i < *zmptrp->nz; i++) {
        if (xyzp->iresid[i] != ires) {
            zmpart->imx = i; break;
        }
   }
   zmpart->imn = ica + 1;
   /*
   zmpart->imn = ica;
   */
   if (zmpart->imx == -1) zmpart->imx = *zmptrp->nz;
   else zmpart->imx++;

   if (ires <= calfptr->ncalf-1) zmpart->imx = ica2;

   if (zmpart->imx > zmpart->imn) zmpart->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 = xyzp->iresid[isel];

   if (ires < 0) {
	zmpart->imn = isel + 1;
	zmpart->imx = *zmptrp->nz;

	if (zmpart->imx > zmpart->imn) zmpart->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 (zmptrp->ianz[ica+2] == 8) { 
		sidechainstart--; 
	}
   } else {
/* if start residue there might be an N missing at nz+2 */

	if (zmptrp->ianz[ica+4] != 1 && zmptrp->ianz[ica+3] == 1) 
		sidechainstart--; 
   }

   if (isel < sidechainstart) return;

   for (i=sidechainstart; i < *zmptrp->nz; i++) {
        if (xyzp->iresid[i] != ires) {
            zmpart->imx = i; break;
        }
   }
   zmpart->imn = sidechainstart + 1;
   zmpart->imx = zmpart->imx + 1;

   if (zmpart->imx > zmpart->imn) zmpart->ipart = 1;
}

int AmiCom(iopt,x,y)
int iopt;
int x;
int y;
{

  if (ZMEAA || (!(ZMEup && *zmptrp->ihaszm) && *ipdbon) ) {
        int ires,i,iflp,ihis;

	iflp = 0;
	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;

	if (has_opengl && (*fancy || *fullgl)) {
	   if (aminotyp == 9 || aminotyp == 13) {
		List.list = AmiNQOpt; List.nents = 16;
	   } else if (aminotyp == 16) {
		List.list = AmiHOpt; List.nents = 16;
	   } else {
		List.list = AmiBOpt; List.nents = 15;
	   }

           if (calfptr->iamino[ires-1] > 23 || 
		(!(ZMEup && *zmptrp->ihaszm) && *ipdbon)) {

		if (aminotyp == 9 || aminotyp == 13 || aminotyp == 16) {
		   List.nents = 7;
		} else {
		   List.nents = 6;
		}
	   } else {
		if (aminotyp == 9 || aminotyp == 13 || aminotyp == 16) {
		   if (ires == calfptr->ncalf) List.nents = 17;
		} else {
		   if (ires == calfptr->ncalf) List.nents = 16;
		}
	   }
	} else if (!has_opengl || (has_opengl && !(*fancy || *fullgl) )) {

	   if (aminotyp == 9 || aminotyp == 13) {
	        List.list = AmiNQOptS; List.nents = 14;
	   } else if (aminotyp == 16) {
	        List.list = AmiHOptS; List.nents = 14;
	   } else {
	        List.list = AmiBOptS; List.nents = 13;
	   }

           if (calfptr->iamino[ires-1] > 23 || 
		(!(ZMEup && *zmptrp->ihaszm) && *ipdbon)) {

		if (aminotyp == 9 || aminotyp == 13 || aminotyp == 16) {
		   List.nents = 5;
		} else {
		   List.nents = 4;
		}
	   } else {
		if (aminotyp == 9 || aminotyp == 13 || aminotyp == 16) {
		   if (ires == calfptr->ncalf) List.nents = 15;
		} else {
		   if (ires == calfptr->ncalf) List.nents = 14;
		}
	   }
	}
  
	   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;
	   }

	   if (aminotyp == 9 || aminotyp == 13) {
		if (iamin == 4) iflp = 1;
		if (iflp) {
#if defined(VMS) || defined(UNDERSC)
		    sngflp(&ires,
#else
#ifdef CRAY
		    SNGFLP(&ires,
#else
		    sngflp_(&ires,
#endif
#endif
			calfptr->iamino,xyzp->coo);
#ifdef DOGL
		    ogres(ires,1,1);
		    update_model = 0;
#endif
		    update_struct();
		    return(0);
		} else {
	   	    if (iamin > 4) iamin--;
		}
	   }

	   if (aminotyp == 16) {
		if (iamin == 4) iflp = 1;
		if (iflp) {
	           List.list = HisOpt; List.nents = 3;

	   	   if (iopt) {
			if (DoPopUp(win,x,y,&List,&ihis,0) == -1) return 0;
	   	   } else {
			if (DoPopUp(ZMEwin,
			   ZMEAAbut[i].x+5,ZMEAAbut[i].y+5,
			   &List,&ihis,0) == -1) return 0;
	   	   }

		   ihis++;
#if defined(VMS) || defined(UNDERSC)
		   sethis(&ires,&ihis,
#else
#ifdef CRAY
		   SETHIS(&ires,&ihis,
#else
		   sethis_(&ires,&ihis,
#endif
#endif
			xyzp->coo,xyzp->qat,xyzp->iresid,xyzp->iatclr,
			xyzp->iaton,xyzp->iconn,xyzp->ianz,&calfptr->ncalf,
			calfptr->icalf,xyzp->ityp,xyzp->ipdbt);
#ifdef DOGL
		   ogres(ires,1,1);
		   update_model = 0;
#endif
		   update_struct();
		   return(0);

		} else {
	   	    if (iamin > 4) iamin--;
		}
	   }

	if (!has_opengl || (has_opengl && !(*fancy || *fullgl) )) {
	   if (iamin >= 4) {
		iamin++;
		iamin++;
	   }
	}

	   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,&ZERO,&ONE,&THRESH);
#else
#ifdef CRAY
			PROXIC(&calfptr->icalf[ires-1][0],backb,&ZERO,&ONE,&THRESH);
#else
			proxic_(&calfptr->icalf[ires-1][0],backb,&ZERO,&ONE,&THRESH);
#endif
#endif
			XMapRaised(display,DISTwin);
			distup = 1;
			RedrawDIST();
			return(1);
			break;
	   case 4:
#if defined(VMS) || defined(UNDERSC)
			proxic(&calfptr->icalf[ires-1][0],backb,&ONE,&ONE,&THRESH);
			initsrf();
#else
#ifdef CRAY
			PROXIC(&calfptr->icalf[ires-1][0],backb,&ONE,&ONE,&THRESH);
	 		INITSRF();
#else
			proxic_(&calfptr->icalf[ires-1][0],backb,&ONE,&ONE,&THRESH);
			initsrf_();
#endif
#endif
			XMapRaised(display,DISTwin);
			distup = 1;
			RedrawDIST();
			return(1);
			break;
	   case 5:
			calfptr->iams[ires-1] = 1;
#if defined(VMS) || defined(UNDERSC)
			initsrf();
#else
#ifdef CRAY
	 		INITSRF();
#else
			initsrf_();
#endif
#endif
		/*	return(1);*/
			break;
	   case 6:
#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 7:
			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 8:	{
			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 = calfptr->irsnr[ires-1];
			ReplaceSequence(Sequence,1,0,ires);
    			calfptr->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 9:	  
			if (!AddCap(ires)) return(0);
			return(1);
			break;
	   case 10:	{  
			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) 
				zmptrp->bet[aaptr[ires-1].chi1] = 
					aminozmt[aminotyp].rots[inrs].rots[0];
			if (aminozmt[aminotyp].chis[1] != -1) 
				zmptrp->bet[aaptr[ires-1].chi2] = 
					aminozmt[aminotyp].rots[inrs].rots[1];
			if (aminozmt[aminotyp].chis[2] != -1) 
				zmptrp->bet[aaptr[ires-1].chi3] = 
					aminozmt[aminotyp].rots[inrs].rots[2];
			if (aminozmt[aminotyp].chis[3] != -1) 
				zmptrp->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 11:	{  
			void scanrot(int,int);

			scanrot(ires,aminotyp);

			}
			break;
	   case 12:	{  
			void onerot(int);

			onerot(ires);

			}
			break;
	   case 13:	
			{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 14:	
			initflx();
			for (i=0; i < *xyzp->iatoms; i++) {
			   if (xyzp->iresid[i] == ires) {
				xyzp->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 15:	
#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 && *zmptrp->ihaszm) && *ipdbon) ) {
        int ires,i;
	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 = 9;

#else
	   List.list = HetOpt; List.nents = 8;

#endif
  
	   if (DoPopUp(win,x,y,&List,&iamin,0) == -1) return 0;

	   switch (iamin) {
	   case 0:
			i = FindSel(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,
					*xyzp->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(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,
					*xyzp->iatoms,x,y,MINDIFF);
			i++; 
#if defined(VMS) || defined(UNDERSC)
			proxic(&i,backb,&ZERO,&ONE,&THRESH);
#else
#ifdef CRAY
			PROXIC(&i,backb,&ZERO,&ONE,&THRESH);
#else
			proxic_(&i,backb,&ZERO,&ONE,&THRESH);
#endif
#endif
			XMapRaised(display,DISTwin);
			distup = 1;
			RedrawDIST();
			return(1);
			break;
	   case 2:
			i = FindSel(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,
					*xyzp->iatoms,x,y,MINDIFF);
			i++; 
#if defined(VMS) || defined(UNDERSC)
			proxic(&i,backb,&ONE,&ONE,&THRESH);
			initsrf();
#else
#ifdef CRAY
			PROXIC(&i,backb,&ONE,&ONE,&THRESH);
	 		INITSRF();
#else
			proxic_(&i,backb,&ONE,&ONE,&THRESH);
			initsrf_();
#endif
#endif
			XMapRaised(display,DISTwin);
			distup = 1;
			RedrawDIST();
			return(1);
			break;
	   case 3:
			inichg(ires);
			break;
	   case 4:
			DelHet(ires);
			return(1);
			break;
	   case 5:
			LigandStruct(ires);
			break;
	   case 6:
			if (CheckWGET()) {
			   LigandHydro(ires);
			} else {
			   LigandHydroPBE(ires);
			}

#ifdef DOGL
			if (*fancy) {
			    oghet(0);
			} else {
			    oglines();
			}
			update_model = 0;
#endif
			update_struct();
			break;
	   case 7:
			if (ires < 0) {
			   int aires;

			   aires = ABS(ires);

			   if (aires < MXHETA) 
				calfptr->ihet[aires] = 0;

			   if (DoPopUp(win, x,y,
				  NULL,Snstr,0) == -1) break;
			   *Sinct = 330;
			   *Sincp = ires;

			   sndon(ires,1,*Snstr);
			   return(1);
			}
			break;
	   case 8:
			if (ires < 0) {
			   int aires;

			   aires = ABS(ires);

			   if (aires < MXHETA) 
				calfptr->ihets[aires] = 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 (*zmptrp->nz <= 2) nvar = *zmptrp->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,*zmptrp->nz)) k = 1;;
	if (QBoxPaste(ZMEwin,BLbox,*zmptrp->nz)) k = 1;;
	if (QBoxPaste(ZMEwin,ALPHbox,*zmptrp->nz)) k = 1;;
	if (QBoxPaste(ZMEwin,BETbox,*zmptrp->nz)) k = 1;;
	if (!k) OnTop();
	return(0);
  } else { 

     if (!ZMEAA) {
        i = ClickBox(IANZbox,*zmptrp->nz,x,y);
        if (i>=0) {
   	   DeActZME();
	   IANZbox[i].col = ZC_AT1;
	   IANZbox[i].active = 1; UpdateZME();
	   if (zmptrp->imap[i]-1 >= 0) xyzp->iaton[zmptrp->imap[i]-1] = 3;
	   sprintf(ZMEerr, "Line %d Atom %d",i+1,zmptrp->imap[i]);
	   RedrawStatus();
	   update_model = 0;
	   update_sel = 1;
	   return(1);
        }
        i = ClickBox(BLbox,*zmptrp->nz,x,y);
        if (i>=0) {
	   ActVar(i,0,butnr);
	   return(1);
        }
        i = ClickBox(ALPHbox,*zmptrp->nz,x,y);
        if (i>=0) {
	   ActVar(i,1,butnr);
	   return(1);
        }
     }
     i = ClickBox(BETbox,*zmptrp->nz,x,y);
     if (i>=0) {
	ActVar(i,2,butnr);
	return(1);
     }
     for (i=0; i<*zmptrp->nz; i++) {
	j = ClickBox(&IZbox[i*4],4,x,y);
	if (j>=0) {
		update_model = 0;
		DeActZME(); 
		iptr = izz(i,j)-1;
		if (iptr < *zmptrp->nz && iptr >= 0) {
			IANZbox[iptr].col = ZC_AT2+j;
			xyzp->iaton[zmptrp->imap[iptr]-1] = 4+j;
		}
		IANZbox[i].col = ZC_AT1;
		IZbox[i*4+j].active = 1;
		UpdateZME();
		if (zmptrp->imap[i]-1 >= 0) xyzp->iaton[zmptrp->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[istruct][j] = 0;
			    SSdone[istruct] = 0;
			    RedrawSTRC();
			    *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 < *zmptrp->nz && row >= 0) {
				for (j=row+1; j < *zmptrp->nz; j++) {
					for (k=0; k < 4; k++)
						if (izz(j,k) == row+1) 
							deloke = 0;
					if (deloke) {
					if (ABS(zmptrp->ibl[j]) == row+1) 
						deloke = -1;
					if (ABS(zmptrp->ialph[j]) == row+1) 
						deloke = -1;
					if (ABS(zmptrp->ibet[j]) == row+1) 
						deloke = -1;
					}
				}
			} else {
				deloke = -2;
			}
			if (deloke == 1) {
				DelLine(row,1,0,NULL);
				if (ZME_window_pos >= *zmptrp->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;
			   cell->ichx = 0;
			   *natorg = 0;
			   DeActZME();
			   *xyzp->iatoms = 0;
			   for (j=0; j < 3; j++)
			      for (k=0; k < 3; k++)
				xyzp->coo[j*3+k] = 0.0;
			   *zmptrp->nz = 0;
			   ZME_window_pos = 0;
			   *zmptrp->ihaszm = 1;
			   geo1ptr->ieav = 0;
			   calfptr->ncalf = 0;
			   *backb = 0;
			   calfptr->nchain = 0;
			   LastAmino = -1;
			   calfptr->issdon = 0;
			   ZMEAA = 0;
          		   SetQZME(); RedrawZME();
			   nwater[istruct] = 0;
			   if (ATMup) {
				UpdateATM();
				XMapRaised(display,ATMwin);
				RedrawATM();
			   }
			   send_expose();
			   empty_model(istruct,1);
			   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,0)) {
				   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();
			RedrawwinMC(0,0,WINMCWIDE,WINMCHIGH);
			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 <*xyzp->iatoms; i++) 
				   if (i < *xyzp->mxnat) jring[i] = 0;
				Selecting = 1; ZMEsel = 1;
				dflag = 1;
				aflag = *xyzp->iatoms; 
				anum = *xyzp->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 < *xyzp->iatoms; i++ ) 
				if (xyzp->iaton[i] > 1) nat++;
			if (!nat) {
				strcpy(ZMEerr,"Invalid Selection: No atoms selected");
				if (*ibell) XBell(display,0);
				RedrawStatus();
				return(0);
			}
			if (nat > *zmptrp->mxzat) {
			   strcpy(ZMEerr,"Invalid Selection: Too many atoms selected");
			   if (*ibell) XBell(display,0);
			   RedrawStatus();
			   for ( i = 0; i < *xyzp->iatoms; i++ ) 
				if (xyzp->iaton[i] >= 2) xyzp->iaton[i] = 1;
			   update_sel = 1;
		  	   return(1);
			}
			else {
			   AGLAB:
			   nprev = -1;
			   nattmp = 0;
			   for ( i = 0; i < *xyzp->iatoms; i++ ) {
				if (xyzp->iaton[i] >= 2) {
			  	    nattmp++;
				    if (i != nprev+1) {
					for ( j = 0; j < *xyzp->iatoms-i; j++ ) {
					    for (k=0; k < 3; k++)
						xyzp->coo[(nprev+1+j)*3+k] = 
						   xyzp->coo[(i+j)*3+k];
					    xyzp->ianz[nprev+1+j] = xyzp->ianz[i+j];
					    xyzp->iaton[nprev+1+j] = xyzp->iaton[i+j];
					    xyzp->iatclr[nprev+1+j] = xyzp->iatclr[i+j];
					    xyzp->iresid[nprev+1+j] = xyzp->iresid[i+j];
					    xyzp->qat[nprev+1+j] = xyzp->qat[i+j];
					    xyzp->ipdbt[nprev+1+j] = xyzp->ipdbt[i+j];
					    xyzp->ityp[nprev+1+j] = xyzp->ityp[i+j];
					}
					if (nattmp < nat) goto AGLAB;
				    }
				    nprev = i;
				}
			   }
		 	   *xyzp->iatoms = nat;
			   cell->ichx = 0; cellpnt->iclon = 0;
			   *ipdbon = 0;
			   ZMEAA = 0;
			   ApplSel(1);
			   empty_model(istruct,1);
			   *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
   }



#if defined(VMS) || defined(UNDERSC)
   intzmt(&ZERO);
#else
#ifdef CRAY
   INTZMT(&ZERO);
#else
   intzmt_(&ZERO);
#endif
#endif

   if (qdpptr->ihasq) maparr(NULL,xyzp->qat,NULL,xyzp->ityp,1);
   maparr(NULL,NULL,NULL,xyzp->ityp,3);
   maparr(NULL,NULL,NULL,xyzp->ipdbt,3);
   maparr(NULL,NULL,xyzp->iatclr,NULL,2);
   maparr(NULL,NULL,xyzp->iresid,NULL,2);

   for ( i = 0; i < *xyzp->iatoms; i++ ) {
	if (xyzp->iaton[i] >= 2) xyzp->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)*(*zmptrp->mxzat))) 
	   != NULL) {

	   for (j=0; j<*zmptrp->nz; j++) {
	      if (zmptrp->imap[j] > 0) {
		flarrt[j] = flarr[zmptrp->imap[j]-1];
	      } else {
		flarrt[j] = 0.0;
	      }
	   }
	   for (j=0; j<*zmptrp->nz; j++) flarr[j] = flarrt[j];
	   free(flarrt);
	}
	break;
   case 1:
	if ((dblarrt = (double *) malloc((sizeof *dblarrt)*(*zmptrp->mxzat))) 
	   != NULL) {

	   for (j=0; j<*zmptrp->nz; j++) {
	      if (zmptrp->imap[j] > 0) {
		dblarrt[j] = dblarr[zmptrp->imap[j]-1];
	      } else {
		dblarrt[j] = 0.0;
	      }
	   }
	   for (j=0; j<*zmptrp->nz; j++) dblarr[j] = dblarrt[j];
	   free(dblarrt);
	}
	break;
   case 2:
	if ((intarrt = (int *) malloc((sizeof *intarrt)*(*zmptrp->mxzat))) 
	   != NULL) {

	   for (j=0; j<*zmptrp->nz; j++) {
	      if (zmptrp->imap[j] > 0) {
		intarrt[j] = intarr[zmptrp->imap[j]-1];
	      } else {
		intarrt[j] = 0;
	      }
	   }
	   for (j=0; j<*zmptrp->nz; j++) intarr[j] = intarrt[j];
	   free(intarrt);
	}
	break;
   case 3:
	if ((shintarrt = (short int *) malloc((sizeof *shintarrt)*(*zmptrp->mxzat))) 
	   != NULL) {

	   for (j=0; j<*zmptrp->nz; j++) {
	      if (zmptrp->imap[j] > 0) {
		shintarrt[j] = shintarr[zmptrp->imap[j]-1];
	      } else {
		shintarrt[j] = 0;
	      }
	   }
	   for (j=0; j<*zmptrp->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 i,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
   or
   wh : wn = slideh : 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 < SCRMIN) 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 (sc->win == DPTwin) {
		RedrawScroll(&dptscr[0]);
		UpdateDPT();
	   } 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 = &zmptrp->ibl[isel] ; break;
	case 1: ii = &zmptrp->ialph[isel]; break;
	case 2: ii = &zmptrp->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 < *zmptrp->nz && iptr >= 0) {
		IANZbox[iptr].col = ZC_AT2+j;
		xyzp->iaton[zmptrp->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 (zmptrp->imap[i]-1 >= 0) xyzp->iaton[zmptrp->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 (xyzp->iresid[isel] > 0) update_res = xyzp->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 = &zmptrp->bl[isel]; 
		if (zmptrp->ibl[isel] > 1) {
		   animptr.variable = &zmptrp->bl[zmptrp->ibl[isel] - 1];
		   animptr.isel = zmptrp->ibl[isel] - 1;
		}
		break;
	    case 1: 
		animptr.variable = &zmptrp->alph[isel]; 
		if (zmptrp->ialph[isel] > 1) {
		   animptr.variable = &zmptrp->alph[zmptrp->ialph[isel] - 1];
		   animptr.isel = zmptrp->ialph[isel] - 1;
		}
		break;
	    case 2: 
		animptr.variable = &zmptrp->bet[isel]; 
		if (ABS(zmptrp->ibet[isel]) > 1) {
		   animptr.variable = &zmptrp->bet[ABS(zmptrp->ibet[isel])-1];
		   animptr.isel = ABS(zmptrp->ibet[isel])-1;
		}
		break;
	}
	animptr.varinit = *animptr.variable;
	animptr.vartype = itype;
	animptr.on = 1;
	FindZRangeFromBox(isel);
	if (zmpart->ipart) animptr.part = zmpart->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 = zmptrp->ibl[isel]; break;
	    case 1: iop = zmptrp->ialph[isel]; break;
	    case 2: iop = zmptrp->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,*zmptrp->nz,
						xev.xbutton.x,xev.xbutton.y); 
				if (ABS(zmptrp->ibl[iop-1]) > 1) ilnkerr = 1;
				break;
			case 1: iop = 1+ClickBox(ALPHbox,*zmptrp->nz,
						xev.xbutton.x,xev.xbutton.y); 
				if (ABS(zmptrp->ialph[iop-1]) > 1) ilnkerr = 1;
				break;
			case 2: iop = 1+ClickBox(BETbox,*zmptrp->nz,
						xev.xbutton.x,xev.xbutton.y); 
				if (ABS(zmptrp->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: 
		zmptrp->ibl[isel] = iop; 
		BLbox[isel].col = icol; 
		BLbox[isel].changed = 1;
		break;
	case 1: 
		zmptrp->ialph[isel] = iop; 
		ALPHbox[isel].col = icol; 
		ALPHbox[isel].changed = 1; 
		break;
	case 2: 
		zmptrp->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) zmpart->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 (zmpart->ipart) return;

	for (i=0; i<*zmptrp->nz; i++) {
	    switch (animptr.vartype) {
		case 0:
		   if (zmptrp->ibl[i] > 1 && 
			zmptrp->ibl[i] - 1 == animptr.isel)
			zmptrp->bl[i] = vartmp;
		   break;
		case 1:
		   if (zmptrp->ialph[i] > 1 &&
			zmptrp->ialph[i] - 1 == animptr.isel)
			zmptrp->alph[i] = vartmp;
		   break;
		case 2:
		   if (ABS(zmptrp->ibet[i]) > 1 && 
			ABS(zmptrp->ibet[i]) - 1 == animptr.isel) {
			if (zmptrp->ibet[i] > 0) {
			   zmptrp->bet[i] = vartmp;
			} else {
			   zmptrp->bet[i] = -vartmp;
			}
		   }
		   break;
	    }
	}
}

DefSlide(sc,win,x,y,w,h,sh,wn,wpos,rat,callback)
SLIDESTRU	*sc;
Window		win;
int		x,y;
unsigned int	w,h;
int		sh;
int		*wn;
int		*wpos;
float		*rat;
ptr_void_proc	callback;
{
  sc->win = win;
  sc->x = x;  sc->y = y;  sc->w = w;  sc->h = h;
  sc->wn = wn;
  sc->wpos = wpos;
  sc->ratio = rat;
  *sc->ratio = *wpos / *wn;
  sc->sh = sh;
  sc->callback = callback;
}


RedrawSlide(sc)
SLIDESTRU *sc;
{
  int slidey,slideh;

  slideh = sc->sh;
  slidey = (int) (sc->h - sc->sh) * (*sc->ratio);

  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);

}

int SlideScroll(sc,x,y)
SLIDESTRU *sc;
int x;
int y;
{
  int i,inslide,wposold;
  XEvent xev;

  inslide = 0;
  if (VIERKANT(x, y, sc->x, sc->y, sc->w, sc->h)) {
	inslide = 1;
  }

  wposold = -1;
  while (inslide) {

	if (*sc->wpos > *sc->wn) *sc->wpos = *sc->wn;
	if (*sc->wpos < 0) *sc->wpos = 0;

        if (*sc->wpos != wposold) {
	   if (sc->win == OMAPwin) {
		if (sc == &omapscr[0]) {
		   RedrawSlide(&omapscr[0]);
		   UpdateOMAP1();
		} else if (sc == &omapscr[1]) {
		   RedrawSlide(&omapscr[1]);
		   UpdateSLAB1();
		} else if (sc == &omapscr[2]) {
		   RedrawSlide(&omapscr[2]);
		   UpdateOMAP2();
		} else if (sc == &omapscr[3]) {
		   RedrawSlide(&omapscr[3]);
		   UpdateSLAB2();
		} else if (sc == &omapscr[4]) {
		   RedrawSlide(&omapscr[4]);
		   UpdateOMAP3();
		} else if (sc == &omapscr[5]) {
		   RedrawSlide(&omapscr[5]);
		   UpdateSLAB3();
		}
	   } else {
		RedrawSlide(sc);
	   }
	   XSync(display,True);
	}
	wposold = *sc->wpos;

	   XNextEvent(display, &xev);
	   switch (xev.type) {
		case ButtonRelease:
		case LeaveNotify:
		   return(1);
		   break;
		case MotionNotify:
		   if (xev.xmotion.window == sc->win)  {
			*sc->ratio = ((float) xev.xmotion.y - (float) sc->y) 
				/ (float) (sc->h - sc->sh);
			if (*sc->ratio < 0.0) *sc->ratio = 0.0;
			if (*sc->ratio > 1.0) *sc->ratio = 1.0;
			*sc->wpos = *sc->wn * (*sc->ratio);
		   }
		   break;
	   }
  } 

  return(0);

}

DefScroll(sc,win,x,y,w,h,wn,wpos,wh,callback)
SCRSTRU		*sc;
Window		win;
int		x,y;
unsigned int	w,h;
int		*wn;
int		*wpos;
int		wh;
ptr_void_proc	callback;
{
  sc->win = win;
  sc->x = x;  sc->y = y;  sc->w = w;  sc->h = h;
  sc->wn = wn;
  sc->wpos = wpos;
  sc->wh = wh;
  sc->callback = callback;
}


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 (zmptrp->imap[i]-1 >= 0)
		xyzp->iaton[zmptrp->imap[i]-1] = 1;
	break;
  case 1:
	iptr = izz(i,0)-1;
	if (iptr < *zmptrp->nz && iptr >= 0) {
		IANZbox[iptr].col = ZC_DEF;
		xyzp->iaton[zmptrp->imap[iptr]-1] = 1;
	}
	IANZbox[i].col = ZC_DEF;
	BLbox[i].active = 0;
	if (zmptrp->imap[i]-1 >= 0)
		xyzp->iaton[zmptrp->imap[i]-1] = 1;
	break;
  case 2:
	for (j=0; j<2; j++) {
		iptr = izz(i,j)-1;
		if (iptr < *zmptrp->nz && iptr >= 0) {
			IANZbox[iptr].col = ZC_DEF;
			xyzp->iaton[zmptrp->imap[iptr]-1] = 1;
		}
	}
	IANZbox[i].col = ZC_DEF;
	ALPHbox[i].active = 0;
	if (zmptrp->imap[i]-1 >= 0)
		xyzp->iaton[zmptrp->imap[i]-1] = 1;
	break;
  case 3:
	for (j=0; j<3; j++) {
		iptr = izz(i,j)-1;
		if (iptr < *zmptrp->nz && iptr >= 0) {
			IANZbox[iptr].col = ZC_DEF;
			xyzp->iaton[zmptrp->imap[iptr]-1] = 1;
		}
	}
	IANZbox[i].col = ZC_DEF;
	BETbox[i].active = 0;
	if (zmptrp->imap[i]-1 >= 0)
		xyzp->iaton[zmptrp->imap[i]-1] = 1;
	break;
  case 4:
	iptr = izz(i,j)-1;
	if (iptr < *zmptrp->nz && iptr >= 0) {
		IANZbox[iptr].col = ZC_DEF;
		xyzp->iaton[zmptrp->imap[iptr]-1] = 1;
	}
	IANZbox[i].col = ZC_DEF;
	IZbox[i*4+j].active = 0;
	if (zmptrp->imap[i]-1 >= 0)
		xyzp->iaton[zmptrp->imap[i]-1] = 1;
	break;
  }
  update_sel = 1;
}

UndoZME()
{
  int i,j,type;

  activeZME(&type,&i,&j);
  switch(type) {
  case 0:
        if (zmptrp->ianz[i] >= 0 && zmptrp->ianz[i] < 100)
             sprintf(stemp,"%s",elements[zmptrp->ianz[i]]);
        else sprintf(stemp,"%s","?");
	strcpy(IANZbox[i].str,stemp);
	PromptBox(&IANZbox[i]);
	break;
  case 1:
	sprintf(stemp,"%f",zmptrp->bl[i]);
	strcpy(BLbox[i].str,stemp);
	PromptBox(&BLbox[i]);
	break;
  case 2:
	sprintf(stemp,"%f",zmptrp->alph[i]);
	strcpy(ALPHbox[i].str,stemp);
	PromptBox(&ALPHbox[i]);
	break;
  case 3:
	sprintf(stemp,"%f",zmptrp->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<*zmptrp->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)*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, fsel.win, WaitCursor);
	XDefineCursor(display, ZMEwin, WaitCursor);
	if (specup) XDefineCursor(display, winspec, WaitCursor);
	if (FRup) XDefineCursor(display, FrBox, WaitCursor);
	if (FLXup) XDefineCursor(display, FLXwin, WaitCursor);
	if (STRup) XDefineCursor(display, STRwin, WaitCursor);
	if (STRCup) XDefineCursor(display, STRCwin, WaitCursor);
	if (OMAPup) XDefineCursor(display, OMAPwin, WaitCursor);
   } else {
	XUndefineCursor(display, win);
	XUndefineCursor(display, winMC);
	XUndefineCursor(display, winC);
	XUndefineCursor(display, fsel.win);
	XUndefineCursor(display, ZMEwin);
	if (specup) XUndefineCursor(display, winspec);
	if (FRup) XUndefineCursor(display, FrBox);
	if (FLXup) XUndefineCursor(display, FLXwin);
	if (STRup) XUndefineCursor(display, STRwin);
	if (STRCup) XUndefineCursor(display, STRCwin);
	if (OMAPup) XUndefineCursor(display, OMAPwin);
   }
   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,w,h;

   if (!xison) return;
#ifdef DOGL
   dispsf();
#endif

   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 16: 
		InitOmap(0);
		omapr = 1;
		return;
		break;
	case 17: 
		strcpy(statstr,"WARNING Mol2: atom type inconsistancy, please retyp !");
		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;
	case 21: 
		strcpy(statstr,"MD complete");
		break;
	case 22: 
		InitOmap(1);
		omapr = 2;
		return;
		break;
	default:
		break;
   }

   x = event.xbutton.x_root; y = event.xbutton.y_root;
   w = DisplayWidth(display,screen);
   h = DisplayHeight(display,screen);
   if (x < 0 || x > w) x = w / 2;
   if (y < 0 || y > h) y = h / 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 6:	sprintf(stemp,"J-Coupling %#11.5f",val);
		nval = 22;
		aselkeep[0] = asel[0];
		aselkeep[1] = asel[1];
		monmode = opt;
		break;
   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];
		monmode = opt;
		break;
   default:	break;
   }
   XDrawString(display, distpix, gc, 10, 15, stemp, nval);

   if (opt == 2 || opt == 6) {
	ActBut(&clbut[BMONI],1);
   } else {
	ActBut(&clbut[BMONI],0);
   }

   if (!distup) {
	XMapRaised(display,DISTwin);
	RedrawDIST();
	distup = 1;
   } else {
	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 (monmode == 2) {
#if defined(VMS) || defined(UNDERSC)
		   setmon(aselkeep,&anum);
#else
#ifdef CRAY
		   SETMON(aselkeep,&anum);
#else
		   setmon_(aselkeep,&anum);
#endif
#endif
		} else if (monmode == 6) {
		   double coupl;

		   coupl = jcoupl[(aselkeep[0]-1)*NAT->natoms + aselkeep[1]-1];
#if defined(VMS) || defined(UNDERSC)
		   stjmon(&coupl,aselkeep,&TWO);
#else
#ifdef CRAY
		   STJMON(&coupl,aselkeep,&TWO);
#else
		   stjmon_(&coupl,aselkeep,&TWO);
#endif
#endif
		}
		if (has_opengl && (*fancy || *fullgl)) {
		   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<xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)]; j++) {
		   if (ABS(xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)+1+j]) == aselkeep[1]) 
			iscon1 = j;
       		}
		for (j=0; j<xyzp->iconn[(aselkeep[1]-1)*(MXCON+1)]; j++) {
		   if (ABS(xyzp->iconn[(aselkeep[1]-1)*(MXCON+1)+1+j]) == aselkeep[0]) 
			iscon2 = j;
       		}
		if (iscon1 != -1 || iscon2 != -1) {
		    if (iscon1 != -1) {
			for (j=iscon1; j<xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)]-1; j++) 
			   xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)+1+j] = 
				xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)+2+j];
			xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)] = 
				xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)] - 1;
		    }
		    if (iscon2 != -1) {
			for (j=iscon2; j<xyzp->iconn[(aselkeep[1]-1)*(MXCON+1)]-1; j++) 
			   xyzp->iconn[(aselkeep[1]-1)*(MXCON+1)+1+j] = 
				xyzp->iconn[(aselkeep[1]-1)*(MXCON+1)+2+j];
			xyzp->iconn[(aselkeep[1]-1)*(MXCON+1)] = 
				xyzp->iconn[(aselkeep[1]-1)*(MXCON+1)] - 1;
		    }
		} else {
		   if (xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)] < MXCON) {
			xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)] = 
			   xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)] + 1;
			xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)+xyzp->iconn[(aselkeep[0]-1)*(MXCON+1)]] =
			aselkeep[1];
		   }
		   if (xyzp->iconn[(aselkeep[1]-1)*(MXCON+1)] < MXCON) {
			xyzp->iconn[(aselkeep[1]-1)*(MXCON+1)] = 
			   xyzp->iconn[(aselkeep[1]-1)*(MXCON+1)] + 1;
			xyzp->iconn[(aselkeep[1]-1)*(MXCON+1)+xyzp->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 = potcom->nplev+1;
    if (hlpsrf->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 || *fullgl) && hlpsrf->itsrf)) {
		if (DoPopUp(win,cursorx-20,cursory,NULL,&j,0) == -1) return 0;
		i = (cursory - jy) / PEH;
		if (i > potcom->nplev) i = potcom->nplev;
		potcom->ipcol[i] = j;
		*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 (hlpsrf->itsrf) return(0);

 if (*doesp) {
	i = FindSel(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,*xyzp->iatoms,
			cursorx,cursory,MINDIFF);
	if (i >= 0) {
	    MkDistWin(xyzp->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 = potcom->nplev+1;
  if (hlpsrf->itsrf) NE = 5;
  PEH = 20;
  PW = 70;
  PH = NE*PEH;
  MW = 10;

  jx = width-PW-20;
  jy = 20;


  if (hlpsrf->itsrf) {
     if (has_opengl && (*fancy || *fullgl) ) {
	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 || *fullgl) ) {
	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[potcom->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[potcom->ipcol[i]]);
	   XFillRectangle(display, molcur, gc, jx,jy+(i * PH)/NE, PW,PEH);
	}
     }
  }

  XSetForeground(display, gc, Black);
  if (hlpsrf->itsrf) {
     if (has_opengl && (*fancy || *fullgl) ) {
	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",potcom->plevel[i]);
	if (has_opengl && (*fancy || *fullgl) ) 
	   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 (MLTup) DirBox(MLTwin,1);
	if (PARup) DirBox(PARwin,1);
	if (FLXup) DirBox(FLXwin,1);
	if (fsel.qbrfile) DirBox(fsel.win,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 (FLRup) DirBox(FLRwin,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);

	if (STRCup) DirBox(STRCwin,1);
	if (STRup) DirBox(STRwin,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("Element 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, -elmptr->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, -elmptr->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",elmptr->vdwr[propat]);
		break;
	    case PDISRAD:
		sprintf(qboxes[QRADI].str,"%f",elmptr->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;
	elmptr->icol[propat] = csel;
	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, 
		-elmptr->icol[propat]);

	DrwBut(&AtmBut[i]);

	break;
    case PVDWRAD:
	sprintf(qboxes[QRADI].str,"%f",elmptr->vdwr[propat]);
	RedrawCOL();
#if defined(VMS) || defined(UNDERSC)
	doconn();
#else
#ifdef CRAY
	DOCONN();
#else
	doconn_();
#endif
#endif
#ifdef DOGL
        ogsetel20(propat);
        ogsetel20_bs(propat);
        ogsetel12(propat);
        ogsetel12_bs(propat);
#endif
	break;
    case PDISRAD:
	sprintf(qboxes[QRADI].str,"%f",elmptr->vrad[propat]*toangs);
	RedrawCOL();
	break;
    case PESPRAD:
	sprintf(qboxes[QRADI].str,"%f",espvdw[propat]);
	RedrawCOL();
	break;
    }

}

SetRadius()
{
     switch (ipropopt) {
     case PATMCOL: 
		break;
     case PVDWRAD: 
		elmptr->vdwr[propat] = atof(qboxes[QRADI].str);
		break;
     case PDISRAD: 
		elmptr->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",
			cell->cellc[j]);
	else if (j<6) sprintf(qboxes[QCPA+j].str,"%-9.3f",
			cell->cellc[j]*todeg);
 }
 sprintf(qboxes[QCPSPGN].str,"%d",cell->nspg);
 
 if (cell->nspg != 0) {
   i = fndchr(spacegr[cell->nspg - 1],' ');
   if (i == 0) i = 7;
   strncpy(qboxes[QCPSPGS].str,spacegr[cell->nspg - 1],i);
   qboxes[QCPSPGS].str[i] = '\0';
 } else {
   strcpy(qboxes[QCPSPGS].str,"unknown");
 }

 if (cell->nspg == 1 || cell->nspg == 2) CPopt = 0;
 if ((cell->nspg >= 3 && cell->nspg <= 15) ||
	cell->nspg == 231 ) CPopt = 1;
 if (cell->nspg >= 16 && cell->nspg <= 74) CPopt = 2;
 if ((cell->nspg >= 75 && cell->nspg <= 194) ||
       (cell->nspg >= 232 && cell->nspg <= 238)) CPopt = 3;
 if (cell->nspg >= 195 && cell->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++) 
		cell->cellc[j] = atof(qboxes[QCPA+j].str);

	   if (qboxes[QCPSPGN].changed) {

		cell->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) {
			cell->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(xyzp->ianz,xyzp->coo,
#else
#ifdef CRAY
	   CHGPAR(xyzp->ianz,xyzp->coo,
#else
	   chgpar_(xyzp->ianz,xyzp->coo,
#endif
#endif
	   &cell->natc,&cell->icent,&cell->nspg,&cell->ichx,
	   &cell->nopr,cell->ir,cell->it,
	   &cell->xyzc[0],&cell->xyzc[1],&cell->xyzc[2],
	   &cell->xyzc[3],&cell->xyzc[4],&cell->xyzc[5],
	   &cell->cellc[0],&cell->cellc[1],&cell->cellc[2],
	   &cell->cellc[3],&cell->cellc[4],&cell->cellc[5]);

	   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 |
	SubstructureNotifyMask | 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, 170, 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 = "Residue number of selected atom\nSelect atom: 2nd Mouse Button";

   qboxstr(&qboxes[QATOM],&ATMwin,0,0,190,ATMOffx+55,36+2*BUTTN,
	100,QBOXHIGH,2,"Number:"," ",6,QPOSINT,2000,dummyproc);
   qboxes[QATOM].explstr = "Number of selected atom\nType a number \nto change Atom selected";

   DefList(&fftlist,ATMwin,6,35+5*BUTTN+QBOXHIGH,ATMWINW-37,110,
	NULL,9,typs[1],NULL,NULL,NULL,Ntyps[1]);

   UpdateATM();

}

UpdateATM()
{
   int i;

   sprintf(qboxes[QCHARG].str,"%f",xyzp->qat[ATMsel]);
   qboxes[QCHARG].dflt = &xyzp->qat[ATMsel];
   sprintf(qboxes[QRSD].str,"%d",xyzp->iresid[ATMsel]);
   qboxes[QRSD].iflt = &xyzp->iresid[ATMsel];
   sprintf(qboxes[QATOM].str,"%d",ATMselp);
   qboxes[QATOM].iflt = &ATMselp;
   fftlist.list.ilst = ffptr[*fftyp];
   if (xyzp->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(xyzp->ityp[ATMsel]) - 1;
   } else {
	fftlist.select = -1;
	for (i=0; i<*Ntyps[*fftyp]; i++)
	   if (abs(xyzp->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 (xyzp->ianz[ATMsel] == ffatnr[*fftyp][i]) {
		fftlist.lpnt = i;
		break;
	   }
	}
   } else {
	if (fftlist.select != -1) {
	   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 < *xyzp->mxnat) {
     if (xyzp->ianz[ATMsel] >= 0 && xyzp->ianz[ATMsel] < MXEL)
	strcpy(atstr,elements[xyzp->ianz[ATMsel]]);
	
  }

  sprintf(nrstr,"Atom: %s", atstr);
  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]);
  PromptBox(&qboxes[QATOM]);
  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,&xyzp->iatclr[ATMsel],0) == -1) break;
	   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(&cell->ichx);
#else
#ifdef CRAY
	   DOTYP(&cell->ichx);
#else
	   dotyp_(&cell->ichx);
#endif
#endif
	   Progs = TnkProgs;
	   nprogs = 6;
	   if (*fftyp == 7) {
		Progs = AmbProgs; 
		nprogs = 3;
		*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,xyzp->qat);
#else
#ifdef CRAY
	   FIXCHG(&totch,xyzp->qat);
#else
	   fixchg_(&totch,xyzp->qat);
#endif
#endif
	   qdpptr->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,0)) {
		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,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->qat);
	nuse = 2; calcij(&nuse,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->qat);
	nuse = 3; calcij(&nuse,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->qat);
	nuse = 4; calcij(&nuse,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->qat);
#else
#ifdef CRAY
	nuse = 0; CALCIJ(&nuse,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->qat);
	nuse = 2; CALCIJ(&nuse,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->qat);
	nuse = 3; CALCIJ(&nuse,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->qat);
	nuse = 4; CALCIJ(&nuse,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->qat);
#else
	nuse = 0; calcij_(&nuse,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->qat);
	nuse = 2; calcij_(&nuse,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->qat);
	nuse = 3; calcij_(&nuse,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->qat);
	nuse = 4; calcij_(&nuse,xyzp->coo,xyzp->ianz,xyzp->iresid,xyzp->iconn,xyzp->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(xyzp->coo,xyzp->ianz,xyzp->iatoms);
	   conpdb();docent();doscal();setxyv();doclr();qupd();
#else
#ifdef CRAY
	   DUMZM(xyzp->coo,xyzp->ianz,xyzp->iatoms);
	   CONPDB();DOCENT();DOSCAL();SETXYV();doclr();QUPD();
#else
   	   dumzm_(xyzp->coo,xyzp->ianz,xyzp->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 i,xmax;
   
   TNKup = 1;

   Progs = TnkProgs;
   nprogs = 6;
   AddChrg = 0;

   if (*ipdbon && calfptr->ncalf) {
	Cutoff = 1;
   } else {
	Cutoff = 0;
   }

   if (*fftyp == 7) {
	Progs = AmbProgs; 
	nprogs = 3;
	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 
	| SubstructureNotifyMask | 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 = "Choose optimisation/MD program";

   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";


   DefBut(&butTNK[6], TNKwin, TNKOffx+200, TNKBROWY, 100, 23, "Constrain", 
	infobg, ZMBCOL);
   butTNK[6].explstr = "Select rigid and flexible parts";

   DefBut(&butTNK[7], TNKwin, 100, TNKRESY+4*TNKBWIDE, 15, 15, " ", 
	infobg, ZMBCOL);
   butTNK[7].explstr = "Use/Create periodic water box";

   DefBut(&butTNK[8], TNKwin, 210, TNKRESY+4*TNKBWIDE, 15, 15, " ", 
	infobg, ZMBCOL);
   butTNK[8].explstr = "Use cutoffs and switch functions (Faster)";

   if (hasmpi) {
	DefBut(&butTNK[9], TNKwin, 300, TNKRESY+4*TNKBWIDE, 15, 15, " ", 
		infobg, ZMBCOL);
	butTNK[9].explstr = "Use multiple processors";
	DefBut(&butTNK[10], TNKwin, 350, TNKRESY+4*TNKBWIDE-5, 30, 23, " ", 
		infobg, ZMBCOL);
	butTNK[10].explstr = "Use # processors";
	butTNK[10].str = Processors[useproc-1];
   }

   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]);
   }
 
   if (Cutoff) {
	TogDown(&butTNK[8]);
   } else {
	TogUp(&butTNK[8]);
   }
 
   if (hasmpi) {
	if (usempi) {
	   TogDown(&butTNK[9]);
	} else {
	   TogUp(&butTNK[9]);
	}
   }
 
   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<ntnkb; i++) DrwBut(&butTNK[i]);
	if (*tnkprg == 1) {
	   qboxes[QGRD].prompt = "Temperature";
	   qboxes[QMAXIT].prompt = "No. of steps";
	} else {
	   qboxes[QGRD].prompt = "RMS Gradient";
	   qboxes[QMAXIT].prompt = "Max. Iteration";
	}
        LineString(TNKwin, "Water Box",TNKOffx, TNKRESY+4*TNKBWIDE+11);
        LineString(TNKwin, "Use Cutoff",235, TNKRESY+4*TNKBWIDE+11);
	if (hasmpi) LineString(TNKwin, "MPI",325, TNKRESY+4*TNKBWIDE+11);
  } else {
	for (i=0; i<NBUTTNK-6; i++) DrwBut(&butTNK[i]);
	qboxes[QGRD].prompt = "RMS Gradient";
	qboxes[QMAXIT].prompt = "Max. Iteration";
  }
  PromptBox(&qboxes[QGRD]);
  PromptBox(&qboxes[QARCH]);
  PromptBox(&qboxes[QTNKJN]);
  PromptBox(&qboxes[QMAXIT]);

}

int ChkJobName()
{
   char JobName[MAXSTRLEN];

   strcpy(JobName,qboxes[QTNKJN].str);
   strcat(JobName,".xyz");
   if (strcmp(strname,JobName) == 0) {
	DoCan(event.xbutton.x_root, event.xbutton.y_root,
	"Jobname and file currently read can not be the same.",0);
	return(0);
   }
   return(1);
}

int ButtonsTNK(i)
int i;
{
  int nwat;

  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];
	   if (Progs == AmbProgs) {
		pbc->icell = 0;
		butTNK[10].str = Processors[useproc-1];
		if (*tnkprg == 1) {
		   *currgrd = 298.0;
		   sprintf(qboxes[QGRD].str,"%-7.2f",*currgrd);
		   *tnkit = 1000;
		   sprintf(qboxes[QMAXIT].str,"%-5d",*tnkit);
		} else {
	   	   *currgrd = mxgrads[0];
		   sprintf(qboxes[QGRD].str,"%-7.2f",*currgrd);
		   *tnkit = 999;
		   sprintf(qboxes[QMAXIT].str,"%-d",*tnkit);
		   if (*tnkprg == 2) {
			pbc->icell = 1;
#if defined(VMS) || defined(UNDERSC)
			fdat(&EIGHTEEN,&ZERO,&ZERO,&ZERO,&ZERO,&ZERO);
#else
#ifdef CRAY
			FDAT(&EIGHTEEN,&ZERO,&ZERO,&ZERO,&ZERO,&ZERO);
#else
			fdat_(&EIGHTEEN,&ZERO,&ZERO,&ZERO,&ZERO,&ZERO);
#endif
#endif
		   }
		}
	  	RedrawTNK();
	   } else {
	   	*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 */
	if (ChkJobName()) {
#ifdef DOGL
	   ogunsel();
#endif
	   if (*ipdbon) {
#ifdef DOGL
		if (!bckrig) empty_ribb();
#endif

#if defined(VMS) || defined(UNDERSC)
		quwat(&nwat);
#else
#ifdef CRAY
		QUWAT(&nwat);
#else
		quwat_(&nwat);
#endif
#endif
		if (nwat > 0) {
		    if (!DoCan(event.xbutton.x_root,event.xbutton.y_root,
		"Waters without Hydrogens detected.\n Should Molden clean up waters ?",1)) {
			if (*fftyp != 7) typit(7,0);
#if defined(VMS) || defined(UNDERSC)
			evwat();
#else
#ifdef CRAY
			EVWAT();
#else
			evwat_();
#endif
#endif
#ifdef DOGL
			if (*fancy) {
			   oghet(0);
			} else {
			   oglines();
			}
			update_model = 0;
#endif
			update_struct();
		    }
	       }
	   
	   }
	   *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(&calfptr->ishoh);
#else
#ifdef CRAY
		CLCEEM(&calfptr->ishoh);
#else
		clceem_(&calfptr->ishoh);
#endif
#endif
	   }
	   if (*ibox || Box) *igfmap = 0;

	   *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;
  case 6:	
	if (!FLRup) CreateFLR();
	break;
  case 7:	
/* Box */
	Box = ! TogBut(&butTNK[7]);
	break;
  case 8:	
/* Cutoffs */
	Cutoff = ! TogBut(&butTNK[8]);
	break;
  case 9:	
/* mpi */
	if (hasmpi) usempi = ! TogBut(&butTNK[9]);
	break;
  case 10:	
/* number of processors */
	{
	LSSTRU List;
	List.list = Processors; List.nents = maxproc;
	if (DoPopUp(TNKwin,butTNK[10].x+1,
		   butTNK[10].y-(maxproc/2)*BUTTH,&List,&useproc,0) == -1) break;
	useproc++;
	butTNK[10].str = Processors[useproc-1];
	DrwBut(&butTNK[10]);
	}
	break;
  default:
	break;
  }
  return(0);
}

rearr(itarr,arr)
int *itarr;
int *arr;
{
   int j;

   for (j=0; j<*zmptrp->nz; j++) {
	itarr[j] = arr[zmptrp->imap[j]-1];
   }
   for (j=0; j<*zmptrp->nz; j++) {
	arr[j] = itarr[j];
   }
}

rearrs(itarr,arr)
int *itarr;
short int *arr;
{
   int j;

   for (j=0; j<*zmptrp->nz; j++) {
	itarr[j] = (int) arr[zmptrp->imap[j]-1];
   }
   for (j=0; j<*zmptrp->nz; j++) {
	arr[j] = (short int) itarr[j];
   }
}

rearrd(itarr,arr)
double *itarr;
double *arr;
{
   int j;

   for (j=0; j<*zmptrp->nz; j++) {
	itarr[j] = arr[zmptrp->imap[j]-1];
   }
   for (j=0; j<*zmptrp->nz; j++) {
	arr[j] = itarr[j];
   }
}

rearrz(itarr)
int *itarr;
{
   int j;

   for (j=0; j<*zmptrp->nz; j++) itarr[j] = -1;
   for (j=0; j<*zmptrp->nz; j++) {
	if (zmptrp->imap[j] > 0) {
	   itarr[zmptrp->imap[j]-1] = j;
	}
   }
}

int mapchk()
{
   int j;

    if (*ialtyp) return(1);

    for (j=0; j<*zmptrp->nz; j++) {
	if (zmptrp->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 (!*zmptrp->ihaszm) { 
	   if (!DoCan(200,100,
		"Do You want to create a Z-matrix for this molecule ?",1)) {
	     *ioke = 1;
	     if (*xyzp->iatoms > *zmptrp->mxzat - 100) {
		*ioke = 0;
                if (AllocZMat(*xyzp->mxnat,ZERO)) *ioke = 1;
	     }
	   }
	}
}

int DoPDB()
{
int i,j,k;
double d;
int *iarr;
double *darr;
int imarr[NUMCAL];
int ioke;


	if (!*zmptrp->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 (*xyzp->iatoms > *zmptrp->mxzat - 100) {
		ioke = 0;
		if (AllocZMat(*xyzp->mxnat,ZERO)) 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 (*zmptrp->ihaszm) {

		   if ((iarr = (int *) malloc((sizeof j)*(*zmptrp->mxzat))) 
				!= NULL) {

			rearr(iarr,xyzp->iatclr);
			rearr(iarr,xyzp->iresid);
			rearr(iarr,xyzp->iaton);
			rearrs(iarr,xyzp->ityp);
			rearrs(iarr,xyzp->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)*(*zmptrp->mxzat))) 
				!= NULL) {

			rearrd(darr,xyzp->qat);
			free(darr);
		   }

/* old, with centering */   /*conpdb();chkbck();docent();doclr();qupd();*/

#if defined(VMS) || defined(UNDERSC)
		   dumzm(xyzp->coo,xyzp->ianz,xyzp->iatoms);
		   conpdb();chkbck();doclr();qupd();
		   if (*backb) {
			for (i=0;i<4;i++) 
			   acthel(&ONE,&i,&clfhptr->isndcl[i],&ZERO);
		   }
#else
#ifdef CRAY
		   DUMZM(xyzp->coo,xyzp->ianz,xyzp->iatoms);
		   CONPDB();CHKBCK();doclr();QUPD();
		   if (*backb) {
			for (i=0;i<4;i++)
			   ACTHEL(&ONE,&i,&clfhptr->isndcl[i],&ZERO);
		   }
#else
		   dumzm_(xyzp->coo,xyzp->ianz,xyzp->iatoms);
		   conpdb_();chkbck_();doclr();qupd_();
		   if (*backb) {
			for (i=0;i<4;i++) 
			   acthel_(&ONE,&i,&clfhptr->isndcl[i],&ZERO);
		   }
#endif
#endif
		   make_aa();
		
		   if (ZMEup) {
			SetQZME();
			if (ZME_window_pos >= *zmptrp->nz) ZME_window_pos = 0;
			RedrawZME();
			RedrawScroll(&zscroll);
		   }
		}
		SSdone[istruct] = 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 = *xyzp->mxnat - cell->natc;
	while (i < cell->natc) {
	  if (xyzp->iaton[i] == 2) {
	    for (j=i; j < cell->natc - 1; j++) {
		xyzp->iatclr[nstor+j] = xyzp->iatclr[nstor+j+1];
		xyzp->ianz[nstor+j] = xyzp->ianz[nstor+j+1];
		xyzp->ipdbt[nstor+j] = xyzp->ipdbt[nstor+j+1];
		xyzp->ityp[nstor+j] = xyzp->ityp[nstor+j+1];
		xyzp->qat[j] = xyzp->qat[j+1];
		for (k=0; k < 3; k++)
		   xyzp->coo[(nstor+j)*3+k] = xyzp->coo[(nstor+j+1)*3+k];
		kcon = 0;
		for (k=0; k < xyzp->iconn[(nstor+j+1)*(MXCON+1)]; k++) {
		   noab = xyzp->iconn[(nstor+j+1)*(MXCON+1)+k+1];
		   ab = ABS(noab);
		   if (ab > i+1) {
			if (noab > 0) {
			   xyzp->iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab - 1;
			} else {
			   xyzp->iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab + 1;
			}
			kcon++;
		   } else if (ab != i+1) {
			xyzp->iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab;
			kcon++;
		   }
		}
		xyzp->iconn[(nstor+j)*(MXCON+1)] = kcon;
		xyzp->iaton[j] = xyzp->iaton[j+1];
	    }
	    cell->natc = cell->natc - 1;
	    for (j=0; j < i; j++) {
		kcon = 0;
		for (k=0; k < xyzp->iconn[(nstor+j)*(MXCON+1)]; k++) {
		   noab = xyzp->iconn[(nstor+j)*(MXCON+1)+k+1];
		   ab = ABS(noab);
		   if (ab > i+1) {
			if (noab > 0) {
			   xyzp->iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab - 1;
			} else {
			   xyzp->iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab + 1;
			}
			kcon++;
		   } else if (ab != i+1) {
			xyzp->iconn[(nstor+j)*(MXCON+1)+kcon+1] = noab;
			kcon++;
		   }
		}
		xyzp->iconn[(nstor+j)*(MXCON+1)] = kcon;
	    }
	  } else {
	    i++;
	  }
	}
	nold = nstor;
	nstor = *xyzp->mxnat - cell->natc;
	for (j=cell->natc - 1; j >= 0; j--) {
	   xyzp->iatclr[nstor+j] = xyzp->iatclr[nold+j];
	   xyzp->ianz[nstor+j] = xyzp->ianz[nold+j];
	   xyzp->ipdbt[nstor+j] = xyzp->ipdbt[nold+j];
	   xyzp->ityp[nstor+j] = xyzp->ityp[nold+j];
 	   for (k=0; k < 3; k++)
		xyzp->coo[(nstor+j)*3+k] = xyzp->coo[(nold+j)*3+k];
	   for (k=0; k < xyzp->iconn[(nold+j)*(MXCON+1)]+1; k++)
		xyzp->iconn[(nstor+j)*(MXCON+1)+k] = xyzp->iconn[(nold+j)*(MXCON+1)+k];
	}
	update_sel = 1;
}

MoveCellAtoms(CellTrans)
double *CellTrans;
{
int i,k,nstor;

	i = 0; 
	nstor = *xyzp->mxnat - cell->natc;

	for (i=0; i < cell->natc; i++) {
	    if (xyzp->iaton[i] == 2) {
		for (k=0; k < 3; k++)
		   xyzp->coo[(nstor+i)*3+k] = 
			xyzp->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;
	   update_sel = 1;
	   if (!CTdel && CTconn) return(2);
	   else return(1);
	   break;

	case 1:
	   for (i=0; i < *xyzp->iatoms; i++ ) 
		if (xyzp->iaton[i] > 1) xyzp->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 (zmptrp->ianz[nz+2] == 8) { 
		sidechainstart--; 
	   }
	} else {
/* if start residue there might be an N missing at nz+2 */

	   if (zmptrp->ianz[nz+4] != 1 && zmptrp->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 (zmptrp->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],
		zmptrp->bet[aaptr[i].phi],zmptrp->bet[aaptr[i].psi],
		zmptrp->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();
}

FreeAllFirst()
{

	if (xyz.mxorg) {
	   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.mxorg) {
	   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.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.mxorg) {
	   free(geopntr.formax);
	   free(geopntr.forrms);
	   free(geopntr.dismax);
	   free(geopntr.disrms);
	   free(geopntr.epoints);
	   free(geopntr.isav);
	}
	if (zmptr.mxzorg) {
	   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);
 	}
}

FreePixmaps()
{
   XFreePixmap(display,stipple);
   XFreePixmap(display,qwgrey);
   XFreePixmap(display,tqwgrey);
   XFreePixmap(display,molPix);
   XFreePixmap(display,upPix);
   XFreePixmap(display,downPix);
   XFreePixmap(display,lPix);
   XFreePixmap(display,rPix);
   XFreePixmap(display,ballPix);
   XFreePixmap(display,HourPix);
   XFreePixmap(display,gPix);
   XFreePixmap(display,SkullPix);
   XFreePixmap(display,FFPix);
   XFreePixmap(display,MLFPix);
   XFreePixmap(display,HPix);
   XFreePixmap(display,VRMLPix);
   XFreePixmap(display,AlignPix);
   XFreePixmap(display,OrigPix);
   XFreePixmap(display,CellPix);
   XFreePixmap(display,SurfPix);
   XFreePixmap(display,FotoPix);
   XFreePixmap(display,ColPix);
   XFreePixmap(display,slowPix);
   XFreePixmap(display,fastPix);
   XFreePixmap(display,blastPix);
   XFreePixmap(display,BigPix);
   XFreePixmap(display,OGLPix);
   XFreePixmap(display,icon_pixmap);
#ifdef DOGL
   glXDestroyContext(display,cx);
#endif
}

FreeOne(sel)
int sel;
{

	xyzp   = &COO[sel]->coo;
	geop   = &COO[sel]->geop;
	zmptrp = &COO[sel]->zmt;
	stocp  = &COO[sel]->stoc;
	dorbp  = &COO[sel]->dorb;
	orbp   = &COO[sel]->orb;

	if (xyzp->mxorg) FreeCoo(*xyzp);

	if (dorbp->mxorg) {
	   free(dorbp->focc);
	   free(dorbp->focb);
	   free(dorbp->vectrs);
	   free(dorbp->vectrb);
	   free(dorbp->p);
	   free(dorbp->paa);
	   free(dorbp->eiga);
	   free(dorbp->eigb);
	   free(dorbp->stoalfa);
	   free(dorbp->stobnorm);
	   free(dorbp->istos);
	   free(orbp->qd);
	   free(orbp->pd);
	   free(orbp->gd);
	   free(orbp->hd);
	}

	if (geop->mxorg) {
	   free(geop->formax);
	   free(geop->forrms);
	   free(geop->dismax);
	   free(geop->disrms);
	   free(geop->epoints);
	   free(geop->isav);
	}

	if (zmptrp->mxzorg) {
	   free(zmptrp->bl);
	   free(zmptrp->ibl);
	   free(zmptrp->alph);
	   free(zmptrp->ialph);
	   free(zmptrp->bet);
	   free(zmptrp->imap);
	   free(zmptrp->ianz);
	   free(zmptrp->iz);
	   free(stocp->cstoc);
	   free(stocp->czstoc);
	   free(stocp->astoc);
	   free(stocp->bstoc);
	   free(stocp->ianstc);
	   free(COO[sel]->IANZbox);
	   free(COO[sel]->BLbox);
	   free(COO[sel]->ALPHbox);
	   free(COO[sel]->BETbox);
	   free(COO[sel]->IZbox);
	}
	free(COO[sel]);

	if (watres[sel] != NULL) free(watres[sel]);
	if (watanz[sel] != NULL) free(watanz[sel]);
	if (watcoo[sel] != NULL) free(watcoo[sel]);
	if (watcon[sel] != NULL) free(watcon[sel]);
	if (watmap[sel] != NULL) free(watmap[sel]);

	empty_model(sel,0);

}

FreeAll(delpix)
int delpix;
{
   int i;

   if (!*multstruct) {
	FreeAllFirst();
   } else {

      for (i=0; i<nstruct; i++) FreeOne(i);
   }
   if (delpix) FreePixmaps();
}

DeleteOne()
{
   int i,j;

   update_model = 0;
   if (nstruct == 1) {
	DeleteAll();
   } else {
	FreeOne(istruct);
	free(strfiles[istruct]);
	for (i=0; i<nstruct-1; i++) 
	    if (i >= istruct) {
		COO[i]       = COO[i+1];
		strfiles[i]  = strfiles[i+1];
		scl[i]       = scl[i+1];
#ifdef DOGL
		MoveOne(i);
#endif
	    }
#ifdef DOGL
	initOne(nstruct-1);
#endif
	strfiles[nstruct-1] = NULL;
	COO[nstruct-1] = NULL;
	nstruct--;
	if (istruct > nstruct - 1) istruct = nstruct - 1;
	if (istruct < 0) istruct = 0;
	strlist.select = istruct;
	RedrawSTR();

	NewActiveStruct();

	doclr();
	if (NMols[istruct] == -1) update_model = 1;
	update_struct();
   }
}

DeleteAll()
{
   int i;

   FreeAll(0);
   for (i=0; i<nstruct; i++) {
	free(strfiles[i]);
	strfiles[i] = NULL;
	COO[i] = NULL;
   }

   istruct = nstruct = 0;
   nfilesstart = 0;
   NSurf[0] = 0;

   xyzp   = &xyz;
   geop   = &geopntr;
   zmptrp = &zmptr;
   stocp  = &stoc;
   dorbp  = &dorb;
   orbp   = &orb;

   IANZbox = IANZboxes;
   BLbox = BLboxes;
   ALPHbox = ALPHboxes;
   BETbox = BETboxes;
   IZbox = (QBOXSTRU *) IZboxes;

   *backb = 0;
   *xyz.iatoms = 0;
   *zmptr.nz = 0;
   *zmptr.ihaszm = 0;
   calfptr->ncalf = 0;
   zmptr.mxzorg = 0;
   geo1ptr->gcvav = 0;
   cnvptr->icvav1 = 0;
   cnvptr->icvav2 = 0;
   out_spec = NULL;
   FRQ->nfreq = 0;

   XDestroyWindow(display,STRwin);STRup = 0;

   doclr();
   update_model = 1;
   update_struct();
}

int AllocZMat(ZSize,first)
int ZSize;
int first;
{
   int memstat,i,j;
   double f;
   int ii;
   QBOXSTRU *TMPIANZbox;
   QBOXSTRU *TMPBLbox;
   QBOXSTRU *TMPALPHbox;
   QBOXSTRU *TMPBETbox;
   QBOXSTRU *TMPIZbox;

   memstat = 1;

   if (first) {
	ZSize = MAXAT;
   } else {
	TMPzmptr = *zmptrp;
	TMPstoc = *stocp;
	TMPIANZbox = IANZbox;
	TMPBLbox = BLbox;
	TMPALPHbox = ALPHbox;
	TMPBETbox = BETbox;
	TMPIZbox = IZbox;
   }

   if ((zmptrp->bl = (double *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptrp->ibl = (int *) malloc((sizeof ii)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptrp->alph = (double *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptrp->ialph = (int *) malloc((sizeof ii)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptrp->bet = (double *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptrp->ibet = (int *) malloc((sizeof ii)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptrp->imap = (int *) malloc((sizeof ii)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptrp->ianz = (int *) malloc((sizeof ii)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((zmptrp->iz = (int *) malloc((sizeof ii)*ZSize*4)) == NULL) {
	memstat = 0;
   }

   if ((stocp->cstoc = (double *) malloc((sizeof f)*ZSize*3)) == NULL) {
	memstat = 0;
   }

   if ((stocp->czstoc = (double *) malloc((sizeof f)*ZSize*3)) == NULL) {
	memstat = 0;
   }

   if ((stocp->astoc = (double *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((stocp->bstoc = (double *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((stocp->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");
	if (!first) {
	   *zmptrp = TMPzmptr;
	   *stocp = TMPstoc;
	}
	return(0);
   } else {
	if (first) {

	   zmptrp->ibl[0] = 0;
	   zmptrp->ialph[0] = zmptrp->ialph[1] = 0;
	   zmptrp->ibet[0] = zmptrp->ibet[1] = zmptrp->ibet[2] = 0;
	   zmptrp->bl[0] = 0.0;
	   zmptrp->alph[0] = zmptrp->alph[1] = 0.0;
	   zmptrp->bet[0] = zmptrp->bet[1] = zmptrp->bet[2] = 0.0;
	   for (i=0; i<ZSize*4; i++) zmptrp->iz[i] = 0;

	   zmptrp->nz = zmptr.nz;
	   zmptrp->ihaszm = zmptr.ihaszm;
	   zmptrp->mxzat = zmptr.mxzat;

	} else {

	   for (i=0; i < *zmptrp->mxzat; i++) {
		zmptrp->bl[i] = TMPzmptr.bl[i];
		zmptrp->ibl[i] = TMPzmptr.ibl[i];
		zmptrp->alph[i] = TMPzmptr.alph[i];
		zmptrp->ialph[i] = TMPzmptr.ialph[i];
		zmptrp->bet[i] = TMPzmptr.bet[i];
		zmptrp->ibet[i] = TMPzmptr.ibet[i];
		zmptrp->imap[i] = TMPzmptr.imap[i];
		zmptrp->ianz[i] = TMPzmptr.ianz[i];
		for (j=0; j<3; j++)
		   zmptrp->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];

	   }
	   if (TMPzmptr.mxzorg) {
		FreeZmt(TMPzmptr,TMPstoc,
			TMPIANZbox,TMPBLbox,TMPALPHbox,TMPBETbox,TMPIZbox);
	   }

	}
	if (COO[istruct] != NULL) {
		COO[istruct]->IANZbox = IANZbox;
		COO[istruct]->BLbox   = BLbox;
		COO[istruct]->ALPHbox = ALPHbox;
		COO[istruct]->BETbox  = BETbox;
		COO[istruct]->IZbox   = IZbox;
	}
	zmptrp->mxzorg = 1;
	*zmptrp->mxzat = ZSize;
	return(ZSize);
   }
}

#if defined(VMS) || defined(UNDERSC)
allorb(ZSizep,first)
#else
#ifdef CRAY
ALLORB(ZSizep,first)
#else
allorb_(ZSizep,first)
#endif
#endif
int *ZSizep;
int *first;
{
   int memstat;
   double d;
   float f;
   int i;
   int ZSize;

   memstat = 1;
   if (*first) {
	ZSize = MAXORB;
   } else {
	ZSize = *ZSizep;
	TMPdorb = *dorbp;
	TMPorb = *orbp;
   }


   if ((dorbp->focc = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorbp->focb = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorbp->vectrs = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorbp->vectrb = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorbp->p = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorbp->paa = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorbp->averag = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorbp->eiga = (float *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorbp->eigb = (float *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorbp->stoalfa = (float *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorbp->stobnorm = (float *) malloc((sizeof f)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((dorbp->istos = (int *) malloc((sizeof i)*ZSize*5)) == NULL) {
	memstat = 0;
   }

   if ((orbp->qd = (double *) malloc((sizeof d)*ZSize*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((orbp->pd = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((orbp->gd = (double *) malloc((sizeof d)*ZSize*3)) == NULL) {
	memstat = 0;
   }

   if ((orbp->hd = (double *) malloc((sizeof d)*ZSize*6)) == NULL) {
	memstat = 0;
   }

   if (!memstat) {
	fprintf(stderr,"Out of memory\n");
	if (!*first) {
	   *dorbp = TMPdorb;
	   *orbp = TMPorb;
	}
   } else {
	if (*first) {
	   dorbp->ncols  = dorb.ncols;
	   dorbp->ncolb  = dorb.ncolb;
	   dorbp->nocc   = dorb.nocc;
	   dorbp->nocb   = dorb.nocb;
	   dorbp->naorbs = dorb.naorbs;
	   dorbp->mxorb  = dorb.mxorb;
 	} else {
	   if (TMPdorb.mxorg) {
		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);
	   }
	}
	dorbp->mxorg  = 1;
	*dorbp->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.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.mxorg = 1;
	*sgrd.mx3d = ZSize;
	*sgrd.mx3d2 = ZSize*ZSize;
   }
}

#if defined(VMS) || defined(UNDERSC)
allgeo(ZSizep,first)
#else
#ifdef CRAY
ALLGEO(ZSizep,first)
#else
allgeo_(ZSizep,first)
#endif
#endif
int *ZSizep;
int *first;
{
   int memstat;
   double d;
   int i, mxpnto,mxorgo;
   int ZSize;

   memstat = 1;
   if (*first) {
	ZSize = MAXPNT;
   } else {
	ZSize = *ZSizep;
	TMPgeopntr = *geop;
   }

   if ((geop->formax = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((geop->forrms = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((geop->dismax = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((geop->disrms = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((geop->epoints = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((geop->isav = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if (!memstat) {
	fprintf(stderr,"Out of memory\n");
	if (!*first) *geop = TMPgeopntr;
   } else {
	if (TMPgeopntr.mxorg) {
		free(TMPgeopntr.formax);
		free(TMPgeopntr.forrms);
		free(TMPgeopntr.dismax);
		free(TMPgeopntr.disrms);
		free(TMPgeopntr.epoints);
		free(TMPgeopntr.isav);
	}
	geop->mxorg = 1;
	geo1ptr->mxpnt = ZSize;
   }
}

typedef struct {
  int ptr;
  float depth;
} DepthIndex;

DepthIndex dptdemo;
DepthIndex dpt[NUMAT];
DepthIndex *dptptr = dpt;
static int dptsiz = NUMAT;

FreeCoo(txyz)
COOSTRU txyz;
{
   free(txyz.coo);
   free(txyz.rzp);
   free(txyz.qat);
   free(txyz.isurf);
   free(txyz.icont);
   free(txyz.lwrit);
   free(txyz.lring);
   free(txyz.ianz);
   free(txyz.iaton);
   free(txyz.iatclr);
   free(txyz.iresid);
   free(txyz.ixp);
   free(txyz.iyp);
   free(txyz.iconn);
   free(txyz.inat);
   free(txyz.ityp);
   free(txyz.ipdbt);
}

FreeZmt(tzmt,tstoc,tbox1,tbox2,tbox3,tbox4,tbox5)
ZMSTRU tzmt;
STOCSTRU tstoc;
QBOXSTRU *tbox1,*tbox2,*tbox3,*tbox4,*tbox5;
{
   free(tzmt.bl);
   free(tzmt.ibl);
   free(tzmt.alph);
   free(tzmt.ialph);
   free(tzmt.bet);
   free(tzmt.ibet);
   free(tzmt.imap);
   free(tzmt.ianz);
   free(tzmt.iz);
   free(tstoc.cstoc);
   free(tstoc.czstoc);
   free(tstoc.astoc);
   free(tstoc.bstoc);
   free(tstoc.ianstc);
   free(tbox1);
   free(tbox2);
   free(tbox3);
   free(tbox4);
   free(tbox5);
}

#if defined(VMS) || defined(UNDERSC)
allcoo(ZSizep,first)
#else
#ifdef CRAY
ALLCOO(ZSizep,first)
#else
allcoo_(ZSizep,first)
#endif
#endif
int *ZSizep;
int *first;
{
   int memstat;
   double d;
   int i;
   short int j;
   int ZSize;

   memstat = 1;
   if (*first) {
	ZSize = NUMAT;
   } else {
	ZSize = *xyzp->mxnat + *ZSizep;
	TMPxyz = *xyzp;
   }


   if ((xyzp->coo = (double *) malloc((sizeof d)*ZSize*3)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->rzp = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->qat = (double *) malloc((sizeof d)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->isurf = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->icont = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->lwrit = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->lring = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->ianz = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->iaton = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->iatclr = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->iresid = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->ixp = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->iyp = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->iconn = (int *) malloc((sizeof i)*ZSize*(MXCON+1))) == NULL) {
	memstat = 0;
   }

   if ((xyzp->inat = (int *) malloc((sizeof i)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->ityp = (short int *) malloc((sizeof j)*ZSize)) == NULL) {
	memstat = 0;
   }

   if ((xyzp->ipdbt = (short int *) malloc((sizeof j)*ZSize)) == NULL) {
	memstat = 0;
   }

   if (ZSize > dptsiz) {
	if ((dptptr = (DepthIndex *) malloc((sizeof dptdemo)*ZSize)) == NULL) {
	   memstat = 0;
	} else {
	   dptsiz = ZSize;
	}
   }

   if (!memstat) {
	fprintf(stderr,"Out of memory\n");
	if (!*first) *xyzp = TMPxyz;
   } else {
	if (*first) {
	   xyzp->iatoms = xyz.iatoms;
	   xyzp->ncont = xyz.ncont;
	   xyzp->mxnat = xyz.mxnat;
	} else {
	   for (i=0; i < *xyzp->iatoms; i++) {
	   	for (j=0; j<3; j++) xyzp->coo[i*3+j] = TMPxyz.coo[i*3+j];
		xyzp->qat[i] = TMPxyz.qat[i];
		xyzp->ianz[i] = TMPxyz.ianz[i];
		xyzp->iaton[i] = TMPxyz.iaton[i];
		xyzp->iatclr[i] = TMPxyz.iatclr[i];
		xyzp->iresid[i] = TMPxyz.iresid[i];
		xyzp->ityp[i] = TMPxyz.ityp[i];
		xyzp->ipdbt[i] = TMPxyz.ipdbt[i];
		for (j=0; j<MXCON; j++)
		   xyzp->iconn[i*(MXCON+1)+j] = TMPxyz.iconn[i*(MXCON+1)+j];
	   }
	   if (TMPxyz.mxorg) FreeCoo(TMPxyz);
	}
	xyzp->mxorg = 1;
	*xyzp->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.mxorg) {
	   free(TMPmgrd.fmap);
	}
	mgrd.mxorg = 1;
	*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,NULL);
   }

   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],elmptr->icol[i-1],
		elmptr->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);
}

UpdateDPT()
{
   double i;

   *uscl = (double) (5.0*(double) dptwpos[0] / 200.0);
   if (*uscl <= 0.0) *uscl = 0.01;

   update_struct();
   
}


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,UpdateDPT);
   }

}

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]);

}

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<*xyzp->iatoms; i++)
	   fprintf(out,"%s ",elements[xyzp->ianz[i]]);
	fprintf(out,"\n");
	fprintf(out,"    </stringArray>\n");

	fprintf(out,"    <floatArray builtin=\"x3\">\n");
	fprintf(out,"      ");
	for (i=0; i<*xyzp->iatoms; i++)
	   fprintf(out,"%f ",xyzp->coo[i*3]*toangs);
	fprintf(out,"\n");
	fprintf(out,"    </floatArray>\n");

	fprintf(out,"    <floatArray builtin=\"y3\">\n");
	fprintf(out,"      ");
	for (i=0; i<*xyzp->iatoms; i++)
	   fprintf(out,"%f ",xyzp->coo[i*3+1]*toangs);
	fprintf(out,"\n");
	fprintf(out,"    </floatArray>\n");

	fprintf(out,"    <floatArray builtin=\"z3\">\n");
	fprintf(out,"      ");
	for (i=0; i<*xyzp->iatoms; i++)
	   fprintf(out,"%f ",xyzp->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, 355, 50, 23,
	"Apply", infobg, -15);

  DefBut(&mapbut[1], MAPwin, 375, 355, 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];

  DefBut(&mapbut[4], MAPwin, 390, 180, 15, 15, "", infobg, 0);
  DefBut(&mapbut[5], MAPwin, 390, 200, 15, 15, "", infobg, 0);
  DefBut(&mapbut[6], MAPwin, 20, 40, 70, 23, "Map file:", infobg, 0);

  if (*icpsa) TogDown(&mapbut[4]);
  if (*idtpsa) TogDown(&mapbut[5]);

  qboxstr(&qboxes[QMFILE],&MAPwin,0,0,190,15,40, 
	350,QBOXHIGH,2,"                 ","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, 
	250,QBOXHIGH,2,"Contour Value    ","0.1",12,QREAL,2000,dummyproc);
  } else {
	qboxstr(&qboxes[QCNTVAL],&MAPwin,0,0,190,15,MAPOFFY, 
	250,QBOXHIGH,2,"Contour Value    ","0.02",12,QREAL,2000,dummyproc);
  }
  sprintf(qboxes[QCNTVAL].str,"%f", cntval);

  for (i=0; i<5; i++) {
	qboxstr(&qboxes[QCOLVAL1+i],&MAPwin,0,0,190,38,MAPOFFY+60+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]);
  }

  qboxstr(&qboxes[QPOLVAL1],&MAPwin,0,0,190,MAPOFFX+140,MAPOFFY, 
	110,QBOXHIGH,2,"<","0.001",12,QREAL,2000,dummyproc);
  sprintf(qboxes[QPOLVAL1].str,"%f", *pol);

  qboxstr(&qboxes[QPOLVAL2],&MAPwin,0,0,190,MAPOFFX+250,MAPOFFY, 
	105,QBOXHIGH,2,">","0.001",12,QREAL,2000,dummyproc);
  sprintf(qboxes[QPOLVAL2].str,"%f", *pol2);

  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);
   LineString(MAPwin,"Apolar potential range (for PSA):",280,120);
   ULineString(MAPwin,"Color         Elec. potential:",38,182);
   LineString(MAPwin,"Mark PSA        ",280,195);
   LineString(MAPwin,"Incl. Topol. PSA",280,215);

/*
   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]);
   PromptBox(&qboxes[QPOLVAL1]); 
   PromptBox(&qboxes[QPOLVAL2]); 

}

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);
	cntval = atof(qboxes[QCNTVAL].str);
	*pol = atof(qboxes[QPOLVAL1].str);
	*pol2 = atof(qboxes[QPOLVAL2].str);
	for (j=0; j<5; j++) mapval[j] = atof(qboxes[QCOLVAL1+j].str);
	if (iviropt == 0) *ivtwo = 1;
	if (iviropt == 1) *ivtwo = 3;
	if (iviropt == 2) *ivtwo = 4;
	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 = 3;
	   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;
   case 4: 
	if (*icpsa) {
	   *icpsa = 0;
	   TogUp(&mapbut[4]);
	} else {
	   *icpsa = 1;
	   TogDown(&mapbut[4]);
	}
	break;
   case 5: 
	if (*idtpsa) {
	   *idtpsa = 0;
	   TogUp(&mapbut[5]);
	} else {
	   *idtpsa = 1;
	   TogDown(&mapbut[5]);
	}
	break;
   case 6: 
	gsel.qbrfile = 1;
	gsel.subopt = 1;
	FileSelectList(&gsel);
	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 |
	SubstructureNotifyMask | 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[jobcom->icopth+3];
  onbut[OMULTH].str = spopt[jobcom->ispopth-1];
  onbut[OMETHL].str = mopt[imoptl];
  onbut[OBASSL].str = bopt[iboptl];
  onbut[OCHARL].str = copt[jobcom->icoptl+3];
  onbut[OMULTL].str = spopt[jobcom->ispoptl-1];
  onbut[OMETHM].str = mopt[imoptm];
  onbut[OBASSM].str = bopt[iboptm];
  onbut[OCHARM].str = copt[jobcom->icoptm+3];
  onbut[OMULTM].str = spopt[jobcom->ispoptm-1];

  if (*fftyp != 3) {
     for (i=0;i<*xyzp->iatoms;i++) {
	xyzp->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 < *xyzp->iatoms; i++ ) {
                   if (xyzp->ityp[i] >= 10000) 
			xyzp->ityp[i] -= (xyzp->ityp[i]/10000)*10000
;
                   xyzp->iatclr[i] = ONIHCOL;
                }
		ret = 1;
                break;
  case OALLM:
                strcpy(ONIerr,"M level for all atoms");
                RedrawONIStatus();
                for ( i = 0; i < *xyzp->iatoms; i++ ) {
                   if (xyzp->ityp[i] >= 20000) {
                      xyzp->ityp[i] -= 10000;
                   } else {
                      if (xyzp->ityp[i]<10000) xyzp->ityp[i] += 10000;
                   }
                   xyzp->iatclr[i] = ONIMCOL;
                }
		ret = 1;
                break;
  case OALLL:
                strcpy(ONIerr,"L level for all atoms");
                RedrawONIStatus();
                for ( i = 0; i < *xyzp->iatoms; i++ ) {
                   if (xyzp->ityp[i] < 20000) 
			xyzp->ityp[i] += (2-xyzp->ityp[i]/10000)*10000;
                   xyzp->iatclr[i] = ONILCOL;
                }
		ret = 1;
                break;
  case OSELH:
                Selecting = 0;
                nat = 0;
                for ( i = 0; i < *xyzp->iatoms; i++ ) if (xyzp->iaton[i] > 1) nat++;
                if (!nat) {
                        strcpy(ONIerr,"Invalid Selection: No atoms selected");
                        if (*ibell) XBell(display,0);
                        RedrawONIStatus();
                        return(0);
                }
                if (nat > *zmptrp->mxzat) {
                   strcpy(ONIerr,"Invalid Selection: Too many atoms selected");
                   if (*ibell) XBell(display,0);
                   RedrawONIStatus();
                   for ( i = 0; i < *xyzp->iatoms; i++ )
                        if (xyzp->iaton[i] >= 2) xyzp->iaton[i] = 1;
                   ret = 1;
                }
                else {
                   strcpy(ONIerr,"Selected atoms at H level");
                   RedrawONIStatus();
                   for ( i = 0; i < *xyzp->iatoms; i++ ) {
                        if (xyzp->iaton[i] >= 2) {
                            if (xyzp->ityp[i] >= 10000) xyzp->ityp[i] -= 
                                (xyzp->ityp[i] /10000)*10000;
                                xyzp->iatclr[i] = ONIHCOL;
                        }
                        xyzp->iaton[i] = 1;
                   }
		   ret = 1;
                }
                break;
  case OSELM:
		Selecting = 0;
		nat = 0;
		for ( i = 0; i < *xyzp->iatoms; i++ ) if (xyzp->iaton[i] > 1) nat++;
		if (!nat) {
			strcpy(ONIerr,"Invalid Selection: No atoms selected");
			if (*ibell) XBell(display,0);
			RedrawONIStatus();
			return(0);
		}
		if (nat > *zmptrp->mxzat) {
		   strcpy(ONIerr,"Invalid Selection: Too many atoms selected");
		   if (*ibell) XBell(display,0);
		   RedrawONIStatus();
		   for ( i = 0; i < *xyzp->iatoms; i++ ) 
			if (xyzp->iaton[i] >= 2) xyzp->iaton[i] = 1;
	  	   ret = 1;
		}
		else {
		   strcpy(ONIerr,"Selected atoms at M level");
		   RedrawONIStatus();
		   for ( i = 0; i < *xyzp->iatoms; i++ ) {
			if (xyzp->iaton[i] >= 2) {
				if (xyzp->ityp[i] >= 20000) {
		      		   xyzp->ityp[i] -= 10000;
		   		} else {
		   	   	   if (xyzp->ityp[i] < 10000) 
				   xyzp->ityp[i] += 10000;
		   		}
			       xyzp->iatclr[i] = ONIMCOL;
			}
			xyzp->iaton[i] = 1;
		   }
		   ret = 1;
	        }
		break;
  case OSELL:
		Selecting = 0;
		nat = 0;
		for ( i = 0; i < *xyzp->iatoms; i++ ) if (xyzp->iaton[i] > 1) nat++;
		if (!nat) {
			strcpy(ONIerr,"Invalid Selection: No atoms selected");
			if (*ibell) XBell(display,0);
			RedrawONIStatus();
			return(0);
		}
		if (nat > *zmptrp->mxzat) {

		   strcpy(ONIerr,"Invalid Selection: Too many atoms selected");
		   if (*ibell) XBell(display,0);
		   RedrawONIStatus();
		   for ( i = 0; i < *xyzp->iatoms; i++ ) 
			if (xyzp->iaton[i] >= 2) xyzp->iaton[i] = 1;
	  	   ret = 1;

		} else {

		   strcpy(ONIerr,"Selected atoms at L level");
		   RedrawONIStatus();
		   for ( i = 0; i < *xyzp->iatoms; i++ ) {
			if (xyzp->iaton[i] >= 2) {
			   if (xyzp->ityp[i] < 20000) xyzp->ityp[i] += 
                              (2-xyzp->ityp[i]/10000)*10000;
			   xyzp->iatclr[i] = ONILCOL;
			}
			xyzp->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,&jobcom->icopth,1) == -1) break;
		jobcom->icopth = jobcom->icopth - 3;
		onbut[OCHARH].str = copt[jobcom->icopth+3];
		break;
  case OMULTH:
		List.list = spopt; List.nents = 8;
		if (DoPopUp(ONIwin,
			onbut[OMULTH].x+OBOXBLEN/2,onbut[OMULTH].y+BUTTH,
			&List,&jobcom->ispopth,1) == -1) break;
		jobcom->ispopth = jobcom->ispopth + 1;
		onbut[OMULTH].str = spopt[jobcom->ispopth-1];
		break;
  case OCHARM:
		List.list = copt; List.nents = 7;
		if (DoPopUp(ONIwin,
			onbut[OCHARM].x+OBOXBLEN/2,onbut[OCHARM].y+BUTTH,
			&List,&jobcom->icoptm,1) == -1) break;
		jobcom->icoptm = jobcom->icoptm - 3;
		onbut[OCHARM].str = copt[jobcom->icoptm+3];
		break;
  case OMULTM:
		List.list = spopt; List.nents = 8;
		if (DoPopUp(ONIwin,
			onbut[OMULTM].x+OBOXBLEN/2,onbut[OMULTM].y+BUTTH,
			&List,&jobcom->ispoptm,1) == -1) break;
		jobcom->ispoptm = jobcom->ispoptm + 1;
		onbut[OMULTM].str = spopt[jobcom->ispoptm-1];
		break;
  case OCHARL:
		List.list = copt; List.nents = 7;
		if (DoPopUp(ONIwin,
			onbut[OCHARL].x+OBOXBLEN/2,onbut[OCHARL].y+BUTTH,
			&List,&jobcom->icoptl,1) == -1) break;
		jobcom->icoptl = jobcom->icoptl - 3;
		onbut[OCHARL].str = copt[jobcom->icoptl+3];
		break;
  case OMULTL:
		List.list = spopt; List.nents = 8;
		if (DoPopUp(ONIwin,
			onbut[OMULTL].x+OBOXBLEN/2,onbut[OMULTL].y+BUTTH,
			&List,&jobcom->ispoptl,1) == -1) break;
		jobcom->ispoptl = jobcom->ispoptl + 1;
		onbut[OMULTL].str = spopt[jobcom->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);
}


CreateFLR()
{
  int i;
   
  FLRup = 1;
  bckrig = 0;
  *icst = 1;

  FLRwin = CreateWindow("FlexRigid","-80-80",
                         FBOXWIDE,FBOXHIGH,infobg,infofg,(Window)0);
  subFLR = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],FLRwin);
  XSelectInput(display, FLRwin,
        ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask |
	SubstructureNotifyMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask);

  XMapWindow(display,FLRwin);

  DefBut(&flrbut[FRIGD],  FLRwin, FBOXOFFX, 30, FBOXBLEN, 23, 
        "All Rigid", infobg, -FRIGCOL);
  flrbut[FRIGD].explstr = "All atoms are assigned rigid";

  DefBut(&flrbut[FSELR],  FLRwin, FBOXOFFX, 35+5*BUTTN, FBOXBLEN, 23, 
        "Selection Rigid", infobg, -FRIGCOL);
  flrbut[FSELR].explstr = "Assign currently selected atoms rigid";


  DefBut(&flrbut[FFLEX],  FLRwin, FBOXOFFX+110, 30, FBOXBLEN, 23,
        "All Flexible", infobg,-FLEXCOL);
  flrbut[FFLEX].explstr = "All atoms are assigned flexible";

  DefBut(&flrbut[FSELF],  FLRwin, FBOXOFFX+110, 35+5*BUTTN, FBOXBLEN+20, 23,
        "Selection Flexible", infobg,-FLEXCOL);
  flrbut[FSELF].explstr = "Assign currently selected atoms flexible";

  DefBut(&flrbut[FSEL],   FLRwin, FBOXOFFX,     35+2*BUTTN, FBOXBLEN+20, 23,
        "Select by pointer", infobg, -15);
  flrbut[FSEL].explstr = "Select atoms to be assigned rigid/flexible\nSelect: Left mouse button+drag+release";

  DefBut(&flrbut[FUSEL],  FLRwin, FBOXOFFX+125, 35+2*BUTTN, FBOXBLEN-20, 23,
        "DeSelect", infobg,-15);
  flrbut[FUSEL].explstr = "Deselect atoms to be assigned\nDeselect: Left mouse button+drag+release";

  DefBut(&flrbut[FSELA],  FLRwin, FBOXOFFX+220, 35+2*BUTTN, FBOXBLEN, 23,
        "Select residue", infobg,-15);
  flrbut[FSELA].explstr = "Select residue to be assigned rigid/flexible\nSelect: click residue with left mouse button";
  if (*ipdbon == 0) ActBut(&flrbut[FSELR],0);

  DefBut(&flrbut[FCONT],  FLRwin, FBOXOFFX, 35+3*BUTTN, FBOXBLEN+105, 23,
        "residue/ligand + neighbours", infobg,-15);
  flrbut[FCONT].explstr = "Select residue/ligand + neighbours \nto be assigned rigid/flexible.\nSelect: click residue with left mouse button";
  if (*ipdbon == 0) ActBut(&flrbut[FCONT],0);

  DefBut(&flrbut[FBACK],  FLRwin, FBOXOFFX, 39+6*BUTTN, 15, 15,
        " ", infobg,-15);
  flrbut[FBACK].explstr = "Backbone rigid";

  DefBut(&flrbut[FCLOS],  FLRwin, FBOXOFFX+110, 35+7*BUTTN, FBOXBLEN, 23,
        "Close", infobg,-15);

  if (bckrig) {
	TogDown(&flrbut[FBACK]);
  } else {
	TogUp(&flrbut[FBACK]);
  }

  for ( i = 0; i < *xyzp->iatoms; i++ ) {
	xyzp->isurf[i] = 1;
	xyzp->iatclr[i] = FLEXCOL;
  }
}

RedrawFLR()
{
  int i;

  butje(FLRwin,0,0,FBOXWIDE,FBOXHIGH,4,0,0,1,None,0,0,0);
  ULineString(FLRwin,"Selection:",FBOXOFFX,46+1*BUTTN);
  ULineString(FLRwin,"Apply selection:",FBOXOFFX,49+4*BUTTN);
  LineString(FLRwin,"Backbone rigid",FBOXOFFX+20,49+6*BUTTN);
  for (i=0; i<NBUTSF; i++) DrwBut(&flrbut[i]);


}

int ButtonsFLR(k)
int k;
{
  LSSTRU List;
  int ret=0;
  int i,j;

  switch (k) {
  case FRIGD:
                for (i=0; i < *xyzp->iatoms; i++ ) {
		   xyzp->isurf[i] = 0;
                   xyzp->iatclr[i] = FRIGCOL;
                }
		ret = 1;
                break;
  case FFLEX:
                for ( i = 0; i < *xyzp->iatoms; i++ ) {
		   xyzp->isurf[i] = 1;
                   xyzp->iatclr[i] = FLEXCOL;
                }
		if (bckrig) {
		    for (i=0; i < calfptr->ncalf; i++ ) {
			for (j=0; j < 4; j++ ) {
			    if (calfptr->icalf[i][j] >= 0) {
				xyzp->isurf[calfptr->icalf[i][j]-1] = 0;
				xyzp->iatclr[calfptr->icalf[i][j]-1] = FRIGCOL;
			    }
			}
		    }
		}
		ret = 1;
                break;
  case FSELR:
                Selecting = 0;
                for (i=0; i<*xyzp->iatoms; i++ ) {
                        if (xyzp->iaton[i] >= 2) {
			   xyzp->isurf[i] = 0;
                           xyzp->iaton[i] = 1;
			   xyzp->iatclr[i] = FRIGCOL;
			}
                }
		ret = 1;
                break;
  case FSELF:
		Selecting = 0;
                for (i = 0;i < *xyzp->iatoms; i++ ) {
                        if (xyzp->iaton[i] >= 2) {
			   xyzp->isurf[i] = 1;
                           xyzp->iaton[i] = 1;
			   xyzp->iatclr[i] = FLEXCOL;
			}
                }
		ret = 1;
		break;
  case FSEL:
                Selecting = 1;
                ZoomEnable = True;Select = True;
                break;
  case FUSEL:
                ZoomEnable = True;Select = False;
                break;
  case FSELA:
		if (*ipdbon) {
		   bflag = 1; bretval = 565;
		   XDefineCursor(display,win,AtomCursor);
		} else {
		   ActBut(&flrbut[FSELR],0);
		}
                break;
  case FCLOS:
	        XDestroyWindow(display,FLRwin);FLRup = 0;
		return(0);
                break;
  case FBACK:
		TogBut(&flrbut[FBACK]);
		if (bckrig) bckrig = 0;
		else bckrig = 1;
		break;
  case FCONT:
		if (*ipdbon) {
		   bflag = 1; bretval = 566;
		   XDefineCursor(display,win,AtomCursor);
		} else {
		   ActBut(&flrbut[FCONT],0);
		}
		break;
  default: break;
  }

  RedrawFLR();

  update_sel = 1;

  if (ret) {
     return(1);
  } else {
     return(0);
  }

}

calc_spectrum(int iupd) 
{

  int i, j, spnew;
  double intensity, frq, center, rel_offset;
  double (*lineshape)(double);
  double spec_mx_tmp;

  spec_mx_tmp = spec_mx;

  if (iupd && specup) {
	hwhm = atof(qboxes[QHW].str);
	freq_scale = atof(qboxes[QSSCAL].str);
	min_freq = atoi(qboxes[QMINF].str);
	max_freq = atoi(qboxes[QMAXF].str);
  }

  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 < *spnfrq; j++) {
      center = (double) spfrq[j]*freq_scale;
      rel_offset = (frq - center) / hwhm;
      intensity += spint[j] * lineshape(rel_offset);
    }
    out_spec[i] = intensity;
  }

  INTextr();
  if (iupd && (spec_mx_tmp != spec_mx)) spec_mx = spec_mx_tmp;

/*
  for (i=1; i < n_freqs; i++) {
     fprintf(stderr,"%d %11.6f\n",i,out_spec[i]);
  }
*/
  return;
}

write_spectrum(char *fname, int orient, int opt) {

	specps = 1;
	spout = fopen(fname,"w");
	fprintf(spout,"\%\%!PS-Adobe-1.\0%\n");
	fprintf(spout,"\%\%\%\%Title: Molden\n");
	if (orient) {
	   fprintf(spout,"\%\%\%\%BoundingBox: 0 0 612 792\n");
	} else {
	   if (opt) {
	      //fprintf(spout,"\%\%\%\%BoundingBox: 40 -250 500 50\n");
	   } else {
	      fprintf(spout,"\%\%\%\%BoundingBox: 40 -550 770 50\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");
	if (orient) {
	   fprintf(spout,"90 rotate\n");
	}
	if (opt) {
	   fprintf(spout,"1.75 1.75 scale\n");
	   fprintf(spout,"-20 280 translate\n");
	} else {
	   fprintf(spout,"1.3 2.0 scale\n");
	   fprintf(spout,"10 0 translate\n");
        }
        drwspec();
	fprintf(spout,"showpage\n");
	fclose(spout);
	specps = 0;
}

void wrjdx(filename)
    char *filename;
{
    int i,j,k,ifrq,xmax,xmin;
    double frq,yscale;
    FILE *jdxfile,*molfile,*xyzfile;
    char line[MAXCMD];
    char tline[MAXCMD];
    char *q;

    jdxfile = fopen(filename,"w");
    if (!jdxfile) {
	fprintf(stderr,"Output Error: Unable to create jdx file %s\n",filename);
	return;
    }

    yscale = 1.0 / spec_mx;
    fprintf(jdxfile,"##TITLE=molden generated spectrum\n");
    fprintf(jdxfile,"##JCAMP-DX=4.24\n");
    fprintf(jdxfile,"##DATA TYPE=INFRARED SPECTRUM\n");

    molfile = fopen("mol.mol","r");
    if (molfile) {
	fprintf(jdxfile,"##$MODELS=\n");
	fprintf(jdxfile,"<Models>\n");
	fprintf(jdxfile,"<ModelData id=\"mol\" type=\"MOL\">\n");

	while (fgets(line,MAXCMD,molfile) != NULL) {
    	   fprintf(jdxfile,"%s",line);
	}
    	fclose(molfile);
        fprintf(jdxfile,"</ModelData>\n");

	xyzfile = fopen("mol.xyz","r");
	if (xyzfile) {

	   fprintf(jdxfile,"<ModelData id=\"1\" type=\"XYZVIB\" baseModel=\"mol\" vibrationScale=\".1\">\n");

	   for (i=0; i < FRQ->nfreq; i++) {
		ifrq = i + 1;
#if defined(VMS) || defined(UNDERSC)
		nrmi(&ifrq);
#else
#ifdef CRAY
		NRMI(&ifrq);
#else
		nrmi_(&ifrq);
#endif
#endif
		fgets(line,MAXCMD,xyzfile);
		fprintf(jdxfile,"%s",line);
		fgets(line,MAXCMD,xyzfile);
		fprintf(jdxfile,"%d Freq: %#5.1f %s",ifrq,FRQ->freq[i],line);

		k = 0;
		while (fgets(line,MAXCMD,xyzfile) != NULL) {
		   q = strchr(line,'\n');
		   sprintf(q," %#12.6f %#12.6f %#12.6f\n",
			FRQ->a[k][0]*toangs,FRQ->a[k][1]*toangs,FRQ->a[k][2]*toangs);
		   fprintf(jdxfile,"%s",line);
		   k++;
		}

		rewind(xyzfile);
	   }
    	   fclose(xyzfile);
           fprintf(jdxfile,"</ModelData>\n");
	}
        fprintf(jdxfile,"</Models>\n");

    }

    fprintf(jdxfile,"##$PEAKS=\n");
    fprintf(jdxfile,"<Peaks type=\"IR\" xUnitsExpected=\"1/cm\">\n");
    for (i=0; i < FRQ->nfreq; i++)  {
	ifrq = i + 1;
	if (i>0 && i < FRQ->nfreq-1) {
	   xmin = (int) (FRQ->freq[i] - (FRQ->freq[i] - FRQ->freq[i-1]) / 2.0);
	   xmax = (int) (FRQ->freq[i] + (FRQ->freq[i+1] - FRQ->freq[i]) / 2.0);
	   xmax--;
	} else {
	   if (i == 0) {
		xmin = 0;
	   	xmax = (int) (FRQ->freq[i] + (FRQ->freq[i+1] - FRQ->freq[i]) / 2.0);
	        xmax--;
	   }
	   if (i == FRQ->nfreq-1) {
		xmin = (int) (FRQ->freq[i] - (FRQ->freq[i] - FRQ->freq[i-1]) / 2.0);
	   	xmax = max_freq;
	   }
	}
	fprintf(jdxfile,"<PeakData id=\"%d\" title=\"Freq %#6.1f\" peakShape=\"broad\" model=\"1.%d\" xMax=\"%d\" xMin=\"%d\">\n",ifrq,FRQ->freq[i],ifrq,xmax,xmin);
    }
    fprintf(jdxfile,"</Peaks>\n");

    fprintf(jdxfile,"##XUNITS=1/CM\n");
    fprintf(jdxfile,"##YUNITS=ABSORBANCE\n");
    fprintf(jdxfile,"##XLABEL=Wavenumbers (cm-1)\n");
    fprintf(jdxfile,"##YLABEL=%% Absorbance\n");
    fprintf(jdxfile,"##XFACTOR=1\n");
    fprintf(jdxfile,"##YFACTOR=1\n");
    fprintf(jdxfile,"##DELTAX=1\n");
    fprintf(jdxfile,"##FIRSTX=%d\n",min_freq);
    fprintf(jdxfile,"##LASTX=%d\n",max_freq);
    fprintf(jdxfile,"##FIRSTY=%f\n",spec_mn);
    fprintf(jdxfile,"##MAXX=%d\n",max_freq);
    fprintf(jdxfile,"##MINX=%d\n",min_freq);
    fprintf(jdxfile,"##MAXY=%f\n",spec_mx);
    fprintf(jdxfile,"##MINY=%f\n",spec_mn);
    fprintf(jdxfile,"##NPOINTS=%d\n",n_freqs);
    fprintf(jdxfile,"##XYDATA=(X++(Y..Y))\n");

    for (i=0; i < n_freqs; i += 5) {
	frq = min_freq + i*freq_step;
	fprintf(jdxfile,"%-11.6f",frq);
	for (j=0; j < 5; j++) {
	   if (i+j < n_freqs) {
		fprintf(jdxfile," %6.4f",out_spec[i+j]*yscale);
	   }
	}
	fprintf(jdxfile,"\n");
    }
    fprintf(jdxfile,"##END=\n");
/*
387.000000 0.9245 0.9240 0.9235 0.9231 0.9227
*/

    fclose(jdxfile);


    return;
}

#if defined(VMS) || defined(UNDERSC)
void jdxwr()
#else
#ifdef CRAY
void JDXWR()
#else
void jdxwr_()
#endif
#endif
{
  char *fnam    = "mol.jdx";
  wrjdx(fnam);
}

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,1,0);
	drwspec();
}

void updcallb(char *str)
{
	if (nmrptr->ihsnmr) prep_nmr();
	calc_spectrum(1);
	drwspec();
}

int ButtonsSPC(i)
int i;
{
  int iupd;
  float tmp;

  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.nents = 2;

	   if (FRQ->ihasi) {
		if (*ihasex) {
		    List.nents = 1;
		    List.list = uvsptyp;
		} else {
		    List.list = sptyp;
		}

		if (DoPopUp(winspec,spbut[1].x+20,spbut[1].y,
		    &List,&spmode,0) == -1) return 0;
		if (*ihasex) {
		   spbut[1].str = *uvsptyp;
		   spint = FRQ->frint; 
		} else {
		   spbut[1].str = sptyp[spmode];
        	   if (spmode) {
			spint = FRQ->ramint; 
	   	   } else {
			spint = FRQ->frint; 
		   }
		}
	   	
	   	frlist.list.flst = spint;
           	if (FRup) RedrawList(&frlist);
	   	DrwBut(&spbut[1]);

	   } else if (nmrptr->ihsnmr) {

		List.list = nmrsptyp;

		if (DoPopUp(winspec,spbut[1].x+20,spbut[1].y,
		    &List,&spmode,0) == -1) return 0;
		spbut[1].str = nmrsptyp[spmode];
		if (spmode) {
		    NMRnuc = 6;
		    nmrref  = &nmr13Cref;
		    freq_step = nmr13Cstep;
		} else {
		    NMRnuc = 1;
		    nmrref  = &nmr1Href;
		    freq_step = nmr1Hstep;
		}
		sprintf(qboxes[QTMS].str,"%6.2f",*nmrref);
		qboxes[QTMS].qflt = nmrref;
	   	DrwBut(&spbut[1]);
		prep_nmr();
		FRQextr();
		sprintf(qboxes[QMINF].str,"%d",min_freq);
		sprintf(qboxes[QMAXF].str,"%d",max_freq);
           }
        }
        break;
  case 2:	{
        XDestroyWindow(display,winspec);
        specup = 0;
	if (nmrptr->ihsnmr) TogUp(&cbut[BFORC]);
	if (peaks != NULL) {
	   free(peaks);
	   peaks = NULL;
	}
	if (inten != NULL) {
	   free(inten);
	   inten = NULL;
	}
	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;
  case 5:
        qboxstr(&qboxes[QSFIL],NULL,1,0,-1,DEFQX,DEFQY,
                QBOXWIDE,QBOXHIGH,0,"Filename ? ",NULL,
                0,0,2000,wrjdx);
        break;
  case 6:
	avch3(); prep_nmr();
        break;
  }

  iupd = 1;
  if (nmrptr->ihsnmr) {
	iupd = 0;
	tmp = atof(qboxes[QTMS].str);
	if (tmp != *nmrref) iupd = 1;
	*nmrref = tmp;
	tmp = atof(qboxes[QFREQ].str);
	if (tmp != NMRbas) iupd = 1;
	NMRbas = tmp;
	if (iupd) prep_nmr();
  }
  calc_spectrum(iupd);
  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) {
	if (RIBindex[istruct].end[3] < RIBindex[istruct].start[3]) {
	     NSurf[istruct] = RIBindex[istruct].start[2] + 
				RIBindex[istruct].nrna;
	} else {
	     NSurf[istruct] = RIBindex[istruct].start[3] + 
				RIBindex[istruct].ncoil;
	}
    }
    else NSurf[istruct] = 0;
    if (NSurf[istruct] < 0) NSurf[istruct] = 0;
}

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;
}

#if defined(VMS) || defined(UNDERSC)
stowat(ino)
#else
#ifdef CRAY
STOWAT(ino)
#else
stowat_(ino)
#endif
#endif
int *ino;
{
   int i,j,k,kk,n,ncon;
   int icnn[MXCON+1];

   if (!*ipdbon) return;

   if (watcoo[istruct] == NULL || 
	(watcoo[istruct] != NULL && *ino > nwater[istruct])) {
      if (watcoo[istruct] != NULL) free(watcoo[istruct]);
      if ((watcoo[istruct] = 
	(double *) malloc((sizeof(double))*(*ino*3))) == NULL) {
	fprintf(stderr, "Memory allocation error for store water\n");
	return;
      }
   }

   if (watanz[istruct] == NULL || 
	(watanz[istruct] != NULL && *ino > nwater[istruct])) {
      if (watanz[istruct] != NULL) free(watanz[istruct]);
      if ((watanz[istruct] = 
	(int *) malloc((sizeof(int))*(*ino))) == NULL) {
	fprintf(stderr, "Memory allocation error for store water\n");
	return;
      }
   }

   if (watres[istruct] == NULL || 
	(watres[istruct] != NULL && *ino > nwater[istruct])) {
      if (watres[istruct] != NULL) free(watres[istruct]);
      if ((watres[istruct] = 
	(int *) malloc((sizeof(int))*(*ino))) == NULL) {
	fprintf(stderr, "Memory allocation error for store water\n");
	return;
      }
   }

   if (watcon[istruct] == NULL || 
	(watcon[istruct] != NULL && *ino > nwater[istruct])) {
      if (watcon[istruct] != NULL) free(watcon[istruct]);
      if ((watcon[istruct] = 
	(int *) malloc((sizeof(int))*(MXCON+1)*(*ino))) == NULL) {
	fprintf(stderr, "Memory allocation error for store water\n");
	return;
      }
   }

   if (watmap[istruct] == NULL || 
	(watmap[istruct] != NULL && *ino > nwater[istruct])) {
      if (watmap[istruct] != NULL) free(watmap[istruct]);
      if ((watmap[istruct] = 
	(int *) malloc((sizeof(int))*(*xyzp->mxnat))) == NULL) {
	fprintf(stderr, "Memory allocation error for store water\n");
	return;
      }
   }

   n = 0;
   for (i=0; i < *xyzp->iatoms; i++ ) {
	watmap[istruct][i] = -1;
	if (xyzp->ianz[i] < 100 && xyzp->iaton[i] == 1) {
	    watmap[istruct][i] = n;
	    n++;
	}
   }

   n = 0;
   for (i=0; i < *xyzp->iatoms; i++ ) {
	if (xyzp->ianz[i] < 100 && xyzp->iaton[i] == 1) {
	    for (k=0; k < 3; k++) 
		watcoo[istruct][n*3+k] = xyzp->coo[i*3+k];
	    watanz[istruct][n] = xyzp->ianz[i];
	    watres[istruct][n] = xyzp->iresid[i];
	    ncon = 0;
	    for (k=1; k < MXCON+1; k++) {
		kk = xyzp->iconn[i*(MXCON+1)+k];
		if (kk > 0 && kk < *xyzp->mxnat) {
		   kk--;
		   if (watmap[istruct][kk] != -1) {
			icnn[ncon] = watmap[istruct][kk];
			ncon++;
		   }
		}
	    }
	    watcon[istruct][n*(MXCON+1)] = ncon;
	    for (k=0; k < ncon; k++) 
		watcon[istruct][n*(MXCON+1)+k+1] = icnn[k];
	    n++;
	}
   }
   nwater[istruct] = n;
   free(watmap[istruct]);
   watmap[istruct] = NULL;

}

/*
int watcon(coo1,coo2)
double *coo1;
double *coo2;
{
  double v[3],d;
  int i, iflag;

  iflag = 0;

  for (i=0; i<3; i++) v[i] = coo2[i] - coo1[i];
  d = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
  if (d > 0.0) d = sqrt(d);
  if (d*0.52917706 < 1.2) iflag = 1;

  return(iflag);
}
*/

reswat()
{
   int i,j,k,n,ia,ic,icnn[2],ncon;

   if (!*ipdbon || (*ipdbon && zmpart->ipart) ) return;

   if (watcoo[istruct] == NULL || watanz[istruct] == NULL || 
	watres[istruct] == NULL) return;

   ia = *xyzp->iatoms;
   n = nwater[istruct];
   if (n+ia > *xyzp->mxnat) n = *xyzp->mxnat - ia;

   for (i=0; i < n; i++ ) {
	for (k=0; k < 3; k++) 
	   xyzp->coo[(i+ia)*3+k] = watcoo[istruct][i*3+k];
	xyzp->iconn[(i+ia)*(MXCON+1)] = watcon[istruct][i*(MXCON+1)];
	for (k=1; k < MXCON+1; k++) 
	   xyzp->iconn[(i+ia)*(MXCON+1)+k] = 
		ia + watcon[istruct][i*(MXCON+1)+k] + 1;
	xyzp->ianz[ia+i] = watanz[istruct][i];
	xyzp->iresid[ia+i] = watres[istruct][i];
	xyzp->iatclr[ia+i] = 1;
	if (*backb && !calfptr->ihets[ABS(watres[istruct][i])] ) {
	   xyzp->iaton[ia+i] = 0;
	} else {
	   xyzp->iaton[ia+i] = 1;
	}
   }
   *xyzp->iatoms = ia + n;
}

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))*(*xyzp->mxnat))) == NULL) {
	fprintf(stderr, "Memory allocation error for itypBackup\n");
	return;
      } else {
          for (i=0; i<*xyzp->mxnat; i++) itypBackup[i] = xyzp->ityp[i];
      }
   }
*/
   *fftyp = 7;
   cell->ichx = 0;

#if defined(VMS) || defined(UNDERSC)
   dotyp(&cell->ichx);
#else
#ifdef CRAY
   DOTYP(&cell->ichx);
#else
   dotyp_(&cell->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
	*tnkprg = 0;
	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 < *xyzp->iatoms; i++) {
		if (xyzp->iresid[i] == resrot[0].idrs[j]) xyzp->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,NULL,&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 < *xyzp->iatoms; i++) {
		if (xyzp->iresid[i] == resrot[0].idrs[l]) {
		   xyzp->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);
}

UpdateSTRC()
{
   int i;

   if (!STRCup) return;

   DefList(&strclist,STRCwin,STRX,20,STRW,80,
	NULL,5,sndstr[istruct],NULL,NULL,&SSon[istruct],&NSurf[istruct]);

}

inistrc()
{
  if (!xison) return(0);

  STRCup = 1;
  STRCwin = CreateWindow("Surfaces","-100+525",STRWINW,STRWINH+20,
	 		 infobg,infofg,(Window)0);
  subSTRC = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],STRCwin);
  XSelectInput(display, STRCwin, 
	SubstructureNotifyMask | ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask | PointerMotionMask | EnterWindowMask);

  XMapWindow(display,STRCwin);

  DefBut(&strcbut[0], STRCwin, STRX, 110, 90, 23,
	"Set Color", infobg, -15);
  strcbut[0].explstr = "Set Surface Color";

  DefBut(&strcbut[1], STRCwin, STRX+120, 115, 15, 15,
	" ", infobg, -15);
  strcbut[1].explstr = "Render surfaces transparent";

  DefBut(&strcbut[2], STRCwin, STRX+120, 115+BUTTH, 15, 15,
	" ", infobg, -15);
  strcbut[2].explstr = "Render surfaces as lines";

  DefBut(&strcbut[3], STRCwin, STRX, 110+BUTTN, 90, 23,
	"Delete Active", infobg, -15);
  strcbut[3].explstr = "Delete Active Surface";

  DefBut(&strcbut[4], STRCwin, STRX, 110+3*BUTTN, 50, 23,
	"Helix", infobg, -15);
  strcbut[4].explstr = "activate Helix";

  DefBut(&strcbut[5], STRCwin, STRX+60, 110+3*BUTTN, 50, 23,
	"Beta", infobg, -15);
  strcbut[5].explstr = "activate Beta sheet";

  DefBut(&strcbut[6], STRCwin, STRX+2*60, 110+3*BUTTN, 50, 23,
	"RNA", infobg, -15);
  strcbut[6].explstr = "activate RNA/DNA";

  DefBut(&strcbut[7], STRCwin, STRX+3*60, 110+3*BUTTN, 50, 23,
	"Coil", infobg, -15);
  strcbut[7].explstr = "activate Coil";

  DefBut(&strcbut[8], STRCwin, STRX, 110+4*BUTTN, 75, 23,
	"Activ. All", infobg, -15);
  strcbut[8].explstr = "Activate All surfaces";

  DefBut(&strcbut[9], STRCwin, STRX+80, 110+4*BUTTN, 90, 23,
	"Deactiv. All", infobg, -15);
  strcbut[9].explstr = "Deactivate All surfaces";

  DefBut(&strcbut[12], STRCwin, STRX+180, 110+4*BUTTN, 45, 23,
	"Invert", infobg, -15);
  strcbut[12].explstr = "Invert Activations";

  DefBut(&strcbut[11], STRCwin, STRX+120, 115+5*BUTTN, 70, 23,
	"Write All", infobg, -15);
  strcbut[11].explstr = "Write all surfaces to molden.ogl";

  DefBut(&strcbut[10], STRCwin, STRX, 115+5*BUTTN, 60, 23,
	"Close", infobg, -15);
  strcbut[10].explstr = "Close window";

  if (TRANS) {
	TogDown(&strcbut[1]);
	TRANSb = 1;
  } else {
	TogUp(&strcbut[1]);
	TRANSb = 0;
  }

  if (DoLines) {
	TogDown(&strcbut[2]);
  } else {
	TogUp(&strcbut[2]);
  }

  if (denmode) {
	ActBut(&strcbut[4],2);
	ActBut(&strcbut[5],2);
	ActBut(&strcbut[6],2);
	ActBut(&strcbut[7],2);
  }

  UpdateSTRC();

}

RedrawSTRC()
{
   int i;

   if (!STRCup) return;

   butje(STRCwin,0,0,STRWINW,STRWINH+20,4,0,0,1,None,0,0,0);

   for (i=0; i < STRCBN; i++) DrwBut(&strcbut[i]);

   LineString(STRCwin, "Transparent", STRX+140,128);
   LineString(STRCwin, "Lines", STRX+140,128+BUTTH);
   ULineString(STRCwin, "Activate:", STRX,128+2*BUTTN);

   RedrawList(&strclist);

}

int ButtonsSTRC(i)
int i;
{
   LSSTRU List; int j,k;

   switch(i) {
   case 0:
	if (DoPopUp(STRCwin, 
	   strcbut[0].x,strcbut[0].y-100, NULL,&j,0) == -1) break;
	for (k=0; k < NSurf[istruct]; k++) 
	   if (SSon[istruct][k]) SetSurfColor(k,j);
	break;
   case 1:
	TRANSb = ! TogBut(&strcbut[1]);
	for (j=0; j < NSurf[istruct]; j++) 
	   if (SSon[istruct][j]) trns[istruct][j] = TRANSb;
	break;
   case 2:
	DoLines = ! TogBut(&strcbut[2]);
	break;
   case 3:
	DeleteActiveSurfaces();
	break;
   case 4:
	for (j=RIBindex[istruct].start[0]; 
		j <= RIBindex[istruct].end[0]; j++) {
		SSon[istruct][j] = 1;
	}
	break;
   case 5:
	for (j=RIBindex[istruct].start[1]; 
		j <= RIBindex[istruct].end[1]; j++) {
		SSon[istruct][j] = 1;
	}
	break;
   case 6:
	for (j=RIBindex[istruct].start[2]; 
		j <= RIBindex[istruct].end[2]; j++) {
		SSon[istruct][j] = 1;
	}
	break;
   case 7:
	for (j=RIBindex[istruct].start[3]; 
		j <= RIBindex[istruct].end[3]; j++) {
		SSon[istruct][j] = 1;
	}
	break;
   case 8:
	for (j=0; j < NSurf[istruct]; j++) SSon[istruct][j] = 1;
	break;
   case 9:
	for (j=0; j < NSurf[istruct]; j++) SSon[istruct][j] = 0;
	break;
   case 10:
	XDestroyWindow(display,STRCwin);STRCup = 0;
	return(0);
	break;
   case 11:
#if defined(VMS) || defined(UNDERSC)
	curs(&ONE);
	wrtall();
	curs(&ZERO);
#else
#ifdef CRAY
	CURS(&ONE);
	wrtall();
	CURS(&ZERO);
#else
	curs_(&ONE);
	wrtall();
	curs_(&ZERO);
#endif
#endif
	strcpy(molwstr,"Wrote file molden.ogl");
	StatusStr(0,0);
	break;
   case 12:
	for (j=0; j < NSurf[istruct]; j++) {
	   if (SSon[istruct][j]) {
		SSon[istruct][j] = 0;
	   } else {
		SSon[istruct][j] = 1;
	   }
	}
	break;
   }

   dispsf();
   RedrawSTRC();
   return(0);
}

inistr()
{
  if (!xison) return(0);

  STRup = 1;
  STRwin = CreateWindow("Structures","-80+525",STRWINW,STRWINH,
	 		 infobg,infofg,(Window)0);
  subSTR = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],STRwin);
  XSelectInput(display, STRwin, 
	SubstructureNotifyMask | ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | LeaveWindowMask | PointerMotionMask | EnterWindowMask);

  XMapWindow(display,STRwin);

  DefBut(&strbut[0], STRwin, STRX, 110, 90, 23,
	"Delete Active", infobg, -15);
  strbut[0].explstr = "Delete the currently active\ndisplayed structure";

  DefBut(&strbut[1], STRwin, STRX+100, 110, 80, 23,
	"Delete All", infobg, -15);
  strbut[1].explstr = "Delete all structures";

  DefBut(&strbut[2], STRwin, STRX, 80+STRSH, 60, 23,
	"Combine", infobg, -15);
  strbut[2].explstr = "Add structure from the lower list\nto structure from the upper list";

  DefBut(&strbut[3], STRwin, STRX+70, 80+STRSH, 60, 23,
	"Align", infobg, -15);
  strbut[3].explstr = "Align structure from the lower list\nto structure from the upper list";

  DefBut(&strbut[4], STRwin, STRX+140, 80+STRSH, 90, 23,
	"Align+Combine", infobg, -15);
  strbut[4].explstr = "Align and add structure from the lower list\nto structure from the upper list";

  DefList(&strlist,STRwin,STRX,20,STRW,80,
	NULL,5,strfiles,NULL,NULL,NULL,&nstruct);
  strlist.select = istruct;
  strlist.lpnt = 0;
  DefList(&str2list,STRwin,STRX,20+STRSH,STRW,50,
	NULL,3,strfiles,NULL,NULL,NULL,&nstruct);
  str2list.select = 0;
  str2list.lpnt = 0;

}

RedrawSTR()
{
   int i;

   if (!STRup) return;

   butje(STRwin,0,0,STRWINW,STRWINH,4,0,0,1,None,0,0,0);

   for (i=0; i < 5; i++) DrwBut(&strbut[i]);

   RedrawList(&strlist);
   RedrawList(&str2list);

}

int ButtonsSTR(i)
int i;
{
   LSSTRU List; int j;

   switch(i) {
   case 0:
	DeleteOne();
	break;
   case 1:
	DeleteAll();
	break;
   case 2:
	if (str2list.select > 0 && strlist.select < nstruct) 
	   sstruct = str2list.select;
	if (sstruct>0 && sstruct <= nstruct) {
#if defined(VMS) || defined(UNDERSC)
	   curs(&ONE);
#else
#ifdef CRAY
	   CURS(&ONE);
#else
	   curs_(&ONE);
#endif
#endif
	   CombineStructs(sstruct,1);
	   update_model = 1;
	   update_struct();
#if defined(VMS) || defined(UNDERSC)
	   curs(&ZERO);
#else
#ifdef CRAY
	   CURS(&ZERO);
#else
	   curs_(&ZERO);
#endif
#endif
	} else {
	   if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
		"Structure should be in the range\n 1 to # of structures",0)) {}
	}
	break;
   case 3:
	if (str2list.select > 0 && strlist.select < nstruct) 
	   sstruct = str2list.select;
	if (sstruct>0 && sstruct <= nstruct) {
#if defined(VMS) || defined(UNDERSC)
	   curs(&ONE);
#else
#ifdef CRAY
	   CURS(&ONE);
#else
	   curs_(&ONE);
#endif
#endif
	   AlignStructs(sstruct);
	   update_model = 1;
	   update_struct();
#if defined(VMS) || defined(UNDERSC)
	   curs(&ZERO);
#else
#ifdef CRAY
	   CURS(&ZERO);
#else
	   curs_(&ZERO);
#endif
#endif
	} else {
	   if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
		"Structure should be in the range\n 1 to # of structures",0)) {}
	}
	break;
   case 4:
	if (str2list.select > 0 && strlist.select < nstruct) 
	   sstruct = str2list.select;
	if (sstruct>0 && sstruct <= nstruct) {
#if defined(VMS) || defined(UNDERSC)
	   curs(&ONE);
#else
#ifdef CRAY
	   CURS(&ONE);
#else
	   curs_(&ONE);
#endif
#endif
	   if (AlignStructs(sstruct)) CombineStructs(sstruct,0);
	   update_model = 1;
	   update_struct();
#if defined(VMS) || defined(UNDERSC)
	   curs(&ZERO);
#else
#ifdef CRAY
	   CURS(&ZERO);
#else
	   curs_(&ZERO);
#endif
#endif
	} else {
	   if (DoCan(event.xbutton.x_root,event.xbutton.y_root,
		"Structure should be in the range\n 1 to # of structures",0)) 
		break;
	}
	break;
   }
   RedrawSTR();
   return(0);
}

inichg(iopt)
int iopt;
{
  int i,ne = 0;

  if (!xison) return(0);

  CHGopt = iopt;

  if (iopt == 1) {
     for (i=0; i<*xyzp->iatoms; i++) {
	if (xyzp->ianz[i] >= 0 && xyzp->ianz[i] < 99) 
	   ne = ne + xyzp->ianz[i];
     }
  } else {
     for (i=0; i<*xyzp->iatoms; i++) {
	if (xyzp->iresid[i] == CHGopt) 
	   if (xyzp->ianz[i] >= 0 && xyzp->ianz[i] < 99) 
		ne = ne + xyzp->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, 110, 20+BUTTN, 70, 23,
	"Charge", infobg, -15);

  DefBut(&chgbut[1], CHGwin, 25, 20+3*BUTTN, 70, 23,
	"Apply", infobg, -15);

  DefBut(&chgbut[2], CHGwin, 225, 20+BUTTN, 70, 23,
	"Apply", infobg, -15);

  if (iopt == 1) {
     icopt = 3;
  } else {
     int aCHGopt;

     aCHGopt = abs(CHGopt);

     if (aCHGopt < MXHETA) {
	if (!clfstrptr->ihqset[aCHGopt]) LigandQ(CHGopt);
	if (clfstrptr->ihqset[aCHGopt]) {
	   icopt = clfstrptr->ihetq[aCHGopt] + 3;
	} else {
	   icopt = 3;
	}
     } else {
	icopt = 3;
     }
  }

  chgbut[0].str = copt[icopt];
  chgbut[2].str = eems[ieemopt];
}

RedrawCHG()
{
   int i;

   if (!CHGup) return;

   butje(CHGwin,0,0,CHGWINW,CHGWINH,4,0,0,1,None,0,0,0);

   for (i=0; i < 3; 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;
	*Sincp = ieemopt+1;
	*itot = icopt - 3;

	if (CHGopt == 1) {
	    LigandHydroQ(1,1,1,*itot);
#ifdef DOGL
	    if (*fancy) {
		oghet(0);
	    } else {
		oglines();
	    }
	    update_model = 0;
#endif
	    update_struct();

	} else {
	    int aCHGopt;

	    aCHGopt = abs(CHGopt);

	    if (aCHGopt < MXHETA)
		clfstrptr->ihetq[aCHGopt] = icopt - 3;

	    if (ieemopt == 4) {
#if defined(VMS) || defined(UNDERSC)
		calgas(&CHGopt,&CHGstat);
#else
#ifdef CRAY
		CALGAS(&CHGopt,&CHGstat);
#else
		calgas_(&CHGopt,&CHGstat);
#endif
#endif
	    } else {
#if defined(VMS) || defined(UNDERSC)
		eem(Sincp,&CHGopt,&CHGstat);
#else
#ifdef CRAY
		EEM(Sincp,&CHGopt,&CHGstat);
#else
		eem_(Sincp,&CHGopt,&CHGstat);
#endif
#endif
	    }
	}
	return(0);
	break;
   case 2:
	{
	List.list = eems; List.nents = 5;

	if (DoPopUp(CHGwin,chgbut[2].x+1,
		chgbut[2].y+BUTTH,&List,&ieemopt,0) == -1) return(0);
	chgbut[2].str = eems[ieemopt];
	DrwBut(&chgbut[2]);
	}
	break;
   }
   return(0);
}

#if defined(VMS) || defined(UNDERSC)
initsrf()
#else
#ifdef CRAY
INITSRF()
#else
initsrf_()
#endif
#endif
{
  if (SRFup) return;   

  SRFup = 1;

  srfsep = 1;
  srftyp = 1;
  SRFwin = CreateWindow("Create Surface","-0+0",SRFWINW,SRFWINH,
	 		 infobg,infofg,(Window)0);
  subSRF = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],SRFwin);
  XSelectInput(display, SRFwin, SubstructureNotifyMask |
	KeyPressMask | ExposureMask | ButtonPressMask | ButtonReleaseMask |
	LeaveWindowMask | PointerMotionMask | EnterWindowMask);
  XMapWindow(display,SRFwin);

  DefBut(&srfbut[0], SRFwin, 50, 25, 15, 15,
	" ", infobg, -15);
  srfbut[0].explstr = "Color code the electrostatic potential\ncalculated from point charges onto the surface";

  DefBut(&srfbut[1], SRFwin, 50, 50, 15, 15,
	" ", infobg, -15);
  srfbut[1].explstr = "Use only nearby (fast) or all (slow)\npoint charges to calculate the potential";

  DefBut(&srfbut[2], SRFwin, 50, 130, 100, 23,
	"Create Surface", infobg, -15);
  srfbut[2].explstr = "Create surface of selected residues.\nClick 2nd MB on residue ->Add to Surface";

  DefBut(&srfbut[3], SRFwin, 210, 25, 50, 23,
	"Color", infobg, -15);
  srfbut[3].explstr = "When no potential is mapped\nselect color of surface";

  DefBut(&srfbut[4], SRFwin, 50, 75, 15, 15,
	" ", infobg, -15);
  srfbut[4].explstr = "Use a separate grid for each residue.\nYields higher quality but slower surfaces";

  DefBut(&srfbut[5], SRFwin, 50, 100, 120, 23,
	" ", infobg, -15);
  srfbut[5].explstr = "Use solvent accessible surface or\napproxim. electron density surfaces";

  srfbut[5].str = srf2opt[srftyp];
  srfbut[3].fg = -cursrfcoli;

  if (hlpsrf->srfmap) {
	TogDown(&srfbut[0]);
  } else {
	TogUp(&srfbut[0]);
  }

  if (hlpsrf->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]);
   DrwBut(&srfbut[5]);

   LineString(SRFwin, "Map Electrostatic Pot.", 70, 35);
   LineString(SRFwin, "Local potential (fast)", 70, 60);
   LineString(SRFwin, "Each Res. Separate Surf.", 70, 85);
   LineString(SRFwin, "Surface type", 175, 115);

}

int ButtonsSRF(i)
int i;
{
   int j,k,calc, NStmp;

   switch(i) {
   case 0:
	hlpsrf->srfmap = 1 - TogBut(&srfbut[0]);
	break;
   case 1:
	hlpsrf->srfloc = 1 - TogBut(&srfbut[1]);
	break;
   case 2:
	update_model = 0;
	XDestroyWindow(display,SRFwin);SRFup = 0;
	calc = 1;

	if (srftyp) {

	   NStmp = NSurf[istruct];

	   if (hlpsrf->srfmap) {
		molsrf(cursrfcoli,1,1);
	   } else {
		molsrf(cursrfcoli,1,0);
	   }

	} else {

	   NStmp = NSurf[istruct];
	   if (hlpsrf->srfmap) hlpsrf->srfmap = 3;
	   if (srfsep) {
	     if (DEBUG) fprintf(stderr,"surface residues\n");
	     for (j=0; j<calfptr->ncalf; j++) {
		if (calfptr->iams[j]) {
		   if (DEBUG) fprintf(stderr,"%d\n",j);
                   for (k=0; k<*xyzp->iatoms; k++) {
			if (xyzp->iresid[k] == j+1) {xyzp->isurf[k] = 1;}
			else {xyzp->isurf[k] = 0;}
		   }
#if defined(VMS) || defined(UNDERSC)
	   	   asurf(&hlpsrf->srfmap,&calc);csrft(xyzp->isurf);
#else
#ifdef CRAY
	   	   ASURF(&hlpsrf->srfmap,&calc);CSRFT(xyzp->isurf);
#else
	   	   asurf_(&hlpsrf->srfmap,&calc);csrft_(xyzp->isurf);
#endif
#endif
		}
	     }
	     for (j=4; j<NHetAtm; j++) {
		if (calfptr->ihets[j]) {
		   if (DEBUG) fprintf(stderr,"%d\n",j);
                   for (k=0; k<*xyzp->iatoms; k++) {
			if (xyzp->iresid[k] == -j) {xyzp->isurf[k] = 1;}
			else {xyzp->isurf[k] = 0;}
		   }
#if defined(VMS) || defined(UNDERSC)
	   	   asurf(&hlpsrf->srfmap,&calc);csrft(xyzp->isurf);
#else
#ifdef CRAY
	   	   ASURF(&hlpsrf->srfmap,&calc);CSRFT(xyzp->isurf);
#else
	   	   asurf_(&hlpsrf->srfmap,&calc);csrft_(xyzp->isurf);
#endif
#endif
		}
	     }
	   } else {
#if defined(VMS) || defined(UNDERSC)
	     alasrf();asurf(&hlpsrf->srfmap,&calc);csrft(xyzp->isurf);
#else
#ifdef CRAY
	     ALASRF();ASURF(&hlpsrf->srfmap,&calc);CSRFT(xyzp->isurf);
#else
	     alasrf_();asurf_(&hlpsrf->srfmap,&calc);csrft_(xyzp->isurf);
#endif
#endif
	   }
	}
	for (j=0; j<calfptr->ncalf; j++) calfptr->iams[j] = 0;
	for (j=0; j<MXHETA; j++) calfptr->ihets[j] = 0;
	for (k=NStmp; k<NSurf[istruct]; k++) 
	    for (j=0; j<4; j++) 
		diffuseColor[istruct][k][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) {
	   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]);
	break;
   case 5:
	{
	LSSTRU List;
	List.list = srf2opt; List.nents = 2; int iii;
	if (DoPopUp(SRFwin,
		srfbut[5].x-8,srfbut[5].y+BUTTH,
		&List,&srftyp,0) == -1) break;
	srfbut[5].str = srf2opt[srftyp];
	DrwBut(&srfbut[5]);
	}
	break;
   }
}

initMLT()
{


  if (MLTup) return;   

  MLTup = 1;

  MLTwin = CreateWindow("Multi-mol file","-0+0",MLTWINW,MLTWINH,
	 		 infobg,infofg,(Window)0);
  subMLT = CreateWindow("Subwindow","",10,10,
                            colors[0],colors[15],MLTwin);
  XSelectInput(display, MLTwin, SubstructureNotifyMask |
	KeyPressMask | ExposureMask | ButtonPressMask | ButtonReleaseMask |
	LeaveWindowMask | PointerMotionMask | EnterWindowMask);

  XMapWindow(display,MLTwin);

  DefBut(&mltbut[0], MLTwin, 50, 250, 50, 23, "Close", infobg, -15);
  mltbut[0].explstr = "Close Window";

  DefList(&mltlist,MLTwin,DIRX,DIRY,DIRW,DIRH,NULL,
			NFLS,mlftit,NULL,NULL,NULL,&ntits);
  mltlist.select = mfdata->imol-1;
  if (mltlist.select < 0) mltlist.select = 0;

  WinName(win,mlftit[mltlist.select]);
}


RedrawMLT()
{
   if (!MLTup) return;

   butje(MLTwin,0,0,MLTWINW,MLTWINH,4,0,0,1,None,0,0,0);

   RedrawList(&mltlist);

   DrwBut(&mltbut[0]);

}

int ButtonsMLT(i)
int i;
{
   int j,k;

   switch(i) {
   case 0:
	if (MLTup) {
	    XDestroyWindow(display,MLTwin);
	    MLTup = 0;
	}
	break;
   }
}

#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 */

   for (i=0; i < 3; i++) hs[i] = -1;

   if (ires == -1) {

	row = GetRow(1);
	if (row < 0) return(0);

	row = izz(row,0)-1;
	if (row < 0) return(0);

	atm = zmptrp->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 < xyzp->iconn[atm*(MXCON+1)]; i++) {
	iatje = xyzp->iconn[atm*(MXCON+1)+1+i]-1;
	if (xyzp->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;
   }

   if (hs[1] > 0) {
      AddFrag(ACE,6,120.0,0.0,hs[1],1,1); 
      zmptrp->bet[hs[1]] = 180.0;
      SetQZME();
   }
   if (hs[2] > 0) {
      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 < xyzp->iconn[row*(MXCON+1)]; i++) {
	   iatje = xyzp->iconn[row*(MXCON+1)+1+i]-1;
	   if (xyzp->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 < 21) 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(cyclopentane,PENT,109.471,-90.0,-1,1,1); iret = 1; break;
	case 11: AddFrag(pyrrole,PYRROLE,120.0,180.0,-1,1,1); iret = 1; break;
	case 12: AddFrag(CL,1,109.471,180.0,-1,1,1); iret = 1; break;
	case 13: AddFrag(BR,1,109.471,180.0,-1,1,1); iret = 1; break;
	case 14: AddFrag(I,1,109.471,180.0,-1,1,1); iret = 1; break;
	case 15: AddFrag(OCH3,5,109.471,180.0,-1,1,1); iret = 1; break;
	case 16: AddFrag(SH,2,109.471,180.0,-1,1,1); iret = 1; break;
	case 17: AddFrag(NO2,3,117.38,180.0,-1,1,1); iret = 1; break;
	case 18: AddFrag(CH4,5,117.38,180.0,-1,1,1); iret = 1; break;
	case 19: 
		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 20: 

        /* 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 21: 
		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 22: 
		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) {

      while(XCheckTypedWindowEvent(display, win, MotionNotify,&event));

      if ( *ball && (moving || gmoving)) {
        update_model = 0;
	if (XCheckMaskEvent(display,ButtonReleaseMask,&event)) {
	   if ((*fancy || *fullgl) && 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 || *fullgl) && has_opengl) 
		motion(event.xmotion.x, event.xmotion.y, 0);
	   else qupd();
#else
#ifdef CRAY
       	   MKTRN(inct,incp);
	   if ((*fancy || *fullgl) && has_opengl) 
		motion(event.xmotion.x, event.xmotion.y, 0);
	   else QUPD();
#else
           mktrn_(inct,incp);
	   if ((*fancy || *fullgl) && 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 || *fullgl) {
		   Ca = FindCa(xyzp->iaton,xyzp->iyp,xyzp->ixp,
			event.xmotion.x,event.xmotion.y,MINDIFF);

		   if (Ca >= 0) {
		       parse_label(Ca,0,xyzp->ixp,xyzp->iyp);
		       if (OMAPup && omapfol && !omaplck) res_dens(Ca);
		   } else {
		       Ca = FindSel(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,
				*xyzp->iatoms,
				event.xmotion.x,event.xmotion.y,MINDIFF);
		       if (Ca>=0) parse_labelp(xyzp->iresid[Ca]-1,Ca,xyzp->ixp,xyzp->iyp);
		       else parse_labelp(RESUND,0,xyzp->ixp,xyzp->iyp);
		   }

	        } else {

		   Ca = FindCaP(event.xmotion.x,event.xmotion.y,MINDIFF);

		   if (Ca >= 0) {
		       parse_labelp(Ca,0,xyzp->ixp,xyzp->iyp);
		   } else {
		       Ca = FindSel(xyzp->iaton,xyzp->iyp,xyzp->ixp,0,
				*xyzp->iatoms,
				event.xmotion.x,event.xmotion.y,MINDIFF);
		       if (Ca>=0) parse_labelp(xyzp->iresid[Ca]-1,Ca,xyzp->ixp,xyzp->iyp);
		       else parse_labelp(RESUND,0,xyzp->ixp,xyzp->iyp);
		   }
	        }
	     }

	}
      }
   }

}

void ressel()
{
      int i,j,ires;


	for (ires = 1; ires < calfptr->ncalf+1; ires++ ) {
	   if (calfptr->iams[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++) {
		   if (ipdb[i] > 0) xyzp->iaton[ipdb[i]-1] = 2;
		}

		for (i=0; i<3*MXHSYM; i++) {
		   if (ihpdb[i] > 0) xyzp->iaton[ihpdb[i]-1] = 2;
		}
	   }

	}
}

#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 = vfork();
    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, int *iorb, 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,iorb,dens);

   if (dowrt) fclose(out);
   dowrt = 0;

   if (!has_opengl) launchViewer(1);

}

#if defined(VMS) || defined(UNDERSC)
void ogspst()
#else
#ifdef CRAY
void OGSPST()
#else
void ogspst_()
#endif
#endif
{

    if (dowrt) fclose(out);
    dowrt = 0;

    if (!has_opengl) 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
{
   if (!has_opengl) launchViewer(0);
}

BuildList(r,cnst,nnpts1,nnpts2,iorb,dens)
double *r;
double *cnst;
int *nnpts1;
int *nnpts2;
int *iorb;
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) {
	if (*iorb) {
	   fprintf(out,"[ELEVATIONGRID] \"Orbital %d\"\n",*iorb);
	} else {
	   fprintf(out,"[ELEVATIONGRID] \"Density\"\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,iorb,cntval)
#else
#ifdef CRAY
void OGBEG(isurf,iorb,cntval)
#else
void ogbeg_(isurf,iorb,cntval)
#endif
#endif
int *isurf;
int *iorb;
double *cntval;
{
      int surf,surfabs;
      double cval;

      if (!dowrt) return;

      surf = *isurf;
      surfabs = abs(surf);

      cval = *cntval;
      if (surfabs == 2) cval = cval * -1.0;

      if (surfabs == 3) {
	   fprintf(out,"[SURFACE] MAPPED \"Density %3d isocontour %7.4f\"\n",*iorb,cval);
      } else {
	if (surf<0) {
	   fprintf(out,"[SURFACE] TRANS COLOR 1.0 1.0 0.0 \"Density %3d isocontour %7.4f\"\n",*iorb,cval);
	} else {
	   fprintf(out,"[SURFACE] \"Orbital %3d isocontour %7.4f\"\n",*iorb,cval);
	}
      }

}

#if defined(VMS) || defined(UNDERSC)
void ogend()
#else
#ifdef CRAY
void OGEND()
#else
void ogend_()
#endif
#endif
{
      int i;

      i = 0;
}


void initnthe() 
{
   int i,j;

   for (i=0; i<MAXSTRUCT; i++) scl[i] = 1.0;
}

double dveclen(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 = (double) sqrt(tot);

      return(vl);

}

int getusr(tmps)
char* tmps;
{

   char *tmpf;
   int i,j,status;

   strcpy(tmps,"");
   tmpf = getenv("APPDATA");
   if (tmpf != NULL) {
	strcat(tmps,tmpf);
	j = strlen(tmps);
	for (i=0; i<j; i++)
	   if (tmps[i] == '\\') tmps[i] = '/';
	strcat(tmps,"/Molden");
	if (access(tmps,F_OK) != 0) {
	    status = mkdir(tmps, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
	    if (status == -1) {
		fprintf(stderr,"Directory %s not created\n",tmps);
		return(0);
	    }
	}
	strcat(tmps,"/srf");
   }
   return(1);
}

#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.6},
  {1.0,0.0,1.0,0.6},
  {0.0,1.0,0.0,0.6},
  {0.6,0.6,0.6,0.6},
  {0.5,1.0,0.5,0.6},
  {1.0,1.0,1.0,0.6},
  {1.0,0.5,0.5,0.6}
};
 

static GLdouble theEQ1[4] = {  0.0,  0.0, -1.0, 0.0};
static GLdouble theEQ2[4] = {  0.0,  0.0,  1.0, 0.0};
static GLdouble theEQ3[4] = { -1.0,  0.0,  0.0, 0.0};
static GLdouble theEQ4[4] = {  1.0,  0.0,  0.0, 0.0};
static GLdouble theEQ5[4] = {  0.0, -1.0,  0.0, 0.0};
static GLdouble theEQ6[4] = {  0.0,  1.0,  0.0, 0.0};

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 PERSP = 0;
static int AXES = 0;
static int l1on = 0;
static int l2on = 0;
static int l3on = 1;
static int stacks = 10;
static int DoCap = 0;
static GLfloat fdens = 0.03;
static int DoLights = 0;
static int DoNorms = 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 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[MAXSTRUCT][4];
static float light1_position[MAXSTRUCT][4];
static float light2_position[MAXSTRUCT][4];
static float light0_position_def[] = {-2.0, -2.0, 0.0, 1.0};
static float light1_position_def[] = {4.0, 4.0, 4.0, 1.0};
static float light2_position_def[] = {0.0, 0.0, 4.0, 1.0};

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;

#define MXMOL 1000
static GLuint theSurf[MAXSTRUCT][MAXSURF];
static GLuint theMol[MAXSTRUCT][MXMOL];
static GLuint theLines[MAXSTRUCT];
static GLuint theFLines[MAXSTRUCT];
static GLuint thePoints[MAXSTRUCT];
static GLuint theForces[MAXSTRUCT];
static GLuint theDipole[MAXSTRUCT];
static GLuint theBox[MAXSTRUCT];
static GLuint theNorm;
static GLuint theAxes;
static GLuint theBack;
static GLuint theElem_20[MXEL];
static GLuint theElem_20_bs[MXEL];
static GLuint theElem_12[MXEL];
static GLuint theElem_12_bs[MXEL];
static GLuint theElsm;
static GLuint theRes[MAXSTRUCT][NUMCAL];
static GLuint theBck[MAXSTRUCT][NUMCAL];
static GLuint theMon[MAXSTRUCT];
static GLuint theSel[MAXSTRUCT];
static GLUquadricObj *cyl;
static GLUquadricObj *sphere;
static GLUquadricObj *disk;

#define ROTINCR 5.0
static GLfloat xrot = -45.0;
static GLfloat yrot = 240.0;

void ResetRes()
{
   int j;

   for (j=0; j<NUMCAL; j++) {
        glDeleteLists(theRes[istruct][j],1);
	theRes[istruct][j] = -1;
	theBck[istruct][j] = -1;
   }
}

void MoveOne(i)
int i;
{
	int j,k;

	SSdone[i]    = SSdone[i+1];
	NSurf[i]     = NSurf[i+1];
	NMols[i]     = NMols[i+1];
	CMols[i]     = CMols[i+1];

	theLines[i]  = theLines[i+1];
	theFLines[i] = theFLines[i+1];
	thePoints[i] = thePoints[i+1];
	theForces[i] = theForces[i+1];
	theDipole[i] = theDipole[i+1];
	theBox[i]    = theBox[i+1];
	theMon[i]    = theMon[i+1];
	theSel[i]    = theSel[i+1];

	for (j=0;j < MAXSURF;j++) {
	   theSurf[i][j] = theSurf[i+1][j];
	   SSon[i][j]    = SSon[i+1][j];
	   SStyp[i][j]   = SStyp[i+1][j];
	   Schain[i][j]   = Schain[i+1][j];
	   sndstr[i][j]  = sndstr[i+1][j];
	   srfvert[i][j] = srfvert[i+1][j];
	   clp[i][j]    = clp[i+1][j];
	   trns[i][j]    = trns[i+1][j];
	   for (k=0;k < 4;k++)  
		diffuseColor[i][j][k] = diffuseColor[i+1][j][k];
	}

	for (j=0;j < NUMCAL;j++) { 
	   theRes[i][j] = theRes[i+1][j];
	   theBck[i][j] = theBck[i+1][j];
	}

	for (j=0;j < MAXMOL;j++)  
	   theMol[i][j] = theMol[i+1][j];

	for (j=0;j < 4;j++) {
	   light0_position[i][j] = light0_position[i+1][j];
	   light1_position[i][j] = light1_position[i+1][j];
	   light2_position[i][j] = light2_position[i+1][j];
	}  

	nwater[i] = nwater[i+1];
	watcoo[i] = watcoo[i+1];
	watanz[i] = watanz[i+1];
	watres[i] = watres[i+1];
	watcon[i] = watcon[i+1];
	watmap[i] = watmap[i+1];

	RedrawSTRC();
}

RibClear(ist)
int ist;
{
   int j;

   for (j=0; j<4; j++) {
	RIBindex[ist].start[j] = -1;
	RIBindex[ist].end[j] = -1;
   }

   RIBindex[ist].nhelx = 0;
   RIBindex[ist].nbeta = 0;
   RIBindex[ist].nrna = 0;
   RIBindex[ist].ncoil = 0;
}

void initOne(i) 
int i;
{
   int j,k;

   SSdone[i] = -1;
   NSurf[i] = 0;
   NMols[i] = -1;
   CMols[i] = 0;
   theLines[i] = -1;
   theFLines[i] = -1;
   thePoints[i] = -1;
   theForces[i] = -1;
   theDipole[i] = -1;
   theDipole[i] = -1;
 
   for (j=0; j<4; j++) {
      light0_position[i][j] = light0_position_def[j];
      light1_position[i][j] = light1_position_def[j];
      light2_position[i][j] = light2_position_def[j];
   }
   for (j=0; j<MAXSURF; j++) {
	theSurf[i][j] = -1;
	sndstr[i][j] = NULL;
	srfvert[i][j] = NULL;
	nvert[i][j] = 0;
	nvrtmx[i][j] = 0;
	Schain[i][j] = -1;
	for (k=0; k<4; k++) {
	   diffuseColor[i][j][k] = diffColor[j][k];
	   specularColor[j][k] = specColor[k];
	}
   }
   for (j=0; j<MAXMOL; j++) theMol[i][j] = -1;
   for (j=0; j<NUMCAL; j++) {
      theRes[i][j] = -1;
      theBck[i][j] = -1;
   }

   RibClear(i);

   nwater[i] = 0;
   watcoo[i] = NULL;
   watanz[i] = NULL;
   watres[i] = NULL;
   watcon[i] = NULL;
   watmap[i] = NULL;
}

void initthe() 
{
   int i;

   for (i=0; i<MAXSTRUCT; i++) initOne(i);
}

void deletebox()
{
   if (theBox[istruct] > 0) 
	glDeleteLists(theBox[istruct],1);
   theBox[istruct] = -1;
}

void srfprop()
{
	SetSurfColor(omapsrf,10);
        clp[istruct][omapsrf] = 1;
	trns[istruct][omapsrf] = 1;
	if (omapPandN) {
	   trns[istruct][omapsrf] = 0;
	   SetSurfColor(omapsrf,6);
	   SetSurfColor(omapsrf+1,5);
           clp[istruct][omapsrf+1] = 1;
	   trns[istruct][omapsrf+1] = 0;
	}
	TRANS = 0;
}

DeleteSurface(isrf)
int isrf;
{
   int i,j,k,NStmp;


   NStmp = NSurf[istruct];

   glDeleteLists(theSurf[istruct][isrf],1);
   free(sndstr[istruct][isrf]);
   free(srfvert[istruct][isrf]);

   for (j=0; j<4; j++) {
	if (isrf < RIBindex[istruct].start[j]) {
			RIBindex[istruct].start[j]--;
			RIBindex[istruct].end[j]--;
	} else if (isrf >= RIBindex[istruct].start[j] 
		        && isrf <= RIBindex[istruct].end[j]) {
			RIBindex[istruct].end[j]--;
			if (RIBindex[istruct].start[j] == 
				RIBindex[istruct].end[j]) {
			   RIBindex[istruct].start[j] = -1;
			   RIBindex[istruct].end[j] = -1;
			}
	}
		
   }

   for (j=isrf; j<NSurf[istruct]-1; j++) {
	for (k=0; k<3; k++) 
	   diffuseColor[istruct][j][k] = diffuseColor[istruct][j+1][k];
	theSurf[istruct][j] = theSurf[istruct][j+1];
	SSon[istruct][j] = SSon[istruct][j+1];
	clp[istruct][j] = clp[istruct][j+1];
	trns[istruct][j] = trns[istruct][j+1];
	SStyp[istruct][j] = SStyp[istruct][j+1];
	Schain[istruct][j] = Schain[istruct][j+1];
	sndstr[istruct][j] = sndstr[istruct][j+1];
	srfvert[istruct][j] = srfvert[istruct][j+1];
	nvert[istruct][j] = nvert[istruct][j+1];
	nvrtmx[istruct][j] = nvrtmx[istruct][j+1];
   }
   NSurf[istruct]--;
   if (NSurf[istruct] < 0) NSurf[istruct] = 0;


   for (j=NSurf[istruct]; j < NStmp; j++) { 
	theSurf[istruct][j] = -1;
	SSon[istruct][j] = 0;
	clp[istruct][j] = 0;
	trns[istruct][j] = 0;
	srfvert[istruct][j] = NULL;
	nvert[istruct][j] = 0;
	nvrtmx[istruct][j] = 0;
	sndstr[istruct][j] = NULL;
   }
}

DeleteActiveSurfaces()
{
  int i,j,k,NStmp;

  i = 0;

  NStmp = NSurf[istruct];

  while (i<NSurf[istruct]) {

	if (SSon[istruct][i]) {

	   glDeleteLists(theSurf[istruct][i],1);
	   free(sndstr[istruct][i]);
	   free(srfvert[istruct][i]);

	   for (j=0; j<4; j++) {
		if (i < RIBindex[istruct].start[j]) {
			RIBindex[istruct].start[j]--;
			RIBindex[istruct].end[j]--;
		} else if (i >= RIBindex[istruct].start[j] 
		        && i <= RIBindex[istruct].end[j]) {
			RIBindex[istruct].end[j]--;
			if (RIBindex[istruct].start[j] == 
				RIBindex[istruct].end[j]) {
			   RIBindex[istruct].start[j] = -1;
			   RIBindex[istruct].end[j] = -1;
			}
		}
		
	   }

	   for (j=i; j<NSurf[istruct]-1; j++) {
		for (k=0; k<3; k++) 
		   diffuseColor[istruct][j][k] = 
			 diffuseColor[istruct][j+1][k];
		theSurf[istruct][j] = theSurf[istruct][j+1];
		SSon[istruct][j] = SSon[istruct][j+1];
		clp[istruct][j] = clp[istruct][j+1];
		trns[istruct][j] = trns[istruct][j+1];
		SStyp[istruct][j] = SStyp[istruct][j+1];
		Schain[istruct][j] = Schain[istruct][j+1];
		sndstr[istruct][j] = sndstr[istruct][j+1];
		srfvert[istruct][j] = srfvert[istruct][j+1];
		nvert[istruct][j] = nvert[istruct][j+1];
		nvrtmx[istruct][j] = nvrtmx[istruct][j+1];
	   }
	   NSurf[istruct]--;
	   if (NSurf[istruct] < 0) NSurf[istruct] = 0;

	} else {
	   i++;
	}
  }

  for (j=NSurf[istruct]; j < NStmp; j++) { 
	theSurf[istruct][j] = -1;
	SSon[istruct][j] = 0;
	clp[istruct][j] = 0;
	trns[istruct][j] = 0;
	srfvert[istruct][j] = NULL;
	nvert[istruct][j] = 0;
	nvrtmx[istruct][j] = 0;
	sndstr[istruct][j] = NULL;
  }
}

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();                 

    if (StarNet) {
	theBack = glGenLists(1);
	glNewList(theBack, GL_COMPILE_AND_EXECUTE);
    }

    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();

    if (StarNet) glEndList();

    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;
    
    if (labinfo == NULL) {
	id = mfinfo->fid;
	first = (GLuint) mfinfo->min_char_or_byte2;
	last = (GLuint) mfinfo->max_char_or_byte2;
    } else {
	id = labinfo->fid;
	first = (GLuint) labinfo->min_char_or_byte2;
	last = (GLuint) labinfo->max_char_or_byte2;
    }

    last++;

    base = glGenLists((GLsizei) last);
    if (base == 0) {
        fprintf(stderr,"out of display lists\n");
        exit(0);
    }
    glXUseXFont(id, (int) first, (int) last, (int) 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)
{
   GLfloat r,g,b;

   if (init) initPrintStrings(1);

	glLoadIdentity();

	y = height  - y;

	glViewport( x - 1, y - 1, 0, 0 );

	r = ((GLfloat) colorr[*ifntcl]) / 65535.0 ;
	g = ((GLfloat) colorg[*ifntcl]) / 65535.0 ;
	b = ((GLfloat) colorb[*ifntcl]) / 65535.0 ;

	glColor3f(r,g,b);
	glRasterPos4f( 0, 0, 1, 1 );

	glPushAttrib(GL_LIST_BIT);
	glListBase((GLuint) base);
	glCallLists((GLsizei) 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();

}
#define NSELE 4
int SelElem[NSELE] = {0,5,6,7};

void ogsetel20(int j)
{
      double rad;

      theElem_20[j] = glGenLists(1);
      glNewList(theElem_20[j], GL_COMPILE);
      rad = elmptr->vdwr[j]*1.4/0.52917706;
      gluSphere(sphere, rad, 20, 20);
      glEndList();
}

void ogsetel20_bs(int j)
{
      double rad;

      theElem_20_bs[j] = glGenLists(1);
      glNewList(theElem_20_bs[j], GL_COMPILE);
      rad = elmptr->vdwr[j]*0.5/0.52917706;
      gluSphere(sphere, rad, 20, 20);
      glEndList();
}

void ogsetel12(int j)
{
      double rad;

      theElem_12[j] = glGenLists(1);
      glNewList(theElem_12[j], GL_COMPILE);
      rad = elmptr->vdwr[j]*1.4/0.52917706;
      gluSphere(sphere, rad, 12, 12);
      glEndList();
}

void ogsetel12_bs(int j)
{
      double rad;

      theElem_12_bs[j] = glGenLists(1);
      glNewList(theElem_12_bs[j], GL_COMPILE);
      rad = elmptr->vdwr[j]*0.5/0.52917706;
      gluSphere(sphere, rad, 12, 12);
      glEndList();
}

void ogelem()
{
    int i;
    double rad;

    for (i=0; i<MXEL; i++) {
      theElem_20[i] = -1;
      theElem_20_bs[i] = -1;
      theElem_12[i] = -1;
      theElem_12_bs[i] = -1;
    }

    for (i=0; i<NSELE; i++) {

      ogsetel20(SelElem[i]);
      ogsetel20_bs(SelElem[i]);
      ogsetel12(SelElem[i]);
      ogsetel12_bs(SelElem[i]);

    }

    theElsm = glGenLists(1);
    glNewList(theElsm, GL_COMPILE);
    rad = 0.13/0.52917706;
    gluSphere(sphere, rad, 12, 12);
    glEndList();

}

void ogChkElem()
{
    int i,ia;
    int ElPres[MXEL];

    for (i=0; i<MXEL; i++) ElPres[i] = 0;
    for (i=0; i < *xyzp->iatoms; i++) {
	ia = xyzp->ianz[i]-1;
	ElPres[ia] = 1;
    }

    for (i=0; i<MXEL; i++) {

      if (ElPres[i]) {
	ogsetel20(i);
	ogsetel20_bs(i);
	ogsetel12(i);
	ogsetel12_bs(i);
      }

    }

}

void ogfstsph(int ic, int ia, float *p1, int type)
{

      glPushMatrix();
      glTranslatef(p1[0],p1[1],p1[2]);
      setAtomColor(ic);
      if (type && ! (*ivdwpl == 2)) {
	 glCallList(theElsm);
      } else {
         if (*ivdwpl == 2) {
	   if (*ipdbon && *xyzp->iatoms > 500 && !has_shader) {
	    glCallList(theElem_12_bs[ia]);
	   } else {
	    glCallList(theElem_20_bs[ia]);
	   }
	 } else {
	   if (*ipdbon && *xyzp->iatoms > 500 && !has_shader) {
	    glCallList(theElem_12[ia]);
	   } else {
	    glCallList(theElem_20[ia]);
	   }
	 }
      }
      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 && *xyzp->iatoms > 500 && !has_shader) {
	    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, colv[3];
    float tmp1[3],tmp2[3], tmp3[3];
    int i,j,k,l,m,n, 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) xyzp->coo[iatom*3+l];
    *dijsq = tmp1[0]*tmp1[0] + tmp1[1]*tmp1[1] + tmp1[2]*tmp1[2];

    if (xyzp->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 && *xyzp->iatoms > 500 && !has_shader) lowres = 1;

    doclr = 0;
    if (xyzp->iatclr != NULL && !*atcol) doclr = 1;

    if (xyzp->iaton[iatom] >= 1  && !(xyzp->iresid[iatom] <= 0 
	&& xyzp->iresid[iatom] >= -3 && xyzp->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 = xyzp->ianz[iatom];

	 if (doclr) {
            ic = xyzp->iatclr[iatom]-1;
	 } else {
	    ic = 0;
	    if (ia >=1 ) ic = elmptr->icol[ia-1]-1;
	 }

	 if (!(dsurf && !dcell)) {

	 if (*ivdwpl == 1 && *fancy && !dsurf) {

 	   if (iatom <= cell_up && iatom >= cell_low) {
		ogfstsph(ic,ia-1,tmp1,0);
		roddef = elmptr->vdwr[ia-1]/0.52917706;
		for (k=0; k<xyzp->iconn[iatom*(MXCON+1)]; k++) {
		   m = xyzp->iconn[iatom*(MXCON+1)+k+1];
		   j = ABS(m) - 1;
		   if (j > iatom) {
			for (l=0; l<3; l++) 
			   tmp3[l] = (float) xyzp->coo[j*3+l];
			ogrod(ic,tmp1,tmp3,roddef,1,0);
		   }
		}
	   } else {
		if (idorad) {
		   roddef = xyzp->qat[iatom]/0.52917706;
		} else {
		   roddef = elmptr->vdwr[ia-1]*1.4/0.52917706;
		}
		ogfstsph(ic,ia-1,tmp1,0);
	   }

	 } else {

	   issolv = 0;
	   it = xyzp->iconn[iatom*(MXCON+1)];
	   if (*ipdbon && xyzp->iresid[iatom] == -(calfptr->ishoh) && it) issolv = 1;

           roddef = 0.13/0.52917706;

           if (!issolv && *fancy) {
              if ((lowres && !it) || !lowres) {
		ogfstsph(ic,ia-1,tmp1,1);
	      } else {
		if ( *ivdwpl == 2) {
	   	   ogfstsph(ic,ia-1,tmp1,0);
		}
	      }
	   }

           for (k=0; k<xyzp->iconn[iatom*(MXCON+1)]; k++) {

	    m = xyzp->iconn[iatom*(MXCON+1)+k+1];
            j = ABS(m) - 1;

	    if (xyzp->iconn[iatom*(MXCON+1)+k+1] < 0) 
		    roddef = (0.13/0.52917706)/4.0;
            ja = xyzp->ianz[j];
	    if (doclr) {
               jc = xyzp->iatclr[j]-1;
	    } else {
               jc = elmptr->icol[ja-1]-1;
	    }
            for (l=0; l<3; l++) 
		tmp2[l] = (float) xyzp->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 (*fancy) {
		   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);
		} else {
		   colv[0] = ((GLdouble) colorr[ic+1]) / 65535.0 ; 
		   colv[1] = ((GLdouble) colorg[ic+1]) / 65535.0 ; 
		   colv[2] = ((GLdouble) colorb[ic+1]) / 65535.0 ; 
		   if (m < 0) {
			glEnd();
			glLineStipple(4,0xAAAA);
			glEnable(GL_LINE_STIPPLE);
			glBegin(GL_LINES);
		   }
		   glColor4d(colv[0],colv[1],colv[2],tr_val);
		   glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
		   glVertex3d(tmp3[0],tmp3[1],tmp3[2]);
		   if (m < 0) {
			glEnd();
			glDisable(GL_LINE_STIPPLE);
			glBegin(GL_LINES);
			isdraw = 1;
		   }
		}
	    }

	   } /* end for k */
	 } /* end if (*ivdwpl && !dsurf)*/
	 } 
     } /* end if (xyzp->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, colv[3];
    float tmp1[3],tmp2[3], tmp3[3];

/* consider making this routine do the same for solid and fullgl stick */

    if (! (*fancy || *fullgl)) return;
    if (!xison) return;

      roddef = (0.13/0.52917706)/4.0;
      doclr = 0;
      if (xyzp->iatclr != NULL && !*atcol) doclr = 1;

      if (!glIsList(theMon[istruct])) glDeleteLists(theMon[istruct],1);

      theMon[istruct] = glGenLists(1);
      glNewList(theMon[istruct], GL_COMPILE_AND_EXECUTE);

      if (*fancy) {
        glDisable(GL_COLOR_MATERIAL);
      } else {
	glDisable(GL_LIGHTING);
	glLineWidth(1.0);
	glLineStipple(4,0xAAAA);
	glEnable(GL_LINE_STIPPLE);
	glEnable(GL_LINE_SMOOTH);
	glEnable(GL_COLOR_MATERIAL);
	glBegin(GL_LINES);
      }


      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) xyzp->coo[i1*3+l];
	 for (l=0; l<3; l++) 
	    tmp2[l] = (float) xyzp->coo[i2*3+l];
	 for (l=0; l<3; l++) 
	    tmp3[l] = (tmp2[l] - tmp1[l])/2.0 + tmp1[l];

         ia = xyzp->ianz[i1];
	 if (doclr) {
            ic = xyzp->iatclr[i1]-1;
	 } else {
            ic = elmptr->icol[ia-1]-1;
	 }

         if (*fancy) {
		ogrod(ic,tmp1,tmp3,roddef,0,0);
	 } else {
		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]);
	 }

         ia = xyzp->ianz[i2];
	 if (doclr) {
            ic = xyzp->iatclr[i2]-1;
	 } else {
            ic = elmptr->icol[ia-1]-1;
	 }

         if (*fancy) {
		ogrod(ic,tmp2,tmp3,roddef,0,0);
	 } else {
		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(tmp2[0],tmp2[1],tmp2[2]);
		glVertex3d(tmp3[0],tmp3[1],tmp3[2]);
	 }

      }

      if (! *fancy) {
	glEnd();
	glDisable(GL_LINE_STIPPLE);
	glDisable(GL_COLOR_MATERIAL);
	glEnable(GL_LIGHTING);
      }

      glEndList();
}

void ogunsel()
{
 int j;

    for (j=0; j < *zmptrp->nz; j++) 
         if (xyzp->iaton[j] >= 2) xyzp->iaton[j] = 1;
    for (j=0; j < *xyzp->iatoms; j++) 
         if (xyzp->iaton[j] >= 2) xyzp->iaton[j] = 1;
    update_sel = 1;
}

void ogsel()
{
  int i;
  float tmp[3];
  GLdouble srad;

  theSel[istruct] = glGenLists(1);
  glNewList(theSel[istruct], GL_COMPILE_AND_EXECUTE);

  for (i=0; i<*xyzp->iatoms; i++) {
        tmp[0] = (float) (xyzp->coo[i*3]);
        tmp[1] = (float) (xyzp->coo[i*3+1]);
        tmp[2] = (float) (xyzp->coo[i*3+2]);
        if (xyzp->iaton[i] >= 2)  {
           if (ZMEup || aflag || cflag || ATMup || SelDel || ONIup || 
		scoup || NMRup) {
	      if (*ivdwpl == 1) {
		srad = 3.0;
              } else if (*ivdwpl == 2) {
		srad = (0.55/0.52917706);
              } else {
		srad = (1.5*0.13/0.52917706);
	      }
	      ogsphere(rimcols[xyzp->iaton[i]]-1,tmp,srad,0);
	   }
	}
  }
  glEndList();
  update_sel = 0;
}

void updfog(iset)
int iset;
{
   int l;

   if (posz > 0.0) posz = sqrt(posz);
   scl[istruct] = posz;
   if (scl[istruct] == 0.0) scl[istruct] = 1.0;
   posz = -1.6*posz;
   for (l=0; l<3; l++)
	light2_position[istruct][l] = light2_position_def[l]*scl[istruct]*5.0;
   if (iset) poszset = 1;
}

void ogbck(isec)
int isec;
{
      int i,j,ires;
      double dijsq;

	if (!(has_opengl && (*fancy || *fullgl) )) return;

	if (*fancy) ogChkElem();
	for (ires = 1; ires < calfptr->ncalf+1; ires++ ) {
	   if (calfptr->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[istruct][ires-1] = glGenLists(1);
		glNewList(theBck[istruct][ires-1], GL_COMPILE);
		
		for (i=0; i<3; i++) {
		   if (ipdb[i] > 0) {
			xyzp->iaton[ipdb[i]-1] = 1;
			ogatbnd(ipdb[i]-1,&dijsq);
		   }
		}
		glEndList();
	   }

	}
}

void ogres_(ires,iopt,iupd)
int *ires;
int *iopt;
int *iupd;
{
     ogres(*ires,*iopt,*iupd);
}

void ogres(ires,iopt,iupd)
int ires;
int iopt;
int iupd;
{
      int i,j;
      double dijsq;

      if (!((*fancy || *fullgl) && has_opengl)) {
	update_struct();
	return;
      }

      if (!calfptr->reson[ires-1]) return;
/*
      glDeleteLists(theRes[istruct][ires-1],1);
      theRes[istruct][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[istruct][ires-1])) 
		theRes[istruct][ires-1] = glGenLists(1);
      glNewList(theRes[istruct][ires-1], GL_COMPILE);

      if (*fancy) {
        glDisable(GL_COLOR_MATERIAL);
      } else {
	glDisable(GL_LIGHTING);
	glLineWidth(2.0);
	glEnable(GL_LINE_SMOOTH);
	glEnable(GL_COLOR_MATERIAL);
	glBegin(GL_LINES);
      }

      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;
	}
      }

      if (! *fancy) {
	glEnd();
	glDisable(GL_COLOR_MATERIAL);
	glEnable(GL_LIGHTING);
      }

      glEndList();
      if (iupd) dispsf();
}


void oghet(int iopt)
{
    double dijsq;
    int i, ioff, num_atoms;

    theMol[istruct][NMols[istruct]] = glGenLists(1);
    glNewList(theMol[istruct][NMols[istruct]], GL_COMPILE);
    glDisable(GL_COLOR_MATERIAL);

    ioff = 0;
    num_atoms = *xyzp->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 (xyzp->iresid[i] < -3) {
	ogatbnd(i,&dijsq);
	if (!iopt && (!addfile || !poszset) ) if (dijsq > posz) posz = dijsq;
       }
    } 

    glEndList();
}

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 || *fullgl) ) return;

    glXMakeCurrent(display, win, cx);
    if (!iopt && !addfile) posz = 0.0;

    glPopMatrix();
    glPushMatrix();

    if (NMols[istruct] >= MXMOL - 1) return;

    if (NMols[istruct] != -1 && !iopt) {
       NMols[istruct] = -1;
       NMols[istruct]++;
       glDeleteLists(theMol[istruct][NMols[istruct]],1);
       theMol[istruct][NMols[istruct]] = -1;
    } else NMols[istruct]++;

    if (*xyzp->iatoms == 0) return;

    if (iopt) {
	glDeleteLists(theMol[istruct][1],1);
	theMol[istruct][1] = -1;
	NMols[istruct] = 1;
    }

/* do residues */

    for (ires=0;ires < calfptr->ncalf;ires++) {
	l = calfptr->icalf[ires][0];
	for (i=0; i<3; i++) 
	   tmp1[i] = (float) xyzp->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 */

    oghet(iopt);

    if (!iopt && (!addfile || !poszset) ) updfog(1);

    dispsf();
}


void ogmoll(int iopt)
{
    double dijsq;
    int i,j,k,l, doclr, ioff, num_atoms;
    int cell_low, cell_up;


    if (!(*fancy || *fullgl)) return;

    if (*fancy) ogChkElem();

    if (*ipdbon) {
	ogpdb(iopt);
	return;
    }

    glXMakeCurrent(display, win, cx);
    if (!iopt && !addfile) posz = 0.0;

    glPopMatrix();
    glPushMatrix();

    if (NMols[istruct] >= MXMOL - 1) return;

    if (NMols[istruct] != -1 && !iopt) {
       NMols[istruct] = -1;
       NMols[istruct]++;
       glDeleteLists(theMol[istruct][NMols[istruct]],1);
       theMol[istruct][NMols[istruct]] = -1;
    } else NMols[istruct]++;

    if (*xyzp->iatoms == 0) return;

    if (iopt) {
	glDeleteLists(theMol[istruct][1],1);
	theMol[istruct][1] = -1;
	NMols[istruct] = 1;
    }

    theMol[istruct][NMols[istruct]] = glGenLists(1);
    glNewList(theMol[istruct][NMols[istruct]], GL_COMPILE);
    glDisable(GL_COLOR_MATERIAL);


    ioff = 0;
    num_atoms = *xyzp->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) ) updfog(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(rotptr->td);
#else
#ifdef CRAY
    DODCNT(rotptr->td);
#else
    dodcnt_(rotptr->td);
#endif
#endif

    adj = *adjuss;
    glXMakeCurrent(display, win, cx);
    posz = 0.0;
    dijsq = 0.0;

    roddef = (0.13/adj);

    glPopMatrix();
    glPushMatrix();

    glDeleteLists(theMol[istruct][0],1);
    theMol[istruct][0] = -1;
    NMols[istruct] = 1;

    theMol[istruct][0] = glGenLists(1);
    glNewList(theMol[istruct][0], GL_COMPILE);
    glDisable(GL_COLOR_MATERIAL);

    for (i=0; i< NAT->natoms; i++) {

         ia = NAT->nat[i];
         ic = elmptr->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 = elmptr->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< NAT->natoms; j++) {

            ja = NAT->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 = (elmptr->vdwr[ia-1] + elmptr->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();

    updfog(0);

    dispsf();
}

void oglines()
{
    double dmaxsq, dijsq, colv[3];
    float tmp1[3],tmp2[3], tmp3[3];
    int i,j,k,l,m, ia, ic, ja, ido, doclr, dsurf ;


    if (!addfile) posz = 0.0;

    doclr = 0;
    if (xyzp->iatclr != NULL && !*atcol) doclr = 1;

    if (NMols[istruct] >= MXMOL - 1) return;
    if (*xyzp->iatoms == 0) return;

    if (theLines[istruct] > 0) glDeleteLists(theLines[istruct],1);
    theLines[istruct] = -1;
    theLines[istruct] = glGenLists(1);

    if (theFLines[istruct] > 0) glDeleteLists(theFLines[istruct],1);
    theFLines[istruct] = -1;
    theFLines[istruct] = glGenLists(1);

    if (thePoints[istruct] > 0) glDeleteLists(thePoints[istruct],1);
    thePoints[istruct] = -1;
    thePoints[istruct] = glGenLists(1);

/*
theLines is intended as lines in combination with solid atoms
the lines would be used to display a mesh surface
*/

    glNewList(theLines[istruct], GL_COMPILE);
    glDisable(GL_LIGHTING);
    glLineWidth(2.0);
    glEnable(GL_LINE_SMOOTH);
    glEnable(GL_COLOR_MATERIAL);
    glBegin(GL_LINES);

    for (i=0; i<*xyzp->iatoms; i++) {

	if (xyzp->iaton[i] >= 1  && 
	   !(xyzp->iresid[i] <= 0 && xyzp->iresid[i] >= -3 && xyzp->ianz[i] == 100)) {

	 dsurf = 0;
	 if (i >= *natorg && *natorg != 0) dsurf = 1;

	 if (dsurf) {

            ia = xyzp->ianz[i];
	    if (doclr || *doesp) {
               ic = xyzp->iatclr[i]-1;
	    } else {
               ic = elmptr->icol[ia-1]-1;
            }
            for (l=0; l<3; l++) 
               tmp1[l] = (float) xyzp->coo[i*3+l];


           for (k=0; k<xyzp->iconn[i*(MXCON+1)]; k++) {

	    
            m = xyzp->iconn[i*(MXCON+1)+k+1];
            j = ABS(m) - 1;
            ja = xyzp->ianz[j];

            for (l=0; l<3; l++) 
	       tmp2[l] = (float) xyzp->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 ; 
	       if (m < 0) {
		   glEnd();
		   glLineStipple(4,0xAAAA);
		   glEnable(GL_LINE_STIPPLE);
		   glBegin(GL_LINES);
	       }
	       glColor4d(colv[0],colv[1],colv[2],tr_val);
	       glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
	       glVertex3d(tmp3[0],tmp3[1],tmp3[2]);
	       if (m < 0) {
		   glEnd();
		   glDisable(GL_LINE_STIPPLE);
		   glBegin(GL_LINES);
	       }

	    }

	   }
	 }
	}
    }

    glEnd();

    for (i=0; i<*xyzp->iatoms; i++) {

	if (xyzp->iaton[i] >= 1  && 
	   !(xyzp->iresid[i] <= 0 && xyzp->iresid[i] >= -3 && xyzp->ianz[i] == 100) && xyzp->iconn[i*(MXCON+1)] == 0 && ! *fancy) {

            ia = xyzp->ianz[i];
	    if (doclr || *doesp) {
               ic = xyzp->iatclr[i]-1;
	    } else {
               ic = elmptr->icol[ia-1]-1;
            }

	    colv[0] = ((GLdouble) colorr[ic+1]) / 65535.0 ; 
	    colv[1] = ((GLdouble) colorg[ic+1]) / 65535.0 ; 
	    colv[2] = ((GLdouble) colorb[ic+1]) / 65535.0 ; 

            for (l=0; l<3; l++) {
               tmp1[l] = (float) xyzp->coo[i*3+l];
	    }
            glBegin(GL_LINES);
	    glColor4d(colv[0],colv[1],colv[2],tr_val);
	    for (j=0; j<6; j++) {
		glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
           	for (l=0; l<3; l++) {
		   tmp3[l] = (float)(tmp1[l] + CV[j][l]);
		}
		glVertex3d(tmp3[0],tmp3[1],tmp3[2]);
	    }
            glEnd();
	}
    }

    glDisable(GL_COLOR_MATERIAL);
    glEnable(GL_LIGHTING);
    glEndList();

/*
theFLines is intended as lines replacing the solid atoms (non residues) in full opengl
*/

    glNewList(theFLines[istruct], GL_COMPILE);
    glDisable(GL_LIGHTING);
    glEnable(GL_COLOR_MATERIAL);
    glLineWidth(2.0);
    glEnable(GL_LINE_SMOOTH);
    glBegin(GL_LINES);

    for (i=0; i<*xyzp->iatoms; i++) {

	if (xyzp->iaton[i] >= 1  && 
	   !(xyzp->iresid[i] <= 0 && xyzp->iresid[i] >= -3 && xyzp->ianz[i] == 100)) {

	 dsurf = 0;
	 if (i >= *natorg && *natorg != 0) dsurf = 1;

	 if (!dsurf && xyzp->iresid[i] < 0) {
            ia = xyzp->ianz[i];
	    if (doclr || *doesp) {
               ic = xyzp->iatclr[i]-1;
	    } else {
               ic = elmptr->icol[ia-1]-1;
            }
            for (l=0; l<3; l++) 
               tmp1[l] = (float) xyzp->coo[i*3+l];


           for (k=0; k<xyzp->iconn[i*(MXCON+1)]; k++) {

	    
            m = xyzp->iconn[i*(MXCON+1)+k+1];
            j = ABS(m) - 1;
            ja = xyzp->ianz[j];

            for (l=0; l<3; l++) 
	       tmp2[l] = (float) xyzp->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 ; 
	       if (m < 0) {
		   glEnd();
		   glLineStipple(4,0xAAAA);
		   glEnable(GL_LINE_STIPPLE);
		   glBegin(GL_LINES);
	       }
	       glColor4d(colv[0],colv[1],colv[2],tr_val);
	       glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
	       glVertex3d(tmp3[0],tmp3[1],tmp3[2]);
	       if (m < 0) {
		   glEnd();
		   glDisable(GL_LINE_STIPPLE);
		   glBegin(GL_LINES);
	       }

	    }

	   }
	 }
	}
    }


    glEnd();
    glDisable(GL_COLOR_MATERIAL);
    glEnable(GL_LIGHTING);
    glEndList();

    glNewList(thePoints[istruct], GL_COMPILE);
    glDisable(GL_LIGHTING);
    glPointSize(2.5);
    glEnable(GL_COLOR_MATERIAL);
    glBegin(GL_POINTS);

    for (i=0; i<*xyzp->iatoms; i++) {

        for (l=0; l<3; l++) 
            tmp1[l] = (float) xyzp->coo[i*3+l];
	dijsq = tmp1[0]*tmp1[0] + tmp1[1]*tmp1[1] + tmp1[2]*tmp1[2];
	if (dijsq > posz) posz = dijsq;

	if (xyzp->iaton[i] >= 1  && 
	   !(xyzp->iresid[i] <= 0 && xyzp->iresid[i] >= -3 && 
	     xyzp->ianz[i] == 100)) {

           m = xyzp->iconn[i*(MXCON+1)];

	   if (!m || (m == 1 && xyzp->iconn[i*(MXCON+1)+1] < 0)) {

               ia = xyzp->ianz[i];
	       if (doclr || *doesp) {
                  ic = xyzp->iatclr[i]-1;
	       } else {
                  ic = elmptr->icol[ia-1]-1;
               }

	       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]);

	   }
	}
    }


    glEnd();
    glDisable(GL_COLOR_MATERIAL);
    glEnable(GL_LIGHTING);
    glEndList();

    if (!addfile) updfog(0);
}

void ogbox()
{
    double tmp1[3],tmp2[3], tmp3[3];
    double o[3] = { 0.0,0.0,0.0 };
    double x[3] = { 1.0,0.0,0.0 };
    double y[3] = { 0.0,1.0,0.0 };
    double z[3] = { 0.0,0.0,1.0 };
    double xy[3] = { 1.0,1.0,0.0 };
    double xz[3] = { 1.0,0.0,1.0 };
    double yz[3] = { 0.0,1.0,1.0 };
    double xyz[3] = { 1.0,1.0,1.0 };

    if (theBox[istruct] > 0) glDeleteLists(theBox[istruct],1);
    theBox[istruct] = -1;
    theBox[istruct] = glGenLists(1);


    glNewList(theBox[istruct], GL_COMPILE);
    glDisable(GL_LIGHTING);
    glLineWidth(1.0);
    glEnable(GL_LINE_SMOOTH);
    glEnable(GL_COLOR_MATERIAL);
    glBegin(GL_LINES);

    rotbck_(&o[0],&o[1],&o[2],tmp1);
    rotbck_(&x[0],&x[1],&x[2],tmp2);

/* only for orthogonal box
    glColor4d(comsrfptr->v1[0],comsrfptr->v1[1],comsrfptr->v1[2],tr_val);
*/
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[2]);

    rotbck_(&y[0],&y[1],&y[2],tmp2);
/* only for orthogonal box
    glColor4d(comsrfptr->v2[0],comsrfptr->v2[1],comsrfptr->v2[2],tr_val);
*/
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[2]);

    rotbck_(&z[0],&z[1],&z[2],tmp2);
/* only for orthogonal box
    glColor4d(comsrfptr->v3[0],comsrfptr->v3[1],comsrfptr->v3[2],tr_val);
*/
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[2]);

    rotbck_(&x[0],&x[1],&x[2],tmp1);
    rotbck_(&xy[0],&xy[1],&xy[2],tmp2);
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[2]);

    rotbck_(&y[0],&y[1],&y[2],tmp1);
    rotbck_(&xy[0],&xy[1],&xy[2],tmp2);
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[2]);

    rotbck_(&x[0],&x[1],&x[2],tmp1);
    rotbck_(&xz[0],&xz[1],&xz[2],tmp2);
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[2]);

    rotbck_(&z[0],&z[1],&z[2],tmp1);
    rotbck_(&xz[0],&xz[1],&xz[2],tmp2);
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[2]);

    rotbck_(&z[0],&z[1],&z[2],tmp1);
    rotbck_(&yz[0],&yz[1],&yz[2],tmp2);
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[2]);

    rotbck_(&y[0],&y[1],&y[2],tmp1);
    rotbck_(&yz[0],&yz[1],&yz[2],tmp2);
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[2]);

    rotbck_(&xyz[0],&xyz[1],&xyz[2],tmp1);
    rotbck_(&xy[0],&xy[1],&xy[2],tmp2);
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[2]);

    rotbck_(&xyz[0],&xyz[1],&xyz[2],tmp1);
    rotbck_(&xz[0],&xz[1],&xz[2],tmp2);
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[2]);

    rotbck_(&xyz[0],&xyz[1],&xyz[2],tmp1);
    rotbck_(&yz[0],&yz[1],&yz[2],tmp2);
    glColor4d(1.0,1.0,1.0,tr_val);
    glVertex3d(tmp1[0],tmp1[1],tmp1[2]);
    glVertex3d(tmp2[0],tmp2[1],tmp2[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[istruct] > 0) glDeleteLists(theForces[istruct],1);
    theForces[istruct] = -1;
    theForces[istruct] = glGenLists(1);
    glNewList(theForces[istruct], GL_COMPILE);

    ic = 0;

    for (i=0; i<*xyzp->iatoms; i++) {

	if (xyzp->iaton[i] >= 1  && 
	   !(xyzp->iresid[i] <= 0 && xyzp->iresid[i] >= -3 && xyzp->ianz[i] == 100)) {



           for (k=0; k<3; k++) 
             tmp1[k] = (float) xyzp->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[istruct],1);

    theDipole[istruct] = -1;
    theDipole[istruct] = glGenLists(1);

    glNewList(theDipole[istruct], GL_COMPILE);

    ic = 2;

#if defined(VMS) || defined(UNDERSC)
    cntvec(
#else

#ifdef CRAY
    CNTVEC(
#else
    cntvec_(
#endif
#endif
	tmp2,xyzp->coo,xyzp->ianz,xyzp->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,iopt,ityp,iorb,cntval,mapped,name)
#else
#ifdef CRAY
void OGBEGG(isurf,iopt,ityp,iorb,cntval,mapped,name)
#else
void ogbegg_(isurf,iopt,ityp,iorb,cntval,mapped,name)
#endif
#endif
int *isurf;
int *mapped;
int *iopt;
int *ityp;
int *iorb;
double* cntval;
char *name;
{
      int itrns,isf,i,n,len,two;
      double cval;
      char *endquote;
      char *srftyp[] = { "orbital", "normal density", "laplacian",
			 "mapped surface",
			 "elec. pot.","diff. density",
			 "unknown"};

      glXMakeCurrent(display, win, cx);
      glPopMatrix();
      glPushMatrix();

      itrns = 0;
      if (*isurf < 0) {
	  itrns = 1;
      }
      TRANS = itrns;
      isf = abs(*isurf); isf--;

      cval = *cntval;

      NSurf[istruct]++;

      two = 1;

      if (*iopt) {
	switch(*ityp) {
	case 0:
	  sndstr[istruct][NSurf[istruct]-1] = (char *) malloc(31);
	  sprintf(sndstr[istruct][NSurf[istruct]-1], 
			"Orbital %3d isocontour %7.4f",*iorb,cval);
	  break;
	default:
	  len = strlen(srftyp[*ityp]) + 20;
	  sndstr[istruct][NSurf[istruct]-1] = (char *) malloc(len);
	  sprintf(sndstr[istruct][NSurf[istruct]-1], 
			"%s isocontour %7.4f",srftyp[*ityp],cval);
	  break;
	}
        if (*ityp == 1 || *ityp == 3) two = 0;
      } else {
	  endquote = strchr(name,'\"');
	  if (endquote != NULL) endquote[0] = '\0';
	  sndstr[istruct][NSurf[istruct]-1] = (char *) malloc(strlen(name)+1);
	  strcpy(sndstr[istruct][NSurf[istruct]-1], name);
      }

      allocvert(MXVERT4,1);

      if (theSurf[istruct][NSurf[istruct]-1] > 0) 
	glDeleteLists(theSurf[istruct][NSurf[istruct]-1],1);
      theSurf[istruct][NSurf[istruct]-1] = glGenLists(1);

      if (denmode) {
	  n = NSurf[istruct] - 2;
	  if (NSurf[istruct] > 1 && (two && isf) ) n--;

	  for (i=0; i<=n; i++) SSon[istruct][i] = 0;
      }

      if (isf > 1) isf = 1;

      SSon[istruct][NSurf[istruct]-1] = 1;
      clp[istruct][NSurf[istruct]-1] = 0;
      trns[istruct][NSurf[istruct]-1] = itrns;

      if (!STRCup && denmode) inistrc();
      RedrawSTRC();

      for (i=0; i<3; i++) {
	diffuseColor[istruct][NSurf[istruct]-1][i] = cursrfcol[isf][i];
	specularColor[NSurf[istruct]-1][i] = specColor[i];
      }

      glNewList(theSurf[istruct][NSurf[istruct]-1], GL_COMPILE);

      SStyp[istruct][NSurf[istruct]-1] = 0;
      Schain[istruct][NSurf[istruct]-1] = -1;
      if (*mapped) {
        glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE);
	glEnable(GL_COLOR_MATERIAL);
	SStyp[istruct][NSurf[istruct]-1] = 1;
      }

      glBegin(GL_TRIANGLES);
}

#if defined(VMS) || defined(UNDERSC)
void ogendd(ichain)
#else
#ifdef CRAY
void OGENDD(ichain)
#else
void ogendd_(ichain)
#endif
#endif
int *ichain;
{
      glEnd();
      glDisable(GL_COLOR_MATERIAL);
      glEndList();
      if (*ichain != -1) Schain[istruct][NSurf[istruct]-1] = *ichain;
}

allocvert(siz,first)
int siz;
int first;
{
   VRTSTRU *spnt;
   VRTSTRU tmp;
   int i;

   spnt = srfvert[istruct][NSurf[istruct]-1];

   if (first) {
	nvert[istruct][NSurf[istruct]-1] = 0;
	nvrtmx[istruct][NSurf[istruct]-1] = 0;
   }

   srfvert[istruct][NSurf[istruct]-1] = 
	(VRTSTRU *) malloc((sizeof tmp)*siz);


   if (srfvert[istruct][NSurf[istruct]-1] == NULL) {
	srfvert[istruct][NSurf[istruct]-1] = spnt;
	dovrt = 0;
	fprintf(stderr,"failed to allocate memory to store vertices \n");
   } else {
	if (spnt != NULL) {
	    if (!first) {
		for (i=0; i<nvert[istruct][NSurf[istruct]-1]-1; i++) 
		    srfvert[istruct][NSurf[istruct]-1][i] = spnt[i];
	    }
	    free(spnt);
	}
	nvrtmx[istruct][NSurf[istruct]-1] = siz;
   }
}

putvrt(v1,v2,v3,type)
double *v1;
double *v2;
double *v3;
int type;
{
      int isrf,siz;

      if (!dovrt) return;

      isrf = NSurf[istruct]-1;

      nvert[istruct][isrf]++;

      if (nvert[istruct][isrf] > nvrtmx[istruct][isrf]) {
	  switch (nvrtmx[istruct][isrf]) {
	  case 0:
		siz = MXVERT;
		break;
	  case MXVERT:
		siz = MXVERT2;
		break;
	  case MXVERT2:
		siz = MXVERT3;
		break;
	  case MXVERT3:
		siz = MXVERT4;
		break;
	  case MXVERT4:
		siz = MXVERT5;
		break;
	  case MXVERT5:
		siz = MXVERT6;
		break;
	  case MXVERT6:
		siz = MXVERT7;
		break;
	  case MXVERT7:
		siz = MXVERT8;
		break;
	  case MXVERT8:
		siz = MXVERT9;
		break;
	  case MXVERT9:
		siz = MXVERT10;
		break;
	  case MXVERT10:
		siz = MXVERT11;
		break;
	  case MXVERT11:
		siz = MXVERT12;
		break;
	  default:
		siz = 0;
	  }
	  if (siz) allocvert(siz,0);
	  else dovrt = 0;
		
      }
      if (dovrt) {
	srfvert[istruct][isrf][nvert[istruct][isrf]-1].vert[0] = (float) *v1;
	srfvert[istruct][isrf][nvert[istruct][isrf]-1].vert[1] = (float) *v2;
	srfvert[istruct][isrf][nvert[istruct][isrf]-1].vert[2] = (float) *v3;
	srfvert[istruct][isrf][nvert[istruct][isrf]-1].type = type;
      }
}

#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
{


      putvrt(v1,v2,v3,0);

      glColor4d(*v1,*v2,*v3,tr_val);
}


void ogelev(name)
char *name;
{
      int i;
      char *endquote;

      glPopMatrix();
      glPushMatrix();

      NSurf[istruct]++;
      endquote = strchr(name,'\"');
      if (endquote != NULL) endquote[0] = '\0';
      sndstr[istruct][NSurf[istruct]-1] = (char *) malloc(strlen(name)+1);
      strcpy(sndstr[istruct][NSurf[istruct]-1],name);
      allocvert(MXVERT,1);

      theSurf[istruct][NSurf[istruct]-1] = glGenLists(1); 
      glNewList(theSurf[istruct][NSurf[istruct]-1], GL_COMPILE);

      for (i=0; i<4; i++)
	diffuseColor[istruct][NSurf[istruct]-1][i] = materialColor[ecol][i];
      SStyp[istruct][NSurf[istruct]-1] = 2;
      Schain[istruct][NSurf[istruct]-1] = -1;

      glBegin(GL_QUADS);
}

#if defined(VMS) || defined(UNDERSC)
void ogribb(iscnd)
#else
#ifdef CRAY
void OGRIBB(iscnd)
#else
void ogribb_(iscnd)
#endif
#endif
int *iscnd;
{
      int i;

      if (NSurf[istruct] >= MAXSURF) return;

      NSurf[istruct]++;
      if (sndstr[istruct][NSurf[istruct]-1] != NULL) 
	free(sndstr[istruct][NSurf[istruct]-1]);

      switch (*iscnd) {
	case 0:
		RIBindex[istruct].nhelx++;
		sndstr[istruct][NSurf[istruct]-1] =
			(char *) malloc(10);
		sprintf(sndstr[istruct][NSurf[istruct]-1], 
			"Helix %d",RIBindex[istruct].nhelx);
		break;
	case 1:
		RIBindex[istruct].nbeta++;
		sndstr[istruct][NSurf[istruct]-1] =
			(char *) malloc(9);
		sprintf(sndstr[istruct][NSurf[istruct]-1], 
			"Beta %d",RIBindex[istruct].nbeta);
		break;
	case 2:
		RIBindex[istruct].nrna++;
		sndstr[istruct][NSurf[istruct]-1] =
			(char *) malloc(8);
		sprintf(sndstr[istruct][NSurf[istruct]-1], 
			"RNA %d",RIBindex[istruct].nrna);
		break;
	case 3:
		RIBindex[istruct].ncoil++;
		sndstr[istruct][NSurf[istruct]-1] =
			(char *) malloc(9);
		sprintf(sndstr[istruct][NSurf[istruct]-1], 
			"Coil %d",RIBindex[istruct].ncoil);
		break;
      }

      if (theSurf[istruct][NSurf[istruct]-1] > 0) 
	glDeleteLists(theSurf[istruct][NSurf[istruct]-1],1);
      theSurf[istruct][NSurf[istruct]-1] = glGenLists(1); 
      allocvert(MXVERT,1);
      glEnable(GL_COLOR_MATERIAL);
      glNewList(theSurf[istruct][NSurf[istruct]-1], GL_COMPILE);
      SStyp[istruct][NSurf[istruct]-1] = 2;
      Schain[istruct][NSurf[istruct]-1] = -1;

      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+b");
  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 = Ysize;
  if (Xsize < Ysize) 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_ribb()
{
  int i,j;
  int SSont[MAXSURF],NStmp;

  for (i=0; i < 4; i++) {
	for (j=RIBindex[istruct].start[i]; 
		j <= RIBindex[istruct].end[i]; j++) {
		if (j >= 0) SSon[istruct][j] = -1;
	}
  }

  NStmp = 0;
  for (i=0; i < NSurf[istruct]; i++) 
	if (SSon[istruct][i] != -1) {
		SSont[NStmp] = SSon[istruct][i];
		NStmp++;
	}

  for (i=0; i < NSurf[istruct]; i++) 
	SSon[istruct][i] = 0;

  for (i=0; i < 4; i++) {
	for (j=RIBindex[istruct].start[i]; 
		j <= RIBindex[istruct].end[i]; j++) {
		if (j >= 0) SSon[istruct][j] = 1;
	}
  }

  DeleteActiveSurfaces();

  for (i=0; i < NSurf[istruct]; i++) 
	SSon[istruct][i] = SSont[i];

  RIBindex[istruct].nhelx = 0;
  RIBindex[istruct].nbeta = 0;
  RIBindex[istruct].nrna = 0;
  RIBindex[istruct].ncoil = 0;

  SSdone[istruct] = -1;

}

void empty_model(sel,updis)
int sel;
int updis;
{
  int i;

  if (!has_opengl) return;

  if (theMol[sel][0] != -1)
	glDeleteLists(theMol[sel][0],1);
  theMol[sel][0] = (GLuint) -1;
  for (i=0; i<NSurf[sel]; i++) {
      if (theSurf[sel][i] != -1)
	glDeleteLists(theSurf[sel][i],1);
      theSurf[sel][i] = -1;
      if (sndstr[sel][i] != NULL) free(sndstr[sel][i]);
      sndstr[sel][i] = NULL;
      if (srfvert[sel][i] != NULL) free(srfvert[sel][i]);
      srfvert[sel][i] = NULL;
      nvert[sel][i] = 0;
      nvrtmx[sel][i] = 0;
      Schain[sel][i] = -1;
      clp[sel][i] = -1;
      trns[sel][i] = -1;
      if (!addfile) SSon[sel][i] = 0;
  }

  RIBindex[sel].nhelx = 0;
  RIBindex[sel].nbeta = 0;
  RIBindex[sel].nrna = 0;
  RIBindex[sel].ncoil = 0;

  for (i=0; i<4; i++) {
	RIBindex[sel].start[i] = -1;
	RIBindex[sel].end[i] = -1;
  }

  if (*ipdbon) {
      for (i=0; i<calfptr->ncalf; i++) {
	if (theRes[sel][i] != -1)
	   glDeleteLists(theRes[sel][i],1);
	theRes[sel][i] = -1;
	if (theBck[sel][i] != -1)
	   glDeleteLists(theBck[sel][i],1);
	theBck[sel][i] = -1;
      }
  }
  if (theLines[sel] != -1)
      glDeleteLists(theLines[sel],1);
  theLines[sel] = -1;

  if (theFLines[sel] != -1)
      glDeleteLists(theFLines[sel],1);
  theFLines[sel] = -1;

  if (thePoints[sel] != -1)
      glDeleteLists(thePoints[sel],1);
  thePoints[sel] = -1;

  if (theForces[sel] != -1)
      glDeleteLists(theForces[sel],1);
  theForces[sel] = -1;

  if (theMon[sel] != -1)
      glDeleteLists(theMon[sel],1);
  theMon[sel] = -1;

  if (theSel[sel] != -1)
      glDeleteLists(theSel[sel],1);
  theSel[sel] = -1;

  if (theBox[sel] != -1)
      glDeleteLists(theBox[sel],1);
  theBox[sel] = -1;

  SSdone[sel] = -1;
  NSurf[sel] = 0;

  if (updis) {
     if ((((*fancy || *fullgl) && !denmode) || (*ifdogl && denmode)) 
	&& has_opengl) dispsf();
  }
  RedrawSTRC();
}

void setcl(i)
int i;
{
  if (glIsEnabled(GL_COLOR_MATERIAL)) {
	glColor4f(diffuseColor[istruct][i][0], diffuseColor[istruct][i][1],
	diffuseColor[istruct][i][2],(GLfloat) tr_val);
  }

  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, &diffuseColor[istruct][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.0);
}

#if defined(VMS) || defined(UNDERSC)
void setcll()
#else
#ifdef CRAY
void SETCLL()
#else
void setcll_()
#endif
#endif
{
  int isrf,i;
  float grcol[4] = {0.6,0.6,0.6,0.6};
  float spcol[4] = {0.8,0.8,0.8,1.0};

  glEnd();
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, grcol);
  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, spcol);
  glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100);
  isrf = NSurf[istruct]-1;
  nvert[istruct][isrf]++;
  srfvert[istruct][isrf][nvert[istruct][isrf]-1].type = 2;
  glBegin(GL_QUADS);
  glColor4d(grcol[0], grcol[1], grcol[2], grcol[3]);
}

void pldst()
{
  int i,i1,i2,ixt,iyt,i8;
  char s[9];

  i8 = 8;
  XSetForeground(display, gc, colors[15]);

  for (i=0; i<monptr->ndm; i++) {
	i1 = monptr->idmon[i][0] - 1;
	i2 = monptr->idmon[i][1] - 1;
	ixt = (xyzp->ixp[i1] + xyzp->ixp[i2])/2;
	iyt = (xyzp->iyp[i1] + xyzp->iyp[i2])/2;
	sprintf(s,"%8.3f",monptr->rdm[i]);

#if defined(VMS) || defined(UNDERSC)
	drwstr(&ixt,&iyt,s,&i8);
#else
#ifdef CRAY
	DRWSTR(&ixt,&iyt,s,&i8);
#else
	drwstr_(&ixt,&iyt,s,&i8);
#endif
#endif
  }
}

void prtMat(Mat)
GLdouble *Mat;
{
     fprintf(stderr,"modelV:\n");
     fprintf(stderr,"%f %f %f %f\n",Mat[0],Mat[1],Mat[2],Mat[3]);
     fprintf(stderr,"%f %f %f %f\n",Mat[4],Mat[5],Mat[6],Mat[7]);
     fprintf(stderr,"%f %f %f %f\n",Mat[8],Mat[9],Mat[10],Mat[11]);
     fprintf(stderr,"%f %f %f %f\n",Mat[12],Mat[13],Mat[14],Mat[15]);
}

static GLdouble InvModelMat[16];

InvRotMat()
{
  GLdouble modelMatrix[16];

  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();
  glRotatef(45.0,0.0,1.0,0.0);
  glGetDoublev(GL_MODELVIEW_MATRIX,InvModelMat);
  //invmat(modelMatrix,InvModelMat);
  glPopMatrix();
}

ModelMatInv()
{
  GLdouble modelMatrix[16];

  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
  invmat(modelMatrix,InvModelMat);
  glPopMatrix();
}

SetGLSLVar()
{

  if (has_shader) {
#ifdef GL_COLOR_ATTACHMENT0_EXT
	if (DoShadow) {
	    glUseProgramObjectARB(program[11]);
	} else {
#endif
	    glUseProgramObjectARB(program[0]);
	    if (*shade) {
		glUniform1iARB(dofog, 1);
	    } else {
		glUniform1iARB(dofog, 0);
	    }
	    if (DoBlur) {
		glUniform1iARB(doblur, 1);
	    } else glUniform1iARB(doblur, 0);
	    if (DoSSAO) {
		glUniform1iARB(dossao, 1);
	    } else glUniform1iARB(dossao, 0);
	    if (DoShad) {
		glUniform1iARB(DoShadLoc, 1);
	    } else glUniform1iARB(DoShadLoc, 0);
	    if (TRANS) {
		glUniform1iARB(dotrns, 1);
	    } else glUniform1iARB(dotrns, 0);
#ifdef GL_COLOR_ATTACHMENT0_EXT
	}
#endif
  }
}

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],tmp2[3],xt,yt,zt,srad;

  float tmp[3];
  float axes_light[] = {0.0, 0.0, -4.0, 1};

  glXMakeCurrent(display, win, cx);

  glDisable(GL_CULL_FACE);
  glClearDepth(1);
  if (DoShadow) {
	glClearColor(0.0, 0.0, 0.0, 1.0);
  } else {
	glClearColor(gradcol[0][0],gradcol[0][1],gradcol[0][2],1.0);
  }

#ifdef GL_COLOR_ATTACHMENT0_EXT
  if ((DoBlur || DoSSAO) && has_fbo) {
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[0]);
	glDrawBuffers(2,buffers);
  }

/*
	glEnable(GL_CULL_FACE);
	glCullFace(GL_FRONT);
*/

  if (DoShadow && has_fbo) {
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[0]);
	glDrawBuffers(1,buffers);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_FRONT);
  }
#endif

#ifdef GL_ARB_shader_objects
  if (has_shader) glUseProgramObjectARB(0);
#endif
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

#ifdef GL_COLOR_ATTACHMENT0_EXT
  if (!DoShadow) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#endif

  for (i=0; i < 3; i++) {
     RR[i][1] = rotptr->rx[i];
     RR[i][0] = -rotptr->ry[i];
     RR[i][2] = rotptr->rz[i];
  }

  if (!DoShadow) if (BGmode) bckgrad();

#ifdef GL_COLOR_ATTACHMENT0_EXT
  if (DoSSAO && has_fbo) {
	   glDrawBuffer(GL_COLOR_ATTACHMENT2_EXT);
	   glClearColor(0.0, 0.0, 0.0, 1.0);
	   glClear(GL_COLOR_BUFFER_BIT);
	   glDrawBuffers(3,buffers);
  }
#endif

  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
*/
  }

SHADOW:

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  if (*persp) {
	glFrustum(-0.2*Aspect,0.2*Aspect,-0.2,0.2,0.3,600.0);
  } else {
	glOrtho(1.0*Aspect,-1.0*Aspect,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);
        glEnable(GL_NORMALIZE);
  } else {
	sc = -1.0 / scalptr->scal;
	glScalef(sc,sc,-1.0*sc);
	glTranslatef( 1.0*posptr->yv, -1.0*posptr->xv, 0.0);
        glEnable(GL_NORMALIZE);
  }

/*  glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION, &gradcol[1][0]);*/
  glLightfv(GL_LIGHT0, GL_POSITION, light0_position[istruct]);
  if (DoLights) {
     glPushMatrix();
     glTranslatef(light0_position[istruct][0],light0_position[istruct][1],
		  light0_position[istruct][2]);
     gluSphere(sphere, 1, 10, 10);
     glPopMatrix();
  }

  glLightfv(GL_LIGHT1, GL_POSITION, light1_position[istruct]);
  if (DoLights) {
     glPushMatrix();
     glTranslatef(light1_position[istruct][0],light1_position[istruct][1],
		  light1_position[istruct][2]);
     gluSphere(sphere, 1, 10, 10);
     glPopMatrix();
  }

  glLightfv(GL_LIGHT2, GL_POSITION, light2_position[istruct]);
  if (DoLights) {
     glPushMatrix();
     glTranslatef(light2_position[istruct][0],light2_position[istruct][1],
		  light2_position[istruct][2]);
     gluSphere(sphere, 1, 10, 10);
     glPopMatrix();
  }

/*  glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION, &AxesCol[0][0]);*/

#ifdef GL_COLOR_ATTACHMENT0_EXT
  if (DoShadow) glRotatef(25.0,0.0,1.0,0.0);
#endif

  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]);

#ifdef GL_COLOR_ATTACHMENT0_EXT
  if (DoShadow) {
     setTextureMatrix();
  } else if (DoShad) {
     glPushMatrix();
     glMatrixMode(GL_TEXTURE);
     glActiveTextureARB(GL_TEXTURE7);
     glLoadIdentity();
     glMultMatrixd(TexMat);
     glMatrixMode(GL_MODELVIEW);
     glPopMatrix();
  }
#endif

  glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
  glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
  glGetIntegerv(GL_VIEWPORT,viewport);
  if (viewport[2] != width || viewport[3] != height) {
	glViewport(0,0,width,height);
	viewport[2] = width; viewport[3] = height;
  }

  for (i=0; i<*xyzp->iatoms; i++) {
        tmp1[0] = (GLdouble) (xyzp->coo[i*3]);
        tmp1[1] = (GLdouble) (xyzp->coo[i*3+1]);
        tmp1[2] = (GLdouble) (xyzp->coo[i*3+2]);
        if (gluProject(tmp1[0],tmp1[1],tmp1[2],modelMatrix,projMatrix,viewport,&xt,&yt,&zt)) {
           xyzp->ixp[i] = (height - (int) yt);
           xyzp->iyp[i] = (int) xt;
           xyzp->rzp[i] = (double) zt;
	   if (*persp && zt > 1.0) xyzp->rzp[i] = -1.0;
	}
  }

  EnableFog();

  if (update_sel) {
     ogsel();
  } else {
     glCallList(theSel[istruct]);
  }

  if (has_shader) {
#ifdef GL_COLOR_ATTACHMENT0_EXT
	if (DoShadow) {
#ifdef GL_ARB_shader_objects
	    glUseProgramObjectARB(program[11]);
#endif
	} else {
#endif
#ifdef GL_ARB_shader_objects
	    glUseProgramObjectARB(program[0]);
	    if (*shade) {
		glUniform1iARB(dofog, 1);
	    } else {
		glUniform1iARB(dofog, 0);
	    }
	    if (DoBlur) {
		glUniform1iARB(doblur, 1);
	    } else glUniform1iARB(doblur, 0);
	    if (DoSSAO) {
		glUniform1iARB(dossao, 1);
	    } else glUniform1iARB(dossao, 0);
	    if (DoShad) {
		glUniform1iARB(DoShadLoc, 1);
	    } else glUniform1iARB(DoShadLoc, 0);
	    if (!*fancy) glUseProgramObjectARB(0);
#endif
#ifdef GL_COLOR_ATTACHMENT0_EXT
	}
#endif
  }

#ifdef GL_COLOR_ATTACHMENT0_EXT
#ifdef GL_ARB_shader_objects
  if (DoShad) glUniform1iARB(DoShadLoc, 0);
#endif
#endif

  if (*ipdbon && (*fancy || *fullgl)) {
	for (i=0; i<calfptr->ncalf; i++) {
          if (calfptr->reson[i]) {glCallList(theRes[istruct][i]);}
	  else {
	     int isa;

	     isa = calfptr->isal[i];
	     if (isa >= 0 && isa < MXHETA) {
		if (!calfptr->ihet[calfptr->isal[i]]) 
		   glCallList(theBck[istruct][i]);
	     }
	  }
	}
  }

  glDisable(GL_COLOR_MATERIAL);


  if (*fancy || denmode) {
	glCallList(theMol[istruct][0]);
	if (*irtcel && *ialtyp) glCallList(theMol[istruct][1]);
  } 

  if (*fancy || *fullgl) {
	if (monptr->ndm) glCallList(theMon[istruct]);
  }

  glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

  if (has_shader) glUseProgramObjectARB(0);

  glCallList(theLines[istruct]);
  if (DoNorms) glCallList(theNorm);

  if (!*fancy && !denmode && *fullgl) {
	glCallList(theFLines[istruct]);
	glCallList(thePoints[istruct]);
  }

  SetGLSLVar();

  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  if (*forces_yes_no) glCallList(theForces[istruct]);
  if (qdpptr->idipon) glCallList(theDipole[istruct]);

  if (DoLines) {
	glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	glLineWidth(1.0);
  } else {
	if (!DoShadow) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  }

  for (i=0; i<NSurf[istruct]; i++) {

    if (SSon[istruct][i]) {
      if (clp[istruct][i]) {
	 glEnable(GL_CLIP_PLANE0);
	 glEnable(GL_CLIP_PLANE1);
	 glEnable(GL_CLIP_PLANE2);
	 glEnable(GL_CLIP_PLANE3);
	 glEnable(GL_CLIP_PLANE4);
	 glEnable(GL_CLIP_PLANE5);
	 theEQ1[3] = EQ[0];
	 theEQ2[3] = -EQ[0] + slab[0];
	 theEQ3[3] = EQ[1];
	 theEQ4[3] = -EQ[1] + slab[1];
	 theEQ5[3] = EQ[2];
	 theEQ6[3] = -EQ[2] + slab[2];
	 glClipPlane(GL_CLIP_PLANE0,theEQ1);
	 glClipPlane(GL_CLIP_PLANE1,theEQ2);
	 glClipPlane(GL_CLIP_PLANE2,theEQ3);
	 glClipPlane(GL_CLIP_PLANE3,theEQ4);
	 glClipPlane(GL_CLIP_PLANE4,theEQ5);
	 glClipPlane(GL_CLIP_PLANE5,theEQ6);
      }

      if (TRANS || trns[istruct][i]) {
         glEnable(GL_BLEND);
         glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	 diffuseColor[istruct][i][3] = tr_val;
#ifdef GL_ARB_shader_objects
	 glUniform1iARB(dotrns, 1);
#endif
      } else {
	 diffuseColor[istruct][i][3] = 1.0;
         glDisable(GL_BLEND);
#ifdef GL_ARB_shader_objects
	 glUniform1iARB(dotrns, 0);
#endif
      }

      setcl(i);
      
#ifdef GL_ARB_shader_objects
      if (has_shader) {
	if (SStyp[istruct][i] == 1) {
		glUniform1iARB(colmat, 1);
	} else {
		glUniform1iARB(colmat, 0);
	}
      }
#endif
      
      glCallList(theSurf[istruct][i]);

#ifdef GL_ARB_shader_objects
      if (has_shader && SStyp[istruct][i] == 1) 
		glUniform1iARB(colmat, 0);
#endif

      if (clp[istruct][i]) {
	 glDisable(GL_CLIP_PLANE0);
	 glDisable(GL_CLIP_PLANE1);
	 glDisable(GL_CLIP_PLANE2);
	 glDisable(GL_CLIP_PLANE3);
	 glDisable(GL_CLIP_PLANE4);
	 glDisable(GL_CLIP_PLANE5);
      }
    }

  }

  if (theBox[istruct] != -1) glCallList(theBox[istruct]);

#ifdef GL_COLOR_ATTACHMENT0_EXT
  if (has_fbo) {

     if (DoShadow) {
	if (DoMIPMAP) glGenerateMipmapEXT(GL_TEXTURE_2D);
	blurShadowMap();

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,0);
	glClearColor(gradcol[0][0],gradcol[0][1],gradcol[0][2],1.0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glDisable(GL_CULL_FACE);
	glUseProgramObjectARB(0);
	if (BGmode) bckgrad();
	//glEnable(GL_NORMALIZE);
	glShadeModel(GL_SMOOTH);
	glActiveTexture(GL_TEXTURE7);
	glBindTexture(GL_TEXTURE_2D,fbo.texid[0]);
	//glLightfv(GL_LIGHT2, GL_POSITION, lightPos);
	glEnable(GL_CULL_FACE);
	//glEnable(GL_POLYGON_OFFSET_FILL);
	//glPolygonOffset(-1.2, 4);
	glCullFace(GL_BACK);
	DoShadow = 0;
	goto SHADOW;
     }


     if (DoBlur) DepthBlur();

     if (DoSSAO) SSAO();
  }

  if (DoShad) DoShadow = 1;
#endif

#ifdef GL_ARB_shader_objects
  if (has_shader) glUseProgramObjectARB(0);
#endif

  glFlush();
  glXWaitGL();
  if (StarNetOld) glXSwapBuffers(display, win);
  if (!gmoving && !mmoving && !smoving) {
    glXWaitGL();
    if (StarNetOld) XSetForeground(display, gc, colors[*ifntcl]);
    if (!StarNetOld) initPrintStrings(0);
    if (*dolabs && !denmode) {
     for (i=0; i<*xyzp->iatoms; i++) {
        j = i + 1;
        if (xyzp->iaton[i] >= 1 && xyzp->rzp[i] > 0.0 )  {
#if defined(VMS) || defined(UNDERSC)
   	   pllab(&xyzp->ixp[i],&xyzp->iyp[i],&xyzp->ianz[i],&j,
#else
#ifdef CRAY
   	   PLLAB(&xyzp->ixp[i],&xyzp->iyp[i],&xyzp->ianz[i],&j,
#else
   	   pllab_(&xyzp->ixp[i],&xyzp->iyp[i],&xyzp->ianz[i],&j,
#endif
#endif
		&xyzp->qat[i],&zero,&qdpptr->iqon,&xyzp->iresid[i],&zero);
        }
     }
#if defined(VMS) || defined(UNDERSC)
     plalab(&qdpptr->iqon);
#else
#ifdef CRAY
     PLALAB(&qdpptr->iqon);
#else
     plalab_(&qdpptr->iqon);
#endif
#endif
    }

    pldst();

    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(&xyzp->ixp[j],&xyzp->iyp[j],CellStr[i],&TWO);
#else
#ifdef CRAY
	   DRWSTR(&xyzp->ixp[j],&xyzp->iyp[j],CellStr[i],&TWO);
#else
	   drwstr_(&xyzp->ixp[j],&xyzp->iyp[j],CellStr[i],&TWO);
#endif
#endif
	}
    }
    if (!StarNetOld) endPrintStrings();
  }

  if (has_fbo) {
	if ( !(DoBlur || DoSSAO)) glXSwapBuffers(display, win);
  } else {
	if (!StarNetOld) glXSwapBuffers(display, win);
  }

  if (!gmoving && !mmoving && !smoving) {
    if (*doesp && !denmode) {
	glFlush();
	glXWaitGL();
	PlotColIndex();
	XFlush(display);
	glXWaitX();
    }
  }

  glXMakeCurrent(display,win,cx);

  rsold = RESUND;

  if (DEBUG) fprintf( stderr, "dispsf \n");

}


void Reshape(update)
int update;
{
  int i,dx,dy;
  GLint loc;

  gmoving = 0;
  Aspect = (float) width / (float) height;
  glViewport(0, 0, width, height);

#ifdef GL_ARB_shader_objects
  if (has_shader && has_fbo) {
	glUseProgramObjectARB(program[1]);
	loc   = glGetUniformLocationARB(program[1], "Width");
	glUniform1iARB(loc, width);
	loc   = glGetUniformLocationARB(program[1], "Height");
	glUniform1iARB(loc, height);

#ifdef GL_COLOR_ATTACHMENT0_EXT
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[0]);

	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, fbo.depth[0]);
	glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24,
		width, height);

	glBindTexture(GL_TEXTURE_2D, fbo.texid[0]);
	glTexImage2D(GL_TEXTURE_2D, 0, fbo_type, 
		    width, height, 0, GL_RGBA, GL_FLOAT, NULL);

	glBindTexture(GL_TEXTURE_2D, fbo.texid1[0]);
	glTexImage2D(GL_TEXTURE_2D, 0, fbo_type, 
		    width, height, 0, GL_RGBA, GL_FLOAT, NULL);

	glBindTexture(GL_TEXTURE_2D, fbo.texid2[0]);
	glTexImage2D(GL_TEXTURE_2D, 0, fbo_type, 
		    width, height, 0, GL_RGBA, GL_FLOAT, NULL);

	glBindTexture(GL_TEXTURE_2D, fbo.texid3[0]);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24,  
		width, height, 0,
		GL_DEPTH_COMPONENT, GL_FLOAT, NULL);

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[1]);

	glBindTexture(GL_TEXTURE_2D, fbo.texid[1]);
	glTexImage2D(GL_TEXTURE_2D, 0, fbo_type, 
		    width, height, 0, GL_RGBA, GL_FLOAT, NULL);

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

	for (i = 2; i < NUM_FBOS; i++) {
	   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[i]);

	  glBindTexture(GL_TEXTURE_2D, fbo.texid[i]);
	  glTexImage2D(GL_TEXTURE_2D, 0, fbo_type, 
		    width, height, 
			0, GL_RGBA, GL_FLOAT, NULL);
	}
#endif

	glUseProgramObjectARB(program[3]);
	loc   = glGetUniformLocationARB(program[3], "Width");
	glUniform1iARB(loc, width*2);

	glUseProgramObjectARB(program[4]);
	loc   = glGetUniformLocationARB(program[4], "Height");
	glUniform1iARB(loc, height*2);

	glUseProgramObjectARB(program[7]);
	loc   = glGetUniformLocationARB(program[7], "Width");
	glUniform1iARB(loc, width*2);
	loc   = glGetUniformLocationARB(program[7], "Height");
	glUniform1iARB(loc, height*2);

	glUseProgramObjectARB(program[8]);
	loc   = glGetUniformLocationARB(program[8], "width");
	glUniform1iARB(loc, width);
	loc   = glGetUniformLocationARB(program[8], "height");
	glUniform1iARB(loc, height);

#ifdef GL_COLOR_ATTACHMENT0_EXT
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo.frame[0]);
	glUseProgramObjectARB(program[0]);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
#endif

  }
#endif
  if (update) {
	dispsf();
	update_model = 0;
  } else {
	update_model = 1;
  }
}


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);
*/
  glViewport(0, 0, width, height);
}


void Key( unsigned char key)
{
   int i;

   if (gmoving) return;

   update_model = 0;

   switch (key) {
   case 'x':
      light0_position[istruct][0] += 0.5;
      break;
   case 'X':
      light0_position[istruct][0] -= 0.5;
      break;
   case 'y':
      light0_position[istruct][1] += 0.5;
      break;
   case 'Y':
      light0_position[istruct][1] -= 0.5;
      break;
   case 'z':
      light0_position[istruct][2] += 0.5;
      break;
   case 'Z':
      light0_position[istruct][2] -= 0.5;
      break;
   case 'i':
      light1_position[istruct][0] += 0.5;
      break;
   case 'I':
      light1_position[istruct][0] -= 0.5;
      break;
   case 'j':
      light1_position[istruct][1] += 0.5;
      break;
   case 'J':
      light1_position[istruct][1] -= 0.5;
      break;
   case 'k':
      light1_position[istruct][2] += 0.5;
      break;
   case 'K':
      light1_position[istruct][2] -= 0.5;
      break;
   case '<':
   case ',':
      light2_position[istruct][2] -= 0.5;
      break;
   case '>':
   case '.':
      light2_position[istruct][2] += 0.5;
      break;
   case 'l':
      if (DoLines) {
	DoLines = 0;
      } else {
	DoLines = 1;
      }
      break;
   case 'Q':
   case 'q':
      if (DoNorms) {
	DoNorms = 0;
      } else {
	DoNorms = 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 'b':
      if (DoBlur) {
	DoBlur = 0;
      } else {
	DoBlur = 1;
      }
      break;
   case 'S':
      if (DoSSAO) {
	DoSSAO = 0;
      } else {
	DoSSAO = 1;
      }
      break;
   case 'N':
   case 'n':
      CMols[istruct]++;
      if (CMols[istruct] >= NMols[istruct]) CMols[istruct] = 0;
      break;
   case 'w':
      if (hires) hires = 0;
      else hires = 1;
      update_model = 1;
      break;
   case 'G':
      EQ[0] += 10.0;
      break;
   case 'g':
      EQ[0] -= 10.0;
      break;
   case 'D':
      break;
   case 'd':
      break;
   case 'R':
   case 'r':
      if (has_shader) {
	if (DoShad) DoShad = 0;
	else {
	  DoShad = 1;
	  DoShadow = 1;
	  DoSSAO = 0;
	  DoBlur = 0;
	  for (i=0; i<4; i++) lightPos[i] = light2_position[istruct][i];
	  lightPos[0] = 20.0;
	  lightPos[2] = 0.0;
	}
      }
      break;
   }
   SetGLSLVar();
   update_struct();
}

EnableFog()
{
      int i,fstart, fend;

      if (!*shade || denmode) {
          glDisable(GL_FOG);	  
      } else {
         glEnable(GL_FOG);
         glFogi (GL_FOG_MODE, GL_LINEAR);
         glFogfv (GL_FOG_COLOR, fogColor);
	 for (i=0; i<4; i++) {
	    fog.fogcolor[i] = fogColor[i];
	 }
         glHint (GL_FOG_HINT, GL_DONT_CARE);
	 fstart = posptr->zv;
	 fend = fstart + scalptr->scali*2.0*(*uscl);
	 fog.fstart = fstart;
	 fog.fend = fend;
	 fog.fscale = 1.0 / (fend - fstart);;
	 glFogf (GL_FOG_START, fstart);
	 glFogf (GL_FOG_END, fend);
       }
}

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 ;
*/
   fogColor[0] = ((GLfloat) colorr[0]) / 65535.0 ;
   fogColor[1] = ((GLfloat) colorg[0]) / 65535.0 ;
   fogColor[2] = ((GLfloat) colorb[0]) / 65535.0 ;
}

void initOpengl()
{

    int i,bgmenu,animmenu,trmenu,capmenu;

/*
4th value of a position determines if we are using a positional light (1.0)
                                                or a directional light (0.0)
*/
    static float lmodel_ambient[] = {0.2, 0.2, 0.2, 0.2};
    static float light0_ambient[] = {0.1, 0.1, 0.1, 1.0};
    static float light0_diffuse[] = {1.0, 1.0, 1.0, 1.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[0]);

    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[0]);

    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[0]);

    glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 0.0);
    glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, 1.0);
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);

    glEnable(GL_LIGHTING);

    glEnable(GL_NORMALIZE);
    glShadeModel(GL_SMOOTH);
    glHint(GL_POLYGON_SMOOTH_HINT,GL_NICEST);
    glLineWidth(1.0);

    OBGcolor = *ibgclo;
    BGmode = *ibgmod;
    setobg();

    PERSP = perspon;

#if defined(DARWIN) || defined(__CYGWIN__)
    *fullgl = 1;
    *ifogl = 1;
#endif

    glClearIndex(0.0);
    glClearDepth(1);

    glPushMatrix();
    glLoadIdentity();

    cyl = gluNewQuadric();
    sphere = gluNewQuadric();
    disk = gluNewQuadric();

    ogaxes();

    Reshapi();

    InvRotMat();
}


void ogind()
{
 int i;


    oglines();
    if (*forces_yes_no) ogforces();

    if (denmode) {
	ogmlxyz();
	update_model = 0;
    }
    else {
	if (*irtcel && *ialtyp) {
	   if (NMols[istruct] != 1) ogmoll(0);
	   ogmoll(1);
	}
	else {
	   ogmoll(0);
	}
    }

    if (*ipdbon && SSdone[istruct] == 0) {
       empty_ribb();
#if defined(VMS) || defined(UNDERSC)
       ribgl(calfptr->ianf,&calfptr->nchain,&calfptr->ncalf,xyzp->iatoms);
#else
#ifdef CRAY
       RIBGL(calfptr->ianf,&calfptr->nchain,&calfptr->ncalf,xyzp->iatoms);
#else
       ribgl_(calfptr->ianf,&calfptr->nchain,&calfptr->ncalf,xyzp->iatoms);
#endif
#endif
       SSdone[istruct] = 1;

       for (i=0; i<4; i++) 
	if (!monoscr && calfptr->ihet[i] == 1) sndon(i,0,0);

    }

    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 < *xyzp->iatoms; j++) {
	if (xyzp->iresid[j] == het) {
	   if (!fnd) {
	      istart = j; 
	      fnd = 1;
	   }
	   iend = j;
	}
    }

    if (iend == -1 ) return;
    ndel = iend - istart + 1;
    
    for (j=istart; j < *xyzp->iatoms - ndel; j++) {
	xyzp->iatclr[j] = xyzp->iatclr[j+ndel];
	tmpres = xyzp->iresid[j+ndel];
	if (tmpres < het) tmpres++;
	xyzp->iresid[j] = tmpres;
	xyzp->iaton[j] = xyzp->iaton[j+ndel];
	xyzp->ianz[j] = xyzp->ianz[j+ndel];
	xyzp->ipdbt[j] = xyzp->ipdbt[j+ndel];
	xyzp->ityp[j] = xyzp->ityp[j+ndel];
	if (qdpptr->ihasq) xyzp->qat[j] = xyzp->qat[j+ndel];
	for (k=0; k < 3; k++) {
	   xyzp->coo[j*3+k] = xyzp->coo[(j+ndel)*3+k];
	}
	kcon = 0;
	for (k=0; k < xyzp->iconn[(j+ndel)*(MXCON+1)]; k++) {
	   noab = xyzp->iconn[(j+ndel)*(MXCON+1)+k+1];
	   ab = ABS(noab) - 1;
	   if (ab > istart + ndel) {
		if (noab > 0) {
		   xyzp->iconn[j*(MXCON+1)+kcon+1] = noab - ndel;
		} else {
		   xyzp->iconn[j*(MXCON+1)+kcon+1] = noab + ndel;
		}
		kcon++;
	   } else if (ab < istart) {
		xyzp->iconn[j*(MXCON+1)+kcon+1] = noab;
		kcon++;
	   }
	}
	xyzp->iconn[j*(MXCON+1)] = kcon;
    }

    for (j=0; j < istart; j++) {
	kcon = 0;
	for (k=0; k < xyzp->iconn[j*(MXCON+1)]; k++) {
	   noab = xyzp->iconn[j*(MXCON+1)+k+1];
	   ab = ABS(noab) - 1;
	   if (ab > istart + ndel) {
		if (noab > 0) {
		   xyzp->iconn[j*(MXCON+1)+kcon+1] = noab - ndel;
		} else {
		   xyzp->iconn[j*(MXCON+1)+kcon+1] = noab + ndel;
		}
		kcon++;
	   } else if (ab < istart) {
		xyzp->iconn[j*(MXCON+1)+kcon+1] = noab;
		kcon++;
	   }
	}
	xyzp->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--;

    *xyzp->iatoms = *xyzp->iatoms - ndel;
    if (*natorg > 0) *natorg = *natorg - ndel;
    *zmptrp->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
{

      putvrt(v1,v2,v3,0);

      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
{
      putvrt(v1,v2,v3,1);

      glVertex3d(*v1,*v2,*v3);
}

chkrib(iop)
int iop;
{
   int i,j;

   for (i=RIBindex[istruct].end[iop]; 
	i >= RIBindex[istruct].start[iop]; i--) {
	if (nvert[istruct][i] <= 0) {
		free(sndstr[istruct][i]);
		free(srfvert[istruct][i]);
		glDeleteLists(theSurf[istruct][i],1);
		for (j=i; j < RIBindex[istruct].end[iop]; j++) {
		   sndstr[istruct][j] = sndstr[istruct][j+1];
		   srfvert[istruct][j] = srfvert[istruct][j+1];
		   nvrtmx[istruct][j] = nvrtmx[istruct][j+1];
		   nvert[istruct][j] = nvert[istruct][j+1];
		   theSurf[istruct][j] = theSurf[istruct][j+1];
		   Schain[istruct][j] = Schain[istruct][j+1];
		}
		j = RIBindex[istruct].end[iop];
		sndstr[istruct][j] = NULL;
		srfvert[istruct][j] = NULL;
		nvrtmx[istruct][j] = 0;
		nvert[istruct][j] = 0;
		theSurf[istruct][j] = -1;
		NSurf[istruct]--;
		if (NSurf[istruct] < 0) NSurf[istruct] = 0;
		RIBindex[istruct].end[iop]--;
		switch (iop) {
		case 0: 
			RIBindex[istruct].nhelx--;
			break;
		case 1: 
			RIBindex[istruct].nbeta--;
			break;
		case 2: 
			RIBindex[istruct].nrna--;
			break;
		case 3: 
			RIBindex[istruct].ncoil--;
			break;
		default:
			break;
		}
	}
   }

}

chncol(ich,col,iupd)
int ich;
int col;
int iupd;
{
   int i;

   for (i=0; i < NSurf[istruct]; i++) 
	if (Schain[istruct][i] == ich+1) SetSurfColor(i,col+1);
   if (iupd) dispsf();
}

#if defined(VMS) || defined(UNDERSC)
void ribpnt(int *iopt, int *isnd)
#else
#ifdef CRAY
void RIBPNT(int *iopt, int *isnd)
#else
void ribpnt_(int *iopt, int *isnd)
#endif
#endif
{
    if (*iopt) {
	RIBindex[istruct].start[*isnd] =  NSurf[istruct];
    } else {
	RIBindex[istruct].end[*isnd] = NSurf[istruct]-1;
	chkrib(*isnd);
    }
}

#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[istruct][NSurf[istruct]-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[istruct]++;
      if (theSurf[istruct][NSurf[istruct]-1] > 0) 
	glDeleteLists(theSurf[istruct][NSurf[istruct]-1],1);
      theSurf[istruct][NSurf[istruct]-1] = -1;
      theSurf[istruct][NSurf[istruct]-1] = glGenLists(1);

      if (NSurf[istruct] > 1) {

	  for (i=0; i<= NSurf[istruct] - 2; i++) 
		SSon[istruct][i] = 0;
      }

      SSon[istruct][NSurf[istruct]-1] = 1;
      clp[istruct][NSurf[istruct]-1] = 0;
      trns[istruct][NSurf[istruct]-1] = 0;

      if (*ipsi) {
	  sndstr[istruct][NSurf[istruct]-1] = (char *) malloc(21);
	  sprintf(sndstr[istruct][NSurf[istruct]-1], 
			"Orbital %3d in plane",*ipsi);
      } else {
	  sndstr[istruct][NSurf[istruct]-1] = (char *) malloc(17);
	  sprintf(sndstr[istruct][NSurf[istruct]-1], 
			"Density in plane");
      }
      allocvert(MXVERT,1);

      if (!STRCup) inistrc();
      RedrawSTRC();

      diffuseColor[istruct][NSurf[istruct]-1][0] = 0.0;
      diffuseColor[istruct][NSurf[istruct]-1][1] = 1.0;
      diffuseColor[istruct][NSurf[istruct]-1][2] = 0.0;
      diffuseColor[istruct][NSurf[istruct]-1][3] = 0.8;

      for (i=0; i<3; i++) {
	specularColor[NSurf[istruct]-1][i] = specColor[i];
      }

      glNewList(theSurf[istruct][NSurf[istruct]-1], GL_COMPILE);
      SStyp[istruct][NSurf[istruct]-1] = 2;
      Schain[istruct][NSurf[istruct]-1] = -1; 

      glBegin(GL_QUADS);

      npts1 = hlpsrf->nps1;
      npts2 = hlpsrf->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;


WrtAtm(inp,iatom,SrfArr,lwrit,nc)
FILE *inp;
int iatom;
int SrfArr;
int *lwrit;
int *nc;
{
   int ir;
   float r;

   ir = xyzp->iresid[iatom];

   switch (xyzp->ianz[iatom]) {
	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;
   }

   if (!SrfArr || (SrfArr && ( (ir > 0 && calfptr->iams[ir-1]) ||
			       (ir < 0 && calfptr->ihets[ABS(ir)]))) ) {
	lwrit[*nc] = iatom; *nc = *nc + 1;
	fprintf(inp,"%d %f %8.3f %8.3f %8.3f\n", iatom,r,
		xyzp->coo[iatom*3  ]*toangs,
		xyzp->coo[iatom*3+1]*toangs,
		xyzp->coo[iatom*3+2]*toangs);
   }
}

molsrf(SurfCol,SrfArr,MapSrf)
int SurfCol;
int SrfArr;
int MapSrf;
{
   char cmdfil[MAXCMD];
   char cmdtmp[MAXCMD] = "surf ";
   char tmps[MAXCMD] = "";
   char *tmpf, *p, *q;
   int i,j, iat, ir, irt, ires, nc, co, kk, io, fft,pid;
   double g[3], c[3], col[3], pot;
   FILE *out, *inp;

#if defined(VMS) || defined(UNDERSC)
   curs(&ONE);
#else
#ifdef CRAY
   CURS(&ONE);
#else
   curs_(&ONE);
#endif
#endif

   if (MapSrf && *fftyp != 3 ) {
	fft = *fftyp;
	for (i=0; i<*xyzp->iatoms; i++) 
	   xyzp->lwrit[i] = (int) xyzp->ityp[i];
	
	*fftyp = 3;
#if defined(VMS) || defined(UNDERSC)
	dotyp(&ZERO);
#else
#ifdef CRAY
	DOTYP(&ZERO);
#else
	dotyp_(&ZERO);
#endif
#endif
	for (i=0; i<*xyzp->iatoms; i++) 
	   xyzp->ityp[i] = (short int) xyzp->lwrit[i];
	*fftyp = fft;
   }

   inp = NULL;

#ifdef __CYGWIN__
   if (getusr(tmps)) tmpf = tmps;
#else
   tmpf = tmpnam(NULL);
#endif


   inp = fopen(tmpf,"w");
   if (inp == NULL) return;

   nc = 0;

   if (*ipdbon && !calfptr->ncalf == 0) {
	for (ires = 1; ires < calfptr->ncalf+1; ires++ ) {
#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++) {
		if (ipdb[i] > 0) {
		   WrtAtm(inp,ipdb[i]-1,SrfArr,xyzp->lwrit,&nc);
		}
	   }

	   for (i=0; i<MXHSYM*3; i++) {
		if (ihpdb[i] > 0) {
		   WrtAtm(inp,ihpdb[i]-1,SrfArr,xyzp->lwrit,&nc);
		}
	   }

	}

	for (j=4; j<NHetAtm; j++) {
	   if (calfptr->ihets[j]) {
        	for (i=0; i<*xyzp->iatoms; i++) {
		   if (xyzp->iresid[i] == -j) 
			WrtAtm(inp,i,0,xyzp->lwrit,&nc);
		}
	   }
	}

   } else {
	for (i=0; i<*xyzp->iatoms; i++) 
		WrtAtm(inp,i,0,xyzp->lwrit,&nc);
   }

   fclose(inp);

#ifdef __CYGWIN__
   sprintf(cmdfil,"%ssurf.exe",exepath[0]);
#else
   sprintf(cmdfil,"%ssurf",exepath[0]);
#endif


   if (! (access(cmdfil,F_OK) == 0 && !isdir(cmdfil))) {
#ifdef __CYGWIN__
	sprintf(cmdfil,"%ssurf/surf.exe",exepath[0]);
#else
	sprintf(cmdfil,"%ssurf/surf",exepath[0]);
#endif
	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;
   }

#ifdef __CYGWIN__
   if (p = strstr(cmdfil,".exe")) p[0] = '\0';


    pid = vfork();
    switch(pid) {
    case -1:
          fprintf(stderr,"Couldnt Fork\n");
          break;
    case 0:       /*child */
	  execlp(cmdfil,"surf","-W","1",tmpf,NULL);
	  _exit(0);
          break;
    default:      /*parent*/
	  wait(&pid);
          break;
    }
#else
   strcpy(cmdtmp,cmdfil);
   strcat(cmdtmp," -W 1 ");
   strcat(cmdtmp,tmpf);

   system(cmdtmp);
#endif

   strcpy(cmdtmp,tmpf);
   strcat(cmdtmp,".tri");

   if ((out = fopen(cmdtmp, "r")) == NULL) {
      fprintf(stderr,"Can not open triangle file !: %s\n",cmdtmp);
#if defined(VMS) || defined(UNDERSC)
      curs(&ZERO);
#else
#ifdef CRAY
      CURS(&ZERO);
#else
      curs_(&ZERO);
#endif
#endif
      return;
   }

   SetSurfColor(NSurf[istruct],SurfCol);

   theSurf[istruct][NSurf[istruct]] = glGenLists(1);
   SSon[istruct][NSurf[istruct]] = 1;
   clp[istruct][NSurf[istruct]] = 0;
   trns[istruct][NSurf[istruct]] = 0;

   glNewList(theSurf[istruct][NSurf[istruct]], GL_COMPILE);
   NSurf[istruct]++;

   sndstr[istruct][NSurf[istruct]-1] = (char *) malloc(21);
   sprintf(sndstr[istruct][NSurf[istruct]-1], "Solvent Acc. Surface");
   allocvert(MXVERT,1);


   SStyp[istruct][NSurf[istruct]-1] = 0;
   Schain[istruct][NSurf[istruct]-1] = -1;

/* if color per triangle */

   if (MapSrf) {
        glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE);
        glEnable(GL_COLOR_MATERIAL);
	SStyp[istruct][NSurf[istruct]-1] = 1;
   }

   glBegin(GL_TRIANGLES);

   irt = -1;
   if (out != NULL) {
	   while (fscanf(out,"%d",&iat) != EOF) {

	     if (MapSrf) {
		iat = xyzp->lwrit[iat];
		ir = xyzp->iresid[iat];
		if (ir != irt || irt == -1) {
			nc = 0;

			if (ir < -3) {

			   for (i=0; i < *xyzp->iatoms; i++) {
			       if (xyzp->iresid[i] == ir) {
				   xyzp->icont[nc] = i+1;
				   nc++;
			       }
			   }

			} else {
#if defined(VMS) || defined(UNDERSC)
			   getpdb(&ir,ipdb,ihpdb);
#else
#ifdef CRAY
			   GETPDB(&ir,ipdb,ihpdb);
#else
			   getpdb_(&ir,ipdb,ihpdb);
#endif
#endif
		
			   for (i=0; i<MXSYM; i++)
				if (ipdb[i] > 0) {
				   xyzp->icont[nc] = ipdb[i];
				   nc++;
				}

			   for (i=0; i<MXHSYM*3; i++) 
				if (ihpdb[i] > 0) {
				   xyzp->icont[nc] = ihpdb[i];
				   nc++;
				}
			   if (ir > 1) {
			    /* n,h backbone previous residue */
			    xyzp->icont[nc] = calfptr->icalf[ir-2][1];
			    nc++;
			    xyzp->icont[nc] = calfptr->icalf[ir-2][3];
			    nc++;
			   }
			   if (ir < calfptr->ncalf) {
			    /* c=o backbone next residue */
			    co = calfptr->icalf[ir][2];
			    xyzp->icont[nc] = co;
			    nc++;
			    for (i=0; i < xyzp->iconn[(co-1)*(MXCON+1)]; i++) {
				kk = xyzp->iconn[(co-1)*(MXCON+1)+i+1];
				if (xyzp->ianz[kk-1] == 8) io = kk;
			    }	
			    xyzp->icont[nc] = io;
			    nc++;
			   }
			}
			*xyzp->ncont = nc;

		   irt = ir;
		}
	     }

	     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;

		if (MapSrf) {
#if defined(VMS) || defined(UNDERSC)
		   clmond(c,&pot,&ONE,
			xyzp->coo,xyzp->qat,xyzp->icont,xyzp->ncont);
		   parcol(&pot,col);
		   ogcoll(&col[0],&col[1],&col[2]);
#else
#ifdef CRAY
		   CLMOND(c,&pot,&ONE,
			xyzp->coo,xyzp->qat,xyzp->icont,xyzp->ncont);
		   PARCOL(&pot,col);
		   OGCOLL(&col[0],&col[1],&col[2]);
#else
		   clmond_(c,&pot,&ONE,
			xyzp->coo,xyzp->qat,xyzp->icont,xyzp->ncont);
		   parcol_(&pot,col);
		   ogcoll_(&col[0],&col[1],&col[2]);
#endif
#endif
		}
#if defined(VMS) || defined(UNDERSC)
		ognrm(&g[0],&g[1],&g[2]);
		ogvrt(&c[0],&c[1],&c[2]);
#else
#ifdef CRAY
		OGNRM(&g[0],&g[1],&g[2]);
		OGVRT(&c[0],&c[1],&c[2]);
#else
		ognrm_(&g[0],&g[1],&g[2]);
		ogvrt_(&c[0],&c[1],&c[2]);
#endif
#endif
	     }

	   }
	   glEnd();
	   if (MapSrf) {
		glDisable(GL_COLOR_MATERIAL);
	   }
	   glEndList();
	   fclose(out);
	   unlink(tmpf);
	   unlink(cmdtmp);
	   dispsf();
	   UpdateSTRC();
   }


#if defined(VMS) || defined(UNDERSC)
   curs(&ZERO);
#else
#ifdef CRAY
   CURS(&ZERO);
#else
   curs_(&ZERO);
#endif
#endif
}

#else

/* =====================================
 * backup functions for no openGL 
 * =====================================
*/

chncol(ich,col,iupd)
int ich;
int col;
int iupd;
{
  int i;
      i = 0;
}

void ogforces()
{
  int i;
      i = 0;
}

wrtall()
{
  int i;
      i = 0;
}

DeleteActiveSurfaces()
{
  int i;
      i = 0;
}

#if defined(VMS) || defined(UNDERSC)
bldlst()
#else
#ifdef CRAY
BLDLST()
#else
bldlst_()
#endif
#endif
{
  int i;

  i = 0;
}

molsrf(SurfCol,SrfArr)
int SurfCol;
int SrfArr;
{
  int dummy;

  dummy = 0;
}

#if defined(VMS) || defined(UNDERSC)
void ogbegg(isurf,iopt,ityp,iorb,cntval,mapped,name)
#else
#ifdef CRAY
void OGBEGG(isurf,iopt,ityp,iorb,cntval,mapped,name)
#else
void ogbegg_(isurf,iopt,ityp,iorb,cntval,mapped,name)
#endif
#endif
int *isurf;
int *iorb;
int *ityp;
int *iopt;
double *cntval;
int *mapped;
char *name;
{
  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(iscnd)
#else
#ifdef CRAY
void OGRIBB(iscnd)
#else
void ogribb_(iscnd)
#endif
#endif
int *iscnd;
{
      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(ichain)
#else
#ifdef CRAY
void OGENDD(ichain)
#else
void ogendd_(ichain)
#endif
#endif
int *ichain;
{
      int i;

      i = 0;
}

#if defined(VMS) || defined(UNDERSC)
void ribpnt(int *iopt, int *isnd)
#else
#ifdef CRAY
void RIBPNT(int *iopt, int *isnd)
#else
void ribpnt_(int *iopt, int *isnd)
#endif
#endif
{
      int i;

      i = 0;
}

#if defined(VMS) || defined(UNDERSC)
void setcll()
#else
#ifdef CRAY
void SETCLL()
#else
void setcll_()
#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 ResetRes()
{
  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 update)
{
  int i;

  i = 0;
}

void empty_model(sel,updis)
int sel;
int updis;
{
  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,j;

   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++)
	if (ipdb[i] > 0) xyzpdb[i][j] = xyzp->coo[(ipdb[i]-1)*3+j];

      for (i=0; i<MXHSYM*3; i++) for (j=0; j<3; j++)
	if (ihpdb[i] > 0) xyzhpdb[i][j] = xyzp->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,xyzp->coo[(tmpipdb[i]-1)*3]*toangs,xyzp->coo[(tmpipdb[i]-1)*3+1]*toangs,xyzp->coo[(tmpipdb[i]-1)*3+2]*toangs);
           for (j=0; j<3; j++) { 
	      rtmp = (xyzpdb[i][j] - xyzp->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] - xyzp->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(xyzp->coo,xyzp->ianz,xyzp->iatoms);
   doclr();
   if (iopt) conpdb();
#ifdef DOGL
   ogres(ires,ONE,1);
   update_model = 0;
#endif
   qupd();
   curs(&ZERO);
#else
#ifdef CRAY
   DUMZM(xyzp->coo,xyzp->ianz,xyzp->iatoms);
   doclr();
   if (iopt) CONPDB();
#ifdef DOGL
   ogres(ires,ONE,1);
   update_model = 0;
#endif
   QUPD();
   CURS(&ZERO);
#else
   dumzm_(xyzp->coo,xyzp->ianz,xyzp->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) 
	zmptrp->bet[aaptr[ires-1].chi1] = aminozmt[aminotyp].rots[i].rots[0];
      if (aminozmt[aminotyp].chis[1] != -1) 
	zmptrp->bet[aaptr[ires-1].chi2] = aminozmt[aminotyp].rots[i].rots[1];
      if (aminozmt[aminotyp].chis[2] != -1) 
	zmptrp->bet[aaptr[ires-1].chi3] = aminozmt[aminotyp].rots[i].rots[2];
      if (aminozmt[aminotyp].chis[3] != -1) 
	zmptrp->bet[aaptr[ires-1].chi4] = aminozmt[aminotyp].rots[i].rots[3];
      SetQZME();

      FindZRange(ires);

#if defined(VMS) || defined(UNDERSC)
      dumzm(xyzp->coo,xyzp->ianz,xyzp->iatoms);
#else
#ifdef CRAY
      DUMZM(xyzp->coo,xyzp->ianz,xyzp->iatoms);
#else
      dumzm_(xyzp->coo,xyzp->ianz,xyzp->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) 
	zmptrp->bet[aaptr[ires-1].chi1] = 
		aminozmt[aminotyp].rots[OptRot].rots[0];
   if (aminozmt[aminotyp].chis[1] != -1) 
	zmptrp->bet[aaptr[ires-1].chi2] = 
		aminozmt[aminotyp].rots[OptRot].rots[1];
   if (aminozmt[aminotyp].chis[2] != -1) 
	zmptrp->bet[aaptr[ires-1].chi3] = 
		aminozmt[aminotyp].rots[OptRot].rots[2];
   if (aminozmt[aminotyp].chis[3] != -1) 
	zmptrp->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) 
   	   zmptrp->bet[aaptr[irs-1].chi1] = 
			aminozmt[aminotyp].rots[irot].rots[0];
        if (aminozmt[aminotyp].chis[1] != -1) 
	   zmptrp->bet[aaptr[irs-1].chi2] = 
			aminozmt[aminotyp].rots[irot].rots[1];
        if (aminozmt[aminotyp].chis[2] != -1) 
	   zmptrp->bet[aaptr[irs-1].chi3] = 
			aminozmt[aminotyp].rots[irot].rots[2];
        if (aminozmt[aminotyp].chis[3] != -1) 
	   zmptrp->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(xyzp->coo,xyzp->ianz,xyzp->iatoms);
         dfirot(&l1);
#else
#ifdef CRAY
         DUMZM(xyzp->coo,xyzp->ianz,xyzp->iatoms);
         DFIROT(&l1);
#else
         dumzm_(xyzp->coo,xyzp->ianz,xyzp->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(xyzp->coo,xyzp->ianz,xyzp->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(xyzp->coo,xyzp->ianz,xyzp->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_(xyzp->coo,xyzp->ianz,xyzp->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]);

   }

   zmpart->imx = resrot[sol].mx;
   zmpart->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(xyzp->coo,xyzp->ianz,xyzp->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(xyzp->coo,xyzp->ianz,xyzp->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_(xyzp->coo,xyzp->ianz,xyzp->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);

   zmpart->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(xyzp->coo,xyzp->ianz,xyzp->iatoms);
         dfirot(&l1);
#else
#ifdef CRAY
         DUMZM(xyzp->coo,xyzp->ianz,xyzp->iatoms);
         DFIROT(&l1);
#else
         dumzm_(xyzp->coo,xyzp->ianz,xyzp->iatoms);
         dfirot_(&l1);
#endif
#endif

      


      }
   }

   mx = -1; mn = *zmptrp->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 (zmpart->imx > mx) mx = zmpart->imx;
	if (zmpart->imn < mn) mn = zmpart->imn;
      }
   }
   zmpart->imx = mx; zmpart->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(xyzp->coo,xyzp->ianz,xyzp->iatoms);
		dfiflx(&etot);
#else
#ifdef CRAY
		DUMZM(xyzp->coo,xyzp->ianz,xyzp->iatoms);
		DFIFLX(&etot);
#else
		dumzm_(xyzp->coo,xyzp->ianz,xyzp->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 = zmpart->imx;
		   		resrot[n].mn = zmpart->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);
   zmpart->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 {

	geo1ptr->gcvav = 1;
	geo1ptr->ifmxav = 0;
	geo1ptr->ifrmav = 0;
	geo1ptr->idmxav = 0;
	geo1ptr->idrmav = 0;
	geo1ptr->ieav = 0;
	geo1ptr->ngeoms = 0;
	geo1ptr->nepnts = 0;
	geo1ptr->dmaxt = 0.0;
	geo1ptr->fmaxt = 0.0;
	geo1ptr->drmst = 0.0;
	geo1ptr->frmst = 0.0;
	iframe = 1;
	while(!gfrm(&iframe,step,0)) {
	   if (iframe == 1) istp1 = *step;
	   if (iframe == 2) istp2 = *step;
	   iframe++;
	}
	geo1ptr->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];

/* uses the xdr trajectory reading routines for the .trr file:
   xdr trajectory file */

   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++) xyzp->coo[(i+ioff)*3+j] = v[i][j];
	   for (j=0; j < 3; j++) xyzp->coo[(ioff+3)*3+j] = v[0][j] + v[1][j];
	   for (j=0; j < 3; j++) xyzp->coo[(ioff+4)*3+j] = v[1][j] + v[2][j];
	   for (j=0; j < 3; j++) xyzp->coo[(ioff+5)*3+j] = v[0][j] + v[2][j];
	   for (j=0; j < 3; j++) xyzp->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) xyzp->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;

   geo1ptr->ieav = 0;

MOREMEM:

   if (init_edr(filename) < 0) {
        *istat = -1;
   } else {

	geo1ptr->nepnts = 0;
	for (i=0;i<geo1ptr->mxpnt;i++) geop->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 <= geo1ptr->mxpnt) geop->epoints[nepnts] = ener;
	}
	if (nepntst > geo1ptr->mxpnt) {
	   
	   nepntst++;
#if defined(VMS) || defined(UNDERSC)
	   allgeo(&nepntst,&ZERO);
#else
#ifdef CRAY
	   ALLGEO(&nepntst,&ZERO);
#else
	   allgeo_(&nepntst,&ZERO);
#endif
#endif
	   rewind(stre.fptr);
	   goto MOREMEM;
	}
	geo1ptr->nepnts = nepnts+1;
	geo1ptr->ieav = 1;
	iold = 0;
	for (i=0;i<geo1ptr->nepnts;i++) {
	   if (geop->epoints[i] == eprepos) 
		geop->epoints[i] = geop->epoints[iold];
	   else iold = i;
	}
	(void) cledr();
#if defined(VMS) || defined(UNDERSC)
	gmmcnv(geop->formax,geop->forrms,geop->dismax,geop->disrms,
		geop->epoints,geop->isav);
#else
#ifdef CRAY
	GMMCNV(geop->formax,geop->forrms,geop->dismax,geop->disrms,
		geop->epoints,geop->isav);
#else
	gmmcnv_(geop->formax,geop->forrms,geop->dismax,geop->disrms,
		geop->epoints,geop->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 (animptr.on || *movie || tnkfrk) return;
   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 = ntnkb;
	sub = subTNK;
	winup = &TNKup;
   } else if (win == FLRwin) {
	arr = flrbut; nbut = NBUTSF;
	sub = subFLR;
	winup = &FLRup;
   } 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 if (win == STRwin) {
	arr = strbut; nbut = 5;
	sub = subSTR;
	winup = &STRup;
   } else if (win == STRCwin) {
	arr = strcbut; nbut = STRCBN;
	sub = subSTRC;
	winup = &STRCup;
   } else if (win == SRFwin) {
	arr = srfbut; nbut = 6;
	sub = subSRF;
	winup = &SRFup;
   } 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 = *zmptrp->nz;
		if (j == 4) n = *zmptrp->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;
}

#define STR1COL 0
#define STR2COL 11

int AlignStructs(str2)
int str2;
{

  int i,j,k,l,nlines,ires;
  int iat1,iat2,itot,nato1,nato2,nres1,nres2,nhet1,nhet2;
  COOSTRU *xyzp1;
  COOSTRU *xyzp2;
  CALFSTRU *calf1;
  CALFSTRU *calf2;

    xyzp1   = xyzp;
    xyzp2   = &COO[str2]->coo;
    calf1   = calfptr;
    calf2   = &COO[str2]->calf;

    iat1    = *xyzp->iatoms;
    iat2    = COO[str2]->iatoms;
    nato1   = *natorg;
    if (nato1 < iat1) nato1 = iat1;
    nato2   = COO[str2]->natorg;
    if (nato2 < iat2) nato2 = iat2;
    nres1   = calfptr->ncalf;
    nres2   = COO[str2]->calf.ncalf;
    nhet1   = NHetAtm-4;
    nhet2   = COO[str2]->NHetAtm-4;

    if (nres1 <= 0 || nres2 <= 0) {

/* small molecule alignment */

	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\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)) {
	   *iscst = iat1; *nscnd = iat2; *ialtyp = 3;
	   CombineStructs(str2,0);
	   doalign = 1; *irtcel = 2; *irtval = 2; *atcol = 0;
	   TogDown(&cbut[BATCOL]);
#if defined(VMS) || defined(UNDERSC)
	   aln2ml(ialtyp,&idum1);
#else
#ifdef CRAY
	   ALN2ML(ialtyp,&idum1);
#else
	   aln2ml_(ialtyp,&idum1);
#endif
#endif
	   return(0);
	}
	return(0);
    }

/* protein alignment */

#if defined(VMS) || defined(UNDERSC)
    curs(&ONE);
    supimp( xyzp1->coo,xyzp2->coo,&iat1,&iat2, 
    	calf1->iamino,calf2->iamino,calf1->icalf,calf2->icalf,
    	&calf1->ncalf,&calf2->ncalf,calf1->isal,calf2->isal);
    curs(&ZERO);
#else
#ifdef CRAY
    CURS(&ONE);
    SUPIMP( xyzp1->coo,xyzp2->coo,&iat1,&iat2, 
    	calf1->iamino,calf2->iamino,calf1->icalf,calf2->icalf,
    	&calf1->ncalf,&calf2->ncalf,calf1->isal,calf2->isal);
    CURS(&ZERO);
#else
    curs_(&ONE);
    supimp_( xyzp1->coo,xyzp2->coo,&iat1,&iat2, 
    	 calf1->iamino,calf2->iamino,calf1->icalf,calf2->icalf,
    	&calf1->ncalf,&calf2->ncalf,calf1->isal,calf2->isal);
    curs_(&ZERO);
#endif
#endif
#if defined(VMS) || defined(UNDERSC)
    cntvec(
#else

#ifdef CRAY
    CNTVEC(
#else
    cntvec_(
#endif
#endif
	COO[str2]->rot.t,xyzp2->coo,xyzp2->ianz,xyzp2->iatoms);
    return(1);

}

CombineStructs(str2,notaligned)
int str2;
int notaligned;
{

  int i,j,k,l,nlines,ires,pdb1,pdb2,nchstr1;
  int iat1,iat2,itot,nato1,nato2,nres1,nres2,nhet1,nhet2;
  double tmp1[3],tmp2[3],tmp3[3],rad1,rad2,vl;
  COOSTRU *xyzp1;
  COOSTRU *xyzp2;
  CALFSTRU *calf1;
  CALFSTRU *calf2;

    xyzp1   = xyzp;
    xyzp2   = &COO[str2]->coo;
    calf1   = calfptr;
    calf2   = &COO[str2]->calf;
    pdb1    =  *ipdbon;
    pdb2    =  COO[str2]->pdb;

    iat1    = *xyzp->iatoms;
    iat2    = COO[str2]->iatoms;


    nato1 = iat1;
    for (j=iat1-1; j >= 0; j--) {
 	if (xyzp1->ianz[j] != 100) {
		nato1 = j+1;
		break;
	}
    }

    nato2 = iat2;
    for (j=iat2-1; j >= 0; j--) {
 	if (xyzp2->ianz[j] != 100) {
		nato2 = j+1;
		break;
	}
    }

    if (pdb1) {
	nres1   = calfptr->ncalf;
	nhet1   = NHetAtm-4;
    } else {
	nres1   = 0;
	nhet1   = 1;
    }

    if (pdb2) {
	nres2   = COO[str2]->calf.ncalf;
	nhet2   = COO[str2]->NHetAtm-4;
    } else {
	nres2   = 0;
	nhet2   = 1;
    }

    itot = iat1 + iat2;
  
    if (itot > *xyzp->mxnat - 500) {
	itot = itot + 500;
#if defined(VMS) || defined(UNDERSC)
	allcoo(&itot,&ZERO);
#else
#ifdef CRAY
	ALLCOO(&itot,&ZERO);
#else
	allcoo_(&itot,&ZERO);
#endif
#endif
    }

    if (nres1 <= 0 && nres2 <= 0 && notaligned) {
#if defined(VMS) || defined(UNDERSC)
	cntvec(
#else

#ifdef CRAY
	CNTVEC(
#else
	cntvec_(
#endif
#endif
	tmp1,xyzp1->coo,xyzp1->ianz,xyzp1->iatoms);
	getrad(tmp1,xyzp1->coo,xyzp1->iatoms,&rad1);
#if defined(VMS) || defined(UNDERSC)
	cntvec(
#else

#ifdef CRAY
	CNTVEC(
#else
	cntvec_(
#endif
#endif
	tmp2,xyzp2->coo,xyzp2->ianz,xyzp2->iatoms);
	getrad(tmp2,xyzp2->coo,xyzp2->iatoms,&rad2);
	for (j=0; j<3; j++) tmp3[j] = tmp2[j] - tmp1[j];
	vl = dveclen(tmp3);
	if (vl > rad1 + 5.0) {
	   if (!DoCan(event.xbutton.x_root,event.xbutton.y_root,
	      "Molecules very far apart !.\n Move to visible range ?",1)) {
		for (j=0; j<3; j++) {
		    tmp3[j] = -tmp3[j]*(rad1+rad2)/vl - tmp3[j];
		}
		for (j=0; j< *xyzp2->iatoms ; j++) 
#if defined(VMS) || defined(UNDERSC)
		   trcoo(tmp3,&xyzp2->coo[j*3]);
#else

#ifdef CRAY
		   TRCOO(tmp3,&xyzp2->coo[j*3]);
#else
		   trcoo_(tmp3,&xyzp2->coo[j*3]);
#endif
#endif
#if defined(VMS) || defined(UNDERSC)
		cntvec(
#else

#ifdef CRAY
		CNTVEC(
#else
		cntvec_(
#endif
#endif
		   tmp2,xyzp2->coo,xyzp2->ianz,xyzp2->iatoms);
		for (j=0; j<3; j++) {
		    rotptr->t[j] = (tmp1[j] + tmp2[j])/2.0;
		}
	
	   }
	}
    }
/* 
    MOVE FAKE ATOMS for secundary structure visualisation xwindows 
    of the FIRST structure.
    They only should have connections amongst themselves 
*/

    nlines = nato2;

    for (j=0; j < iat1; j++) xyzp1->iatclr[j] = STR1COL + 1;

    for (j=iat1-1; j >= nato1; j--) {
	xyzp1->iatclr[j+nlines] = xyzp1->iatclr[j];
	xyzp1->iresid[j+nlines] = xyzp1->iresid[j];
	xyzp1->iaton[j+nlines] = xyzp1->iaton[j];
	xyzp1->ianz[j+nlines] = xyzp1->ianz[j];
	for (k=0; k < 3; k++) 
	   xyzp1->coo[(j+nlines)*3+k] = xyzp1->coo[j*3+k];
	for (k=0; k < xyzp1->iconn[j*(MXCON+1)]; k++) {
	   xyzp1->iconn[(j+nlines)*(MXCON+1)+k+1] = 
		xyzp1->iconn[j*(MXCON+1)+k+1] + nlines;
	}
	xyzp1->iconn[(j+nlines)*(MXCON+1)] = xyzp1->iconn[j*(MXCON+1)];
    }

/* 
   COPY FAKE ATOMS for secundary structure visualisation xwindows 
   of the SECOND structure TO the FIRST structure.
*/

    nlines = iat1;
    for (j=nato2; j < iat2; j++) {
	xyzp1->iatclr[j+nlines] = xyzp2->iatclr[j];
	xyzp1->iresid[j+nlines] = xyzp2->iresid[j];
	xyzp1->iaton[j+nlines] = xyzp2->iaton[j];
	xyzp1->ianz[j+nlines] = xyzp2->ianz[j];
	for (k=0; k < 3; k++) 
	   xyzp1->coo[(j+nlines)*3+k] = xyzp2->coo[j*3+k];
	for (k=0; k < xyzp2->iconn[j*(MXCON+1)]; k++) {
	   xyzp1->iconn[(j+nlines)*(MXCON+1)+k+1] = 
		xyzp2->iconn[j*(MXCON+1)+k+1] + nlines;
	}
	xyzp1->iconn[(j+nlines)*(MXCON+1)] = xyzp2->iconn[j*(MXCON+1)];
    }

/* 
   COPY REAL ATOMS of the SECOND structure TO the FIRST structure.
*/
    nlines = nato1;
    for (j=0; j < nato2; j++) {
	ires = xyzp2->iresid[j];
	if (pdb2) {
	   if (ires > 0) {
		xyzp1->iresid[j+nlines] = nres1 + xyzp2->iresid[j];
	   } else if (ires < -3) {
		xyzp1->iresid[j+nlines] = xyzp2->iresid[j] - nhet1;
	   } else {
		xyzp1->iresid[j+nlines] = xyzp2->iresid[j];
   	   }
	} else {
	   if (pdb1) {
		xyzp1->iresid[j+nlines] = -NHetAtm;
	   } else {
		xyzp1->iresid[j+nlines] = -4;
	   }
	}

/*
	xyzp1->iatclr[j+nlines] = xyzp2->iatclr[j];
*/
	xyzp1->iatclr[j+nlines] = STR2COL + 1;
	xyzp1->iaton[j+nlines]  = xyzp2->iaton[j];
	xyzp1->ianz[j+nlines]   = xyzp2->ianz[j];
	xyzp1->ipdbt[j+nlines]  = xyzp2->ipdbt[j];
	xyzp1->ityp[j+nlines]   = xyzp2->ityp[j];
	xyzp1->qat[j+nlines]    = xyzp2->qat[j];

	for (k=0; k < 3; k++) 
	   xyzp1->coo[(j+nlines)*3+k] = xyzp2->coo[j*3+k];
	for (k=0; k < xyzp2->iconn[j*(MXCON+1)]; k++) {
	   i = xyzp2->iconn[j*(MXCON+1)+k+1];
	   if (i >= 0) {
	      xyzp1->iconn[(j+nlines)*(MXCON+1)+k+1] = 
		xyzp2->iconn[j*(MXCON+1)+k+1] + nlines;
	   } else {
	      xyzp1->iconn[(j+nlines)*(MXCON+1)+k+1] = 
		xyzp2->iconn[j*(MXCON+1)+k+1] - nlines;
	   }
	}
	xyzp1->iconn[(j+nlines)*(MXCON+1)] = xyzp2->iconn[j*(MXCON+1)];
    }
    *natorg = nato1 + nato2;
    *xyzp->iatoms = iat1 + iat2;
   
    calf1->ncalf = calf1->ncalf + nres2;
    for (i=0; i < nres2; i++) {
	if (nres1+i < NUMCAL) {
	   calf1->reson[nres1+i] = calf2->reson[i];
	   calf1->isal[nres1+i] = calf2->isal[i];
	   calf1->irsnr[nres1+i] = calf2->irsnr[i] + nres1;
	   calf1->iamino[nres1+i] = calf2->iamino[i];
	   calf1->iams[nres1+i] = 0;
           for (j=0; j < 6; j++) 
		calf1->icalf[nres1+i][j] = calf2->icalf[i][j] + nato1;
	}
    }
    if (calf1->ncalf >= NUMCAL) calf1->ncalf = NUMCAL-1;

    for (i=0; i < calf2->nchain; i++) {
	calf1->ianf[calf1->nchain+i] = calf2->ianf[i] + nres1;
	calf1->islu[calf1->nchain+i] = calf2->islu[i] + nres1;
    }
    nchstr1 = calf1->nchain;
    calf1->nchain = calf1->nchain + calf2->nchain;

    if (pdb1 && pdb2) {
	for (j=0; j<nhet2; j++) {
	   if (NHetAtm+j < MXHETA) {
	      HetAtm[NHetAtm+j] = COO[str2]->HetAtm[4+j];
	      calfptr->ihet[NHetAtm+j] = calf2->ihet[4+j];
	   }
	}
	NHetAtm = nhet1 + nhet2 + 4;
	if (NHetAtm >= MXHETA) NHetAtm = MXHETA-1;
    } else {
	HetAtm[NHetAtm] = COO[str2]->fname;
	calfptr->ihet[NHetAtm] = 1;
	NHetAtm = nhet1 + 1 + 4;
    }

#ifdef DOGL
    RibClear(istruct);
    NSurf[istruct] = 0;
#if defined(VMS) || defined(UNDERSC)
    ribgl(calfptr->ianf,&calfptr->nchain,&calfptr->ncalf,xyzp->iatoms);
    chkbck();
#else
#ifdef CRAY
    RIBGL(calfptr->ianf,&calfptr->nchain,&calfptr->ncalf,xyzp->iatoms);
    CHKBCK();
#else
    ribgl_(calfptr->ianf,&calfptr->nchain,&calfptr->ncalf,xyzp->iatoms);
    chkbck_();
#endif
#endif
    alnptr->nalign = 2;
    alnptr->istst[0] = iat1;
    alnptr->istst[1] = iat2;
    alnptr->istres[0] = nres1;
    alnptr->istres[1] = calf1->ncalf;
    alnptr->istch[0] = nchstr1;
    alnptr->istch[1] = calf1->nchain;
    alnptr->istcol[0] = STR1COL;
    alnptr->istcol[1] = STR2COL;

    SSdone[istruct] = 1;
    for (i=0; i<4; i++) 
	if (calfptr->ihet[i]) sndon(i,0,0);

    ColorByStruct();
    dispsf();
#endif

}

AddAtom(i,j,k,bl,alpha,dih,ires)
int i,j,k,ires;
double bl,alpha,dih;
{
	int iret;

#if defined(VMS) || defined(UNDERSC)
	atadd(&i,&j,&k,&ONE,&bl,&alpha,&dih,&iret,
#else
#ifdef CRAY
	ATADD(&i,&j,&k,&ONE,&bl,&alpha,&dih,&iret,
#else
	atadd_(&i,&j,&k,&ONE,&bl,&alpha,&dih,&iret,
#endif
#endif
	 xyzp->ianz,xyzp->iaton,xyzp->iatclr,xyzp->iconn,xyzp->iresid,
	 xyzp->ityp,xyzp->ipdbt,&calfptr->ncalf,calfptr->icalf,xyzp->coo);
	if (iret != 0 && iret < *xyzp->mxnat) 
 		xyzp->iresid[iret-1] = ires;
}

LigandHydro(het)
int het;
{

  int i,j,k,l,nc,xc,ir,ix,iy,iz,size,j1,is,nsp2,ic0,ic1;
  int nat,fnd,istart,iend,itot;
  int ic[3];
  int *sp,*icn;
  float aret,da1,da2,da3;
  double bl,alpha,dih;
  int asel[6],anum,iret;

  size = *xyzp->mxnat;
  sp = (int *) malloc((sizeof i)*size);

  icn = (int *) malloc((sizeof i)*size*(MXCON+1));

  for (j=0; j < *xyzp->iatoms; j++)
     for (k=0; k < MXCON+1; k++)
	icn[k+j*(MXCON+1)] = xyzp->iconn[k+j*(MXCON+1)];

  for (j=0; j < *xyzp->iatoms; j++) {
     sp[j] = 0;
     j1 = j + 1;

/* Oxygen */

     if (xyzp->ianz[j] == 8) {

	for (k=0; k < 3; k++) ic[k] = -1;

	nc = icn[j*(MXCON+1)];

	if (nc == 1) {
	   for (k=0; k < nc; k++) 
		ic[k] = icn[j*(MXCON+1)+k+1];

	   ix = ic[0];
	   xc = icn[(ix-1)*(MXCON+1)];

	   if (xc > 0 && xc <= 4) {
		l = 0;
		for (k=0; k < xc; k++) {
		   iy = icn[(ix-1)*(MXCON+1)+k+1];
		   if (iy != j1) {
			ic[l] = iy;
			l++;
		   }
		}
		alpha = 0.0;
		for (k=0; k < l; k++) {
		   asel[0] = j1;
		   asel[1] = ix;
		   asel[2] = ic[k];
		   anum = 3;

#if defined(VMS) || defined(UNDERSC)
		   tomold(&aret,asel,&anum);
#else
#ifdef CRAY
		   TOMOLD(&aret,asel,&anum);
#else
		   tomold_(&aret,asel,&anum);
#endif
#endif
		   alpha = alpha + aret;
		}

		alpha = alpha / (double) l;

		da1 = ABS(alpha-109.47);
		da2 = ABS(alpha-120.0);

		if (da1 < da2) {
		   sp[j] = 3;

		   AddAtom(ic[0],ix,j1,1.090,109.47,180.0,xyzp->iresid[j]);

		} else {

		   sp[j] = 2;
		}
	   }

	} else if (nc == 2) {
	   sp[j] = 3;
	   
	}
     }

/* Carbon */

     if (xyzp->ianz[j] == 6) {
	ix = -1;
	iy = -1;
	for (k=0; k < 3; k++) ic[k] = -1;

	nc = icn[j*(MXCON+1)];
	if (nc <= 3) {
	   for (k=0; k < nc; k++) 
		ic[k] = icn[j*(MXCON+1)+k+1];

	}

	if (nc == 1) {

	    ix = ic[0];
	    xc = icn[(ix-1)*(MXCON+1)];

	    if (xc > 0 && xc <= 4) {
		l = 0;
		for (k=0; k < xc; k++) {
		   iy = icn[(ix-1)*(MXCON+1)+k+1];
		   if (iy != j1) {
			ic[l] = iy;
			l++;
		   }
		}
		alpha = 0.0;
		for (k=0; k < l; k++) {
		   asel[0] = j1;
		   asel[1] = ix;
		   asel[2] = ic[k];
		   anum = 3;

#if defined(VMS) || defined(UNDERSC)
		   tomold(&aret,asel,&anum);
#else
#ifdef CRAY
		   TOMOLD(&aret,asel,&anum);
#else
		   tomold_(&aret,asel,&anum);
#endif
#endif
		   alpha = alpha + aret;
		}

		alpha = alpha / (double) l;

		da1 = ABS(alpha-109.47);
		da2 = ABS(alpha-120.0);
		da3 = ABS(alpha-180.0);

/*
fprintf(stderr,"%d da1 %f da2 %f da3 %f l %d alpha %f\n",j1,da1,da2,da3,l,alpha);
*/

		if ((da1 < da2 && da1 < da3) || xc == 4) {
		   sp[j] = 3;

		   AddAtom(ic[0],ix,j1,1.090,109.47,180.0,xyzp->iresid[j]);
		   AddAtom(ic[0],ix,j1,1.090,109.47,60.0,xyzp->iresid[j]);
		   AddAtom(ic[0],ix,j1,1.090,109.47,-60.0,xyzp->iresid[j]);

		} else if (da2 < da1 && da2 < da3) {

		   sp[j] = 2;

/* defer adding hydrogens until second round */

		} else {

		   sp[j] = 1;

		   AddAtom(ic[0],ix,j1,1.090,179.9,0.0,xyzp->iresid[j]);

		}
	    }

        }

	if (nc == 2) {

/* calc angle */

	   asel[0] = ic[0];
	   asel[1] = j1;
	   asel[2] = ic[1];
	   anum = 3;

#if defined(VMS) || defined(UNDERSC)
	   tomold(&aret,asel,&anum);
#else
#ifdef CRAY
	   TOMOLD(&aret,asel,&anum);
#else
	   tomold_(&aret,asel,&anum);
#endif
#endif
	   da1 = ABS(aret-109.47);
	   da2 = ABS(aret-120.0);
	   da3 = ABS(aret-180.0);
/*
 C, 2 connections:

 ang = 109.47 Sp3 => add 2 Hyd.
 ang = 120.0  Sp2 => add 1 Hyd.
 ang = 180.0  Sp  => add 0 Hyd.
*/

	   if (da1 < da2 && da1 < da3) {
		sp[j] = 3;

		AddAtom(ic[0],ic[1],j1,1.090,109.47,120.0,xyzp->iresid[j]);
		AddAtom(ic[0],ic[1],j1,1.090,109.47,-120.0,xyzp->iresid[j]);

	   } else if (da2 < da1 && da2 < da3) {

		sp[j] = 2;

/* defer adding hydrogens to second round */

	   } else {
		sp[j] = 1;
	   }
	}

	if (nc == 3) {

/* calc dihedral */

	   asel[0] = ic[0];
	   asel[1] = j+1;
	   asel[2] = ic[1];
	   asel[3] = ic[2];
	   anum = 4;

#if defined(VMS) || defined(UNDERSC)
	   tomold(&aret,asel,&anum);
#else
#ifdef CRAY
	   TOMOLD(&aret,asel,&anum);
#else
	   tomold_(&aret,asel,&anum);
#endif
#endif

/*

 C, 3 connections:

 dih = 120.0  Sp3 => add 1 Hyd.
 dih = 180.0  Sp2 => add 0 Hyd.
*/

	   is = SIGN(aret);
	   aret = ABS(aret);
	   da1 = ABS(180.0 - aret);
	   da2 = ABS(120.0 - aret);
	   if (da1 < da2) {
		sp[j] = 2;
	   } else {
		sp[j] = 3;

		AddAtom(ic[0],ic[1],j1,1.090,109.47,is*120.0,xyzp->iresid[j]);
	   }
	}
     }
  }

/*
   Second round 
*/

  for (j=0; j < *xyzp->iatoms; j++) {
     j1 = j + 1;

     if (xyzp->ianz[j] == 8 && sp[j] == 2) {
	for (k=0; k < 3; k++) ic[k] = -1;

	nc = icn[j*(MXCON+1)];

	if (nc == 1) {
	   for (k=0; k < nc; k++) 
		ic[k] = icn[j*(MXCON+1)+k+1];

	   ix = ic[0];
	   xc = icn[(ix-1)*(MXCON+1)];

	   nsp2 = 0; if (sp[ix-1] == 2) nsp2 = 1;
	   if (xc > 0 && xc <= 4) {
		l = 0;
		for (k=0; k < xc; k++) {
		   iy = icn[(ix-1)*(MXCON+1)+k+1];
		   if (iy != j1) {
			if (sp[iy-1] == 2) nsp2++;
			ic[l] = iy;
			l++;
		   }
		}
		if (l == 2 && nsp2 == 3) {
		   sp[j] = 3;

		   AddAtom(ic[0],ix,j1,1.090,109.47,180.0,xyzp->iresid[j]);
		}
	    }
	}
     }

     if (xyzp->ianz[j] == 6 && sp[j] == 2) {
	ix = -1;
	iy = -1;
	for (k=0; k < 3; k++) ic[k] = -1;

	nc = icn[j*(MXCON+1)];
	if (nc <= 3) {
	   for (k=0; k < nc; k++) 
		ic[k] = icn[j*(MXCON+1)+k+1];

	}

	if (nc == 1) {

	    ix = ic[0];
	    xc = icn[(ix-1)*(MXCON+1)];

	    if (xc > 0 && xc <= 4) {
		l = 0;
		nsp2 = sp[ix-1];
		for (k=0; k < xc; k++) {
		   iy = icn[(ix-1)*(MXCON+1)+k+1];
		   if (iy != j1) {
			if (sp[iy-1] == 2) nsp2++;
			ic[l] = iy;
			l++;
		   }
		}
		alpha = 0.0;
		for (k=0; k < l; k++) {
		   asel[0] = j1;
		   asel[1] = ix;
		   asel[2] = ic[k];
		   anum = 3;

#if defined(VMS) || defined(UNDERSC)
		   tomold(&aret,asel,&anum);
#else
#ifdef CRAY
		   TOMOLD(&aret,asel,&anum);
#else
		   tomold_(&aret,asel,&anum);
#endif
#endif
		   alpha = alpha + aret;
		}

		alpha = alpha / (double) l;

		da1 = ABS(alpha-109.47);
		da2 = ABS(alpha-120.0);
		da3 = ABS(alpha-180.0);

		if (da2 < da1 && da2 < da3) {

		   if (nsp2 >= 2) {

			sp[j] = 3;

		        AddAtom(ic[0],ix,j1,1.090,109.47,180.0,
				xyzp->iresid[j]);
		        AddAtom(ic[0],ix,j1,1.090,109.47,60.0,
				xyzp->iresid[j]);
		        AddAtom(ic[0],ix,j1,1.090,109.47,-60.0,
				xyzp->iresid[j]);

		   } else {

			sp[j] = 2;

		        AddAtom(ic[0],ix,j1,1.090,120.0,0.0,
				xyzp->iresid[j]);
		        AddAtom(ic[0],ix,j1,1.090,120.0,180.0,
				xyzp->iresid[j]);

		   }

		}

	    }

        }

	if (nc == 2) {

/* calc angle */

	   asel[0] = ic[0];
	   asel[1] = j1;
	   asel[2] = ic[1];
	   anum = 3;

#if defined(VMS) || defined(UNDERSC)
	   tomold(&aret,asel,&anum);
#else
#ifdef CRAY
	   TOMOLD(&aret,asel,&anum);
#else
	   tomold_(&aret,asel,&anum);
#endif
#endif
	   da1 = ABS(aret-109.47);
	   da2 = ABS(aret-120.0);
	   da3 = ABS(aret-180.0);
/*
 C, 2 connections:

 ang = 109.47 Sp3 => add 2 Hyd.
 ang = 120.0  Sp2 => add 1 Hyd.
 ang = 180.0  Sp  => add 0 Hyd.
*/

	   if (da2 < da1 && da2 < da3) {

	    ic0 = 1; ic1 = 1;
	    ix = ic[0];
	    iy = ic[1];

	    xc = icn[(ix-1)*(MXCON+1)];

	    if (xc > 0 && xc <= 3) {
		l = 0;
		nsp2 = sp[ix-1];
		for (k=0; k < xc; k++) {
		   iz = icn[(ix-1)*(MXCON+1)+k+1];
		   if (iz != j1) {
			if (sp[iz-1] == 2) nsp2++;
			ic[l] = iz;
			l++;
		   }
		}

		for (k=0; k < l; k++) {

		   asel[0] = ic[k];
		   asel[1] = ix;
		   asel[2] = j1;
		   asel[3] = iy;
		   anum = 4;

#if defined(VMS) || defined(UNDERSC)
		   tomold(&aret,asel,&anum);
#else
#ifdef CRAY
		   TOMOLD(&aret,asel,&anum);
#else
		   tomold_(&aret,asel,&anum);
#endif
#endif
		   da1 = ABS(aret-180.0);
		   da2 = ABS(aret-0.0);
		   if (da2 < da1) da1 = da2; 
		   if (da1 > 10.0) ic0 = 0;
		}

	    } else { 
		ic0 = 0;
	    }

	    xc = icn[(iy-1)*(MXCON+1)];

	    if (xc > 0 && xc <= 3) {
		l = 0;
		nsp2 = sp[iy-1];
		for (k=0; k < xc; k++) {
		   iz = icn[(iy-1)*(MXCON+1)+k+1];
		   if (iz != j1) {
			if (sp[iz-1] == 2) nsp2++;
			ic[l] = iz;
			l++;
		   }
		}

		for (k=0; k < l; k++) {

		   asel[0] = ic[k];
		   asel[1] = iy;
		   asel[2] = j1;
		   asel[3] = ix;
		   anum = 4;

#if defined(VMS) || defined(UNDERSC)
		   tomold(&aret,asel,&anum);
#else
#ifdef CRAY
		   TOMOLD(&aret,asel,&anum);
#else
		   tomold_(&aret,asel,&anum);
#endif
#endif
		   da1 = ABS(aret-180.0);
		   da2 = ABS(aret-0.0);
		   if (da2 < da1) da1 = da2; 
		   if (da1 > 10.0) ic1 = 0;
		}

	    } else { 
		ic1 = 0;
	    }

	    if (ic0 || ic1) {

		sp[j] = 2;

		AddAtom(ix,iy,j1,1.090,120.0,180.0,xyzp->iresid[j]);

	    } else {

		sp[j] = 3;

		AddAtom(ix,iy,j1,1.090,109.47,120.0,xyzp->iresid[j]);
		AddAtom(ix,iy,j1,1.090,109.47,-120.0,xyzp->iresid[j]);

	    }

	   }
	}

     }
  }

/*
   Third round 
*/

  for (j=0; j < *xyzp->iatoms; j++) {
     j1 = j + 1;

     if (xyzp->ianz[j] == 7) {

	ix = -1;
	iy = -1;
	for (k=0; k < 3; k++) ic[k] = -1;

	nc = icn[j*(MXCON+1)];
	if (nc <= 3) {
	   for (k=0; k < nc; k++) 
		ic[k] = icn[j*(MXCON+1)+k+1];

	}

	if (nc == 1) {

	    ix = ic[0];
	    xc = icn[(ix-1)*(MXCON+1)];

	    if (xc > 0 && xc <= 4) {
		l = 0;
		for (k=0; k < xc; k++) {
		   iy = icn[(ix-1)*(MXCON+1)+k+1];
		   if (iy != j1) {
			ic[l] = iy;
			l++;
		   }
		}
		alpha = 0.0;
		for (k=0; k < l; k++) {
		   asel[0] = j1;
		   asel[1] = ix;
		   asel[2] = ic[k];
		   anum = 3;

#if defined(VMS) || defined(UNDERSC)
		   tomold(&aret,asel,&anum);
#else
#ifdef CRAY
		   TOMOLD(&aret,asel,&anum);
#else
		   tomold_(&aret,asel,&anum);
#endif
#endif
		   alpha = alpha + aret;
		}

		alpha = alpha / (double) l;

		da1 = ABS(alpha-109.47);
		da2 = ABS(alpha-120.0);
		da3 = ABS(alpha-180.0);

		if ((da1 < da2 && da1 < da3) || xc == 4) {
		   sp[j] = 3;

		   AddAtom(ic[0],ix,j1,1.090,109.47,180.0,xyzp->iresid[j]);
		   AddAtom(ic[0],ix,j1,1.090,109.47,60.0,xyzp->iresid[j]);

		} else if (da2 < da1 && da2 < da3) {

		   sp[j] = 2;

		   AddAtom(ic[0],ix,j1,1.090,120.0,180.0,xyzp->iresid[j]);


		} else {

		   sp[j] = 1;


		}
	    }

        }

	if (nc == 2) {

/* calc angle */

	   asel[0] = ic[0];
	   asel[1] = j1;
	   asel[2] = ic[1];
	   anum = 3;

#if defined(VMS) || defined(UNDERSC)
	   tomold(&aret,asel,&anum);
#else
#ifdef CRAY
	   TOMOLD(&aret,asel,&anum);
#else
	   tomold_(&aret,asel,&anum);
#endif
#endif
	   da1 = ABS(aret-109.47);
	   da2 = ABS(aret-120.0);
	   da3 = ABS(aret-180.0);
/*
 N, 2 connections:

 ang = 109.47 Sp3 => add 1 Hyd.
 ang = 120.0  Sp2 => add 0 Hyd.
 ang = 180.0  Sp  => add 0 Hyd.
*/

	   if (da1 < da2 && da1 < da3) {
		sp[j] = 3;

		AddAtom(ic[0],ic[1],j1,1.090,109.47,120.0,xyzp->iresid[j]);

	   } else if (da2 < da1 && da2 < da3) {

		sp[j] = 2;


	   } else {
		sp[j] = 1;
	   }
	}
     }
  }

  free(sp);
  free(icn);
}

#if defined(VMS) || defined(UNDERSC)
void chkmpi()
#else
#ifdef CRAY
void CHKMPI()
#else
void chkmpi_()
#endif
#endif
{
 FILE *pip;
 char line[256];
 char *p;
 char *pth;
 int ns = 10000;
 int ts;

#ifndef __CYGWIN__
 if ((pip = popen("/usr/bin/locate mpirun 2>&1","r")) ) {
	while ( fgets(line,sizeof line, pip) ) {
	   ts = strlen(line);
	   if ((p = strrchr(line, '/'))) {
		p++;
		if (strlen(p) == 7 && ts < ns ) {
		   if (strlen(line) < MAXCMD) {
			strcpy(mpicmd,line);
			if ((p = strrchr(mpicmd,'\n'))) *p = '\0';
			ns = ts;
		   }
		}
	   }
	}
	pclose(pip);
	strcpy(line," ");
	if (getexe(0,1,line)) {
	    hasmpi = 1;
	    strcpy(mpilib,mpicmd);
	    if ((p = strrchr(mpilib, '/'))) {
		p--;p--;p--;
		*p= '\0';
		strcat(mpilib,"lib");
		pth = getenv("LD_LIBRARY_PATH");
		if (pth != NULL) {
		   strcpy(npth,pth);
		   strcat(npth,":");
		   strcat(npth,mpilib);
		}

	    }

	    if ((pip = popen("grep -c processor /proc/cpuinfo","r")) ) {
		while ( fgets(line,sizeof line, pip) ) {
		    maxproc = atoi(line);
		    useproc = maxproc;
		}
		pclose(pip);
	    }
	}
 }
#endif

 if (hasmpi) {
	ntnkb++;
	ntnkb++;
 }

}

int DoWGET(wwwstr,argm,retstr)
char *wwwstr;
char *argm;
char *retstr;
{
   char cmdfil[500];
   char cmdtmp[500];
   char *wget = "wget";
   int i,istat,pid;
   char *p;

#if defined(VMS) || defined(UNDERSC)
   curs(&ONE);
#else
#ifdef CRAY
   CURS(&ONE);
#else
   curs_(&ONE);
#endif
#endif

   istat = 1;

#ifdef __CYGWIN__
   getusr(retstr);
   sprintf(cmdtmp,"%s%s.exe",exepath[0],wget);
   spaesc(cmdtmp);
#else
   strcpy(retstr,tmpnam(NULL));
   strcpy(cmdtmp,wget);
#endif


#ifdef __CYGWIN__

   if ((access(cmdtmp,F_OK) == 0 && !isdir(cmdtmp))) {

	if (p = strstr(cmdtmp,".exe")) p[0] = '\0';

	 strcpy(cmdfil,wwwstr);
	 strcat(cmdfil,argm);

	 pid = vfork();
	 switch(pid) {
	 case -1:
          fprintf(stderr,"Couldnt Fork\n");
          break;
	 case 0:       /*child */
	  execlp(cmdtmp,"wget",cmdfil,"-O",retstr,NULL);
	  _exit(0);
          break;
	 default:      /*parent*/
	  wait(&pid);
          break;
	}
	istat = 0;
   } else {
	fprintf(stderr,"%s not found\n",cmdtmp);
   }
#else
   strcat(cmdtmp," \"");
   strcat(cmdtmp,wwwstr);
   if (argm != NULL) strcat(cmdtmp,argm);
   if (strstr(wwwstr,"cml")) strcat(cmdtmp,".cml");
   strcat(cmdtmp,"\" -O ");
   strcat(cmdtmp,retstr);
   strcat(cmdtmp," 2> /dev/null");

   fprintf(stderr,"Dowget: %s\n",cmdtmp);

   istat = system(cmdtmp);
#endif

#if defined(VMS) || defined(UNDERSC)
   curs(&ZERO);
#else
#ifdef CRAY
   CURS(&ZERO);
#else
   curs_(&ZERO);
#endif
#endif
   return(istat);

}

int CheckWGET()
{
   char *wwwstr = "http://www.google.com/index.html";
   char retstr[500] = "";
   int status;

   if (!hasWGET) {
        status = DoWGET(wwwstr,"",retstr);
	if (!status) {
	    hasWGET = 1;
	} else {
	    fprintf(stderr,"\nWARNING:\nThe standard HETATM hydrogen adding routine,\ndepends on the program \"wget\".\nYou can download wget from : http://ftp.gnu.org/gnu/wget/\n");

	}
   } else {
	status = 0;
   }
   
   return(status);

}

void GetPDBWWW(het,retstr)
char *het;
char *retstr;
{
   char *wwwstr = "http://www.rcsb.org/pdb/downloadFile.do?fileFormat=pdb&compression=NO&structureId=";

   DoWGET(wwwstr,het,retstr);
}

int GetOMAPWWW(het,retstr)
char *het;
char *retstr;
{
   struct stat filestat;
   char *wwwstr = "http://eds.bmc.uu.se/cgi-bin/eds/gen_zip.pl?pdbCode=";
   char wwwstr2[MAXSTRLEN];
   int pid;

   unsetenv("TMP");
   unsetenv("TEMP");
   unsetenv("TMPDIR");

   DoWGET(wwwstr,het,retstr);
   sprintf(wwwstr2,"http://eds.bmc.uu.se/eds/dfs/%c%c/%s/%s.tar.gz",
	het[1],het[2],het,het);

   DoWGET(wwwstr2,"",retstr);

#ifdef __CYGWIN__
	    sprintf(stemp,"%s/%s.omap",het,het);
	    pid = vfork();
	    switch(pid) {
	    case -1:
	 	fprintf(stderr,"Couldnt Fork\n");
		break;
	    case 0:	/*child */
		execlp("tar","tar","-zxvf",retstr,stemp,
			"--strip-components","1",NULL);
		_exit(0);
		break;
	    default:	/*parent*/
		wait(&pid);
		break;
	    }
#else
   stat(retstr,&filestat);

   if (filestat.st_size) {
	sprintf(wwwstr2,"tar zxvf %s %s/%s.omap --strip-components 1\n",
		retstr,het,het);
	if (!system(wwwstr2)) {

#endif
	    *Sinct = 584; *Snstr = 9;
	    sprintf(wwwstr2,"%s.omap",het);
	    cpstr(wwwstr2,Sstr,strlen(wwwstr2));
	    return(1);

#ifndef __CYGWIN__
	}
   } else {
	DoCan(event.xbutton.x_root, event.xbutton.y_root,
	"No omap file available.\nCheck at http://eds.bmc.uu.se/eds/",0);
   }
#endif
   return(0);
}

void LigandQ(ihet)
int ihet;
{
   FILE *out;
   char cmdtmp[500] = "";
   char cmdfil[500];
   char *spntr;
   char *het;
   int i,j,istat,aihet,ifnd;
   int fnd,iend,itch=-15;

   char *wwwtotq = "ftp://ftp.ebi.ac.uk/pub/databases/msd/pdbechem/files/cml/";

   aihet = abs(ihet);

   if (aihet >= MXHETA) {
	fprintf(stderr,"\nLigandQ: hetatm residue outside array bounds\n\n");
	return;
   }

   fnd = 0;
   iend = -1;

   for (j=0; j < *xyzp->iatoms; j++) {
	if (xyzp->iresid[j] == ihet) {
	   if (!fnd) {
	      fnd = 1;
	   }
	   iend = j;
	}
   }

   if (iend == -1 ) return;

   het = (char *) malloc(80);


   strcpy(het,HetAtm[aihet]);

   het[3] = '\0';

   fprintf(stderr,"\nRetrieving Ligand Charge from PDBeChem\n\n");

   istat = DoWGET(wwwtotq,het,cmdtmp);

   ifnd = 0;

   out = fopen(cmdtmp,"r");

   if (out != NULL) {
	while (fgets(cmdfil,MAXCMD,out) != NULL) {
	   if (strstr(cmdfil,"formalCharge") != NULL) {
		spntr = strstr(cmdfil,"formalCharge=\"");
		if (spntr) {
		    spntr = spntr + 14;
		    sscanf(spntr,"%d",&itch);
		}
		ifnd = 1;
		break;
	   }
	}
	fclose(out);
	if (ifnd) {
	   fprintf(stderr,"formalCharge %d\n",itch);
	   clfstrptr->ihetq[aihet] = itch;
	   clfstrptr->ihqset[aihet] = 1;
	} else {
	   fprintf(stderr,"NO formalCharge found\n");
	}
   }
}
/* Ligand2Amino NOT used */

int Ligand2Amino(ihet)
int ihet;
{
   int i,j,k,nc,iac;

   iac = 0;
   for (j=0; j < *xyzp->iatoms; j++) {

	if (xyzp->iresid[j] == ihet) {

	  nc = xyzp->iconn[j*(MXCON+1)];

	  for (k=0; k < nc; k++) {
		i = xyzp->iconn[j*(MXCON+1)+k+1];

		if (i > 0) if (xyzp->iresid[i] != ihet) iac++;
	  }
	}
    }
    return(iac);
}

void CheckHydro(ihet)
int ihet;
{
   int i,j,inoth,ih,aihet;

   inoth = 0; ih = 0;

   for (j=0; j < *xyzp->iatoms; j++) {
	if (xyzp->iresid[j] == ihet) {
	    if (xyzp->ianz[j] == 1) ih++;
	    else inoth++;
	}
   }

   aihet = abs(ihet);
   if (((float) ih/(float) inoth) > 0.2) clfstrptr->ihhadd[aihet] = 1;
}

/*
- HEM:
  CAC 1*H (HAC) is added
  CAB 1*H (HAB) is added
  O2A 1*H (H2A) we choose NOT to add it
  O2B 1*H (H2B) we choose NOT to add it

  Discription HEM should include 2H's for CAB,CAC. It does not, This means
  the connections with amino acids are taken into account.

  discription HEM includes Fe (probably Fe2+, offsets 2*COO- charges:
  total Neutral, which is the initial formal charge given. But
  actually it should be 2+, because the description uses 2*COOH).

  Message 1: do NOT subtract because of connections with amino acids.
  Message 2: exclude FE from partial charge calculation, and set q(FE)=+2
*/

void LigandHydroPBE(ihet)
int ihet;
{
   FILE *out;
   char cmdtmp[500];
   char cmdfil[500];
   char chemid[10];
   char chemidOld[10] = "-1";
   char *spntr;
   char *het;
   double angles3[3] = {180.0,60.0,-60.0};
   double angles3a[2] = {120.0,-120.0};
   double angles2[3] = {0.0,180.0};
   int ic[MXCON];
   int i,j,k,l,l0,j1,k0,la,lanz,is,xc,ix,iy,idum,size,npdbe,hasH,aihet;
   int *sp, *nh, *ian, *ifl;
   int nc,fnd,iend,natoms,istat,itch=0,iac,notu,nht;
   float aret;
   int asel[6],anum;
   char **hetz;
   char *strp;
   char *wwwstr = "ftp://ftp.ebi.ac.uk/pub/databases/msd/pdbechem/files/cml/";
   aihet = abs(ihet);

   if (aihet >= MXHETA) {
	fprintf(stderr,"\nLigandHydroPBE: hetatm residue outside array bounds\n\n");
	return;
   }

   fnd = 0;
   iend = -1;

   for (j=0; j < *xyzp->iatoms; j++) {
	if (xyzp->iresid[j] == ihet) {
	   if (!fnd) {
	      fnd = 1;
	   }
	   iend = j;
	}
   }

   if (iend == -1 ) return;

   size = MXHETLAB;

   sp   = (int *) malloc((sizeof i)*size);
   nh   = (int *) malloc((sizeof i)*size);
   ifl   = (int *) malloc((sizeof i)*size);
   hetz = (char **) malloc((sizeof *hetz)*size);

   for (i=0; i < size; i++) {
	nh[i] = 0; sp[i] = 0; ifl[i] = 0; hetz[i] = NULL;
   }

   het = (char *) malloc(80);
   strp = HetAtm[aihet];
   if (strp[0] == ' ') strp++;
   strcpy(het,strp);
   het[3] = '\0';

   fprintf(stderr,"\nRetrieving Ligand information from PDBeChem\n\n");

   iac = Ligand2Amino(ihet);

   istat = DoWGET(wwwstr,het,cmdtmp);

   out = fopen(cmdtmp,"r");

   npdbe = 0;
   if (out != NULL) {
	while (fgets(cmdfil,MAXCMD,out) != NULL) {
	   if (strstr(cmdfil,"formalCharge") != NULL) {
		spntr = strstr(cmdfil,"formalCharge=\"");
		if (spntr) {
		    spntr = spntr + 14;
		    sscanf(spntr,"%d",&itch);
		}
		break;
	   }
	}
	fprintf(stderr,"formalCharge %d\n",itch);
	clfstrptr->ihetq[aihet] = itch;
	clfstrptr->ihqset[aihet] = 1;

	while (fgets(cmdfil,MAXCMD,out) != NULL) {
	   if (strstr(cmdfil,"atomArray") != NULL) {
		while (fgets(cmdfil,MAXCMD,out) != NULL) {
		   if (strstr(cmdfil,"atom id=") != NULL) {
			spntr = strstr(cmdfil,"atom id=\"");
			if (spntr) {
			    /*spntr = spntr + 3;*/
			    spntr = spntr + 9;
		   	    sscanf(spntr,"%[^\"]",chemid);

			    if (strcmp(chemidOld,"-1") == 0) {

				strcpy(chemidOld,chemid);
				hetz[0] = (char *) malloc(strlen(chemid)+1);
				strcpy(hetz[0],chemid);

			    } else if (strcmp(chemid,chemidOld) != 0) {

				strcpy(chemidOld,chemid);
				npdbe++;
				hetz[npdbe] = 
					(char *) malloc(strlen(chemid)+1);
				strcpy(hetz[npdbe],chemid);

			    }

			    spntr = strstr(cmdfil,"hydrogenCount=\"");
			    if (spntr) {
				spntr = spntr + 15;
		   	        sscanf(spntr,"%d",&nh[npdbe]);
			    }

			}
		   }
		}
	    }
	}
	fclose(out);
   }
   npdbe++;

   nht = 0;

   if (npdbe == 1) goto nolab;

   clfstrptr->ihhadd[aihet] = 1;

   i = -1;

   natoms = iend + 1;

   for (j=0; j < natoms; j++) {

	if (xyzp->iresid[j] == ihet) {

	  i++;
	  j1 = j + 1;

	  l0 = -1;
	  for (l=0; l < hetlab.NHetLab; l++) 
		if (hetlab.iat[l] == j1) l0 = l;

	  if (l0 == -1) {
		fprintf(stderr,
		"LigandHydroPBE: atom %d : pdb label not found!\n",j1);
	  	return;
	  }


	  k0 = -1;

	  for (l=0; l < npdbe; l++) 
		if (strcmp(hetlab.HetLab[l0],hetz[l]) == 0) k0 = l;

	  hasH = 0;
	  nc = 0;
	  xc = xyzp->iconn[j*(MXCON+1)];

	  for (k=0; k < 3; k++) ic[k] = -1;

	  for (k=0; k < xc; k++) {
		l = xyzp->iconn[j*(MXCON+1)+k+1];
		la = abs(l);
		lanz = 0;
		if (la > 0) lanz = xyzp->ianz[la-1];

		if (l > 0 && lanz > 1) {
		    ic[nc] = l;
		    nc++;
		} else if (lanz == 1) {
		    hasH = 1;
		}
	  }

	  if (k0 != -1) {
	     if (strcmp(het,"HEM") == 0) {
		if (strcmp(hetz[k0],"O2A") == 0 || 
		    strcmp(hetz[k0],"O2D") == 0) {
			nht = nht + nh[k0];
			k0 = -1;
		}
	     }
	  }

	  if (k0 != -1 && hasH) ifl[k0] = 1;

	  if (k0 != -1 && !hasH) {

	   notu = nht;
	   nht = nht + nh[k0];

           ifl[k0] = 1;

	   switch(nc) {
		case 1:
			ix = ic[0];
			xc = xyzp->iconn[(ix-1)*(MXCON+1)];

			if (xc > 0 && xc <= 4) {
			   l = 0;
			   for (k=0; k < xc; k++) {
				iy = xyzp->iconn[(ix-1)*(MXCON+1)+k+1];
				if (iy != j1) {
				    ic[l] = iy;
				    l++;
				}
			   }
			   switch(nh[k0]) {
				case 3:
/* 1 + 3 = 4 connections; atom is C sp3, N sp3 */
					for (k=0; k < 3; k++) {
					   AddAtom(ic[0],ix,j1,1.090,109.47,
						   angles3[k], xyzp->iresid[j]);
				           nht--;
					}
					break;
				case 2:
/* 1 + 2 = 3 connections; atom is C sp2 or N sp3,sp2 */
					for (k=0; k < 2; k++) {
					   AddAtom(ic[0],ix,j1,1.090,120.0,
						   angles2[k], xyzp->iresid[j]);
				           nht--;
					}
					break;
				case 1:
/* 1 + 1 = 2 connections; atom is C sp or N sp2 or O sp3 */
					switch(xyzp->ianz[j]) {
					   case 7:
					   	AddAtom(ic[0],ix,j1,
						1.090,120.0,180.0,
						xyzp->iresid[j]);
				        	nht--;
						break;
					   case 8:
					   	AddAtom(ic[0],ix,j1,
						1.090,109.47,180.0,
						xyzp->iresid[j]);
				        	nht--;
						break;
					   default:
					   case 6:
					   	AddAtom(ic[0],ix,j1,
						1.090,179.9,0.0,
						xyzp->iresid[j]);
				        	nht--;
						break;
					}
					break;
				default:
					break;
			   }
			}

			break;
		case 2:
			switch(nh[k0]) {
/* 2 + 2 = 4 connections; atom is C sp3 */
			   case 2:
				   if (xyzp->ianz[j] == 8) break;
				   for (k=0; k < nh[k0]; k++) {
					AddAtom(ic[0],ic[1],j1,1.090,109.47,
					angles3a[k],xyzp->iresid[j]);
				        nht--;
				   }
				   break;
			   case 1:
/* 2 + 1 = 3 connections; atom is  C sp2  or N sp3,sp2 */
				   if (xyzp->ianz[j] == 8) break;
				   AddAtom(ic[0],ic[1],j1,1.090,120.0,
					180.0,xyzp->iresid[j]);
				   nht--;
				   break;
			   default:
				   break;
			}
			break;
		case 3:
			switch(nh[k0]) {
			   case 1:
/* 3 + 1 = 4 connections; atom is C sp3 */
				   asel[0] = ic[0];
				   asel[1] = j1;
				   asel[2] = ic[1];
				   asel[3] = ic[2];
				   anum = 4;

#if defined(VMS) || defined(UNDERSC)
				   tomold(&aret,asel,&anum);
#else
#ifdef CRAY
	 			   TOMOLD(&aret,asel,&anum);
#else
				   tomold_(&aret,asel,&anum);
#endif
#endif

				   is = SIGN(aret);
				   AddAtom(ic[0],ic[1],j1,1.090,109.47,
					is*120.0,xyzp->iresid[j]);
				   nht--;
				   break;
			   default:
				   break;
			}
			break;
		default:
			break;
	   }
	  }
	}
     
   }

   fnd = 0;
   for (j=0; j < npdbe; j++) {
	if (nh[j] != 0 && ifl[j] == 0) {
	    fnd++;
	}
   }

   if (fnd) {

	fprintf(stderr,
	   "\nSome labels in PBE entry %s, not found in HETATM from pdb file\n\n",het);

	fprintf(stderr,"PBE labels:\n\n");
	for (j=0; j < npdbe; j++) 
	   fprintf(stderr,"%s nh %d used %d\n",hetz[j],nh[j],ifl[j]);

	fprintf(stderr,"\npdb file HETATM labels:\n\n");

	for (j=0; j < *xyzp->iatoms; j++) 
	   if (xyzp->iresid[j] == ihet) {
		j1 = j + 1;

		l0 = -1;
		for (l=0; l < hetlab.NHetLab; l++) 
		   if (hetlab.iat[l] == j1) l0 = l;

		if (l0 != -1)
	   	   fprintf(stderr,"atom %d %s\n",j1,hetlab.HetLab[l0]);
	   }
   }

nolab:

   if (nht) {

	   fprintf(stderr,"\nSome Hydrogens not used:\n");
	   fprintf(stderr,"\nDecreasing formal charge by %d units\n",nht);
/*
	if (iac) {
	   fprintf(stderr,"\n%s has connections with amino acids:\n",het);
	   fprintf(stderr,"\nIncreasing formal charge by %d units\n",iac);
	}

	clfstrptr->ihetq[aihet] = 
		clfstrptr->ihetq[aihet] - nht + iac;
*/
	clfstrptr->ihetq[aihet] = 
		clfstrptr->ihetq[aihet] - nht;

	fprintf(stderr,"New formalCharge %d\n",clfstrptr->ihetq[aihet]);
   }

   free(sp);
   free(nh);
   free(ifl);
   for (j=0; j < npdbe; j++) 
	if (hetz != NULL) free(hetz[j]);
   free(hetz);


}

/* 
  specify:

  DoHyd		Add Hydrogens
  DoChg		Calculate Charge, with ieemopt and CHGtot
  DoFF		Type by Ambfor Force Field 
*/

void LigandHydroQ(DoHyd,DoChg,DoFF,CHGtot)
int DoHyd;
int DoChg;
int DoFF;
int CHGtot;
{
      int i,imn,nhmol,TmpEemOpt,CHGstat,onemol;
      CHGstat = 0;

      TmpEemOpt = ieemopt + 1;

      if (*ipdbon) {

#if defined(VMS) || defined(UNDERSC)
	numhed(&nhmol,
#else
#ifdef CRAY
	NUMHED(&nhmol,
#else
	numhed_(&nhmol,
#endif
#endif
	xyzp->iresid);

	onemol = 0;
	if (nhmol == 4) onemol = 1;

	for (i=4; i<nhmol+1; i++) {

	    imn = -i;

	    if (i != calfptr->ishoh) {

		if (clfstrptr->ihashz) {
		    fprintf(stderr,"\nHETATM residue %s\n\n",HetAtm[i]);
		} else {
		    fprintf(stderr,"\nHETATM residue %d\n\n",(i-4));
		}

		if (DoHyd) CheckHydro(imn);

		if (DoHyd && !clfstrptr->ihhadd[i]) LigandHydroPBE(imn);

		if (DoFF) {

		    if (clfstrptr->ihqset[i]) {
			*itot = clfstrptr->ihetq[i];
		    } else {
			if (onemol) {
			   *itot = CHGtot;
			} else {
			   *itot = 0;
			}
		    }

		    *fftyp == 7; 
		    typit(7,1);
		}

		if (DoChg) {

		    if (clfstrptr->ihqset[i]) {
			*itot = clfstrptr->ihetq[i];
		    } else {
			if (onemol) {
			   *itot = CHGtot;
			} else {
			   *itot = 0;
			}
		    }

		    if (ieemopt == 4) {

#if defined(VMS) || defined(UNDERSC)
			calgas(&imn,&CHGstat);
#else
#ifdef CRAY
			CALGAS(&imn,&CHGstat);
#else
			calgas_(&imn,&CHGstat);
#endif
#endif
		    } else {

#if defined(VMS) || defined(UNDERSC)
			eem(&TmpEemOpt,&imn,&CHGstat);
#else
#ifdef CRAY
			EEM(&TmpEemOpt,&imn,&CHGstat);
#else
			eem_(&TmpEemOpt,&imn,&CHGstat);
#endif
#endif
		    }

		    if (CHGstat) 
			fprintf(stderr,
			"WARNING: element missing charge scheme parameters!");
		}
	    }
	}


      } else {

	*itot = CHGtot;

	if (ieemopt == 4) {

#if defined(VMS) || defined(UNDERSC)
	    calgas(&ONE,&CHGstat);
#else
#ifdef CRAY
	    CALGAS(&ONE,&CHGstat);
#else
	    calgas_(&ONE,&CHGstat);
#endif
#endif

	} else {

#if defined(VMS) || defined(UNDERSC)
	    eem(&TmpEemOpt,&ONE,&CHGstat);
#else
#ifdef CRAY
	    EEM(&TmpEemOpt,&ONE,&CHGstat);
#else
	    eem_(&TmpEemOpt,&ONE,&CHGstat);
#endif
#endif
	}
	if (CHGstat) 
	    fprintf(stderr,
		"WARNING: element missing charge scheme parameters!");
      }


}

LigandStruct(het)
int het;
{

  int i,j,k,l,nc,ir;
  int nat,fnd,istart,iend,itot,ahet;
  COOSTRU *xyzpo;

    ahet = ABS(het);

    if (ahet >= MXHETA) {
	fprintf(stderr,"\nLigandStruct: hetatm residue outside array bounds\n\n");
	return;
    }

    if (istruct == 0 && &COO[istruct]->coo == NULL) {
	    AllocateStructure(&COO[0]);
	    SaveFirstStruct();
	    nstruct++;
    }

    xyzpo   = &COO[istruct]->coo;

    fnd = 0;
    istart = 0;
    iend = -1;

    for (j=0; j < *xyzpo->iatoms; j++) {
	if (xyzpo->iresid[j] == het) {
	   if (!fnd) {
	      istart = j; 
	      fnd = 1;
	   }
	   iend = j;
	}
    }

    if (iend == -1 ) return;

    nat = iend - istart + 1;

    AllocateStructure(&COO[nstruct]);
    if (nstruct != 0) SaveActiveStruct();

    NHetAtm = 1;
    HetAtm[0] = HetAtm[ahet];

    AllocateSubStructures(HetAtm[0]);

    if (nat > *xyzp->mxnat) {
	itot = nat + 500;
#if defined(VMS) || defined(UNDERSC)
	allcoo(&itot,&ZERO);
#else
#ifdef CRAY
	ALLCOO(&itot,&ZERO);
#else
	allcoo_(&itot,&ZERO);
#endif
#endif
    }

    for (j=0; j < nat; j++) {
	xyzp->iresid[j] = -4;
	xyzp->iatclr[j] = xyzpo->iatclr[j+istart];
	xyzp->iaton[j]  = xyzpo->iaton[j+istart];
	xyzp->ianz[j]   = xyzpo->ianz[j+istart];
	xyzp->ipdbt[j]  = xyzpo->ipdbt[j+istart];
	xyzp->ityp[j]   = xyzpo->ityp[j+istart];
	xyzp->qat[j]    = xyzpo->qat[j+istart];

	for (k=0; k < 3; k++) 
	   xyzp->coo[j*3+k] = xyzpo->coo[(j+istart)*3+k];

	nc = 0;
	for (k=0; k < xyzpo->iconn[(j+istart)*(MXCON+1)]; k++) {
	   i = xyzpo->iconn[(j+istart)*(MXCON+1)+k+1];
	   ir = xyzpo->iresid[i-1];
	   if (ir == het) {
		if (i >= 0) {
		   xyzp->iconn[j*(MXCON+1)+nc+1] = 
			xyzpo->iconn[(j+istart)*(MXCON+1)+k+1] - istart;
		} else {
		   xyzp->iconn[j*(MXCON+1)+nc+1] = 
			xyzpo->iconn[(j+istart)*(MXCON+1)+k+1] + istart;
		}
		nc++;
	   }
	}
	xyzp->iconn[j*(MXCON+1)] = nc;
    }
    *natorg = nat;
    *xyzp->iatoms = nat;
    clfstrptr->ihashz = 0;
    *ipdbon = 0;
    *backb = 0;

#if defined(VMS) || defined(UNDERSC)
    docent();doscal();
#else
#ifdef CRAY
    DOCENT();DOSCAL();
#else
    docent_();doscal_();
#endif
#endif
    posptr->zv = 2.0*scalptr->scali;
    posptr->xv = 0.0;
    posptr->yv = 0.0;
#ifdef DOGL
    posz = scalptr->scali;
    updfog(0);
#endif

    update_model = 1;
    update_struct();
    RedrawSTR();

    ZMEswitch[0].toggle = 1; ZMEAA = 0; EXPbox[0].fake = 1; 
    LastAmino = -1;
    CurAmino = -1;

    for (j=0; j < *xyzp->iatoms; j++) {
	if (xyzp->ianz[j] < 100) {
	   xyzp->iaton[j] = 2;
	} else {
	   xyzp->iaton[j] = 1;
	}
    }

#if defined(VMS) || defined(UNDERSC)
    intzmt(&ZERO);
#else
#ifdef CRAY
    INTZMT(&ZERO);
#else
    intzmt_(&ZERO);
#endif
#endif

    for (j=0; j < *xyzp->iatoms; j++) xyzp->iaton[j] = 1;

    pdb = 0;
    calfptr->ncalf = 0;
   
}

#ifdef DOGL

#if defined(VMS) || defined(UNDERSC)
void oglin()
#else
#ifdef CRAY
void OGLIN()
#else
void oglin_()
#endif
#endif
{

      theLines[istruct] = glGenLists(1);

      glNewList(theLines[istruct], GL_COMPILE);

      glDisable(GL_LIGHTING);
      glEnable(GL_COLOR_MATERIAL);
      glBegin(GL_LINES);
}

ogrdmol(char *top, double *r, double *adjus, int *natoms, int *nat, int *iatclr,
        double *coo, int *iopt, int *conn, int *iconn)
{
      int i,j,atcol;

      *adjus = 0.529177;
      if (strstr(top,"AU")) *adjus = 1.0;
      *conn = 0;
      if (strstr(top,"CONN")) *conn = 1;
      *iopt = 0;
      if (strstr(top,"UNSCALED")) *iopt = 1;
      atcol = 1;
      if (strstr(top,"GRPCOL")) atcol = 0;
      
      if (*iopt) {
        r[0] = 1.0;
      } else {
	fgets(top,100,out);
	sscanf(top,"%lf %lf %lf",&r[0],&r[1],&r[2]);
      }
      fgets(top,100,out);
      sscanf(top,"%d",natoms);

      for (i=0; i<*natoms; i++) {
	  fgets(top,132,out);
	  if (atcol) {
	    sscanf(top,"%d %lf %lf %lf %d %d %d %d %d %d %d %d %d %d %d %d %d",
		&nat[i],&coo[i*3],&coo[i*3+1],&coo[i*3+2],
		&iconn[i*(MXCON+1)],
		&iconn[i*(MXCON+1)+1],&iconn[i*(MXCON+1)+2],
		&iconn[i*(MXCON+1)+3],&iconn[i*(MXCON+1)+4],
		&iconn[i*(MXCON+1)+5],&iconn[i*(MXCON+1)+6],
		&iconn[i*(MXCON+1)+7],&iconn[i*(MXCON+1)+8],
		&iconn[i*(MXCON+1)+9],&iconn[i*(MXCON+1)+10],
		&iconn[i*(MXCON+1)+11],&iconn[i*(MXCON+1)+12]);
	  } else {
	    sscanf(top,"%d %d %lf %lf %lf %d %d %d %d %d %d %d %d %d %d %d %d %d",
		&nat[i],&iatclr[i],&coo[i*3],&coo[i*3+1],&coo[i*3+2],
		&iconn[i*(MXCON+1)],
		&iconn[i*(MXCON+1)+1],&iconn[i*(MXCON+1)+2],
		&iconn[i*(MXCON+1)+3],&iconn[i*(MXCON+1)+4],
		&iconn[i*(MXCON+1)+5],&iconn[i*(MXCON+1)+6],
		&iconn[i*(MXCON+1)+7],&iconn[i*(MXCON+1)+8],
		&iconn[i*(MXCON+1)+9],&iconn[i*(MXCON+1)+10],
		&iconn[i*(MXCON+1)+11],&iconn[i*(MXCON+1)+12]);
	  }
	  xyzp->iaton[i] = 1;
	  for (j=0; j<3; j++) 
		coo[i*3+j] = coo[i*3+j]/(*adjus);
      }
}

ogsize(int *natoms, double *coo, double *r)
{
   int i;
   double dijsq;

   for (i=0; i<*natoms; i++) {
	dijsq = coo[i*3]*coo[i*3] + 
		coo[i*3+1]*coo[i*3+1] + 
		coo[i*3+2]*coo[i*3+2];
	dijsq = dijsq / (r[0]*r[0]);
	if (dijsq > 0.0) dijsq = sqrt(dijsq);
	if (dijsq > posz) posz = dijsq;

   }
}

dist(double *coo, double *dsq)
{
  double d;

  d = coo[0]*coo[0] + coo[1]*coo[1] + coo[2]*coo[2]; 
  if (d > 0.0) d = sqrt(d);
  if (d > *dsq) *dsq = d;
}

dentr()
{
   int i;
   double t;

   for (i=0; i<*xyzp->iatoms; i++) {
	t = xyzp->coo[i*3];
	xyzp->coo[i*3] = -1.0*xyzp->coo[i*3+1];
	xyzp->coo[i*3+1] = -1.0*t;
	xyzp->coo[i*3+2] = -1.0*xyzp->coo[i*3+2];
   }
}

void ogxyz(out)
FILE *out;
{
    double tmp[3], dsq, dmaxsq, adj;
    int i,j,l,ia,ja,nc,icnn[MXCON];

    adj = *adjuss;

    fprintf(out,"[MOLECULE] UNSCALED CONN\n");
    fprintf(out,"%d\n",NAT->natoms);

    for (i=0; i< NAT->natoms; i++) {

           ia = NAT->nat[i];
	   nc = 0;

           for (j=0; j< NAT->natoms; j++) {

            ja = NAT->nat[j];

	    dsq = 0;
            for (l=0; l<3; l++) {
                tmp[l] = (XYZ->xyz[j][l] - XYZ->xyz[i][l]);
		dsq = dsq + tmp[l]*tmp[l];
	    }
            dmaxsq = (elmptr->vdwr[ia-1] + elmptr->vdwr[ja-1])/adj;
            dmaxsq = dmaxsq * dmaxsq;

	    if (i != j && dsq < dmaxsq && nc < MXCON) {
		icnn[nc] = j+1;
		nc++;
	    }

	   }

	   for (j=0; j<3; j++) 
		tmp[j] = (XYZ->xyz[i][j]-rotptr->t[j]) * adj;

	   fprintf(out,"%3d %12.6f %12.6f %12.6f %2d",
		NAT->nat[i],tmp[0],tmp[1],tmp[2],nc);
	   for (j=0; j<nc; j++) 
		fprintf(out," %5d ",icnn[j]);
	   fprintf(out,"\n");

    } 

}

woglmol(out)
FILE *out;
{
   int i,j,k, nc, doit, natoms, icnn[MXCON];
   double tmp[3],t[3];

   fprintf(out,"[MOLECULE] UNSCALED GRPCOL CONN\n");

   for (i=0; i<*xyzp->iatoms; i++) xyzp->lring[i] = 0;

   natoms = 0;

   for (i=0; i<*xyzp->iatoms; i++) {
	doit = 0;
	if (*ipdbon) {
	   if (xyzp->iresid[i] > 0) {
		if (calfptr->reson[xyzp->iresid[i]-1] == 1) doit = 1;
	   } else if (xyzp->iresid[i] < -3) {
		doit = 1;
	   }
	} else {
	   doit = 1;
	}
	if (xyzp->ianz[i] < 100 && xyzp->ianz[i] > 0 &&
	    xyzp->iaton[i] > 0 && doit) {
	    natoms++;
	    xyzp->lring[i] = natoms;
	}
   }

   fprintf(out,"%d\n",natoms);

   for (i=0; i<*xyzp->iatoms; i++) {

	nc = 0;
	for (k=0; k < xyzp->iconn[i*(MXCON+1)]; k++) {
	   j = xyzp->iconn[i*(MXCON+1)+k+1];
	   if (j >= 0) {
		if (xyzp->lring[j-1] > 0) {
		   icnn[nc] = xyzp->lring[j-1];
		   nc++;
		}
	   }
	}

	doit = 0;
	if (*ipdbon) {
	   if (xyzp->iresid[i] > 0) {
		if (calfptr->reson[xyzp->iresid[i]-1] == 1) doit = 1;
	   } else if (xyzp->iresid[i] < -3) {
		doit = 1;
	   }
	} else {
	   doit = 1;
	}

	if (xyzp->iaton[i] > 0 && doit) {
	   for (j=0; j<3; j++) 
		tmp[j] = (xyzp->coo[i*3+j]-rotptr->t[j]) * (double)toangs;
	   fprintf(out,"%3d %2d %12.6f %12.6f %12.6f %2d",
		xyzp->ianz[i],xyzp->iatclr[i],tmp[0],tmp[1],tmp[2],nc);
	   for (j=0; j<nc; j++) 
		fprintf(out," %5d ",icnn[j]);
	   fprintf(out,"\n");
	   
	}
   }
}

wrtall()
{
   int i,j,k,snd;
   char colstr[18];
   FILE *out;
   double tmp[3],adj;


   out = fopen("molden.ogl","w");
   if (out == NULL) {
      fprintf(stderr,"Couldnt open file molden.ogl\n");
      return;
   }

   fprintf(out,"[MOLDENOGL]\n");

   if (denmode) {
	adj = *adjuss;
	ogxyz(out);
   } else {
	adj = toangs;
	woglmol(out);
   }

   if (!dovrt) fprintf(stderr,"Due to failed memory allocation, written surfaces may be incomplete\n");

   for (i=0; i < NSurf[istruct]; i++) {

	if (nvert[istruct][i] > 4 && srfvert[istruct][i] != NULL) {

	   sprintf(colstr,"COLOR %3.1f %3.1f %3.1f",
		diffuseColor[istruct][i][0],
		diffuseColor[istruct][i][1],
		diffuseColor[istruct][i][2]);

	   switch(SStyp[istruct][i]) {
	   case 0:
		fprintf(out,"[SURFACE] %s \"%s\"\n",
			colstr,sndstr[istruct][i]);
		break;
	   case 1:
		fprintf(out,"[SURFACE] MAPPED %s \"%s\"\n",
			colstr,sndstr[istruct][i]);
		break;
	   case 2:
		snd = 0;
		for (j=0; j < 4; j++) {
		   if (i >= RIBindex[istruct].start[j] 
		    && i <= RIBindex[istruct].end[j]) {
	   		fprintf(out,"[RIBBON] %s %s \"%s\"\n",
				strsnd[j],colstr,sndstr[istruct][i]);
			snd = 1;
		   }
		}
		if (!snd) fprintf(out,"[ELEVATIONGRID] %s \"%s\"\n",
		   colstr,sndstr[istruct][i]);
		break;
	   }

	   for (j=0; j < nvert[istruct][i]; j++) {
		k = srfvert[istruct][i][j].type;
		if (k == 2) {
		   fprintf(out,"[HELIXIN]\n");
		} else if (k == 1) {
		   for (k=0; k < 3; k++) 
		    tmp[k] = 
			(srfvert[istruct][i][j].vert[k] - rotptr->t[k])*adj;
		   fprintf(out,"%f %f %f\n",tmp[0],tmp[1],tmp[2]);
		} else {
		   for (k=0; k < 3; k++) 
		    tmp[k] = srfvert[istruct][i][j].vert[k];
		   fprintf(out,"%f %f %f\n",tmp[0],tmp[1],tmp[2]);
		}
	   }
	}
   }

   fclose(out);
}

srfcen()
{
   int i,j,k,n;
   float cen[3],dt,dist;

   n = 0;
   for (i=0; i < 3; i++) cen[i] = 0.0;

   for (i=0; i < NSurf[istruct]; i++) {
	for (j=0; j < nvert[istruct][i]; j++) {
		k = srfvert[istruct][i][j].type;
		if (k == 1) {
		   for (k=0; k < 3; k++) 
			cen[k] = cen[k] + srfvert[istruct][i][j].vert[k];
		   n++;
		}
	}
   }

   for (i=0; i < 3; i++) rotptr->t[i] = cen[i]/(double) n;
   
   scalptr->scali = 0.0;
   for (i=0; i < NSurf[istruct]; i++) {
	for (j=0; j < nvert[istruct][i]; j++) {
		k = srfvert[istruct][i][j].type;
		if (k == 1) {
		   dist = 0.0;
		   for (k=0; k < 3; k++) {
			dt = (srfvert[istruct][i][j].vert[k] - rotptr->t[k]);
			dist = dist + dt*dt;
		   }
		   if (dist > scalptr->scali) scalptr->scali = dist;
		}
	}
   }
   scalptr->scali = sqrt(scalptr->scali);
   scalptr->scal = scalptr->scali*2.4*scalptr->smag;
   posptr->zv = scalptr->scali;
   posptr->xv = 0.0;
   posptr->yv = 0.0;
   posptr->pincr = 0.02*scalptr->scali;
   posz = scalptr->scali;
   updfog(0);

}

int rdoglfile(infile)
char *infile;
{
   double adjus, r[3];
   int conn, mopt, mapped, iorb, isurf, ityp, icolset;
   int iopt,fend,i,j,ic,ichain,elev,ribb,surf,loop,iribc,iscnd;
   char rdstr[132];
   char *colstr;
   char *namestr;
   double v[3],vt[3],vc[3],dis,cntval;
   float coltmp[3];

   if (has_opengl) {
      *ifogl = 1;
      *fancy = 1;
   } else {
      return(1);
   }

   dis = 0.0;
   posz = 0.0;
   *ipdbon = 0;
   NSurf[istruct] = 0;
   iorb = -1;
   cntval = 0.0;
   ichain = -1;

   RIBindex[istruct].nhelx = 0;
   RIBindex[istruct].nbeta = 0;
   RIBindex[istruct].nrna = 0;
   RIBindex[istruct].ncoil = 0;

   for (i=0; i<4; i++) {
	RIBindex[istruct].start[i] = -1; 
	RIBindex[istruct].end[i] = -1; 
   }

   out = fopen(infile,"r");
   if (out == NULL) {
      fprintf(stderr,"Couldnt open file %s\n",infile);
      return(1);
   }

   fgets(rdstr,100,out);
   if (strncmp(rdstr,"[MOLDENOGL]",11) != 0) {
      fprintf(stderr,"This is not an [MOLDENOGL] file !\n");
      return(1);
   }

   iopt = 0;

   while(!(fend = feof(out))) {
      fgets(rdstr,100,out);
      if (strstr(rdstr,"[MOLECULE]") == NULL) goto Surf;
      ogrdmol(rdstr,r,&adjus,xyzp->iatoms,xyzp->ianz,xyzp->iatclr,
	xyzp->coo,&mopt,&conn,xyzp->iconn);
      if (!mopt) dentr();
      ogsize(xyzp->iatoms,xyzp->coo,r);
      ogmoll(0);
#if defined(VMS) || defined(UNDERSC)
      docent();doscal();setxyv();
#else
#ifdef CRAY
      DOCENT();DOSCAL();SETXYV();
#else
      docent_();doscal_();setxyv_();
#endif
#endif
   }


Surf:

   loop = 0;

   elev = 0;
   ribb = 0;
   lines = 0;
   surf = 0;
   isurf = 1;
   ityp = 0;
   mapped = 0;

   while(!(fend = feof(out))) {

      if (loop) fgets(rdstr,100,out);
      loop = 1;
      
      if (strncmp(rdstr,"[LINES",6) == 0) {
#if defined(VMS) || defined(UNDERSC)
	if (surf) ogend();
	oglin();
#else
#ifdef CRAY
	if (surf) OGEND();
	OGLIN();
#else
	if (surf) ogend_();
	oglin_();
#endif
#endif
	surf++;
	lines = 1;
	continue;
      }

      iribc = -1;
      if (strstr(rdstr,"[COL STRANDTOP]") != NULL) iribc = 0;
      if (strstr(rdstr,"[COL STRANDBOTTOM]") != NULL) iribc = 1;
      if (strstr(rdstr,"[COL HELIXOUT]") != NULL) iribc = 2;
      if (strstr(rdstr,"[COL HELIXIN]") != NULL) iribc = 3;
      if (strstr(rdstr,"[COL RNA]") != NULL) iribc = 4;
      if (strstr(rdstr,"[COL COIL]") != NULL) iribc = 5;
      if (iribc != -1) {
	colstr = strstr(rdstr,"]");
	if (colstr != NULL) {
	   colstr = colstr + 1;
	   sscanf(colstr,"%f %f %f",&ribcol[iribc][0],
		&ribcol[iribc][1],&ribcol[iribc][2]);
	}
	continue;
      }

      if (strncmp(rdstr,"[SURFACE",8) == 0 || 
	  strncmp(rdstr,"[ELEVATION",10) == 0 || 
	  strncmp(rdstr,"[RIBBON",7) == 0) {
	lines = 0;
#if defined(VMS) || defined(UNDERSC)
	if (surf) ogendd(&ichain);
#else
#ifdef CRAY
	if (surf) OGENDD(&ichain);
#else
	if (surf) ogendd_(&ichain);
#endif
#endif
	icolset = 0;
	colstr = strstr(rdstr,"COLOR");
	if (colstr != NULL) {
	   icolset = 1;
	   colstr = colstr + 5;
	   sscanf(colstr,"%f %f %f",&coltmp[0],&coltmp[1],&coltmp[2]);
	   for (i=0; i<3; i++) {
		diffuseColor[istruct][surf][i] = coltmp[i];
		cursrfcol[isurf-1][i] = coltmp[i];
	   }
	}

	namestr = strstr(rdstr,"\"");
	if (namestr != NULL) {
	   namestr++;
	} else {
	   namestr = unknown;
	}

	if (strncmp(rdstr,"[RIBBON",7) == 0) {
           iribc = -1;
	   if (strstr(rdstr,"STRANDTOP") != NULL) iribc = 0;
	   if (strstr(rdstr,"STRANDBOTTOM") != NULL) iribc = 1;
	   if (strstr(rdstr,"HELIXOUT") != NULL) iribc = 2;
	   if (strstr(rdstr,"HELIXIN") != NULL) iribc = 3;
	   if (strstr(rdstr,"RNA") != NULL) iribc = 4;
	   if (strstr(rdstr,"COIL") != NULL) iribc = 5;

	}


	if (strstr(rdstr,"MAPPED") != NULL) {
		mapped = 1;
	} else {
		mapped = 0;
	}

	iopt = 1;
	colstr = strstr(rdstr,"TRANS");
	if (colstr != NULL) {
	   colstr = colstr + 5;
	   iopt = -iopt;
	   if (sscanf(colstr,"%lf",&tr_val) <= 0) {
		tr_val = TRDEF;
	   }
	}

	if (strncmp(rdstr,"[ELEVATION",10) == 0 ||
	    strncmp(rdstr,"[RIBBON",7) == 0) {
	   if (strncmp(rdstr,"[ELEVATION",10) == 0) {
		elev = 1;
		ogelev(namestr);
	   } else {
		ribb = 1;
		switch (iribc) {
		case 0:
		case 1:
			iscnd = 1;
			break;
		case 2:
		case 3:
			iscnd = 0;
			break;
		case 4:
			iscnd = 2;
			break;
		case 5:
			iscnd = 3;
			break;
		}
#if defined(VMS) || defined(UNDERSC)
		ogribb(&iscnd);
#else
#ifdef CRAY
		OGRIBB(&iscnd);
#else
		ogribb_(&iscnd);
#endif
#endif
		if (iribc != -1)

		   if (RIBindex[istruct].start[iscnd] == -1) 
			RIBindex[istruct].start[iscnd] = NSurf[istruct]-1; 
		   RIBindex[istruct].end[iscnd] = NSurf[istruct]-1; 

		   if (icolset) {
			for (i=0; i<3; i++) 
			   diffuseColor[istruct][NSurf[istruct]-1][i] = 
				coltmp[i];
		   } else {
			for (i=0; i<3; i++) 
			   diffuseColor[istruct][NSurf[istruct]-1][i] = 
				ribcol[iribc][i];
		   }
		}

	} else {
	   elev = 0; ribb = 0;
#if defined(VMS) || defined(UNDERSC)
	   ogbegg(&isurf,&ZERO,&ityp,&iorb,&cntval,&mapped,namestr);
#else
#ifdef CRAY
	   OGBEGG(&isurf,&ZERO,&ityp,&iorb,&cntval,&mapped,namestr);
#else
	   ogbegg_(&isurf,&ZERO,&ityp,&iorb,&cntval,&mapped,namestr);
#endif
#endif
	   isurf++;
	   if (isurf > 2) isurf = 1;
	}
	surf++;
	fgets(rdstr,100,out);
      }

      if (lines) {

/*
Yes you are right the x and y coordinates are swapped in molden
Have to fix it sometime
*/
	sscanf(rdstr,"%d %lf %lf %lf %lf %lf %lf",
		&ic,&v[1],&v[0],&v[2],&vt[1],&vt[0],&vt[2]);
	for (j=0; j<3; j++) {
	   v[j] = r[0]*v[j] / adjus;
	   vt[j] = r[0]*vt[j] / adjus;
	}

	vc[0] = ((GLdouble) colorr[ic+1]) / 65535.0 ;
	vc[1] = ((GLdouble) colorg[ic+1]) / 65535.0 ;
	vc[2] = ((GLdouble) colorb[ic+1]) / 65535.0 ;

#if defined(VMS) || defined(UNDERSC)
	ogcoll(&vc[0],&vc[1],&vc[2]);
	ogvrt(&v[0],&v[1],&v[2]);
	ogvrt(&vt[0],&vt[1],&vt[2]);
#else
#ifdef CRAY
	OGCOLL(&vc[0],&vc[1],&vc[2]);
	OGVRT(&v[0],&v[1],&v[2]);
	OGVRT(&vt[0],&vt[1],&vt[2]);
#else
	ogcoll_(&vc[0],&vc[1],&vc[2]);
	ogvrt_(&v[0],&v[1],&v[2]);
	ogvrt_(&vt[0],&vt[1],&vt[2]);
#endif
#endif
	continue;

      }

      if (mapped) {
	sscanf(rdstr,"%lf %lf %lf",&v[0],&v[1],&v[2]);
	v[0] = fabs(v[0]);
#if defined(VMS) || defined(UNDERSC)
	ogcoll(&v[0],&v[1],&v[2]);
#else
#ifdef CRAY
	OGCOLL(&v[0],&v[1],&v[2]);
#else
	ogcoll_(&v[0],&v[1],&v[2]);
#endif
#endif
        fgets(rdstr,100,out);
      }

      if (strncmp(rdstr,"[HELIXIN",8) == 0) {
#if defined(VMS) || defined(UNDERSC)
	sribcol(&THREE);
	setcll();
	if (icolset) {
	   for (i=0; i<3; i++) 
		diffuseColor[istruct][NSurf[istruct]-1][i] = coltmp[i];
	} else {
	   sribcol(&TWO);
	}
#else
#ifdef CRAY
	SRIBCOL(&THREE);
	SETCLL();
	if (icolset) {
	   for (i=0; i<3; i++) 
		diffuseColor[istruct][NSurf[istruct]-1][i] = coltmp[i];
	} else {
	   SRIBCOL(&TWO);
	}
#else
	sribcol_(&THREE);
	setcll_();
	if (icolset) {
	   for (i=0; i<3; i++) 
		diffuseColor[istruct][NSurf[istruct]-1][i] = coltmp[i];
	} else {
	   sribcol_(&TWO);
	}
#endif
#endif
        fgets(rdstr,100,out);
      }

      sscanf(rdstr,"%lf %lf %lf",&v[0],&v[1],&v[2]);
/*      for (j=0; j<3; j++) v[j] = 1.0*v[j];*/
#if defined(VMS) || defined(UNDERSC)
      ognrm(&v[0],&v[1],&v[2]);
#else
#ifdef CRAY
      OGNRM(&v[0],&v[1],&v[2]);
#else
      ognrm_(&v[0],&v[1],&v[2]);
#endif
#endif

      fgets(rdstr,100,out);
      sscanf(rdstr,"%lf %lf %lf",&v[0],&v[1],&v[2]);
      for (j=0; j<3; j++) v[j] = r[0]*v[j] / adjus;

#if defined(VMS) || defined(UNDERSC)
      ogvrt(&v[0],&v[1],&v[2]);
#else
#ifdef CRAY
      OGVRT(&v[0],&v[1],&v[2]);
#else
      ogvrt_(&v[0],&v[1],&v[2]);
#endif
#endif
      dist(v,&dis);

      if (elev || ribb) {

       for (i=0; i<3; i++) {

         fgets(rdstr,100,out);
         sscanf(rdstr,"%lf %lf %lf",&v[0],&v[1],&v[2]);
/*         for (j=0; j<3; j++) v[j] = 1.0*v[j];*/

#if defined(VMS) || defined(UNDERSC)
         ognrm(&v[0],&v[1],&v[2]);
#else
#ifdef CRAY
         OGNRM(&v[0],&v[1],&v[2]);
#else
         ognrm_(&v[0],&v[1],&v[2]);
#endif
#endif
         fgets(rdstr,100,out);
         sscanf(rdstr,"%lf %lf %lf",&v[0],&v[1],&v[2]);
	 for (j=0; j<3; j++) v[j] = r[0]*v[j] / adjus;

#if defined(VMS) || defined(UNDERSC)
         ogvrt(&v[0],&v[1],&v[2]);
#else
#ifdef CRAY
         OGVRT(&v[0],&v[1],&v[2]);
#else
         ogvrt_(&v[0],&v[1],&v[2]);
#endif
#endif
         dist(v,&dis);
        }

      }
   }

   if (dis > posz) posz = dis;
   scalptr->scali = posz;
   posptr->zv = posz;

#if defined(VMS) || defined(UNDERSC)
   ogendd(&ichain);
#else
#ifdef CRAY
   OGENDD(&ichain);
#else
   ogendd_(&ichain);
#endif
#endif

   for (i=0; i<NSurf[istruct]; i++) {
	SSon[istruct][i] = 1;
	clp[istruct][i] = 0;
	trns[istruct][i] = 0;
   }


   fclose(out);

   if (*xyzp->iatoms == 0) srfcen();

   plcnrm();

   dispsf();

   if (surf > 1) inistrc();

   UpdateSTRC();
   RedrawSTRC();

   return(0);

}
#else
int rdoglfile(infile)
char *infile;
{
   lViewer(infile);
   return(1);
}
#endif

#define TOANG 0.52917706

double calsrf(v1,v2,v3) 
double *v1;
double *v2;
double *v3;
{
   double a,b,c,s,opp, t1[3],t2[3],t3[3];
   int i;

   for (i = 0; i < 3; i++) {
	t1[i] = v1[i] - v2[i];
	t2[i] = v2[i] - v3[i];
	t3[i] = v1[i] - v3[i];
   }

   a = vln(t1);
   b = vln(t2);
   c = vln(t3);
   s = (a + b + c) / 2.0;
   opp = sqrt(s*(s-a)*(s-b)*(s-c))*TOANG*TOANG;

   return(opp);

}

double clsrf(v1,v2,v3) 
double *v1;
double *v2;
double *v3;
{
   double a,b,c,s,opp, t1[3],t2[3],t3[3];
   int i;

   for (i = 0; i < 3; i++) {
	t1[i] = v1[i] - v2[i];
	t2[i] = v2[i] - v3[i];
	t3[i] = v1[i] - v3[i];
   }

   a = vln(t1);
   b = vln(t2);
   c = vln(t3);
   s = (a + b + c) / 2.0;
   opp = sqrt(s*(s-a)*(s-b)*(s-c));

   return(opp);

}

subdivide(v1,v2,v3,c1,c2,c3,pol,pol2,psa,tsa,exs,depth)
double *v1;
double *v2;
double *v3;
double c1;
double c2;
double c3;
double pol;
double pol2;
double *psa;
double *tsa;
double *exs;
int depth;
{

   double v12[3], v23[3], v31[3], val[3], c12,c23,c31, ctot, fr, s;
   int i, ires;

   ires = 0;
   ctot = 0.0;

   if (c1 > pol)  {ires++;ctot=ctot+(c1-pol);}
   if (c2 > pol)  {ires++;ctot=ctot+(c2-pol);}
   if (c3 > pol)  {ires++;ctot=ctot+(c3-pol);}
   if (ires) ctot = ctot / (double) ires;

   if (!ires) {
	ctot = 0.0;
	if (c1 < pol2)  {ires++;ctot=ctot+(c1-pol2);}
	if (c2 < pol2)  {ires++;ctot=ctot+(c2-pol2);}
	if (c3 < pol2)  {ires++;ctot=ctot+(c3-pol2);}
	if (ires) ctot = ctot / (double) ires;
   }

/*
   if (c1 < pol)  ires++;
   if (c2 < pol)  ires++;
   if (c3 < pol)  ires++;
*/

   fr = (double) ires / 3.0;

   if (ires == 3 || !depth) {
        s = calsrf(v1,v2,v3);
	*psa = *psa + fr*s;
	*tsa = *tsa + s;
	*exs = *exs + fabs(fr*s*ctot);
	return;

   } else {

	for (i = 0; i < 3; i++) {

	   v12[i] = (v1[i] + v2[i]) / 2.0;
	   v23[i] = (v2[i] + v3[i]) / 2.0;
	   v31[i] = (v3[i] + v1[i]) / 2.0;
	}

	c12 = (c1 + c2) / 2.0;
	c23 = (c2 + c3) / 2.0;
	c31 = (c3 + c1) / 2.0;

	subdivide(v1, v12, v31, c1, c12, c31, pol, pol2, psa, tsa, exs, depth-1);
	subdivide(v2, v23, v12, c2, c23, c12, pol, pol2, psa, tsa, exs, depth-1);
	subdivide(v3, v31, v23, c3, c31, c23, pol, pol2, psa, tsa, exs, depth-1);
	subdivide(v12, v23, v31, c12, c23, c31, pol, pol2, psa, tsa, exs, depth-1);

   }

}

#if defined(VMS) || defined(UNDERSC)
calpsa(v,cval,pol,pol2,psa,tsa,exs,depth)
#else
#ifdef CRAY
CALPSA(v,cval,pol,pol2,psa,tsa,exs,depth)
#else
calpsa_(v,cval,pol,pol2,psa,tsa,exs,depth)
#endif
#endif
double v[3][3];
double *cval;
double *pol;
double *pol2;
double *psa;
double *tsa;
double *exs;
int *depth;
{
   double v1[3], v2[3], v3[3];
   int i;
  
   for (i = 0; i < 3; i++) {
	v1[i] = v[0][i];
	v2[i] = v[1][i];
	v3[i] = v[2][i];
   }
   subdivide(v1,v2,v3,cval[0],cval[1],cval[2],*pol,*pol2,psa,tsa,exs,*depth);

}

#if defined(VMS) || defined(UNDERSC)
tstpsa(cval,pol,pol2,ires)
#else
#ifdef CRAY
TSTPSA(cval,pol,pol2,ires)
#else
tstpsa_(cval,pol,pol2,ires)
#endif
#endif
double *cval;
double *pol;
double *pol2;
int *ires;
{
   *ires = 0;

   if (cval[0] > *pol)  (*ires)++;
   if (cval[1] > *pol)  (*ires)++;
   if (cval[2] > *pol)  (*ires)++;

   if (! *ires) {
	if (cval[0] < *pol2)  (*ires)++;
	if (cval[1] < *pol2)  (*ires)++;
	if (cval[2] < *pol2)  (*ires)++;
   }

/*
   if (fabs(cval[0]) > *pol)  (*ires)++;
   if (fabs(cval[1]) > *pol)  (*ires)++;
   if (fabs(cval[2]) > *pol)  (*ires)++;
*/

}

#define X .525731112119133606 
#define Z .850650808352039932
#define SCV 2.0

 

static double icosa[12][3] = {    

   {-X, 0.0, Z}, {X, 0.0, Z}, {-X, 0.0, -Z}, {X, 0.0, -Z},    

   {0.0, Z, X}, {0.0, Z, -X}, {0.0, -Z, X}, {0.0, -Z, -X},    

   {Z, X, 0.0}, {-Z, X, 0.0}, {Z, -X, 0.0}, {-Z, -X, 0.0} 

};

static int tricnt = 0;
static int curat = 0;
static int *idoa = NULL;
static int *ipola = NULL;
static int *nats;
static int *nata;
static double *vpcm;
static double icofi[1280][3][3];

static int icoind[20][3] = { 

   {0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1},    

   {8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3},    

   {7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6}, 

   {6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11} };

void normalize(v)     
double *v;
{
   double d;

   d = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); 

   if (d != 0.0) {

	v[0] /= d; v[1] /= d; v[2] /= d; 

   }


}

subd(v1,v2,v3,depth)
double *v1;
double *v2;
double *v3;
int depth;
{

   double v12[3], v23[3], v31[3];
   int i;

   if (!depth) {
	for (i = 0; i < 3; i++) {
           icofi[tricnt][0][i] = v1[i];
           icofi[tricnt][1][i] = v2[i];
           icofi[tricnt][2][i] = v3[i];
	}
	tricnt++;
	if (tricnt > 1280) 
	   fprintf(stderr,"more triangles than storage allocated\n");

	return;

   } else {

	for (i = 0; i < 3; i++) {

	   v12[i] = (v1[i] + v2[i]) / 2.0;
	   v23[i] = (v2[i] + v3[i]) / 2.0;
	   v31[i] = (v3[i] + v1[i]) / 2.0;
	}

	normalize(v12);
	normalize(v23);
	normalize(v31);

	subd(v1, v12, v31, depth-1);
	subd(v2, v23, v12, depth-1);
	subd(v3, v31, v23, depth-1);
	subd(v12, v23, v31, depth-1);

   }

}

int isfree(v1,v2,vr)
double *v1;
double *v2;
double vr;
{
  double dx,d2;
  int i;
 
  d2 = 0.0;

  for (i = 0; i < 3; i++) {
	dx = v1[i] - v2[i];
	d2 = d2 + dx*dx;
  }

  if (d2 < vr*vr) return(0);
  return(1);
  
}

int verfree(v1,v2,v3)
double *v1;
double *v2;
double *v3;
{
   int i,j, icnt, icnt1,icnt2,icnt3;
   double vr;

   icnt1 = 1;
   icnt2 = 1;
   icnt3 = 1;

   for (i=0; i < *nats; i++ ) {
	if (i != curat && idoa[i]) {
	    vr = vpcm[nata[i]-1];
	    if (nata[i] == 1 && ipola[i] == 2) vr = 1.125 / (double) toangs;
	    if (nata[i] == 1 && ipola[i] == 3) vr = 1.1 / (double) toangs;
	    if (denmode) {
		if (!isfree(v1,&XYZ->xyz[i][0],vr)) icnt1 = 0; 
		if (!isfree(v2,&XYZ->xyz[i][0],vr)) icnt2 = 0; 
		if (!isfree(v3,&XYZ->xyz[i][0],vr)) icnt3 = 0; 
	    } else {
		if (!isfree(v1,&xyzp->coo[i*3],vr)) icnt1 = 0; 
		if (!isfree(v2,&xyzp->coo[i*3],vr)) icnt2 = 0; 
		if (!isfree(v3,&xyzp->coo[i*3],vr)) icnt3 = 0; 
	    }
	}
   }

   icnt = icnt1 + icnt2 + icnt3;
   return(icnt);
}

subd2(v1,v2,v3,psa,depth)
double *v1;
double *v2;
double *v3;
double *psa;
int depth;
{

   double v12[3], v23[3], v31[3], fr, s;
   double colr[3] = {1.0,0.0,0.0};
   double colg[3] = {0.0,1.0,0.0};
   double colb[3] = {0.0,0.0,1.0};
   double *col;
   int i,j, ires;

   ires = verfree(v1,v2,v3);

   fr = (double) ires / 3.0;

   if (ires == 0 && !depth) return;

   if (ires == 3 || !depth) {
        s = calsrf(v1,v2,v3);
	*psa = *psa + fr*s;

	if (ipola[curat] >= 2) {
	    col = colb;
	} else if (ipola[curat] == 1) {
	    col = colr;
	} else {
	    col = colg;
	}
	for (j = 0; j < 3; j++) {
	   if (denmode) {
		v12[j] = XYZ->xyz[curat][j] - v1[j];
	   } else {
		v12[j] = xyzp->coo[curat*3+j] - v1[j];
	   }
	}
	normalize(v12);
#if defined(VMS) || defined(UNDERSC)
	ogcoll(&col[0],&col[1],&col[2]);
	ognrm(&v12[0],&v12[1],&v12[2]);
	ogvrt(&v1[0],&v1[1],&v1[2]);
#else
#ifdef CRAY
	OGCOLL(&col[0],&col[1],&col[2]);
	OGNRM(&v12[0],&v12[1],&v12[2]);
	OGVRT(&v1[0],&v1[1],&v1[2]);
#else
	ogcoll_(&col[0],&col[1],&col[2]);
	ognrm_(&v12[0],&v12[1],&v12[2]);
	ogvrt_(&v1[0],&v1[1],&v1[2]);
#endif
#endif

	for (j = 0; j < 3; j++) {
	   if (denmode) {
		v12[j] = XYZ->xyz[curat][j] - v2[j];
	   } else {
		v12[j] = xyzp->coo[curat*3+j] - v2[j];
	   }
	}
	normalize(v12);
#if defined(VMS) || defined(UNDERSC)
	ogcoll(&col[0],&col[1],&col[2]);
	ognrm(&v12[0],&v12[1],&v12[2]);
	ogvrt(&v2[0],&v2[1],&v2[2]);
#else
#ifdef CRAY
	OGCOLL(&col[0],&col[1],&col[2]);
	OGNRM(&v12[0],&v12[1],&v12[2]);
	OGVRT(&v2[0],&v2[1],&v2[2]);
#else
	ogcoll_(&col[0],&col[1],&col[2]);
	ognrm_(&v12[0],&v12[1],&v12[2]);
	ogvrt_(&v2[0],&v2[1],&v2[2]);
#endif
#endif

	for (j = 0; j < 3; j++) {
	   if (denmode) {
		v12[j] = XYZ->xyz[curat][j] - v3[j];
	   } else {
		v12[j] = xyzp->coo[curat*3+j] - v3[j];
	   }
	}
	normalize(v12);
#if defined(VMS) || defined(UNDERSC)
	ogcoll(&col[0],&col[1],&col[2]);
	ognrm(&v12[0],&v12[1],&v12[2]);
	ogvrt(&v3[0],&v3[1],&v3[2]);
#else
#ifdef CRAY
	OGCOLL(&col[0],&col[1],&col[2]);
	OGNRM(&v12[0],&v12[1],&v12[2]);
	OGVRT(&v3[0],&v3[1],&v3[2]);
#else
	ogcoll_(&col[0],&col[1],&col[2]);
	ognrm_(&v12[0],&v12[1],&v12[2]);
	ogvrt_(&v3[0],&v3[1],&v3[2]);
#endif
#endif

	return;

   } else {

	for (i = 0; i < 3; i++) {

	   v12[i] = (v1[i] + v2[i]) / 2.0;
	   v23[i] = (v2[i] + v3[i]) / 2.0;
	   v31[i] = (v3[i] + v1[i]) / 2.0;
	}

	subd2(v1, v12, v31, psa, depth-1);
	subd2(v2, v23, v12, psa, depth-1);
	subd2(v3, v31, v23, psa, depth-1);
	subd2(v12, v23, v31, psa, depth-1);

   }

}


double icosah(coo,scl)
double *coo;
double scl;
{
   int i,j;
   double v1[3], v2[3], v3[3], psa, d2, dx, vr, vr2;

   psa = 0.0;

   vr = scl;

   for (i=0; i < *nats; i++ ) {
	d2 = 0.0;
	for (j = 0; j < 3; j++) {
	   if (denmode) {
	      dx = coo[j] - XYZ->xyz[i][j];
	   } else {
	      dx = coo[j] - xyzp->coo[i*3+j];
	   }
	   d2 = d2 + dx*dx;
	}
	vr2 = vpcm[nata[i]-1];
	if (nata[i] == 1 && ipola[i] == 2) vr2 = 1.125 / (double) toangs;
	if (nata[i] == 1 && ipola[i] == 3) vr2 = 1.1 / (double) toangs;
	vr2 = vr2 + vr;
	idoa[i] = 0;
	if (d2 < vr2*vr2) idoa[i] = 1;
   }

   for (i = 0; i < 1280; i++) {    
	for (j = 0; j < 3; j++) {    
	   v1[j] = coo[j] + scl*icofi[i][0][j];
	   v2[j] = coo[j] + scl*icofi[i][1][j];
	   v3[j] = coo[j] + scl*icofi[i][2][j];
	}
	subd2(v1, v2, v3, &psa, 3);
   }
   fprintf(stderr,"psa atom %4d: %8.3f\n",curat+1,psa);
   return(psa);
}

#if defined(VMS) || defined(UNDERSC)
tpsa()
#else
#ifdef CRAY
TPSA()
#else
tpsa_()
#endif
#endif
{
   int i,j,k, ichain, mapped, oglon;
   double psa,tsa,vr, vr2, v1[3],v2[3],v3[3],dx,d2,s;
   char *namestr = "Topol. Pol. surface";
  
   if (denmode) {
	nats = &NAT->natoms;
	nata = NAT->nat;
   } else {
	nats = xyzp->iatoms;
	nata = xyzp->ianz;
   }

   ichain = -1;
   mapped = 1;
   tsa = 0.0;
   psa = 0.0;

   tricnt = 0;

   for (i = 0; i < 20; i++) {    

	for (j = 0; j < 3; j++) {    
	   v1[j] = icosa[icoind[i][0]][j];
	   v2[j] = icosa[icoind[i][1]][j];
	   v3[j] = icosa[icoind[i][2]][j];
	}
	subd(v1, v2, v3, 3);

   }

   if ((idoa = (int *) malloc((sizeof i)*(*nats))) == NULL) {
	fprintf(stderr,"failed to allocate memory\n");
	return;
   }

   if ((ipola = (int *) malloc((sizeof i)*(*nats))) == NULL) {
	fprintf(stderr,"failed to allocate memory\n");
	return;
   }

   if ((vpcm = (double *) malloc((sizeof vr)*MXEL)) == NULL) {
	fprintf(stderr,"failed to allocate memory\n");
	return;
   }

   for (i=0; i < MXEL; i++ ) {
	vpcm[i] = SCV*elmptr->vdwr[i]/(double) toangs;
   }

   vpcm[0] = 1.5 / (double) toangs;
   vpcm[5] = 1.92 / (double) toangs;
   vpcm[6] = 1.82 / (double) toangs;
   vpcm[7] = 1.74 / (double) toangs;

   for (i=0; i < *nats; i++ ) {
	ipola[i] = 0;
	if (nata[i] == 8 || nata[i] == 7) ipola[i] = 1;
	if (nata[i] == 1) {
	   vr = elmptr->vdwr[nata[i]-1]/(double) toangs;
	   for (j=0; j < *nats; j++ ) {
		d2 = 0.0;
		for (k = 0; k < 3; k++) {
		   if (denmode) {
			dx = XYZ->xyz[j][k] - XYZ->xyz[i][k];
		   } else {
			dx = xyzp->coo[j*3+k] - xyzp->coo[i*3+k];
		   }
		   d2 = d2 + dx*dx;
		}
		vr2 = elmptr->vdwr[nata[j]-1]/(double) toangs;
		vr2 = vr2 + vr;
		if (d2 < vr2*vr2 && nata[j] == 7) ipola[i] = 2;
		if (d2 < vr2*vr2 && nata[j] == 8) ipola[i] = 3;
	   }
	}
   }


/*
  SCV scale vdw radii to be compatible with publication by Palm
  they took their radii from PCmodel
*/

#if defined(VMS) || defined(UNDERSC)
   curs(&ONE);
   ogbegg(&ichain,&ZERO,&THREE,&i,&tsa,&mapped,namestr);
#else
#ifdef CRAY
   CURS(&ONE);
   OGBEGG(&ichain,&ZERO,&THREE,&i,&tsa,&mapped,namestr);
#else
   curs_(&ONE);
   ogbegg_(&ichain,&ZERO,&THREE,&i,&tsa,&mapped,namestr);
#endif
#endif

   for (i=0; i < *nats; i++ ) {
	curat = i;
	vr = vpcm[nata[i]-1];
	if (nata[i] == 1 && ipola[i] == 2) vr = 1.125 / (double) toangs;
	if (nata[i] == 1 && ipola[i] == 3) vr = 1.1 / (double) toangs;
	if (denmode) {
	   s = icosah(&XYZ->xyz[i][0],vr);
	} else {
	   s = icosah(&xyzp->coo[i*3],vr);
	}
	tsa = tsa + s;
	if (ipola[i]) psa = psa + s;
   }

#if defined(VMS) || defined(UNDERSC)
   ogendd(&ichain);
   curs(&ZERO);
#else
#ifdef CRAY
   OGENDD(&ichain);
   CURS(&ZERO);
#else
   ogendd_(&ichain);
   curs_(&ZERO);
#endif
#endif
   fprintf(stderr,"\nTotal Topological Polar Surface Area: %8.3f\n",psa);
   fprintf(stderr,"Total surface: %8.3f\n",tsa);

   free(ipola);
   free(idoa);
   free(vpcm);
   ipola = NULL;
   idoa = NULL;
   vpcm = NULL;

#ifdef DOGL
   oglon = (*fancy || *fullgl);
   if (denmode) oglon = *ifdogl;
   if (oglon && has_opengl) dispsf();
#endif
}

/*
mxpeak 2^^mxcpl
*/


fndhnmr(iat,jcut,hcont,ncont)
int iat;
float jcut;
int *hcont;
int *ncont;
{
    int i,j,k,l,jat;
    float jc,nuc1;

    *ncont = 0;
    nuc1 = (float) nmrptr->nucshld[iat];

    jat = -1;
    for (i=0; i < xyzp->iconn[iat*(MXCON+1)]; i++) {
	jat = xyzp->iconn[iat*(MXCON+1)+i+1] - 1;
	if (jat >= 0) break;
    }
    if (jat < 0) return;

    for (i=0; i < xyzp->iconn[jat*(MXCON+1)]; i++) {
	j = xyzp->iconn[jat*(MXCON+1)+i+1];
	if (j >= 0) {
	    if (xyzp->ianz[j-1] == 1) {
		if (j-1 > iat) {
		   jc = (float) jcoupl[(j-1)*NAT->natoms + iat];
		} else {
		   jc = (float) jcoupl[iat*NAT->natoms + j-1];
		}
		if (ABS(jc) > jcut && nuc1 != (float) nmrptr->nucshld[j-1]) {
		   hcont[*ncont] = j - 1;
		   (*ncont)++;
		}
	    } else {
		for (k=0; k < xyzp->iconn[(j-1)*(MXCON+1)]; k++) {
		   l = xyzp->iconn[(j-1)*(MXCON+1)+k+1];
		   if (l >= 0 && l != jat) {
			if (xyzp->ianz[l-1] == 1) {
			    if (l-1 > iat) {
				jc = (float) jcoupl[(l-1)*NAT->natoms + iat];
			    } else {
				jc = (float) jcoupl[iat*NAT->natoms + l-1];
			    }
			    if (ABS(jc) > jcut && nuc1 != (float) nmrptr->nucshld[l-1]) {
				hcont[*ncont] = l - 1;
				(*ncont)++;
			    }
			}
		   }
		}
	    }
	}
    }
}

javch3(ih)
int *ih;
{
    int i,j,jj;
    double jav;

    for (i=0; i < NAT->natoms; i++) {
	jav = 0.0;
	for (j=0; j < 3; j++) {
		if (ih[j] > i) {
		   jav = jav + jcoupl[ih[j]*NAT->natoms + i];
		} else {
		   jav = jav + jcoupl[i    *NAT->natoms + ih[j]];
		}
	}
	jav = jav / 3.0;
	for (j=0; j < 3; j++) {
		if (ih[j] > i) {
		   jcoupl[ih[j]*NAT->natoms + i]     = jav;
		} else {
		   jcoupl[i    *NAT->natoms + ih[j]] = jav;
		}
	}
    }
}

avch3()
{
    int i,j,jj,nh,ih[3];
    double nucav;

    for (i=0; i < NAT->natoms; i++) {

	if (xyzp->ianz[i] == 6) {

	    nh = 0;
	    nucav = 0.0;

	    for (j=0; j < xyzp->iconn[i*(MXCON+1)]; j++) {

		jj = xyzp->iconn[i*(MXCON+1)+j+1]-1;
		if (jj >= 0) {
		   if (xyzp->ianz[jj] == 1) {
			ih[nh] = jj;
			nh++;
			nucav = nucav + nmrptr->nucshld[jj];
		   }
		}
	    }
	    if (nh == 3) {
		nucav = nucav / 3.0;
	        for (j=0; j < nh; j++) nmrptr->nucshld[ih[j]] = nucav;
		javch3(ih);
	    }
	}
    }
}

nmrsplit(tpeaks,tinten,npeaks,splt)
float *tpeaks;
double *tinten;
int *npeaks;
float splt;
{
  int i,j,ntp; 
  float tp;
  double ti;

  ntp = *npeaks;

  for (i=0; i < *npeaks; i++) {
	tp = tpeaks[i];
	ti = tinten[i]/2.0;
	tpeaks[i] = tp + splt;
	tinten[i] = ti;
	tpeaks[ntp] = tp - splt;
	tinten[ntp] = ti;
	ntp++;
  }
  *npeaks = ntp;
}

prep_nmr() {

  int i, j, ncl_peaks,npeaks,cl_peaks[mxcpl];
  float f, splt;
  float tpeaks[mxpeak];
  double d,tinten[mxpeak];

  NMRup = 1;

  if (peaks == NULL) {
     if ((peaks = (float *) malloc((sizeof f)*NAT->natoms*mxpeak)) == NULL) {
	fprintf(stderr, "Memory allocation error for nmr spectrum\n");
	return;
     }

     if ((inten = (double *) malloc((sizeof d)*NAT->natoms*mxpeak)) == NULL) {
	fprintf(stderr, "Memory allocation error for nmr spectrum\n");
	return;
     }
  }

  npks = 0;

  for (i=0; i < NAT->natoms; i++) {

    if (xyzp->ianz[i] == NMRnuc) {

	tpeaks[0] = *nmrref - (float) nmrptr->nucshld[i];
	tinten[0] = 1.0;
	npeaks = 1;

	if (NMRnuc == 1 && nmrptr->ihsnmr == 2) {
	    fndhnmr(i,jcut,cl_peaks,&ncl_peaks);
	    for (j=0; j < ncl_peaks; j++) {

		if (cl_peaks[j] > i) {
		    splt = (float) jcoupl[cl_peaks[j]*NAT->natoms + i]/NMRbas;
		} else {
		    splt = (float) jcoupl[i*NAT->natoms + cl_peaks[j]]/NMRbas;
		}

		nmrsplit(tpeaks,tinten,&npeaks,splt);
	    }
	}

	for (j=0; j < npeaks; j++) {
	   peaks[npks] = tpeaks[j];
	   inten[npks] = tinten[j];
           npks++;
	}
    }
  }

}

click_nmr_spec(indx) 
int indx;
{
    int i,iat;
    float frq,dfrq,dfrqmn;

    if (indx < 0 || indx >= NAT->natoms*mxpeak) return;

    frq = spfrq[indx];
    dfrqmn = 10000.0;
    iat = -1;
   
    for (i=0; i < NAT->natoms; i++) {
	if (xyzp->ianz[i] == NMRnuc) {
	    dfrq = ABS(frq - (*nmrref - (float) nmrptr->nucshld[i]));
	    if (dfrq < dfrqmn) {
		dfrqmn = dfrq;
		iat = i;
	    }
	}
    }

    if (iat != -1) {
	for (i=0; i < NAT->natoms; i++) xyzp->iaton[i] = 1;

	for (i=0; i < NAT->natoms; i++) {
	    if (xyzp->ianz[i] == NMRnuc) {
		dfrq = ABS(frq - (*nmrref - (float) nmrptr->nucshld[i]));
		if (dfrq == dfrqmn) {
		    xyzp->iaton[i] = 3;
		}
	    }
	}

	update_sel = 1;
	update_model = 0;
	update_struct();
    }

}

void FRQextr()
{
    int i;

    min_freq = 100000;
    max_freq = -100000;
    for (i=0; i < npks; i++) {
	   if (spfrq[i] < min_freq) min_freq = (int) spfrq[i];
	   if (spfrq[i] > max_freq) max_freq = (int) spfrq[i];
    }
    if (min_freq > 0) min_freq = 0;

    if (spmode) {
	if (max_freq < 220) max_freq = 220;
    } else {
	if (max_freq < 10) max_freq = 10;
    }
}

getrad(t,coo,iatoms,dret)
double *t;
double* coo;
int *iatoms;
double *dret;
{
   double d2,dx,dmx;
   int j,k;

   dmx = 0.0;

   for (j=0; j < *iatoms; j++ ) {
	d2 = 0.0;
	for (k = 0; k < 3; k++) {
	    dx = t[k] - coo[j*3+k];
	    d2 = d2 + dx*dx;
	}
	if (d2 > dmx) dmx = d2;
   }
   dmx = sqrt(dmx);
   *dret = dmx;
}

/*
prtcad_()
{
   prtcal_(calfptr->icalf,&calfptr->ncalf,calfptr->ianf,calfptr->islu,
	&calfptr->nchain,calfptr->iamino,calfptr->isal);
}
*/

prt_(iop)
int *iop;
{
   int i,it,j,k;

   fprintf(stderr,"iop %d multstr %d\n",*iop,*multstruct);
/*
   it = calfptr->icalf[12][0]-1;
   fprintf(stderr,"%d icalf(1,13) %d coo %f  %f %f\n",*iop,it+1,
			xyzp->coo[it*3],xyzp->coo[it*3+1],
			xyzp->coo[it*3+2]);
   fprintf(stderr,"%d ATMsel %d coo %f  %f %f\n",*iop,ATMsel+1,
			xyzp->coo[ATMsel*3],xyzp->coo[ATMsel*3+1],
			xyzp->coo[ATMsel*3+2]);
*/
   
}

#ifdef DOGL

rubber(iopt)
int iopt;
{
   GLfloat x1,y1,x2,y2;
   int v2dx,v2dy;

   glDisable(GL_LIGHTING);           
   glDisable(GL_DEPTH_TEST);         
   glDepthMask(GL_FALSE);            

   glLineWidth(1.0);

   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();

   gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
   glRasterPos2f(-1.0,-1.0);

   if (iopt) {
	v2dx = width;
	v2dy = height;
   } else {
	v2dx = width;
	v2dy = width;
	if (v2dx > height) {
	   v2dx = height;
	   v2dy = height;
	}
   }

   glReadBuffer(GL_BACK);
   glDrawBuffer(GL_FRONT);
   glCopyPixels(0,0,v2dx,v2dy,GL_COLOR);
   glFlush();

   x1 = 2.0*((float) ZoomX1/(float) v2dx) - 1.0;
   y1 = 2.0*((float) (v2dy - ZoomY1 )/(float) v2dy) - 1.0;
   x2 = 2.0*( ((float) ZoomX1 + (float) ZoomW)/(float) v2dx) - 1.0;
   y2 = 2.0*( ((float) v2dy - (float) ZoomY1 - (float) ZoomH) /(float) v2dy) - 1.0;
   glDisable(GL_COLOR_MATERIAL);

   if (StarNet) {
	   theDens = glGenLists(1);
	   glNewList(theDens, GL_COMPILE_AND_EXECUTE);
   }

   glBegin(GL_LINE_LOOP);
   glColor3f(1.0f, 1.0f, 1.0f);
   glVertex2f(x1,y1);
   glVertex2f(x2,y1);
   glVertex2f(x2,y2);
   glVertex2f(x1,y2);
   glVertex2f(x1,y1);
   glEnd();

   if (StarNet) {
	glEndList();
	glDeleteLists(theDens,1);
   }

   glFlush();
   glDrawBuffer(GL_BACK);

   glEnable(GL_DEPTH_TEST);           
   glDepthMask(GL_TRUE);              
   glEnable(GL_LIGHTING);             

   glMatrixMode (GL_PROJECTION);
   glPopMatrix();                     
   glMatrixMode(GL_MODELVIEW);
   glPopMatrix();                     

}

plcnrm()
{
   int isrf,i,j;
   float n[3],v[3];
   isrf = NSurf[istruct]-1;

   theNorm = glGenLists(1);
   glNewList(theNorm, GL_COMPILE);
   glDisable(GL_LIGHTING);
   glLineWidth(1.0);
   glEnable(GL_LINE_SMOOTH);
   glBegin(GL_LINES);

   for (i = 0; i < nvert[istruct][isrf]; i++) {
	if (srfvert[istruct][isrf][i].type == 1) {
	   v[0] = srfvert[istruct][isrf][i].vert[0];
	   v[1] = srfvert[istruct][isrf][i].vert[1];
	   v[2] = srfvert[istruct][isrf][i].vert[2];
	   glVertex3d(v[0],v[1],v[2]);
	   for (j = 0; j < 3; j++) v[j] = v[j] + n[j];
	   glVertex3d(v[0],v[1],v[2]);
/*	   fprintf(stderr,"1 %f %f %f\n",v[0],v[1],v[2]);*/
	} else {
	   n[0] = srfvert[istruct][isrf][i].vert[0];
	   n[1] = srfvert[istruct][isrf][i].vert[1];
	   n[2] = srfvert[istruct][isrf][i].vert[2];
/*	   fprintf(stderr,"0 %f %f %f\n",n[0],n[1],n[2]);*/
	}
   }

   glEnd();
   glEnable(GL_LIGHTING);
   glEndList();
}



typedef struct {
	unsigned char idLength;
	unsigned char colorMapType;
	unsigned char imageTypeCode;
	unsigned char colorMapSpec[5];
	unsigned short xOrigin;
	unsigned short yOrigin; 
	unsigned short width;
	unsigned short height;
	unsigned char bpp;
	unsigned char imageDesc;
} tga_header;

tga_header tgaheader;
static FILE *TGAFile;
unsigned char *imageData;

Load_TGA(filename)
    char *filename;
{
    int i;
    unsigned int color_mode=GL_RGB;

    TGAFile = fopen(filename,"r");

    if (!TGAFile) {
	fprintf(stderr,"Output Error: Unable to read TGA file %s\n",filename);
	return;
    }

    if (fread((char *) &tgaheader, 18, 1, TGAFile) != 1)
       fprintf(stderr,"error reading header\n");

    int imageSize = tgaheader.width * tgaheader.height * (tgaheader.bpp/8);
    imageData = (char*) malloc(imageSize);
 
    fprintf(stderr,"tga: width %d height %d bpp %d\n",tgaheader.width,tgaheader.height,tgaheader.bpp);

    if (fread((char *) imageData, sizeof(char)*imageSize, 1, TGAFile) != 1) 
	fprintf(stderr,"error reading tga data\n");

    if (tgaheader.bpp == 24) {
	for (i = 0; i < imageSize; i+=3) {       
	   char c = imageData[i];
	   imageData[i] = imageData[i+2];
	   imageData[i+2] = c;
	}
    } else {
	if (tgaheader.bpp == 32) {
	   for (i = 0; i < imageSize; i+=4) {       
		char c = imageData[i];
		imageData[i] = imageData[i+2];
		imageData[i+2] = c;
	   }
	   color_mode = GL_RGBA;
	}
    }
 
    fclose(TGAFile);

    glGenTextures(1,&rndid);
    glBindTexture(GL_TEXTURE_2D,rndid);

    glTexImage2D(GL_TEXTURE_2D,0,color_mode,tgaheader.width,tgaheader.height,
	0,color_mode,GL_UNSIGNED_BYTE,imageData);

}

#else
plcnrm()
{
}
#endif
