correction of gen_rand_conf and preminim
[unres4.git] / source / unres / geometry.F90
1                       module geometry
2 !-----------------------------------------------------------------------------
3       use io_units
4       use names
5       use math
6       use MPI_data
7       use geometry_data
8       use control_data
9       use energy_data
10       implicit none
11 !-----------------------------------------------------------------------------
12 ! commom.bounds
13 !      common /bounds/
14 !-----------------------------------------------------------------------------
15 ! commom.chain
16 !      common /chain/
17 !      common /rotmat/
18       real(kind=8),dimension(:,:,:),allocatable :: t,r !(3,3,maxres)
19 !-----------------------------------------------------------------------------
20 ! common.geo
21 !      common /geo/
22 !-----------------------------------------------------------------------------
23 ! common.locmove
24 !     Variables (set in init routine) never modified by local_move
25 !      common /loc_const/
26       integer :: init_called
27       logical :: locmove_output
28       real(kind=8) :: min_theta, max_theta
29       real(kind=8) :: dmin2,dmax2
30       real(kind=8) :: flag,small,small2
31 !     Workspace for local_move
32 !      common /loc_work/
33       integer :: a_n,b_n,res_n
34       real(kind=8),dimension(0:7) :: a_ang
35       real(kind=8),dimension(0:3) :: b_ang
36       real(kind=8),dimension(0:11) :: res_ang
37       logical,dimension(0:2,0:7) :: a_tab
38       logical,dimension(0:2,0:3) :: b_tab
39       logical,dimension(0:2,0:2,0:11) :: res_tab
40 !-----------------------------------------------------------------------------
41 !      integer,dimension(:),allocatable :: itype_pdb !(maxres) initialize in molread
42 !-----------------------------------------------------------------------------
43 !
44 !
45 !-----------------------------------------------------------------------------
46       contains
47 !-----------------------------------------------------------------------------
48 ! arcos.f
49 !-----------------------------------------------------------------------------
50       real(kind=8) function ARCOS(X)
51 !      implicit real*8 (a-h,o-z)
52 !      include 'COMMON.GEO'
53 !el local variables
54       real(kind=8) :: x
55       IF (DABS(X).LT.1.0D0) GOTO 1
56       ARCOS=PIPOL*(1.0d0-DSIGN(1.0D0,X))
57       RETURN
58     1 ARCOS=DACOS(X)
59       return
60       end function ARCOS
61 !-----------------------------------------------------------------------------
62 ! chainbuild.F
63 !-----------------------------------------------------------------------------
64       subroutine chainbuild
65
66 ! Build the virtual polypeptide chain. Side-chain centroids are moveable.
67 ! As of 2/17/95.
68 !
69 !      implicit real*8 (a-h,o-z)
70 !      include 'DIMENSIONS'
71 !      include 'COMMON.CHAIN'
72 !      include 'COMMON.LOCAL'
73 !      include 'COMMON.GEO'
74 !      include 'COMMON.VAR'
75 !      include 'COMMON.IOUNITS'
76 !      include 'COMMON.NAMES'
77 !      include 'COMMON.INTERACT'
78       logical :: lprn
79 !el local variables
80       integer :: i,j
81       real(kind=8) :: be,be1,alfai
82       integer :: nres2
83       nres2=2*nres
84 ! Set lprn=.true. for debugging
85       lprn = .false.
86       print *,"I ENTER CHAINBUILD"
87 !
88 ! Define the origin and orientation of the coordinate system and locate the
89 ! first three CA's and SC(2).
90 !
91 !elwrite(iout,*)"in chainbuild"
92       call orig_frame
93 !elwrite(iout,*)"after orig_frame"
94 !
95 ! Build the alpha-carbon chain.
96 !
97       do i=4,nres
98         call locate_next_res(i)
99       enddo     
100 !elwrite(iout,*)"after locate_next_res"
101 !
102 ! First and last SC must coincide with the corresponding CA.
103 !
104       do j=1,3
105         dc(j,nres+1)=0.0D0
106         dc_norm(j,nres+1)=0.0D0
107         dc(j,nres+nres)=0.0D0
108         dc_norm(j,nres+nres)=0.0D0
109         c(j,nres+1)=c(j,1)
110         c(j,nres+nres)=c(j,nres)
111       enddo
112 !
113 ! Temporary diagnosis
114 !
115       if (lprn) then
116
117       call cartprint
118       write (iout,'(/a)') 'Recalculated internal coordinates'
119       do i=2,nres-1
120         do j=1,3
121           c(j,nres2+2)=0.5D0*(c(j,i-1)+c(j,i+1))        !maxres2=2*maxres
122         enddo
123         be=0.0D0
124         if (i.gt.3) be=rad2deg*beta(i-3,i-2,i-1,i)
125         be1=rad2deg*beta(nres+i,i,nres2+2,i+1)
126         alfai=0.0D0
127         if (i.gt.2) alfai=rad2deg*alpha(i-2,i-1,i)
128         write (iout,1212) restyp(itype(i,1),1),i,dist(i-1,i),&
129         alfai,be,dist(nres+i,i),rad2deg*alpha(nres+i,i,nres2+2),be1
130       enddo   
131  1212 format (a3,'(',i3,')',2(f10.5,2f10.2))
132
133       endif
134
135       return
136       end subroutine chainbuild
137 !-----------------------------------------------------------------------------
138       subroutine orig_frame
139 !
140 ! Define the origin and orientation of the coordinate system and locate 
141 ! the first three atoms.
142 !
143 !      implicit real*8 (a-h,o-z)
144 !      include 'DIMENSIONS'
145 !      include 'COMMON.CHAIN'
146 !      include 'COMMON.LOCAL'
147 !      include 'COMMON.GEO'
148 !      include 'COMMON.VAR'
149 !el local variables
150       integer :: i,j
151       real(kind=8) :: cost,sint
152
153 !el      allocate(t(3,3,nres))  !(3,3,maxres) 
154 !el      allocate(r(3,3,nres))  !(3,3,maxres) 
155 !el      allocate(rt(3,3,nres)) !(3,3,maxres) 
156 !el      allocate(dc_norm(3,0:2*nres))  !(3,0:maxres2)
157 !el      allocate(prod(3,3,nres))       !(3,3,maxres) 
158
159       cost=dcos(theta(3))
160       sint=dsin(theta(3))
161       t(1,1,1)=-cost
162       t(1,2,1)=-sint 
163       t(1,3,1)= 0.0D0
164       t(2,1,1)=-sint
165       t(2,2,1)= cost
166       t(2,3,1)= 0.0D0
167       t(3,1,1)= 0.0D0
168       t(3,2,1)= 0.0D0
169       t(3,3,1)= 1.0D0
170       r(1,1,1)= 1.0D0
171       r(1,2,1)= 0.0D0
172       r(1,3,1)= 0.0D0
173       r(2,1,1)= 0.0D0
174       r(2,2,1)= 1.0D0
175       r(2,3,1)= 0.0D0
176       r(3,1,1)= 0.0D0
177       r(3,2,1)= 0.0D0
178       r(3,3,1)= 1.0D0
179       do i=1,3
180         do j=1,3
181           rt(i,j,1)=t(i,j,1)
182         enddo
183       enddo
184       do i=1,3
185         do j=1,3
186           prod(i,j,1)=0.0D0
187           prod(i,j,2)=t(i,j,1)
188         enddo
189         prod(i,i,1)=1.0D0
190       enddo   
191       c(1,1)=0.0D0
192       c(2,1)=0.0D0
193       c(3,1)=0.0D0
194       c(1,2)=vbld(2)
195       c(2,2)=0.0D0
196       c(3,2)=0.0D0
197       dc(1,0)=0.0d0
198       dc(2,0)=0.0D0
199       dc(3,0)=0.0D0
200       dc(1,1)=vbld(2)
201       dc(2,1)=0.0D0
202       dc(3,1)=0.0D0
203       dc_norm(1,0)=0.0D0
204       dc_norm(2,0)=0.0D0
205       dc_norm(3,0)=0.0D0
206       dc_norm(1,1)=1.0D0
207       dc_norm(2,1)=0.0D0
208       dc_norm(3,1)=0.0D0
209       do j=1,3
210         dc_norm(j,2)=prod(j,1,2)
211         dc(j,2)=vbld(3)*prod(j,1,2)
212         c(j,3)=c(j,2)+dc(j,2)
213       enddo
214       call locate_side_chain(2)
215       return
216       end subroutine orig_frame
217 !-----------------------------------------------------------------------------
218       subroutine locate_next_res(i)
219 !
220 ! Locate CA(i) and SC(i-1)
221 !
222 !      implicit real*8 (a-h,o-z)
223 !      include 'DIMENSIONS'
224 !      include 'COMMON.CHAIN'
225 !      include 'COMMON.LOCAL'
226 !      include 'COMMON.GEO'
227 !      include 'COMMON.VAR'
228 !      include 'COMMON.IOUNITS'
229 !      include 'COMMON.NAMES'
230 !      include 'COMMON.INTERACT'
231 !
232 ! Define the rotation matrices corresponding to CA(i)
233 !
234 !el local variables
235       integer :: i,j    
236       real(kind=8) :: theti,phii
237       real(kind=8) :: cost,sint,cosphi,sinphi
238 #ifdef OSF
239 #ifdef WHAM_RUN
240       theti=theta(i)
241       icrc=0
242       call proc_proc(theti,icrc)
243       if(icrc.eq.1)theti=100.0
244       phii=phi(i)
245       icrc=0
246       call proc_proc(phii,icrc)
247       if(icrc.eq.1)phii=180.0
248 #else
249       theti=theta(i)
250       if (theti.ne.theti) theti=100.0     
251       phii=phi(i)
252       if (phii.ne.phii) phii=180.0     
253 #endif
254 #else
255       theti=theta(i)      
256       phii=phi(i)
257 #endif
258       cost=dcos(theti)
259       sint=dsin(theti)
260       cosphi=dcos(phii)
261       sinphi=dsin(phii)
262 ! Define the matrices of the rotation about the virtual-bond valence angles
263 ! theta, T(i,j,k), virtual-bond dihedral angles gamma (miscalled PHI in this
264 ! program), R(i,j,k), and, the cumulative matrices of rotation RT
265       t(1,1,i-2)=-cost
266       t(1,2,i-2)=-sint 
267       t(1,3,i-2)= 0.0D0
268       t(2,1,i-2)=-sint
269       t(2,2,i-2)= cost
270       t(2,3,i-2)= 0.0D0
271       t(3,1,i-2)= 0.0D0
272       t(3,2,i-2)= 0.0D0
273       t(3,3,i-2)= 1.0D0
274       r(1,1,i-2)= 1.0D0
275       r(1,2,i-2)= 0.0D0
276       r(1,3,i-2)= 0.0D0
277       r(2,1,i-2)= 0.0D0
278       r(2,2,i-2)=-cosphi
279       r(2,3,i-2)= sinphi
280       r(3,1,i-2)= 0.0D0
281       r(3,2,i-2)= sinphi
282       r(3,3,i-2)= cosphi
283       rt(1,1,i-2)=-cost
284       rt(1,2,i-2)=-sint
285       rt(1,3,i-2)=0.0D0
286       rt(2,1,i-2)=sint*cosphi
287       rt(2,2,i-2)=-cost*cosphi
288       rt(2,3,i-2)=sinphi
289       rt(3,1,i-2)=-sint*sinphi
290       rt(3,2,i-2)=cost*sinphi
291       rt(3,3,i-2)=cosphi
292       call matmult(prod(1,1,i-2),rt(1,1,i-2),prod(1,1,i-1))
293       do j=1,3
294         dc_norm(j,i-1)=prod(j,1,i-1)
295         dc(j,i-1)=vbld(i)*prod(j,1,i-1)
296         c(j,i)=c(j,i-1)+dc(j,i-1)
297       enddo
298 !d    print '(2i3,2(3f10.5,5x))', i-1,i,(dc(j,i-1),j=1,3),(c(j,i),j=1,3)
299
300 ! Now calculate the coordinates of SC(i-1)
301 !
302       call locate_side_chain(i-1)
303       return
304       end subroutine locate_next_res
305 !-----------------------------------------------------------------------------
306       subroutine locate_side_chain(i)
307
308 ! Locate the side-chain centroid i, 1 < i < NRES. Put in C(*,NRES+i).
309 !
310 !      implicit real*8 (a-h,o-z)
311 !      include 'DIMENSIONS'
312 !      include 'COMMON.CHAIN'
313 !      include 'COMMON.LOCAL'
314 !      include 'COMMON.GEO'
315 !      include 'COMMON.VAR'
316 !      include 'COMMON.IOUNITS'
317 !      include 'COMMON.NAMES'
318 !      include 'COMMON.INTERACT'
319       integer :: i,j,k
320       real(kind=8),dimension(3) :: xx
321       real(kind=8) :: alphi,omegi,theta2
322       real(kind=8) :: dsci,dsci_inv,sinalphi,cosalphi,cosomegi,sinomegi
323       real(kind=8) :: xp,yp,zp,cost2,sint2,rj
324 !      dsci=dsc(itype(i,1))
325 !      dsci_inv=dsc_inv(itype(i,1))
326       dsci=vbld(i+nres)
327       dsci_inv=vbld_inv(i+nres)
328 #ifdef OSF
329       alphi=alph(i)
330       omegi=omeg(i)
331 #ifdef WHAM_RUN
332 ! detecting NaNQ
333       icrc=0
334       call proc_proc(alphi,icrc)
335       if(icrc.eq.1)alphi=100.0
336       icrc=0
337       call proc_proc(omegi,icrc)
338       if(icrc.eq.1)omegi=-100.0
339 #else
340       if (alphi.ne.alphi) alphi=100.0
341       if (omegi.ne.omegi) omegi=-100.0
342 #endif
343 #else
344       alphi=alph(i)
345       omegi=omeg(i)
346 #endif
347       cosalphi=dcos(alphi)
348       sinalphi=dsin(alphi)
349       cosomegi=dcos(omegi)
350       sinomegi=dsin(omegi) 
351       xp= dsci*cosalphi
352       yp= dsci*sinalphi*cosomegi
353       zp=-dsci*sinalphi*sinomegi
354 ! Now we have to rotate the coordinate system by 180-theta(i)/2 so as to get its
355 ! X-axis aligned with the vector DC(*,i)
356       theta2=pi-0.5D0*theta(i+1)
357       cost2=dcos(theta2)
358       sint2=dsin(theta2)
359       xx(1)= xp*cost2+yp*sint2
360       xx(2)=-xp*sint2+yp*cost2
361       xx(3)= zp
362 !d    print '(a3,i3,3f10.5,5x,3f10.5)',restyp(itype(i,1)),i,
363 !d   &   xp,yp,zp,(xx(k),k=1,3)
364       do j=1,3
365         xloc(j,i)=xx(j)
366       enddo
367 ! Bring the SC vectors to the common coordinate system.
368       xx(1)=xloc(1,i)
369       xx(2)=xloc(2,i)*r(2,2,i-1)+xloc(3,i)*r(2,3,i-1)
370       xx(3)=xloc(2,i)*r(3,2,i-1)+xloc(3,i)*r(3,3,i-1)
371       do j=1,3
372         xrot(j,i)=xx(j)
373       enddo
374       do j=1,3
375         rj=0.0D0
376         do k=1,3
377           rj=rj+prod(j,k,i-1)*xx(k)
378         enddo
379         dc(j,nres+i)=rj
380         dc_norm(j,nres+i)=rj*dsci_inv
381         c(j,nres+i)=c(j,i)+rj
382       enddo
383       return
384       end subroutine locate_side_chain
385 !-----------------------------------------------------------------------------
386 ! checkder_p.F
387 !-----------------------------------------------------------------------------
388       subroutine int_from_cart1(lprn)
389 !      implicit real*8 (a-h,o-z)
390 !      include 'DIMENSIONS'
391 #ifdef MPI
392       include 'mpif.h'
393       integer :: ierror
394 #endif
395 !      include 'COMMON.IOUNITS'
396 !      include 'COMMON.VAR'
397 !      include 'COMMON.CHAIN'
398 !      include 'COMMON.GEO'
399 !      include 'COMMON.INTERACT'
400 !      include 'COMMON.LOCAL'
401 !      include 'COMMON.NAMES'
402 !      include 'COMMON.SETUP'
403 !      include 'COMMON.TIME1'
404       logical :: lprn
405 !el local variables
406       integer :: i,j
407       real(kind=8) :: dnorm1,dnorm2,be
408       integer :: nres2
409       nres2=2*nres
410       if (lprn) write (iout,'(/a)') 'Recalculated internal coordinates'
411 #ifdef TIMING
412       time01=MPI_Wtime()
413 #endif
414
415 #ifdef WHAM_RUN
416       vbld(nres+1)=0.0d0
417 !write(iout,*)"geometry warring, vbld=",(vbld(i),i=1,nres+1)
418       vbld(2*nres)=0.0d0
419       vbld_inv(nres+1)=0.0d0
420       vbld_inv(2*nres)=0.0d0
421 #endif
422
423 #if defined(PARINT) && defined(MPI)
424       do i=iint_start,iint_end
425 #else
426       do i=2,nres
427 #endif
428         dnorm1=dist(i-1,i)
429         dnorm2=dist(i,i+1) 
430         do j=1,3
431           c(j,nres2+2)=0.5D0*(2*c(j,i)+(c(j,i-1)-c(j,i))/dnorm1 &
432            +(c(j,i+1)-c(j,i))/dnorm2)
433         enddo
434         be=0.0D0
435         if (i.gt.2) then
436         if (i.le.nres) phi(i+1)=beta(i-2,i-1,i,i+1)
437         if ((itype(i,1).ne.10).and.(itype(i-1,1).ne.10)) then
438          tauangle(3,i+1)=beta(i+nres-1,i-1,i,i+nres)
439         endif
440         if (itype(i-1,1).ne.10) then
441          tauangle(1,i+1)=beta(i-1+nres,i-1,i,i+1)
442          omicron(1,i)=alpha(i-2,i-1,i-1+nres)
443          omicron(2,i)=alpha(i-1+nres,i-1,i)
444         endif
445         if (itype(i,1).ne.10) then
446          tauangle(2,i+1)=beta(i-2,i-1,i,i+nres)
447         endif
448         endif
449         omeg(i)=beta(nres+i,i,nres2+2,i+1)
450         alph(i)=alpha(nres+i,i,nres2+2)
451         theta(i+1)=alpha(i-1,i,i+1)
452         vbld(i)=dist(i-1,i)
453 !        print *,i,vbld(i),"vbld(i)"
454         vbld_inv(i)=1.0d0/vbld(i)
455         vbld(nres+i)=dist(nres+i,i)
456         if (itype(i,1).ne.10) then
457           vbld_inv(nres+i)=1.0d0/vbld(nres+i)
458         else
459           vbld_inv(nres+i)=0.0d0
460         endif
461       enddo   
462 #if defined(PARINT) && defined(MPI)
463        if (nfgtasks1.gt.1) then
464 !d       write(iout,*) "iint_start",iint_start," iint_count",
465 !d     &   (iint_count(i),i=0,nfgtasks-1)," iint_displ",
466 !d     &   (iint_displ(i),i=0,nfgtasks-1)
467 !d       write (iout,*) "Gather vbld backbone"
468 !d       call flush(iout)
469        time00=MPI_Wtime()
470        call MPI_Allgatherv(vbld(iint_start),iint_count(fg_rank1),&
471          MPI_DOUBLE_PRECISION,vbld(1),iint_count(0),iint_displ(0),&
472          MPI_DOUBLE_PRECISION,FG_COMM1,IERR)
473 !d       write (iout,*) "Gather vbld_inv"
474 !d       call flush(iout)
475        call MPI_Allgatherv(vbld_inv(iint_start),iint_count(fg_rank1),&
476          MPI_DOUBLE_PRECISION,vbld_inv(1),iint_count(0),iint_displ(0),&
477          MPI_DOUBLE_PRECISION,FG_COMM1,IERR)
478 !d       write (iout,*) "Gather vbld side chain"
479 !d       call flush(iout)
480        call MPI_Allgatherv(vbld(iint_start+nres),iint_count(fg_rank1),&
481          MPI_DOUBLE_PRECISION,vbld(nres+1),iint_count(0),iint_displ(0),&
482          MPI_DOUBLE_PRECISION,FG_COMM1,IERR)
483 !d       write (iout,*) "Gather vbld_inv side chain"
484 !d       call flush(iout)
485        call MPI_Allgatherv(vbld_inv(iint_start+nres),&
486          iint_count(fg_rank1),MPI_DOUBLE_PRECISION,vbld_inv(nres+1),&
487          iint_count(0),iint_displ(0),MPI_DOUBLE_PRECISION,FG_COMM1,IERR)
488 !d       write (iout,*) "Gather theta"
489 !d       call flush(iout)
490        call MPI_Allgatherv(theta(iint_start+1),iint_count(fg_rank1),&
491          MPI_DOUBLE_PRECISION,theta(2),iint_count(0),iint_displ(0),&
492          MPI_DOUBLE_PRECISION,FG_COMM1,IERR)
493 !d       write (iout,*) "Gather phi"
494 !d       call flush(iout)
495        call MPI_Allgatherv(phi(iint_start+1),iint_count(fg_rank1),&
496          MPI_DOUBLE_PRECISION,phi(2),iint_count(0),iint_displ(0),&
497          MPI_DOUBLE_PRECISION,FG_COMM1,IERR)
498 #ifdef CRYST_SC
499 !d       write (iout,*) "Gather alph"
500 !d       call flush(iout)
501        call MPI_Allgatherv(alph(iint_start),iint_count(fg_rank1),&
502          MPI_DOUBLE_PRECISION,alph(1),iint_count(0),iint_displ(0),&
503          MPI_DOUBLE_PRECISION,FG_COMM1,IERR)
504 !d       write (iout,*) "Gather omeg"
505 !d       call flush(iout)
506        call MPI_Allgatherv(omeg(iint_start),iint_count(fg_rank1),&
507          MPI_DOUBLE_PRECISION,omeg(1),iint_count(0),iint_displ(0),&
508          MPI_DOUBLE_PRECISION,FG_COMM1,IERR)
509 #endif
510        time_gather=time_gather+MPI_Wtime()-time00
511       endif
512 #endif
513       do i=1,nres-1
514         do j=1,3
515 !#ifdef WHAM_RUN
516 #if defined(WHAM_RUN) || defined(CLUSTER)
517           dc(j,i)=c(j,i+1)-c(j,i)
518 #endif
519           dc_norm(j,i)=dc(j,i)*vbld_inv(i+1)
520         enddo
521       enddo
522       do i=2,nres-1
523         do j=1,3
524 !#ifdef WHAM_RUN
525 #if defined(WHAM_RUN) || defined(CLUSTER)
526           dc(j,i+nres)=c(j,i+nres)-c(j,i)
527 #endif
528           dc_norm(j,i+nres)=dc(j,i+nres)*vbld_inv(i+nres)
529         enddo
530       enddo
531       if (lprn) then
532       do i=2,nres
533        write (iout,1212) restyp(itype(i,1),1),i,vbld(i),&
534        rad2deg*theta(i),rad2deg*phi(i),vbld(nres+i),&
535        rad2deg*alph(i),rad2deg*omeg(i)
536       enddo
537       endif
538  1212 format (a3,'(',i3,')',2(f15.10,2f10.2))
539 #ifdef TIMING
540       time_intfcart=time_intfcart+MPI_Wtime()-time01
541 #endif
542       return
543       end subroutine int_from_cart1
544 #if .not. defined(WHAM_RUN) && .not. defined(CLUSTER)
545 !-----------------------------------------------------------------------------
546 ! check_sc_distr.f
547 !-----------------------------------------------------------------------------
548       subroutine check_sc_distr
549 !      implicit real*8 (a-h,o-z)
550 !      include 'DIMENSIONS'
551 !      include 'COMMON.TIME1'
552 !      include 'COMMON.INTERACT'
553 !      include 'COMMON.NAMES'
554 !      include 'COMMON.GEO'
555 !      include 'COMMON.HEADER'
556 !      include 'COMMON.CONTROL'
557       logical :: fail
558       real(kind=8),dimension(6*nres) :: varia !(maxvar) (maxvar=6*maxres)
559       real(kind=8) :: hrtime,mintime,sectime
560       integer,parameter :: MaxSample=10000000
561       real(kind=8),parameter :: delt=1.0D0/MaxSample
562       real(kind=8),dimension(0:72,0:90) :: prob
563 !el local variables
564       integer :: it,i,j,isample,indal,indom
565       real(kind=8) :: al,om,dV
566       dV=2.0D0*5.0D0*deg2rad*deg2rad
567       print *,'dv=',dv
568       do 10 it=1,1 
569         if (it.eq.10) goto 10 
570         open (20,file=restyp(it,1)//'_distr.sdc',status='unknown')
571         call gen_side(it,90.0D0 * deg2rad,al,om,fail)
572         close (20)
573         goto 10
574         open (20,file=restyp(it,1)//'_distr1.sdc',status='unknown')
575         do i=0,90
576           do j=0,72
577             prob(j,i)=0.0D0
578           enddo
579         enddo
580         do isample=1,MaxSample
581           call gen_side(it,90.0D0 * deg2rad,al,om,fail)
582           indal=rad2deg*al/2
583           indom=(rad2deg*om+180.0D0)/5
584           prob(indom,indal)=prob(indom,indal)+delt
585         enddo
586         do i=45,90
587           do j=0,72 
588             write (20,'(2f10.3,1pd15.5)') 2*i+0.0D0,5*j-180.0D0,&
589                     prob(j,i)/dV
590           enddo
591         enddo
592    10   continue
593       return
594       end subroutine check_sc_distr
595 #endif
596 !-----------------------------------------------------------------------------
597 ! convert.f
598 !-----------------------------------------------------------------------------
599       subroutine geom_to_var(n,x)
600 !
601 ! Transfer the geometry parameters to the variable array.
602 ! The positions of variables are as follows:
603 ! 1. Virtual-bond torsional angles: 1 thru nres-3
604 ! 2. Virtual-bond valence angles: nres-2 thru 2*nres-5
605 ! 3. The polar angles alpha of local SC orientation: 2*nres-4 thru 
606 !    2*nres-4+nside
607 ! 4. The torsional angles omega of SC orientation: 2*nres-4+nside+1
608 !    thru 2*nre-4+2*nside 
609 !
610 !      implicit real*8 (a-h,o-z)
611 !      include 'DIMENSIONS'
612 !      include 'COMMON.VAR'
613 !      include 'COMMON.GEO'
614 !      include 'COMMON.CHAIN'
615       integer :: n,i
616       real(kind=8),dimension(n) :: x
617 !d    print *,'nres',nres,' nphi',nphi,' ntheta',ntheta,' nvar',nvar
618       do i=4,nres
619         x(i-3)=phi(i)
620 !d      print *,i,i-3,phi(i)
621       enddo
622       if (n.eq.nphi) return
623       do i=3,nres
624         x(i-2+nphi)=theta(i)
625 !d      print *,i,i-2+nphi,theta(i)
626       enddo
627       if (n.eq.nphi+ntheta) return
628       do i=2,nres-1
629         if (ialph(i,1).gt.0) then
630           x(ialph(i,1))=alph(i)
631           x(ialph(i,1)+nside)=omeg(i)
632 !d        print *,i,ialph(i,1),ialph(i,1)+nside,alph(i),omeg(i)
633         endif
634       enddo
635       return
636       end subroutine geom_to_var
637 !-----------------------------------------------------------------------------
638       subroutine var_to_geom(n,x)
639 !
640 ! Update geometry parameters according to the variable array.
641 !
642 !      implicit real*8 (a-h,o-z)
643 !      include 'DIMENSIONS'
644 !      include 'COMMON.VAR'
645 !      include 'COMMON.CHAIN'
646 !      include 'COMMON.GEO'
647 !      include 'COMMON.IOUNITS'
648       integer :: n,i,ii
649       real(kind=8),dimension(n) :: x
650       logical :: change !,reduce
651 !el      alph=0.0d0
652 !el      omeg=0.0d0
653 !el      phi=0.0d0
654 !el      theta=0.0d0
655
656       change=reduce(x)
657       if (n.gt.nphi+ntheta) then
658         do i=1,nside
659           ii=ialph(i,2)
660           alph(ii)=x(nphi+ntheta+i)
661           omeg(ii)=pinorm(x(nphi+ntheta+nside+i))
662 !elwrite(iout,*) "alph",ii,alph
663 !elwrite(iout,*) "omeg",ii,omeg
664         enddo      
665       endif
666       do i=4,nres
667         phi(i)=x(i-3)
668 !elwrite(iout,*) "phi",i,phi
669       enddo
670       if (n.eq.nphi) return
671       do i=3,nres
672         theta(i)=x(i-2+nphi)
673 !elwrite(iout,*) "theta",i,theta
674         if (theta(i).eq.pi) theta(i)=0.99d0*pi
675         x(i-2+nphi)=theta(i)
676       enddo
677       return
678       end subroutine var_to_geom
679 !-----------------------------------------------------------------------------
680       logical function convert_side(alphi,omegi)
681 !      implicit none
682       real(kind=8) :: alphi,omegi
683 !el      real(kind=8) :: pinorm
684 !      include 'COMMON.GEO'
685       convert_side=.false.
686 ! Apply periodicity restrictions.
687       if (alphi.gt.pi) then
688         alphi=dwapi-alphi
689         omegi=pinorm(omegi+pi)
690         convert_side=.true.
691       endif
692       return
693       end function convert_side
694 !-----------------------------------------------------------------------------
695       logical function reduce(x)
696 !
697 ! Apply periodic restrictions to variables.
698 !
699 !      implicit real*8 (a-h,o-z)
700 !      include 'DIMENSIONS'
701 !      include 'COMMON.VAR'
702 !      include 'COMMON.CHAIN'
703 !      include 'COMMON.GEO'
704       logical :: zm,zmiana      !,convert_side
705       real(kind=8),dimension(nvar) :: x
706       integer :: i,ii,iii
707       zmiana=.false.
708       do i=4,nres
709         x(i-3)=pinorm(x(i-3))
710       enddo
711       if (nvar.gt.nphi+ntheta) then
712         do i=1,nside
713           ii=nphi+ntheta+i
714           iii=ii+nside
715           x(ii)=thetnorm(x(ii))
716           x(iii)=pinorm(x(iii))
717 ! Apply periodic restrictions.
718           zm=convert_side(x(ii),x(iii))
719           zmiana=zmiana.or.zm
720         enddo      
721       endif
722       if (nvar.eq.nphi) return
723       do i=3,nres
724         ii=i-2+nphi
725         iii=i-3
726         x(ii)=dmod(x(ii),dwapi)
727 ! Apply periodic restrictions.
728         if (x(ii).gt.pi) then
729           zmiana=.true.
730           x(ii)=dwapi-x(ii)
731           if (iii.gt.0) x(iii)=pinorm(x(iii)+pi)
732           if (i.lt.nres) x(iii+1)=pinorm(x(iii+1)+pi)
733           ii=ialph(i-1,1)
734           if (ii.gt.0) then
735             x(ii)=dmod(pi-x(ii),dwapi)
736             x(ii+nside)=pinorm(-x(ii+nside))
737             zm=convert_side(x(ii),x(ii+nside))
738           endif
739         else if (x(ii).lt.-pi) then
740           zmiana=.true.
741           x(ii)=dwapi+x(ii)
742           ii=ialph(i-1,1)
743           if (ii.gt.0) then
744             x(ii)=dmod(pi-x(ii),dwapi)
745             x(ii+nside)=pinorm(-pi-x(ii+nside))
746             zm=convert_side(x(ii),x(ii+nside))
747           endif
748         else if (x(ii).lt.0.0d0) then
749           zmiana=.true.
750           x(ii)=-x(ii)
751           if (iii.gt.0) x(iii)=pinorm(x(iii)+pi)
752           if (i.lt.nres) x(iii+1)=pinorm(x(iii+1)+pi)
753           ii=ialph(i-1,1)
754           if (ii.gt.0) then
755             x(ii+nside)=pinorm(-x(ii+nside))
756             zm=convert_side(x(ii),x(ii+nside))
757           endif
758         endif 
759       enddo
760       reduce=zmiana
761       return
762       end function reduce
763 !-----------------------------------------------------------------------------
764       real(kind=8) function thetnorm(x)
765 ! This function puts x within [0,2Pi].
766       implicit none
767       real(kind=8) :: x,xx
768 !      include 'COMMON.GEO'
769       xx=dmod(x,dwapi)
770       if (xx.lt.0.0d0) xx=xx+dwapi
771       if (xx.gt.0.9999d0*pi) xx=0.9999d0*pi
772       thetnorm=xx 
773       return
774       end function thetnorm
775 #if .not. defined(WHAM_RUN) && .not. defined(CLUSTER)
776 !-----------------------------------------------------------------------------
777       subroutine var_to_geom_restr(n,xx)
778 !
779 ! Update geometry parameters according to the variable array.
780 !
781 !      implicit real*8 (a-h,o-z)
782 !      include 'DIMENSIONS'
783 !      include 'COMMON.VAR'
784 !      include 'COMMON.CHAIN'
785 !      include 'COMMON.GEO'
786 !      include 'COMMON.IOUNITS'
787       integer :: n,i,ii
788       real(kind=8),dimension(6*nres) :: x,xx !(maxvar) (maxvar=6*maxres)
789       logical :: change !,reduce
790
791       call xx2x(x,xx)
792       change=reduce(x)
793       do i=1,nside
794           ii=ialph(i,2)
795           alph(ii)=x(nphi+ntheta+i)
796           omeg(ii)=pinorm(x(nphi+ntheta+nside+i))
797       enddo      
798       do i=4,nres
799         phi(i)=x(i-3)
800       enddo
801       do i=3,nres
802         theta(i)=x(i-2+nphi)
803         if (theta(i).eq.pi) theta(i)=0.99d0*pi
804         x(i-2+nphi)=theta(i)
805       enddo
806       return
807       end subroutine var_to_geom_restr
808 !-----------------------------------------------------------------------------
809 ! gen_rand_conf.F
810 !-----------------------------------------------------------------------------
811       subroutine gen_rand_conf(nstart,*)
812 ! Generate random conformation or chain cut and regrowth.
813       use mcm_data
814 !      implicit real*8 (a-h,o-z)
815 !      include 'DIMENSIONS'
816 !      include 'COMMON.CHAIN'
817 !      include 'COMMON.LOCAL'
818 !      include 'COMMON.VAR'
819 !      include 'COMMON.INTERACT'
820 !      include 'COMMON.IOUNITS'
821 !      include 'COMMON.MCM'
822 !      include 'COMMON.GEO'
823 !      include 'COMMON.CONTROL'
824       logical :: back,fail      !overlap,
825 !el local variables
826       integer :: i,nstart,maxsi,nsi,maxnit,nit,niter
827       integer :: it1,it2,it,j
828 !d    print *,' CG Processor',me,' maxgen=',maxgen
829       maxsi=100
830 !d    write (iout,*) 'Gen_Rand_conf: nstart=',nstart
831       if (nstart.lt.5) then
832         it1=iabs(itype(2,1))
833         phi(4)=gen_phi(4,iabs(itype(2,1)),iabs(itype(3,1)))
834 !       write(iout,*)'phi(4)=',rad2deg*phi(4)
835         if (nstart.lt.3) theta(3)=gen_theta(iabs(itype(2,1)),pi,phi(4))
836 !       write(iout,*)'theta(3)=',rad2deg*theta(3) 
837         if ((it1.ne.10).and.(it.ne.ntyp1)) then
838           nsi=0
839           fail=.true.
840           do while (fail.and.nsi.le.maxsi)
841             call gen_side(it1,theta(3),alph(2),omeg(2),fail)
842             nsi=nsi+1
843           enddo
844           if (nsi.gt.maxsi) return 1
845         endif ! it1.ne.10
846         call orig_frame
847         i=4
848         nstart=4
849       else
850         i=nstart
851         nstart=max0(i,4)
852       endif
853
854       maxnit=0
855
856       nit=0
857       niter=0
858       back=.false.
859       do while (i.le.nres .and. niter.lt.maxgen)
860         if (i.lt.nstart) then
861           if(iprint.gt.1) then
862           write (iout,'(/80(1h*)/2a/80(1h*))') &
863                 'Generation procedure went down to ',&
864                 'chain beginning. Cannot continue...'
865           write (*,'(/80(1h*)/2a/80(1h*))') &
866                 'Generation procedure went down to ',&
867                 'chain beginning. Cannot continue...'
868           endif
869           return 1
870         endif
871         it1=iabs(itype(i-1,molnum(i-1)))
872         it2=iabs(itype(i-2,molnum(i-2)))
873         it=iabs(itype(i,molnum(i)))
874 !       print *,'Gen_Rand_Conf: i=',i,' it=',it,' it1=',it1,' it2=',it2,
875 !    &    ' nit=',nit,' niter=',niter,' maxgen=',maxgen
876         phi(i+1)=gen_phi(i+1,it1,it)
877         if (back) then
878           phi(i)=gen_phi(i+1,it2,it1)
879 !         print *,'phi(',i,')=',phi(i)
880           theta(i-1)=gen_theta(it2,phi(i-1),phi(i))
881           if ((it2.ne.10).and.(it2.ne.ntyp1)) then
882             nsi=0
883             fail=.true.
884             do while (fail.and.nsi.le.maxsi)
885               call gen_side(it2,theta(i-1),alph(i-2),omeg(i-2),fail)
886               nsi=nsi+1
887             enddo
888             if (nsi.gt.maxsi) return 1
889           endif
890           call locate_next_res(i-1)
891         endif
892         theta(i)=gen_theta(it1,phi(i),phi(i+1))
893         if ((it1.ne.10).and.(it1.ne.ntyp1)) then 
894         nsi=0
895         fail=.true.
896         do while (fail.and.nsi.le.maxsi)
897           call gen_side(it1,theta(i),alph(i-1),omeg(i-1),fail)
898           nsi=nsi+1
899         enddo
900         if (nsi.gt.maxsi) return 1
901         endif
902         call locate_next_res(i)
903         if (overlap(i-1)) then
904           if (nit.lt.maxnit) then
905             back=.true.
906             nit=nit+1
907           else
908             nit=0
909             if (i.gt.3) then
910               back=.true.
911               i=i-1
912             else
913               write (iout,'(a)') &
914         'Cannot generate non-overlaping conformation. Increase MAXNIT.'
915               write (*,'(a)') &
916         'Cannot generate non-overlaping conformation. Increase MAXNIT.'
917               return 1
918             endif
919           endif
920         else
921           back=.false.
922           nit=0 
923           i=i+1
924         endif
925         niter=niter+1
926       enddo
927       if (niter.ge.maxgen) then
928         write (iout,'(a,2i5)') &
929        'Too many trials in conformation generation',niter,maxgen
930         write (*,'(a,2i5)') &
931        'Too many trials in conformation generation',niter,maxgen
932         return 1
933       endif
934       do j=1,3
935         c(j,nres+1)=c(j,1)
936         c(j,nres+nres)=c(j,nres)
937       enddo
938       return
939       end subroutine gen_rand_conf
940 !-----------------------------------------------------------------------------
941       logical function overlap(i)
942 !      implicit real*8 (a-h,o-z)
943 !      include 'DIMENSIONS'
944 !      include 'COMMON.CHAIN'
945 !      include 'COMMON.INTERACT'
946 !      include 'COMMON.FFIELD'
947       integer :: i,j,iti,itj,iteli,itelj,k
948       real(kind=8) :: redfac,rcomp
949       integer :: nres2
950       nres2=2*nres
951       data redfac /0.5D0/
952       overlap=.false.
953       iti=iabs(itype(i,1))
954       if (iti.gt.ntyp) return
955 ! Check for SC-SC overlaps.
956 !d    print *,'nnt=',nnt,' nct=',nct
957       do j=nnt,i-1
958         itj=iabs(itype(j,1))
959         if (j.lt.i-1 .or. ipot.ne.4) then
960           rcomp=sigmaii(iti,itj)
961         else 
962           rcomp=sigma(iti,itj)
963         endif
964 !d      print *,'j=',j
965         if (dist(nres+i,nres+j).lt.redfac*rcomp) then
966           overlap=.true.
967 !        print *,'overlap, SC-SC: i=',i,' j=',j,
968 !     &     ' dist=',dist(nres+i,nres+j),' rcomp=',
969 !     &     rcomp
970           return
971         endif
972       enddo
973 ! Check for overlaps between the added peptide group and the preceding
974 ! SCs.
975       iteli=itel(i)
976       do j=1,3
977 !       c(j,nres2+1)=0.5D0*(c(j,i)+c(j,i+1))
978         c(j,nres2+3)=0.5D0*(c(j,i)+c(j,i+1))
979       enddo
980       do j=nnt,i-2
981         itj=iabs(itype(j,1))
982 !d      print *,'overlap, p-Sc: i=',i,' j=',j,
983 !d   &         ' dist=',dist(nres+j,maxres2+1)
984         if (dist(nres+j,nres2+3).lt.4.0D0*redfac) then
985           overlap=.true.
986           return
987         endif
988       enddo
989 ! Check for overlaps between the added side chain and the preceding peptide
990 ! groups.
991       do j=1,nnt-2
992         do k=1,3
993           c(k,nres2+3)=0.5D0*(c(k,j)+c(k,j+1))
994         enddo
995 !d      print *,'overlap, SC-p: i=',i,' j=',j,
996 !d   &         ' dist=',dist(nres+i,maxres2+1)
997         if (dist(nres+i,nres2+3).lt.4.0D0*redfac) then
998           overlap=.true.
999           return
1000         endif
1001       enddo
1002 ! Check for p-p overlaps
1003       do j=1,3
1004         c(j,nres2+4)=0.5D0*(c(j,i)+c(j,i+1))
1005       enddo
1006       do j=nnt,i-2
1007         itelj=itel(j)
1008         do k=1,3
1009           c(k,nres2+4)=0.5D0*(c(k,j)+c(k,j+1))
1010         enddo
1011 !d      print *,'overlap, p-p: i=',i,' j=',j,
1012 !d   &         ' dist=',dist(maxres2+1,maxres2+2)
1013         if(iteli.ne.0.and.itelj.ne.0)then
1014         if (dist(nres2+3,nres2+4).lt.rpp(iteli,itelj)*redfac) then
1015           overlap=.true.
1016           return
1017         endif
1018         endif
1019       enddo
1020       return
1021       end function overlap
1022 !-----------------------------------------------------------------------------
1023       real(kind=8) function gen_phi(i,it1,it2)
1024       use random, only:ran_number
1025 !      implicit real*8 (a-h,o-z)
1026 !      include 'DIMENSIONS'
1027 !      include 'COMMON.GEO'
1028 !      include 'COMMON.BOUNDS'
1029       integer :: i,it1,it2
1030 !      gen_phi=ran_number(-pi,pi)
1031 ! 8/13/98 Generate phi using pre-defined boundaries
1032       gen_phi=ran_number(phibound(1,i),phibound(2,i))
1033       return
1034       end function gen_phi
1035 !-----------------------------------------------------------------------------
1036       real(kind=8) function gen_theta(it,gama,gama1)
1037       use random,only:binorm
1038 !      implicit real*8 (a-h,o-z)
1039 !      include 'DIMENSIONS'
1040 !      include 'COMMON.LOCAL'
1041 !      include 'COMMON.GEO'
1042       real(kind=8),dimension(2) :: y,z
1043       real(kind=8) :: theta_max,theta_min,sig,ak
1044 !el local variables
1045       integer :: j,it,k
1046       real(kind=8) :: gama,gama1,thet_pred_mean,theta_temp
1047 !     print *,'gen_theta: it=',it
1048       theta_min=0.05D0*pi
1049       theta_max=0.95D0*pi
1050       if (dabs(gama).gt.dwapi) then
1051         y(1)=dcos(gama)
1052         y(2)=dsin(gama)
1053       else
1054         y(1)=0.0D0
1055         y(2)=0.0D0
1056       endif
1057       if (dabs(gama1).gt.dwapi) then
1058         z(1)=dcos(gama1)
1059         z(2)=dsin(gama1)
1060       else
1061         z(1)=0.0D0
1062         z(2)=0.0D0
1063       endif  
1064       thet_pred_mean=a0thet(it)
1065       do k=1,2
1066         thet_pred_mean=thet_pred_mean+athet(k,it,1,1)*y(k) &
1067            +bthet(k,it,1,1)*z(k)
1068       enddo
1069       sig=polthet(3,it)
1070       do j=2,0,-1
1071         sig=sig*thet_pred_mean+polthet(j,it)
1072       enddo
1073       sig=0.5D0/(sig*sig+sigc0(it))
1074       ak=dexp(gthet(1,it)- &
1075        0.5D0*((gthet(2,it)-thet_pred_mean)/gthet(3,it))**2)
1076 !     print '(i5,5(1pe14.4))',it,(gthet(j,it),j=1,3)
1077 !     print '(5(1pe14.4))',thet_pred_mean,theta0(it),sig,sig0(it),ak
1078       theta_temp=binorm(thet_pred_mean,theta0(it),sig,sig0(it),ak) 
1079       if (theta_temp.lt.theta_min) theta_temp=theta_min
1080       if (theta_temp.gt.theta_max) theta_temp=theta_max
1081       gen_theta=theta_temp
1082 !     print '(a)','Exiting GENTHETA.'
1083       return
1084       end function gen_theta
1085 !-----------------------------------------------------------------------------
1086       subroutine gen_side(it,the,al,om,fail)
1087       use random, only:ran_number,mult_norm1
1088 !      implicit real*8 (a-h,o-z)
1089 !      include 'DIMENSIONS'
1090 !      include 'COMMON.GEO'
1091 !      include 'COMMON.LOCAL'
1092 !      include 'COMMON.SETUP'
1093 !      include 'COMMON.IOUNITS'
1094       real(kind=8) :: MaxBoxLen=10.0D0
1095       real(kind=8),dimension(3,3) :: Ap_inv,a,vec
1096       real(kind=8),dimension(:,:),allocatable :: z !(3,maxlob)
1097       real(kind=8),dimension(:),allocatable :: W1,detAp !(maxlob)
1098       real(kind=8),dimension(:),allocatable :: sumW !(0:maxlob)
1099       real(kind=8),dimension(2) :: y,cm,eig
1100       real(kind=8),dimension(2,2) :: box
1101       real(kind=8),dimension(100) :: work
1102       real(kind=8) :: eig_limit=1.0D-8
1103       real(kind=8) :: Big=10.0D0
1104       logical :: lprint,fail,lcheck
1105 !el local variables
1106       integer :: it,i,j,k,l,nlobit,ial,iom,iii,ilob
1107       real(kind=8) :: the,al,om,detApi,wart,y2,wykl,radmax
1108       real(kind=8) :: tant,zz1,W1i,radius,zk,fac,dV,sum,sum1
1109       real(kind=8) :: which_lobe
1110       lcheck=.false.
1111       lprint=.false.
1112       fail=.false.
1113       if (the.eq.0.0D0 .or. the.eq.pi) then
1114 #ifdef MPI
1115         write (*,'(a,i4,a,i3,a,1pe14.5)') &
1116        'CG Processor:',me,' Error in GenSide: it=',it,' theta=',the
1117 #else
1118 !d        write (iout,'(a,i3,a,1pe14.5)') 
1119 !d     &   'Error in GenSide: it=',it,' theta=',the
1120 #endif
1121         fail=.true.
1122         return
1123       endif
1124       tant=dtan(the-pipol)
1125       nlobit=nlob(it)
1126       allocate(z(3,nlobit))
1127       allocate(W1(nlobit))
1128       allocate(detAp(nlobit))
1129       allocate(sumW(0:nlobit))
1130       if (lprint) then
1131 #ifdef MPI
1132         print '(a,i4,a)','CG Processor:',me,' Enter Gen_Side.'
1133         write (iout,'(a,i4,a)') 'Processor:',me,' Enter Gen_Side.'
1134 #endif
1135         print *,'it=',it,' nlobit=',nlobit,' the=',the,' tant=',tant
1136         write (iout,*) 'it=',it,' nlobit=',nlobit,' the=',the,&
1137            ' tant=',tant
1138       endif
1139       do i=1,nlobit
1140        zz1=tant-censc(1,i,it)
1141         do k=1,3
1142           do l=1,3
1143             a(k,l)=gaussc(k,l,i,it)
1144           enddo
1145         enddo
1146         detApi=a(2,2)*a(3,3)-a(2,3)**2
1147         Ap_inv(2,2)=a(3,3)/detApi
1148         Ap_inv(2,3)=-a(2,3)/detApi
1149         Ap_inv(3,2)=Ap_inv(2,3)
1150         Ap_inv(3,3)=a(2,2)/detApi
1151         if (lprint) then
1152           write (*,'(/a,i2/)') 'Cluster #',i
1153           write (*,'(3(1pe14.5),5x,1pe14.5)') &
1154           ((a(l,k),l=1,3),censc(k,i,it),k=1,3)
1155           write (iout,'(/a,i2/)') 'Cluster #',i
1156           write (iout,'(3(1pe14.5),5x,1pe14.5)') &
1157           ((a(l,k),l=1,3),censc(k,i,it),k=1,3)
1158         endif
1159         W1i=0.0D0
1160         do k=2,3
1161           do l=2,3
1162             W1i=W1i+a(k,1)*a(l,1)*Ap_inv(k,l)
1163           enddo
1164         enddo
1165         W1i=a(1,1)-W1i
1166         W1(i)=dexp(bsc(i,it)-0.5D0*W1i*zz1*zz1)
1167 !        if (lprint) write(*,'(a,3(1pe15.5)/)')
1168 !     &          'detAp, W1, anormi',detApi,W1i,anormi
1169         do k=2,3
1170           zk=censc(k,i,it)
1171           do l=2,3
1172             zk=zk+zz1*Ap_inv(k,l)*a(l,1)
1173           enddo
1174           z(k,i)=zk
1175         enddo
1176         detAp(i)=dsqrt(detApi)
1177       enddo
1178
1179       if (lprint) then
1180         print *,'W1:',(w1(i),i=1,nlobit)
1181         print *,'detAp:',(detAp(i),i=1,nlobit)
1182         print *,'Z'
1183         do i=1,nlobit
1184           print '(i2,3f10.5)',i,(rad2deg*z(j,i),j=2,3)
1185         enddo
1186         write (iout,*) 'W1:',(w1(i),i=1,nlobit)
1187         write (iout,*) 'detAp:',(detAp(i),i=1,nlobit)
1188         write (iout,*) 'Z'
1189         do i=1,nlobit
1190           write (iout,'(i2,3f10.5)') i,(rad2deg*z(j,i),j=2,3)
1191         enddo
1192       endif
1193       if (lcheck) then
1194 ! Writing the distribution just to check the procedure
1195       fac=0.0D0
1196       dV=deg2rad**2*10.0D0
1197       sum=0.0D0
1198       sum1=0.0D0
1199       do i=1,nlobit
1200         fac=fac+W1(i)/detAp(i)
1201       enddo 
1202       fac=1.0D0/(2.0D0*fac*pi)
1203 !d    print *,it,'fac=',fac
1204       do ial=90,180,2
1205         y(1)=deg2rad*ial
1206         do iom=-180,180,5
1207           y(2)=deg2rad*iom
1208           wart=0.0D0
1209           do i=1,nlobit
1210             do j=2,3
1211               do k=2,3
1212                 a(j-1,k-1)=gaussc(j,k,i,it)
1213               enddo
1214             enddo
1215             y2=y(2)
1216
1217             do iii=-1,1
1218           
1219               y(2)=y2+iii*dwapi
1220
1221               wykl=0.0D0
1222               do j=1,2
1223                 do k=1,2 
1224                   wykl=wykl+a(j,k)*(y(j)-z(j+1,i))*(y(k)-z(k+1,i))
1225                 enddo
1226               enddo
1227               wart=wart+W1(i)*dexp(-0.5D0*wykl)
1228
1229             enddo
1230
1231             y(2)=y2
1232
1233           enddo
1234 !         print *,'y',y(1),y(2),' fac=',fac
1235           wart=fac*wart
1236           write (20,'(2f10.3,1pd15.5)') y(1)*rad2deg,y(2)*rad2deg,wart
1237           sum=sum+wart
1238           sum1=sum1+1.0D0
1239         enddo
1240       enddo
1241 !     print *,'it=',it,' sum=',sum*dV,' sum1=',sum1*dV
1242       return
1243       endif
1244
1245 ! Calculate the CM of the system
1246 !
1247       do i=1,nlobit
1248         W1(i)=W1(i)/detAp(i)
1249       enddo
1250       sumW(0)=0.0D0
1251       do i=1,nlobit
1252         sumW(i)=sumW(i-1)+W1(i)
1253       enddo
1254       cm(1)=z(2,1)*W1(1)
1255       cm(2)=z(3,1)*W1(1)
1256       do j=2,nlobit
1257         cm(1)=cm(1)+z(2,j)*W1(j) 
1258         cm(2)=cm(2)+W1(j)*(z(3,1)+pinorm(z(3,j)-z(3,1)))
1259       enddo
1260       cm(1)=cm(1)/sumW(nlobit)
1261       cm(2)=cm(2)/sumW(nlobit)
1262       if (cm(1).gt.Big .or. cm(1).lt.-Big .or. &
1263        cm(2).gt.Big .or. cm(2).lt.-Big) then
1264 !d        write (iout,'(a)') 
1265 !d     & 'Unexpected error in GenSide - CM coordinates too large.'
1266 !d        write (iout,'(i5,2(1pe14.5))') it,cm(1),cm(2)
1267 !d        write (*,'(a)') 
1268 !d     & 'Unexpected error in GenSide - CM coordinates too large.'
1269 !d        write (*,'(i5,2(1pe14.5))') it,cm(1),cm(2)
1270         fail=.true. 
1271         return
1272       endif
1273 !d    print *,'CM:',cm(1),cm(2)
1274 !
1275 ! Find the largest search distance from CM
1276 !
1277       radmax=0.0D0
1278       do i=1,nlobit
1279         do j=2,3
1280           do k=2,3
1281             a(j-1,k-1)=gaussc(j,k,i,it) 
1282           enddo
1283         enddo
1284 #ifdef NAG
1285         call f02faf('N','U',2,a,3,eig,work,100,ifail)
1286 #else
1287         call djacob(2,3,10000,1.0d-10,a,vec,eig)
1288 #endif
1289 #ifdef MPI
1290         if (lprint) then
1291           print *,'*************** CG Processor',me
1292           print *,'CM:',cm(1),cm(2)
1293           write (iout,*) '*************** CG Processor',me
1294           write (iout,*) 'CM:',cm(1),cm(2)
1295           print '(A,8f10.5)','Eigenvalues: ',(1.0/dsqrt(eig(k)),k=1,2)
1296           write (iout,'(A,8f10.5)') &
1297               'Eigenvalues: ',(1.0/dsqrt(eig(k)),k=1,2)
1298         endif
1299 #endif
1300         if (eig(1).lt.eig_limit) then
1301           write(iout,'(a)') &
1302            'From Mult_Norm: Eigenvalues of A are too small.'
1303           write(*,'(a)') &
1304            'From Mult_Norm: Eigenvalues of A are too small.'
1305           fail=.true.
1306           return
1307         endif
1308         radius=0.0D0
1309 !d      print *,'i=',i
1310         do j=1,2
1311           radius=radius+pinorm(z(j+1,i)-cm(j))**2
1312         enddo
1313         radius=dsqrt(radius)+3.0D0/dsqrt(eig(1))
1314         if (radius.gt.radmax) radmax=radius
1315       enddo
1316       if (radmax.gt.pi) radmax=pi
1317 !
1318 ! Determine the boundaries of the search rectangle.
1319 !
1320       if (lprint) then
1321         print '(a,4(1pe14.4))','W1: ',(W1(i),i=1,nlob(it) )
1322         print '(a,4(1pe14.4))','radmax: ',radmax
1323       endif
1324       box(1,1)=dmax1(cm(1)-radmax,0.0D0)
1325       box(2,1)=dmin1(cm(1)+radmax,pi)
1326       box(1,2)=cm(2)-radmax
1327       box(2,2)=cm(2)+radmax
1328       if (lprint) then
1329 #ifdef MPI
1330         print *,'CG Processor',me,' Array BOX:'
1331 #else
1332         print *,'Array BOX:'
1333 #endif
1334         print '(4(1pe14.4))',((box(k,j),k=1,2),j=1,2)
1335         print '(a,4(1pe14.4))','sumW: ',(sumW(i),i=0,nlob(it) )
1336 #ifdef MPI
1337         write (iout,*)'CG Processor',me,' Array BOX:'
1338 #else
1339         write (iout,*)'Array BOX:'
1340 #endif
1341         write(iout,'(4(1pe14.4))') ((box(k,j),k=1,2),j=1,2)
1342         write(iout,'(a,4(1pe14.4))')'sumW: ',(sumW(i),i=0,nlob(it) )
1343       endif
1344       if (box(1,2).lt.-MaxBoxLen .or. box(2,2).gt.MaxBoxLen) then
1345 #ifdef MPI
1346         write (iout,'(a,i4,a,3e15.5)') 'CG Processor:',me,': bad sampling box.',box(1,2),box(2,2),radmax
1347         write (*,'(a,i4,a)') 'CG Processor:',me,': bad sampling box.'
1348 #else
1349 !        write (iout,'(a)') 'Bad sampling box.'
1350 #endif
1351         fail=.true.
1352         return
1353       endif
1354       which_lobe=ran_number(0.0D0,sumW(nlobit))
1355 !     print '(a,1pe14.4)','which_lobe=',which_lobe
1356       do i=1,nlobit
1357         if (sumW(i-1).le.which_lobe .and. sumW(i).ge.which_lobe) goto 1
1358       enddo
1359     1 ilob=i
1360 !     print *,'ilob=',ilob,' nlob=',nlob(it)
1361       do i=2,3
1362         cm(i-1)=z(i,ilob)
1363         do j=2,3
1364           a(i-1,j-1)=gaussc(i,j,ilob,it)
1365         enddo
1366       enddo
1367 !d    print '(a,i4,a)','CG Processor',me,' Calling MultNorm1.'
1368       call mult_norm1(3,2,a,cm,box,y,fail)
1369       if (fail) return
1370       al=y(1)
1371       om=pinorm(y(2))
1372 !d    print *,'al=',al,' om=',om
1373 !d    stop
1374       return
1375       end subroutine gen_side
1376 !-----------------------------------------------------------------------------
1377       subroutine overlap_sc(scfail)
1378 !
1379 !     Internal and cartesian coordinates must be consistent as input,
1380 !     and will be up-to-date on return.
1381 !     At the end of this procedure, scfail is true if there are
1382 !     overlapping residues left, or false otherwise (success)
1383 !
1384 !      implicit real*8 (a-h,o-z)
1385 !      include 'DIMENSIONS'
1386 !      include 'COMMON.CHAIN'
1387 !      include 'COMMON.INTERACT'
1388 !      include 'COMMON.FFIELD'
1389 !      include 'COMMON.VAR'
1390 !      include 'COMMON.SBRIDGE'
1391 !      include 'COMMON.IOUNITS'
1392       logical :: had_overlaps,fail,scfail
1393       integer,dimension(nres) :: ioverlap !(maxres)
1394       integer :: ioverlap_last,k,maxsi,i,iti,nsi
1395       integer :: ires,j
1396
1397       had_overlaps=.false.
1398       call overlap_sc_list(ioverlap,ioverlap_last)
1399       if (ioverlap_last.gt.0) then
1400         write (iout,*) '#OVERLAPing residues ',ioverlap_last
1401         write (iout,'(20i4)') (ioverlap(k),k=1,ioverlap_last)
1402         had_overlaps=.true.
1403       endif
1404
1405       maxsi=1000
1406       do k=1,1000
1407         if (ioverlap_last.eq.0) exit
1408
1409         do ires=1,ioverlap_last 
1410           i=ioverlap(ires)
1411           iti=iabs(itype(i,1))
1412           if ((iti.ne.10).and.(molnum(i).ne.5).and.(iti.ne.ntyp1)) then
1413             nsi=0
1414             fail=.true.
1415             do while (fail.and.nsi.le.maxsi)
1416               call gen_side(iti,theta(i+1),alph(i),omeg(i),fail)
1417               nsi=nsi+1
1418             enddo
1419             if(fail) goto 999
1420           endif
1421         enddo
1422
1423         call chainbuild
1424         call overlap_sc_list(ioverlap,ioverlap_last)
1425 !        write (iout,*) 'Overlaping residues ',ioverlap_last,
1426 !     &           (ioverlap(j),j=1,ioverlap_last)
1427       enddo
1428
1429       if (k.le.1000.and.ioverlap_last.eq.0) then
1430         scfail=.false.
1431         if (had_overlaps) then
1432           write (iout,*) '#OVERLAPing all corrected after ',k,&
1433                ' random generation'
1434         endif
1435       else
1436         scfail=.true.
1437         write (iout,*) '#OVERLAPing NOT all corrected ',ioverlap_last
1438         write (iout,'(20i4)') (ioverlap(j),j=1,ioverlap_last)
1439       endif
1440
1441       return
1442
1443  999  continue
1444       write (iout,'(a30,i5,a12,i4)') &
1445                      '#OVERLAP FAIL in gen_side after',maxsi,&
1446                      'iter for RES',i
1447       scfail=.true.
1448       return
1449       end subroutine overlap_sc
1450 !-----------------------------------------------------------------------------
1451       subroutine overlap_sc_list(ioverlap,ioverlap_last)
1452       use calc_data
1453 !      implicit real*8 (a-h,o-z)
1454 !      include 'DIMENSIONS'
1455 !      include 'COMMON.GEO'
1456 !      include 'COMMON.LOCAL'
1457 !      include 'COMMON.IOUNITS'
1458 !      include 'COMMON.CHAIN'
1459 !      include 'COMMON.INTERACT'
1460 !      include 'COMMON.FFIELD'
1461 !      include 'COMMON.VAR'
1462 !      include 'COMMON.CALC'
1463       logical :: fail
1464       integer,dimension(nres) :: ioverlap !(maxres)
1465       integer :: ioverlap_last
1466 !el local variables
1467       integer :: ind,iint
1468       real(kind=8) :: redfac,sig        !rrij,sigsq,
1469       integer :: itypi,itypj,itypi1
1470       real(kind=8) :: xi,yi,zi,sig0ij,rcomp,rrij,rij_shift
1471       data redfac /0.5D0/
1472
1473       ioverlap_last=0
1474 ! Check for SC-SC overlaps and mark residues
1475 !      print *,'>>overlap_sc nnt=',nnt,' nct=',nct
1476       ind=0
1477       do i=iatsc_s,iatsc_e
1478         if (itype(i,molnum(i)).eq.ntyp1_molec(molnum(i))) cycle
1479         if (molnum(i).eq.5) print *,"WTF",i,iatsc_s,iatsc_e
1480         if (molnum(i).eq.5) cycle
1481         itypi=iabs(itype(i,molnum(i)))
1482         itypi1=iabs(itype(i+1,1))
1483         xi=c(1,nres+i)
1484         yi=c(2,nres+i)
1485         zi=c(3,nres+i)
1486         dxi=dc_norm(1,nres+i)
1487         dyi=dc_norm(2,nres+i)
1488         dzi=dc_norm(3,nres+i)
1489         dsci_inv=dsc_inv(itypi)
1490 !
1491        do iint=1,nint_gr(i)
1492          do j=istart(i,iint),iend(i,iint)
1493          if (itype(j,molnum(j)).eq.ntyp1_molec(molnum(j))) cycle
1494             ind=ind+1
1495             itypj=iabs(itype(j,molnum(j)))
1496             dscj_inv=dsc_inv(itypj)
1497             sig0ij=sigma(itypi,itypj)
1498             chi1=chi(itypi,itypj)
1499             chi2=chi(itypj,itypi)
1500             chi12=chi1*chi2
1501             chip1=chip(itypi)
1502             chip2=chip(itypj)
1503             chip12=chip1*chip2
1504             alf1=alp(itypi)   
1505             alf2=alp(itypj)   
1506             alf12=0.5D0*(alf1+alf2)
1507           if (j.gt.i+1) then
1508            rcomp=sigmaii(itypi,itypj)
1509           else 
1510            rcomp=sigma(itypi,itypj)
1511           endif
1512 !         print '(2(a3,2i3),a3,2f10.5)',
1513 !     &        ' i=',i,iti,' j=',j,itj,' d=',dist(nres+i,nres+j)
1514 !     &        ,rcomp
1515             xj=c(1,nres+j)-xi
1516             yj=c(2,nres+j)-yi
1517             zj=c(3,nres+j)-zi
1518             dxj=dc_norm(1,nres+j)
1519             dyj=dc_norm(2,nres+j)
1520             dzj=dc_norm(3,nres+j)
1521             rrij=1.0D0/(xj*xj+yj*yj+zj*zj)
1522             rij=dsqrt(rrij)
1523             call sc_angular
1524             sigsq=1.0D0/sigsq
1525             sig=sig0ij*dsqrt(sigsq)
1526             rij_shift=1.0D0/rij-sig+sig0ij
1527
1528 !t          if ( 1.0/rij .lt. redfac*rcomp .or. 
1529 !t     &       rij_shift.le.0.0D0 ) then
1530             if ( rij_shift.le.0.0D0 ) then
1531 !d           write (iout,'(a,i3,a,i3,a,f10.5,a,3f10.5)')
1532 !d     &     'overlap SC-SC: i=',i,' j=',j,
1533 !d     &     ' dist=',dist(nres+i,nres+j),' rcomp=',
1534 !d     &     rcomp,1.0/rij,rij_shift
1535           ioverlap_last=ioverlap_last+1
1536           ioverlap(ioverlap_last)=i         
1537           do k=1,ioverlap_last-1
1538            if (ioverlap(k).eq.i) ioverlap_last=ioverlap_last-1
1539           enddo
1540           ioverlap_last=ioverlap_last+1
1541           ioverlap(ioverlap_last)=j         
1542           do k=1,ioverlap_last-1
1543            if (ioverlap(k).eq.j) ioverlap_last=ioverlap_last-1
1544           enddo 
1545          endif
1546         enddo
1547        enddo
1548       enddo
1549       return
1550       end subroutine overlap_sc_list
1551 #endif
1552 !-----------------------------------------------------------------------------
1553 ! energy_p_new_barrier.F
1554 !-----------------------------------------------------------------------------
1555       subroutine sc_angular
1556 ! Calculate eps1,eps2,eps3,sigma, and parts of their derivatives in om1,om2,
1557 ! om12. Called by ebp, egb, and egbv.
1558       use calc_data
1559 !      implicit none
1560 !      include 'COMMON.CALC'
1561 !      include 'COMMON.IOUNITS'
1562       erij(1)=xj*rij
1563       erij(2)=yj*rij
1564       erij(3)=zj*rij
1565       om1=dxi*erij(1)+dyi*erij(2)+dzi*erij(3)
1566       om2=dxj*erij(1)+dyj*erij(2)+dzj*erij(3)
1567       om12=dxi*dxj+dyi*dyj+dzi*dzj
1568       chiom12=chi12*om12
1569 ! Calculate eps1(om12) and its derivative in om12
1570       faceps1=1.0D0-om12*chiom12
1571       faceps1_inv=1.0D0/faceps1
1572       eps1=dsqrt(faceps1_inv)
1573 ! Following variable is eps1*deps1/dom12
1574       eps1_om12=faceps1_inv*chiom12
1575 ! diagnostics only
1576 !      faceps1_inv=om12
1577 !      eps1=om12
1578 !      eps1_om12=1.0d0
1579 !      write (iout,*) "om12",om12," eps1",eps1
1580 ! Calculate sigma(om1,om2,om12) and the derivatives of sigma**2 in om1,om2,
1581 ! and om12.
1582       om1om2=om1*om2
1583       chiom1=chi1*om1
1584       chiom2=chi2*om2
1585       facsig=om1*chiom1+om2*chiom2-2.0D0*om1om2*chiom12
1586       sigsq=1.0D0-facsig*faceps1_inv
1587       sigsq_om1=(chiom1-chiom12*om2)*faceps1_inv
1588       sigsq_om2=(chiom2-chiom12*om1)*faceps1_inv
1589       sigsq_om12=-chi12*(om1om2*faceps1-om12*facsig)*faceps1_inv**2
1590 ! diagnostics only
1591 !      sigsq=1.0d0
1592 !      sigsq_om1=0.0d0
1593 !      sigsq_om2=0.0d0
1594 !      sigsq_om12=0.0d0
1595 !      write (iout,*) "chiom1",chiom1," chiom2",chiom2," chiom12",chiom12
1596 !      write (iout,*) "faceps1",faceps1," faceps1_inv",faceps1_inv,
1597 !     &    " eps1",eps1
1598 ! Calculate eps2 and its derivatives in om1, om2, and om12.
1599       chipom1=chip1*om1
1600       chipom2=chip2*om2
1601       chipom12=chip12*om12
1602       facp=1.0D0-om12*chipom12
1603       facp_inv=1.0D0/facp
1604       facp1=om1*chipom1+om2*chipom2-2.0D0*om1om2*chipom12
1605 !      write (iout,*) "chipom1",chipom1," chipom2",chipom2,
1606 !     &  " chipom12",chipom12," facp",facp," facp_inv",facp_inv
1607 ! Following variable is the square root of eps2
1608       eps2rt=1.0D0-facp1*facp_inv
1609 ! Following three variables are the derivatives of the square root of eps
1610 ! in om1, om2, and om12.
1611       eps2rt_om1=-4.0D0*(chipom1-chipom12*om2)*facp_inv
1612       eps2rt_om2=-4.0D0*(chipom2-chipom12*om1)*facp_inv
1613       eps2rt_om12=4.0D0*chip12*(om1om2*facp-om12*facp1)*facp_inv**2 
1614 ! Evaluate the "asymmetric" factor in the VDW constant, eps3
1615       eps3rt=1.0D0-alf1*om1+alf2*om2-alf12*om12 
1616 !      write (iout,*) "eps2rt",eps2rt," eps3rt",eps3rt
1617 !      write (iout,*) "eps2rt_om1",eps2rt_om1," eps2rt_om2",eps2rt_om2,
1618 !     &  " eps2rt_om12",eps2rt_om12
1619 ! Calculate whole angle-dependent part of epsilon and contributions
1620 ! to its derivatives
1621       return
1622       end subroutine sc_angular
1623 !-----------------------------------------------------------------------------
1624 ! initialize_p.F
1625       subroutine sc_angular_nucl
1626 ! Calculate eps1,eps2,eps3,sigma, and parts of their derivatives in om1,om2,
1627 ! om12. Called by ebp, egb, and egbv.
1628 !      use calc_data
1629 !      implicit none
1630 !      include 'COMMON.CALC'
1631 !      include 'COMMON.IOUNITS'
1632       use comm_locel
1633       use calc_data_nucl
1634       erij(1)=xj*rij
1635       erij(2)=yj*rij
1636       erij(3)=zj*rij
1637       om1=dxi*erij(1)+dyi*erij(2)+dzi*erij(3)
1638       om2=dxj*erij(1)+dyj*erij(2)+dzj*erij(3)
1639       om12=dxi*dxj+dyi*dyj+dzi*dzj
1640       chiom12=chi12*om12
1641 ! Calculate eps1(om12) and its derivative in om12
1642       faceps1=1.0D0-om12*chiom12
1643       faceps1_inv=1.0D0/faceps1
1644       eps1=dsqrt(faceps1_inv)
1645 ! Following variable is eps1*deps1/dom12
1646       eps1_om12=faceps1_inv*chiom12
1647 ! diagnostics only
1648 !      faceps1_inv=om12
1649 !      eps1=om12
1650 !      eps1_om12=1.0d0
1651 !      write (iout,*) "om12",om12," eps1",eps1
1652 ! Calculate sigma(om1,om2,om12) and the derivatives of sigma**2 in om1,om2,
1653 ! and om12.
1654       om1om2=om1*om2
1655       chiom1=chi1*om1
1656       chiom2=chi2*om2
1657       facsig=om1*chiom1+om2*chiom2-2.0D0*om1om2*chiom12
1658       sigsq=1.0D0-facsig*faceps1_inv
1659       sigsq_om1=(chiom1-chiom12*om2)*faceps1_inv
1660       sigsq_om2=(chiom2-chiom12*om1)*faceps1_inv
1661       sigsq_om12=-chi12*(om1om2*faceps1-om12*facsig)*faceps1_inv**2
1662       chipom1=chip1*om1
1663       chipom2=chip2*om2
1664       chipom12=chip12*om12
1665       facp=1.0D0-om12*chipom12
1666       facp_inv=1.0D0/facp
1667       facp1=om1*chipom1+om2*chipom2-2.0D0*om1om2*chipom12
1668 !      write (iout,*) "chipom1",chipom1," chipom2",chipom2,
1669 !     &  " chipom12",chipom12," facp",facp," facp_inv",facp_inv
1670 ! Following variable is the square root of eps2
1671       eps2rt=1.0D0-facp1*facp_inv
1672 ! Following three variables are the derivatives of the square root of eps
1673 ! in om1, om2, and om12.
1674       eps2rt_om1=-4.0D0*(chipom1-chipom12*om2)*facp_inv
1675       eps2rt_om2=-4.0D0*(chipom2-chipom12*om1)*facp_inv
1676       eps2rt_om12=4.0D0*chip12*(om1om2*facp-om12*facp1)*facp_inv**2
1677 ! Evaluate the "asymmetric" factor in the VDW constant, eps3
1678       eps3rt=1.0D0-alf1*om1+alf2*om2-alf12*om12
1679 !      write (iout,*) "eps2rt",eps2rt," eps3rt",eps3rt
1680 !      write (iout,*) "eps2rt_om1",eps2rt_om1," eps2rt_om2",eps2rt_om2,
1681 !     &  " eps2rt_om12",eps2rt_om12
1682 ! Calculate whole angle-dependent part of epsilon and contributions
1683 ! to its derivatives
1684       return
1685       end subroutine sc_angular_nucl
1686
1687 !-----------------------------------------------------------------------------
1688       subroutine int_bounds(total_ints,lower_bound,upper_bound)
1689 !      implicit real*8 (a-h,o-z)
1690 !      include 'DIMENSIONS'
1691       include 'mpif.h'
1692 !      include 'COMMON.SETUP'
1693       integer :: total_ints,lower_bound,upper_bound,nint
1694       integer,dimension(0:nfgtasks) :: int4proc,sint4proc       !(0:max_fg_procs)
1695       integer :: i,nexcess
1696       nint=total_ints/nfgtasks
1697       do i=1,nfgtasks
1698         int4proc(i-1)=nint
1699       enddo
1700       nexcess=total_ints-nint*nfgtasks
1701       do i=1,nexcess
1702         int4proc(nfgtasks-i)=int4proc(nfgtasks-i)+1
1703       enddo
1704       lower_bound=0
1705       do i=0,fg_rank-1
1706         lower_bound=lower_bound+int4proc(i)
1707       enddo 
1708       upper_bound=lower_bound+int4proc(fg_rank)
1709       lower_bound=lower_bound+1
1710       return
1711       end subroutine int_bounds
1712 !-----------------------------------------------------------------------------
1713       subroutine int_bounds1(total_ints,lower_bound,upper_bound)
1714 !      implicit real*8 (a-h,o-z)
1715 !      include 'DIMENSIONS'
1716       include 'mpif.h'
1717 !      include 'COMMON.SETUP'
1718       integer :: total_ints,lower_bound,upper_bound,nint
1719       integer :: nexcess,i
1720       integer,dimension(0:nfgtasks) :: int4proc,sint4proc       !(0:max_fg_procs)
1721       nint=total_ints/nfgtasks1
1722       do i=1,nfgtasks1
1723         int4proc(i-1)=nint
1724       enddo
1725       nexcess=total_ints-nint*nfgtasks1
1726       do i=1,nexcess
1727         int4proc(nfgtasks1-i)=int4proc(nfgtasks1-i)+1
1728       enddo
1729       lower_bound=0
1730       do i=0,fg_rank1-1
1731         lower_bound=lower_bound+int4proc(i)
1732       enddo 
1733       upper_bound=lower_bound+int4proc(fg_rank1)
1734       lower_bound=lower_bound+1
1735       return
1736       end subroutine int_bounds1
1737 !-----------------------------------------------------------------------------
1738 ! intcartderiv.F
1739 !-----------------------------------------------------------------------------
1740       subroutine chainbuild_cart
1741 !      implicit real*8 (a-h,o-z)
1742 !      include 'DIMENSIONS'
1743       use control_data
1744 #ifdef MPI
1745       include 'mpif.h'
1746 #endif
1747 !      include 'COMMON.SETUP'
1748 !      include 'COMMON.CHAIN' 
1749 !      include 'COMMON.LOCAL'
1750 !      include 'COMMON.TIME1'
1751 !      include 'COMMON.IOUNITS'
1752       integer :: j,i,ierror,ierr
1753       real(kind=8) :: time00,time01
1754 #ifdef MPI
1755       if (nfgtasks.gt.1) then
1756 !        write (iout,*) "BCAST in chainbuild_cart"
1757 !        call flush(iout)
1758 ! Broadcast the order to build the chain and compute internal coordinates
1759 ! to the slaves. The slaves receive the order in ERGASTULUM.
1760         time00=MPI_Wtime()
1761 !      write (iout,*) "CHAINBUILD_CART: DC before BCAST"
1762 !      do i=0,nres
1763 !        write (iout,'(i3,3f10.5,5x,3f10.5)') i,(dc(j,i),j=1,3),
1764 !     &   (dc(j,i+nres),j=1,3)
1765 !      enddo 
1766         if (fg_rank.eq.0) &
1767           call MPI_Bcast(7,1,MPI_INTEGER,king,FG_COMM,IERROR)
1768         time_bcast7=time_bcast7+MPI_Wtime()-time00
1769         time01=MPI_Wtime()
1770         call MPI_Bcast(dc(1,0),6*(nres+1),MPI_DOUBLE_PRECISION,&
1771           king,FG_COMM,IERR)
1772 !      write (iout,*) "CHAINBUILD_CART: DC after BCAST"
1773 !      do i=0,nres
1774 !        write (iout,'(i3,3f10.5,5x,3f10.5)') i,(dc(j,i),j=1,3),
1775 !     &   (dc(j,i+nres),j=1,3)
1776 !      enddo 
1777 !        write (iout,*) "End BCAST in chainbuild_cart"
1778 !        call flush(iout)
1779         time_bcast=time_bcast+MPI_Wtime()-time00
1780         time_bcastc=time_bcastc+MPI_Wtime()-time01
1781       endif
1782 #endif
1783       do j=1,3
1784         c(j,1)=dc(j,0)
1785       enddo
1786       do i=2,nres
1787         do j=1,3
1788           c(j,i)=c(j,i-1)+dc(j,i-1)
1789         enddo
1790       enddo 
1791       do i=1,nres
1792         do j=1,3
1793           c(j,i+nres)=c(j,i)+dc(j,i+nres)
1794         enddo
1795       enddo
1796 !      write (iout,*) "CHAINBUILD_CART"
1797 !      call cartprint
1798       call int_from_cart1(.false.)
1799       return
1800       end subroutine chainbuild_cart
1801 !-----------------------------------------------------------------------------
1802 ! intcor.f
1803 !-----------------------------------------------------------------------------
1804       real(kind=8) function alpha(i1,i2,i3)
1805 !
1806 !  Calculates the planar angle between atoms (i1), (i2), and (i3).
1807 !
1808 !      implicit real*8 (a-h,o-z)
1809 !      include 'DIMENSIONS'
1810 !      include 'COMMON.GEO'
1811 !      include 'COMMON.CHAIN'
1812 !el local variables
1813       integer :: i1,i2,i3
1814       real(kind=8) :: x12,x23,y12,y23,z12,z23,vnorm,wnorm,scalar
1815       x12=c(1,i1)-c(1,i2)
1816       x23=c(1,i3)-c(1,i2)
1817       y12=c(2,i1)-c(2,i2)
1818       y23=c(2,i3)-c(2,i2)
1819       z12=c(3,i1)-c(3,i2)
1820       z23=c(3,i3)-c(3,i2)
1821       vnorm=dsqrt(x12*x12+y12*y12+z12*z12)
1822       wnorm=dsqrt(x23*x23+y23*y23+z23*z23)
1823       scalar=(x12*x23+y12*y23+z12*z23)/(vnorm*wnorm)
1824       alpha=arcos(scalar)
1825       return
1826       end function alpha
1827 !-----------------------------------------------------------------------------
1828       real(kind=8) function beta(i1,i2,i3,i4)
1829 !
1830 !  Calculates the dihedral angle between atoms (i1), (i2), (i3) and (i4)
1831 !
1832 !      implicit real*8 (a-h,o-z)
1833 !      include 'DIMENSIONS'
1834 !      include 'COMMON.GEO'
1835 !      include 'COMMON.CHAIN'
1836 !el local variables
1837       integer :: i1,i2,i3,i4
1838       real(kind=8) :: x12,x23,x34,y12,y23,y34,z12,z23,z34
1839       real(kind=8) :: wx,wy,wz,wnorm,vx,vy,vz,vnorm,scalar,angle
1840       real(kind=8) :: tx,ty,tz
1841       x12=c(1,i1)-c(1,i2)
1842       x23=c(1,i3)-c(1,i2)
1843       x34=c(1,i4)-c(1,i3)
1844       y12=c(2,i1)-c(2,i2)
1845       y23=c(2,i3)-c(2,i2)
1846       y34=c(2,i4)-c(2,i3)
1847       z12=c(3,i1)-c(3,i2)
1848       z23=c(3,i3)-c(3,i2)
1849       z34=c(3,i4)-c(3,i3)
1850 !d    print '(2i3,3f10.5)',i1,i2,x12,y12,z12
1851 !d    print '(2i3,3f10.5)',i2,i3,x23,y23,z23
1852 !d    print '(2i3,3f10.5)',i3,i4,x34,y34,z34
1853       wx=-y23*z34+y34*z23
1854       wy=x23*z34-z23*x34
1855       wz=-x23*y34+y23*x34
1856       wnorm=dsqrt(wx*wx+wy*wy+wz*wz)
1857       vx=y12*z23-z12*y23
1858       vy=-x12*z23+z12*x23
1859       vz=x12*y23-y12*x23
1860       vnorm=dsqrt(vx*vx+vy*vy+vz*vz)
1861       if (vnorm.gt.1.0D-13 .and. wnorm.gt.1.0D-13) then
1862       scalar=(vx*wx+vy*wy+vz*wz)/(vnorm*wnorm)
1863       if (dabs(scalar).gt.1.0D0) &
1864       scalar=0.99999999999999D0*scalar/dabs(scalar)
1865       angle=dacos(scalar)
1866 !d    print '(2i4,10f7.3)',i2,i3,vx,vy,vz,wx,wy,wz,vnorm,wnorm,
1867 !d   &scalar,angle
1868       else
1869       angle=pi
1870       endif 
1871 !     if (angle.le.0.0D0) angle=pi+angle
1872       tx=vy*wz-vz*wy
1873       ty=-vx*wz+vz*wx
1874       tz=vx*wy-vy*wx
1875       scalar=tx*x23+ty*y23+tz*z23
1876       if (scalar.lt.0.0D0) angle=-angle
1877       beta=angle
1878       return
1879       end function beta
1880 !-----------------------------------------------------------------------------
1881       real(kind=8) function dist(i1,i2)
1882 !
1883 !  Calculates the distance between atoms (i1) and (i2).
1884 !
1885 !      implicit real*8 (a-h,o-z)
1886 !      include 'DIMENSIONS'
1887 !      include 'COMMON.GEO'
1888 !      include 'COMMON.CHAIN'
1889 !el local variables
1890       integer :: i1,i2
1891       real(kind=8) :: x12,y12,z12
1892       x12=c(1,i1)-c(1,i2)
1893       y12=c(2,i1)-c(2,i2)
1894       z12=c(3,i1)-c(3,i2)
1895       dist=dsqrt(x12*x12+y12*y12+z12*z12)
1896       return
1897       end function dist
1898 #if .not. defined(WHAM_RUN) && .not. defined(CLUSTER)
1899 !-----------------------------------------------------------------------------
1900 ! local_move.f
1901 !-----------------------------------------------------------------------------
1902       subroutine local_move_init(debug)
1903 !rc      implicit none
1904
1905 !     Includes
1906 !      implicit real*8 (a-h,o-z)
1907 !      include 'DIMENSIONS'  ! Needed by COMMON.LOCAL
1908 !      include 'COMMON.GEO'  ! For pi, deg2rad
1909 !      include 'COMMON.LOCAL'  ! For vbl
1910 !      include 'COMMON.LOCMOVE'
1911
1912 !     INPUT arguments
1913       logical :: debug
1914
1915
1916 !     Determine wheter to do some debugging output
1917       locmove_output=debug
1918
1919 !     Set the init_called flag to 1
1920       init_called=1
1921
1922 !     The following are never changed
1923       min_theta=60.D0*deg2rad  ! (0,PI)
1924       max_theta=175.D0*deg2rad  ! (0,PI)
1925       dmin2=vbl*vbl*2.*(1.-cos(min_theta))
1926       dmax2=vbl*vbl*2.*(1.-cos(max_theta))
1927       flag=1.0D300
1928       small=1.0D-5
1929       small2=0.5*small*small
1930
1931 !     Not really necessary...
1932       a_n=0
1933       b_n=0
1934       res_n=0
1935
1936       return
1937       end subroutine local_move_init
1938 !-----------------------------------------------------------------------------
1939       subroutine local_move(n_start, n_end, PHImin, PHImax)
1940 !     Perform a local move between residues m and n (inclusive)
1941 !     PHImin and PHImax [0,PI] determine the size of the move
1942 !     Works on whatever structure is in the variables theta and phi,
1943 !     sidechain variables are left untouched
1944 !     The final structure is NOT minimized, but both the cartesian
1945 !     variables c and the angles are up-to-date at the end (no further
1946 !     chainbuild is required)
1947 !rc      implicit none
1948       use random,only:ran_number
1949 !     Includes
1950 !      implicit real*8 (a-h,o-z)
1951 !      include 'DIMENSIONS'
1952 !      include 'COMMON.GEO'
1953 !      include 'COMMON.CHAIN'
1954 !      include 'COMMON.VAR'
1955 !      include 'COMMON.MINIM'
1956 !      include 'COMMON.SBRIDGE'
1957 !      include 'COMMON.LOCMOVE'
1958
1959 !     External functions
1960 !EL      integer move_res
1961 !EL      external move_res
1962 !EL      double precision ran_number
1963 !EL      external ran_number
1964
1965 !     INPUT arguments
1966       integer :: n_start, n_end  ! First and last residues to move
1967       real(kind=8) :: PHImin, PHImax  ! min/max angles [0,PI]
1968
1969 !     Local variables
1970       integer :: i,j
1971       real(kind=8) :: min,max
1972       integer :: iretcode
1973
1974
1975 !     Check if local_move_init was called.  This assumes that it
1976 !     would not be 1 if not explicitely initialized
1977       if (init_called.ne.1) then
1978         write(6,*)'   ***   local_move_init not called!!!'
1979         stop
1980       endif
1981
1982 !     Quick check for crazy range
1983       if (n_start.gt.n_end .or. n_start.lt.1 .or. n_end.gt.nres) then
1984         write(6,'(a,i3,a,i3)') &
1985              '   ***   Cannot make local move between n_start = ',&
1986              n_start,' and n_end = ',n_end
1987         return
1988       endif
1989
1990 !     Take care of end residues first...
1991       if (n_start.eq.1) then
1992 !     Move residue 1 (completely random)
1993         theta(3)=ran_number(min_theta,max_theta)
1994         phi(4)=ran_number(-PI,PI)
1995         i=2
1996       else
1997         i=n_start
1998       endif
1999       if (n_end.eq.nres) then
2000 !     Move residue nres (completely random)
2001         theta(nres)=ran_number(min_theta,max_theta)
2002         phi(nres)=ran_number(-PI,PI)
2003         j=nres-1
2004       else
2005         j=n_end
2006       endif
2007
2008 !     ...then go through all other residues one by one
2009 !     Start from the two extremes and converge
2010       call chainbuild
2011       do while (i.le.j)
2012         min=PHImin
2013         max=PHImax
2014 !$$$c     Move the first two residues by less than the others
2015 !$$$        if (i-n_start.lt.3) then
2016 !$$$          if (i-n_start.eq.0) then
2017 !$$$            min=0.4*PHImin
2018 !$$$            max=0.4*PHImax
2019 !$$$          else if (i-n_start.eq.1) then
2020 !$$$            min=0.8*PHImin
2021 !$$$            max=0.8*PHImax
2022 !$$$          else if (i-n_start.eq.2) then
2023 !$$$            min=PHImin
2024 !$$$            max=PHImax
2025 !$$$          endif
2026 !$$$        endif
2027
2028 !     The actual move, on residue i
2029         iretcode=move_res(min,max,i)  ! Discard iretcode
2030         i=i+1
2031
2032         if (i.le.j) then
2033           min=PHImin
2034           max=PHImax
2035 !$$$c     Move the last two residues by less than the others
2036 !$$$          if (n_end-j.lt.3) then
2037 !$$$            if (n_end-j.eq.0) then
2038 !$$$              min=0.4*PHImin
2039 !$$$              max=0.4*PHImax
2040 !$$$            else if (n_end-j.eq.1) then
2041 !$$$              min=0.8*PHImin
2042 !$$$              max=0.8*PHImax
2043 !$$$            else if (n_end-j.eq.2) then
2044 !$$$              min=PHImin
2045 !$$$              max=PHImax
2046 !$$$            endif
2047 !$$$          endif
2048
2049 !     The actual move, on residue j
2050           iretcode=move_res(min,max,j)  ! Discard iretcode
2051           j=j-1
2052         endif
2053       enddo
2054
2055       call int_from_cart(.false.,.false.)
2056
2057       return
2058       end subroutine local_move
2059 !-----------------------------------------------------------------------------
2060       subroutine output_tabs
2061 !     Prints out the contents of a_..., b_..., res_...
2062 !      implicit none
2063
2064 !     Includes
2065 !      include 'COMMON.GEO'
2066 !      include 'COMMON.LOCMOVE'
2067
2068 !     Local variables
2069       integer :: i,j
2070
2071       write(6,*)'a_...'
2072       write(6,'(8f7.1)')(a_ang(i)*rad2deg,i=0,a_n-1)
2073       write(6,'(8(2x,3l1,2x))')((a_tab(i,j),i=0,2),j=0,a_n-1)
2074
2075       write(6,*)'b_...'
2076       write(6,'(4f7.1)')(b_ang(i)*rad2deg,i=0,b_n-1)
2077       write(6,'(4(2x,3l1,2x))')((b_tab(i,j),i=0,2),j=0,b_n-1)
2078
2079       write(6,*)'res_...'
2080       write(6,'(12f7.1)')(res_ang(i)*rad2deg,i=0,res_n-1)
2081       write(6,'(12(2x,3l1,2x))')((res_tab(0,i,j),i=0,2),j=0,res_n-1)
2082       write(6,'(12(2x,3l1,2x))')((res_tab(1,i,j),i=0,2),j=0,res_n-1)
2083       write(6,'(12(2x,3l1,2x))')((res_tab(2,i,j),i=0,2),j=0,res_n-1)
2084
2085       return
2086       end subroutine output_tabs
2087 !-----------------------------------------------------------------------------
2088       subroutine angles2tab(PHImin,PHImax,n,ang,tab)
2089 !     Only uses angles if [0,PI] (but PHImin cannot be 0.,
2090 !     and PHImax cannot be PI)
2091 !      implicit none
2092
2093 !     Includes
2094 !      include 'COMMON.GEO'
2095
2096 !     INPUT arguments
2097       real(kind=8) :: PHImin,PHImax
2098
2099 !     OUTPUT arguments
2100       integer :: n
2101       real(kind=8),dimension(0:3) :: ang
2102       logical,dimension(0:2,0:3) :: tab
2103
2104
2105       if (PHImin .eq. PHImax) then
2106 !     Special case with two 010's
2107         n = 2;
2108         ang(0) = -PHImin;
2109         ang(1) = PHImin;
2110         tab(0,0) = .false.
2111         tab(2,0) = .false.
2112         tab(0,1) = .false.
2113         tab(2,1) = .false.
2114         tab(1,0) = .true.
2115         tab(1,1) = .true.
2116       else if (PHImin .eq. PI) then
2117 !     Special case with one 010
2118         n = 1
2119         ang(0) = PI
2120         tab(0,0) = .false.
2121         tab(2,0) = .false.
2122         tab(1,0) = .true.
2123       else if (PHImax .eq. 0.) then
2124 !     Special case with one 010
2125         n = 1
2126         ang(0) = 0.
2127         tab(0,0) = .false.
2128         tab(2,0) = .false.
2129         tab(1,0) = .true.
2130       else
2131 !     Standard cases
2132         n = 0
2133         if (PHImin .gt. 0.) then
2134 !     Start of range (011)
2135           ang(n) = PHImin
2136           tab(0,n) = .false.
2137           tab(1,n) = .true.
2138           tab(2,n) = .true.
2139 !     End of range (110)
2140           ang(n+1) = -PHImin
2141           tab(0,n+1) = .true.
2142           tab(1,n+1) = .true.
2143           tab(2,n+1) = .false.
2144           n = n+2
2145         endif
2146         if (PHImax .lt. PI) then
2147 !     Start of range (011)
2148           ang(n) = -PHImax
2149           tab(0,n) = .false.
2150           tab(1,n) = .true.
2151           tab(2,n) = .true.
2152 !     End of range (110)
2153           ang(n+1) = PHImax
2154           tab(0,n+1) = .true.
2155           tab(1,n+1) = .true.
2156           tab(2,n+1) = .false.
2157           n = n+2
2158         endif
2159       endif
2160
2161       return
2162       end subroutine angles2tab
2163 !-----------------------------------------------------------------------------
2164       subroutine minmax_angles(x,y,z,r,n,ang,tab)
2165 !     When solutions do not exist, assume all angles
2166 !     are acceptable - i.e., initial geometry must be correct
2167 !      implicit none
2168
2169 !     Includes
2170 !      include 'COMMON.GEO'
2171 !      include 'COMMON.LOCMOVE'
2172
2173 !     Input arguments
2174       real(kind=8) :: x,y,z,r
2175
2176 !     Output arguments
2177       integer :: n
2178       real(kind=8),dimension(0:3) :: ang
2179       logical,dimension(0:2,0:3) :: tab
2180
2181 !     Local variables
2182       real(kind=8) :: num, denom, phi
2183       real(kind=8) :: Kmin, Kmax
2184       integer :: i
2185
2186
2187       num = x*x + y*y + z*z
2188       denom = x*x + y*y
2189       n = 0
2190       if (denom .gt. 0.) then
2191         phi = atan2(y,x)
2192         denom = 2.*r*sqrt(denom)
2193         num = num+r*r
2194         Kmin = (num - dmin2)/denom
2195         Kmax = (num - dmax2)/denom
2196
2197 !     Allowed values of K (else all angles are acceptable)
2198 !     -1 <= Kmin <  1
2199 !     -1 <  Kmax <= 1
2200         if (Kmin .gt. 1. .or. abs(Kmin-1.) .lt. small2) then
2201           Kmin = -flag
2202         else if (Kmin .lt. -1. .or. abs(Kmin+1.) .lt. small2) then
2203           Kmin = PI
2204         else
2205           Kmin = acos(Kmin)
2206         endif
2207
2208         if (Kmax .lt. -1. .or. abs(Kmax+1.) .lt. small2) then
2209           Kmax = flag
2210         else if (Kmax .gt. 1. .or. abs(Kmax-1.) .lt. small2) then
2211           Kmax = 0.
2212         else
2213           Kmax = acos(Kmax)
2214         endif
2215
2216         if (Kmax .lt. Kmin) Kmax = Kmin
2217
2218         call angles2tab(Kmin, Kmax, n, ang, tab)
2219
2220 !     Add phi and check that angles are within range (-PI,PI]
2221         do i=0,n-1
2222           ang(i) = ang(i)+phi
2223           if (ang(i) .le. -PI) then
2224             ang(i) = ang(i)+2.*PI
2225           else if (ang(i) .gt. PI) then
2226             ang(i) = ang(i)-2.*PI
2227           endif
2228         enddo
2229       endif
2230
2231       return
2232       end subroutine minmax_angles
2233 !-----------------------------------------------------------------------------
2234       subroutine construct_tab
2235 !     Take a_... and b_... values and produces the results res_...
2236 !     x_ang are assumed to be all different (diff > small)
2237 !     x_tab(1,i) must be 1 for all i (i.e., all x_ang are acceptable)
2238 !      implicit none
2239
2240 !     Includes
2241 !      include 'COMMON.LOCMOVE'
2242
2243 !     Local variables
2244       integer :: n_max,i,j,index
2245       logical :: done
2246       real(kind=8) :: phi
2247
2248
2249       n_max = a_n + b_n
2250       if (n_max .eq. 0) then
2251         res_n = 0
2252         return
2253       endif
2254
2255       do i=0,n_max-1
2256         do j=0,1
2257           res_tab(j,0,i) = .true.
2258           res_tab(j,2,i) = .true.
2259           res_tab(j,1,i) = .false.
2260         enddo
2261       enddo
2262
2263       index = 0
2264       phi = -flag
2265       done = .false.
2266       do while (.not.done)
2267         res_ang(index) = flag
2268
2269 !     Check a first...
2270         do i=0,a_n-1
2271           if ((a_ang(i)-phi).gt.small .and. &
2272                a_ang(i) .lt. res_ang(index)) then
2273 !     Found a lower angle
2274             res_ang(index) = a_ang(i)
2275 !     Copy the values from a_tab into res_tab(0,,)
2276             res_tab(0,0,index) = a_tab(0,i)
2277             res_tab(0,1,index) = a_tab(1,i)
2278             res_tab(0,2,index) = a_tab(2,i)
2279 !     Set default values for res_tab(1,,)
2280             res_tab(1,0,index) = .true.
2281             res_tab(1,1,index) = .false.
2282             res_tab(1,2,index) = .true.
2283           else if (abs(a_ang(i)-res_ang(index)).lt.small) then
2284 !     Found an equal angle (can only be equal to a b_ang)
2285             res_tab(0,0,index) = a_tab(0,i)
2286             res_tab(0,1,index) = a_tab(1,i)
2287             res_tab(0,2,index) = a_tab(2,i)
2288           endif
2289         enddo
2290 !     ...then check b
2291         do i=0,b_n-1
2292           if ((b_ang(i)-phi).gt.small .and. &
2293                b_ang(i) .lt. res_ang(index)) then
2294 !     Found a lower angle
2295             res_ang(index) = b_ang(i)
2296 !     Copy the values from b_tab into res_tab(1,,)
2297             res_tab(1,0,index) = b_tab(0,i)
2298             res_tab(1,1,index) = b_tab(1,i)
2299             res_tab(1,2,index) = b_tab(2,i)
2300 !     Set default values for res_tab(0,,)
2301             res_tab(0,0,index) = .true.
2302             res_tab(0,1,index) = .false.
2303             res_tab(0,2,index) = .true.
2304           else if (abs(b_ang(i)-res_ang(index)).lt.small) then
2305 !     Found an equal angle (can only be equal to an a_ang)
2306             res_tab(1,0,index) = b_tab(0,i)
2307             res_tab(1,1,index) = b_tab(1,i)
2308             res_tab(1,2,index) = b_tab(2,i)
2309           endif
2310         enddo
2311
2312         if (res_ang(index) .eq. flag) then
2313           res_n = index
2314           done = .true.
2315         else if (index .eq. n_max-1) then
2316           res_n = n_max
2317           done = .true.
2318         else
2319           phi = res_ang(index)  ! Store previous angle
2320           index = index+1
2321         endif
2322       enddo
2323
2324 !     Fill the gaps
2325 !     First a...
2326       index = 0
2327       if (a_n .gt. 0) then
2328         do while (.not.res_tab(0,1,index))
2329           index=index+1
2330         enddo
2331         done = res_tab(0,2,index)
2332         do i=index+1,res_n-1
2333           if (res_tab(0,1,i)) then
2334             done = res_tab(0,2,i)
2335           else
2336             res_tab(0,0,i) = done
2337             res_tab(0,1,i) = done
2338             res_tab(0,2,i) = done
2339           endif
2340         enddo
2341         done = res_tab(0,0,index)
2342         do i=index-1,0,-1
2343           if (res_tab(0,1,i)) then
2344             done = res_tab(0,0,i)
2345           else
2346             res_tab(0,0,i) = done
2347             res_tab(0,1,i) = done
2348             res_tab(0,2,i) = done
2349           endif
2350         enddo
2351       else
2352         do i=0,res_n-1
2353           res_tab(0,0,i) = .true.
2354           res_tab(0,1,i) = .true.
2355           res_tab(0,2,i) = .true.
2356         enddo
2357       endif
2358 !     ...then b
2359       index = 0
2360       if (b_n .gt. 0) then
2361         do while (.not.res_tab(1,1,index))
2362           index=index+1
2363         enddo
2364         done = res_tab(1,2,index)
2365         do i=index+1,res_n-1
2366           if (res_tab(1,1,i)) then
2367             done = res_tab(1,2,i)
2368           else
2369             res_tab(1,0,i) = done
2370             res_tab(1,1,i) = done
2371             res_tab(1,2,i) = done
2372           endif
2373         enddo
2374         done = res_tab(1,0,index)
2375         do i=index-1,0,-1
2376           if (res_tab(1,1,i)) then
2377             done = res_tab(1,0,i)
2378           else
2379             res_tab(1,0,i) = done
2380             res_tab(1,1,i) = done
2381             res_tab(1,2,i) = done
2382           endif
2383         enddo
2384       else
2385         do i=0,res_n-1
2386           res_tab(1,0,i) = .true.
2387           res_tab(1,1,i) = .true.
2388           res_tab(1,2,i) = .true.
2389         enddo
2390       endif
2391
2392 !     Finally fill the last row with AND operation
2393       do i=0,res_n-1
2394         do j=0,2
2395           res_tab(2,j,i) = (res_tab(0,j,i) .and. res_tab(1,j,i))
2396         enddo
2397       enddo
2398
2399       return
2400       end subroutine construct_tab
2401 !-----------------------------------------------------------------------------
2402       subroutine construct_ranges(phi_n,phi_start,phi_end)
2403 !     Given the data in res_..., construct a table of 
2404 !     min/max allowed angles
2405 !      implicit none
2406
2407 !     Includes
2408 !      include 'COMMON.GEO'
2409 !      include 'COMMON.LOCMOVE'
2410
2411 !     Output arguments
2412       integer :: phi_n
2413       real(kind=8),dimension(0:11) :: phi_start,phi_end
2414
2415 !     Local variables
2416       logical :: done
2417       integer :: index
2418
2419
2420       if (res_n .eq. 0) then
2421 !     Any move is allowed
2422         phi_n = 1
2423         phi_start(0) = -PI
2424         phi_end(0) = PI
2425       else
2426         phi_n = 0
2427         index = 0
2428         done = .false.
2429         do while (.not.done)
2430 !     Find start of range (01x)
2431           done = .false.
2432           do while (.not.done)
2433             if (res_tab(2,0,index).or.(.not.res_tab(2,1,index))) then
2434               index=index+1
2435             else
2436               done = .true.
2437               phi_start(phi_n) = res_ang(index)
2438             endif
2439             if (index .eq. res_n) done = .true.
2440           enddo
2441 !     If a start was found (index < res_n), find the end of range (x10)
2442 !     It may not be found without wrapping around
2443           if (index .lt. res_n) then
2444             done = .false.
2445             do while (.not.done)
2446               if ((.not.res_tab(2,1,index)).or.res_tab(2,2,index)) then
2447                 index=index+1
2448               else
2449                 done = .true.
2450               endif
2451               if (index .eq. res_n) done = .true.
2452             enddo
2453             if (index .lt. res_n) then
2454 !     Found the end of the range
2455               phi_end(phi_n) = res_ang(index)
2456               phi_n=phi_n+1
2457               index=index+1
2458               if (index .eq. res_n) then
2459                 done = .true.
2460               else
2461                 done = .false.
2462               endif
2463             else
2464 !     Need to wrap around
2465               done = .true.
2466               phi_end(phi_n) = flag
2467             endif
2468           endif
2469         enddo
2470 !     Take care of the last one if need to wrap around
2471         if (phi_end(phi_n) .eq. flag) then
2472           index = 0
2473           do while ((.not.res_tab(2,1,index)).or.res_tab(2,2,index))
2474             index=index+1
2475           enddo
2476           phi_end(phi_n) = res_ang(index) + 2.*PI
2477           phi_n=phi_n+1
2478         endif
2479       endif
2480
2481       return
2482       end subroutine construct_ranges
2483 !-----------------------------------------------------------------------------
2484       subroutine fix_no_moves(phi)
2485 !      implicit none
2486
2487 !     Includes
2488 !      include 'COMMON.GEO'
2489 !      include 'COMMON.LOCMOVE'
2490
2491 !     Output arguments
2492       real(kind=8) :: phi
2493
2494 !     Local variables
2495       integer :: index
2496       real(kind=8) :: diff,temp
2497
2498
2499 !     Look for first 01x in gammas (there MUST be at least one)
2500       diff = flag
2501       index = 0
2502       do while (res_tab(1,0,index) .or. (.not.res_tab(1,1,index)))
2503         index=index+1
2504       enddo
2505       if (res_ang(index) .le. 0.D0) then ! Make sure it's from PHImax
2506 !     Try to increase PHImax
2507         if (index .gt. 0) then
2508           phi = res_ang(index-1)
2509           diff = abs(res_ang(index) - res_ang(index-1))
2510         endif
2511 !     Look for last (corresponding) x10
2512         index = res_n - 1
2513         do while ((.not.res_tab(1,1,index)) .or. res_tab(1,2,index))
2514           index=index-1
2515         enddo
2516         if (index .lt. res_n-1) then
2517           temp = abs(res_ang(index) - res_ang(index+1))
2518           if (temp .lt. diff) then
2519             phi = res_ang(index+1)
2520             diff = temp
2521           endif
2522         endif
2523       endif
2524
2525 !     If increasing PHImax didn't work, decreasing PHImin
2526 !     will (with one exception)
2527 !     Look for first x10 (there MUST be at least one)
2528       index = 0
2529       do while ((.not.res_tab(1,1,index)) .or. res_tab(1,2,index))
2530         index=index+1
2531       enddo
2532       if (res_ang(index) .lt. 0.D0) then ! Make sure it's from PHImin
2533 !     Try to decrease PHImin
2534         if (index .lt. res_n-1) then
2535           temp = abs(res_ang(index) - res_ang(index+1))
2536           if (res_ang(index+1) .le. 0.D0 .and. temp .lt. diff) then
2537             phi = res_ang(index+1)
2538             diff = temp
2539           endif
2540         endif
2541 !     Look for last (corresponding) 01x
2542         index = res_n - 1
2543         do while (res_tab(1,0,index) .or. (.not.res_tab(1,1,index)))
2544           index=index-1
2545         enddo
2546         if (index .gt. 0) then
2547           temp = abs(res_ang(index) - res_ang(index-1))
2548           if (res_ang(index-1) .ge. 0.D0 .and. temp .lt. diff) then
2549             phi = res_ang(index-1)
2550             diff = temp
2551           endif
2552         endif
2553       endif
2554
2555 !     If it still didn't work, it must be PHImax == 0. or PHImin == PI
2556       if (diff .eq. flag) then
2557         index = 0
2558         if (res_tab(index,1,0) .or. (.not.res_tab(index,1,1)) .or. &
2559              res_tab(index,1,2)) index = res_n - 1
2560 !     This MUST work at this point
2561         if (index .eq. 0) then
2562           phi = res_ang(1)
2563         else
2564           phi = res_ang(index - 1)
2565         endif
2566       endif
2567
2568       return
2569       end subroutine fix_no_moves
2570 !-----------------------------------------------------------------------------
2571       integer function move_res(PHImin,PHImax,i_move)
2572 !     Moves residue i_move (in array c), leaving everything else fixed
2573 !     Starting geometry is not checked, it should be correct!
2574 !     R(,i_move) is the only residue that will move, but must have
2575 !     1 < i_move < nres (i.e., cannot move ends)
2576 !     Whether any output is done is controlled by locmove_output
2577 !rc      implicit none
2578       use random,only:ran_number
2579 !     Includes
2580 !      implicit real*8 (a-h,o-z)
2581 !      include 'DIMENSIONS'
2582 !      include 'COMMON.CHAIN'
2583 !      include 'COMMON.GEO'
2584 !      include 'COMMON.LOCMOVE'
2585
2586 !     External functions
2587 !EL      double precision ran_number
2588 !EL      external ran_number
2589
2590 !     Input arguments
2591       real(kind=8) :: PHImin,PHImax
2592       integer :: i_move
2593
2594 !     RETURN VALUES:
2595 !     0: move successfull
2596 !     1: Dmin or Dmax had to be modified
2597 !     2: move failed - check your input geometry
2598
2599
2600 !     Local variables
2601       real(kind=8),dimension(0:2) :: X,Y,Z,Orig
2602       real(kind=8),dimension(0:2) :: P
2603       logical :: no_moves,done
2604       integer :: index,i,j
2605       real(kind=8) :: phi,temp,radius
2606       real(kind=8),dimension(0:11) :: phi_start,phi_end
2607       integer :: phi_n
2608
2609 !     Set up the coordinate system
2610       do i=0,2
2611         Orig(i)=0.5*(c(i+1,i_move-1)+c(i+1,i_move+1)) ! Position of origin
2612       enddo
2613
2614       do i=0,2
2615         Z(i)=c(i+1,i_move+1)-c(i+1,i_move-1)
2616       enddo
2617       temp=sqrt(Z(0)*Z(0)+Z(1)*Z(1)+Z(2)*Z(2))
2618       do i=0,2
2619         Z(i)=Z(i)/temp
2620       enddo
2621
2622       do i=0,2
2623         X(i)=c(i+1,i_move)-Orig(i)
2624       enddo
2625 !     radius is the radius of the circle on which c(,i_move) can move
2626       radius=sqrt(X(0)*X(0)+X(1)*X(1)+X(2)*X(2))
2627       do i=0,2
2628         X(i)=X(i)/radius
2629       enddo
2630
2631       Y(0)=Z(1)*X(2)-X(1)*Z(2)
2632       Y(1)=X(0)*Z(2)-Z(0)*X(2)
2633       Y(2)=Z(0)*X(1)-X(0)*Z(1)
2634
2635 !     Calculate min, max angles coming from dmin, dmax to c(,i_move-2)
2636       if (i_move.gt.2) then
2637         do i=0,2
2638           P(i)=c(i+1,i_move-2)-Orig(i)
2639         enddo
2640         call minmax_angles(P(0)*X(0)+P(1)*X(1)+P(2)*X(2),&
2641              P(0)*Y(0)+P(1)*Y(1)+P(2)*Y(2),&
2642              P(0)*Z(0)+P(1)*Z(1)+P(2)*Z(2),&
2643              radius,a_n,a_ang,a_tab)
2644       else
2645         a_n=0
2646       endif
2647
2648 !     Calculate min, max angles coming from dmin, dmax to c(,i_move+2)
2649       if (i_move.lt.nres-2) then
2650         do i=0,2
2651           P(i)=c(i+1,i_move+2)-Orig(i)
2652         enddo
2653         call minmax_angles(P(0)*X(0)+P(1)*X(1)+P(2)*X(2),&
2654              P(0)*Y(0)+P(1)*Y(1)+P(2)*Y(2),&
2655              P(0)*Z(0)+P(1)*Z(1)+P(2)*Z(2),&
2656              radius,b_n,b_ang,b_tab)
2657       else
2658         b_n=0
2659       endif
2660
2661 !     Construct the resulting table for alpha and beta
2662       call construct_tab()
2663
2664       if (locmove_output) then
2665         print *,'ALPHAS & BETAS TABLE'
2666         call output_tabs()
2667       endif
2668
2669 !     Check that there is at least one possible move
2670       no_moves = .true.
2671       if (res_n .eq. 0) then
2672         no_moves = .false.
2673       else
2674         index = 0
2675         do while ((index .lt. res_n) .and. no_moves)
2676           if (res_tab(2,1,index)) no_moves = .false.
2677           index=index+1
2678         enddo
2679       endif
2680       if (no_moves) then
2681         if (locmove_output) print *,'   ***   Cannot move anywhere'
2682         move_res=2
2683         return
2684       endif
2685
2686 !     Transfer res_... into a_...
2687       a_n = 0
2688       do i=0,res_n-1
2689         if ( (res_tab(2,0,i).neqv.res_tab(2,1,i)) .or. &
2690              (res_tab(2,0,i).neqv.res_tab(2,2,i)) ) then
2691           a_ang(a_n) = res_ang(i)
2692           do j=0,2
2693             a_tab(j,a_n) = res_tab(2,j,i)
2694           enddo
2695           a_n=a_n+1
2696         endif
2697       enddo
2698
2699 !     Check that the PHI's are within [0,PI]
2700       if (PHImin .lt. 0. .or. abs(PHImin) .lt. small) PHImin = -flag
2701       if (PHImin .gt. PI .or. abs(PHImin-PI) .lt. small) PHImin = PI
2702       if (PHImax .gt. PI .or. abs(PHImax-PI) .lt. small) PHImax = flag
2703       if (PHImax .lt. 0. .or. abs(PHImax) .lt. small) PHImax = 0.
2704       if (PHImax .lt. PHImin) PHImax = PHImin
2705 !     Calculate min and max angles coming from PHImin and PHImax,
2706 !     and put them in b_...
2707       call angles2tab(PHImin, PHImax, b_n, b_ang, b_tab)
2708 !     Construct the final table
2709       call construct_tab()
2710
2711       if (locmove_output) then
2712         print *,'FINAL TABLE'
2713         call output_tabs()
2714       endif
2715
2716 !     Check that there is at least one possible move
2717       no_moves = .true.
2718       if (res_n .eq. 0) then
2719         no_moves = .false.
2720       else
2721         index = 0
2722         do while ((index .lt. res_n) .and. no_moves)
2723           if (res_tab(2,1,index)) no_moves = .false.
2724           index=index+1
2725         enddo
2726       endif
2727
2728       if (no_moves) then
2729 !     Take care of the case where no solution exists...
2730         call fix_no_moves(phi)
2731         if (locmove_output) then
2732           print *,'   ***   Had to modify PHImin or PHImax'
2733           print *,'phi: ',phi*rad2deg
2734         endif
2735         move_res=1
2736       else
2737 !     ...or calculate the solution
2738 !     Construct phi_start/phi_end arrays
2739         call construct_ranges(phi_n, phi_start, phi_end)
2740 !     Choose random angle phi in allowed range(s)
2741         temp = 0.
2742         do i=0,phi_n-1
2743           temp = temp + phi_end(i) - phi_start(i)
2744         enddo
2745         phi = ran_number(phi_start(0),phi_start(0)+temp)
2746         index = 0
2747         done = .false.
2748         do while (.not.done)
2749           if (phi .lt. phi_end(index)) then
2750             done = .true.
2751           else
2752             index=index+1
2753           endif
2754           if (index .eq. phi_n) then
2755             done = .true.
2756           else if (.not.done) then
2757             phi = phi + phi_start(index) - phi_end(index-1)
2758           endif
2759         enddo
2760         if (index.eq.phi_n) phi=phi_end(phi_n-1) ! Fix numerical errors
2761         if (phi .gt. PI) phi = phi-2.*PI
2762
2763         if (locmove_output) then
2764           print *,'ALLOWED RANGE(S)'
2765           do i=0,phi_n-1
2766             print *,phi_start(i)*rad2deg,phi_end(i)*rad2deg
2767           enddo
2768           print *,'phi: ',phi*rad2deg
2769         endif
2770         move_res=0
2771       endif
2772
2773 !     Re-use radius as temp variable
2774       temp=radius*cos(phi)
2775       radius=radius*sin(phi)
2776       do i=0,2
2777         c(i+1,i_move)=Orig(i)+temp*X(i)+radius*Y(i)
2778       enddo
2779
2780       return
2781       end function move_res
2782 !-----------------------------------------------------------------------------
2783       subroutine loc_test
2784 !rc      implicit none
2785
2786 !     Includes
2787 !      implicit real*8 (a-h,o-z)
2788 !      include 'DIMENSIONS'
2789 !      include 'COMMON.GEO'
2790 !      include 'COMMON.LOCAL'
2791 !      include 'COMMON.LOCMOVE'
2792
2793 !     External functions
2794 !EL      integer move_res
2795 !EL      external move_res
2796
2797 !     Local variables
2798       integer :: i,j,imov
2799       integer :: phi_n
2800       real(kind=8),dimension(0:11) :: phi_start,phi_end
2801       real(kind=8) :: phi
2802       real(kind=8),dimension(0:2,0:5) :: R
2803
2804       locmove_output=.true.
2805
2806 !      call angles2tab(30.*deg2rad,70.*deg2rad,a_n,a_ang,a_tab)
2807 !      call angles2tab(80.*deg2rad,130.*deg2rad,b_n,b_ang,b_tab)
2808 !      call minmax_angles(0.D0,3.8D0,0.D0,3.8D0,b_n,b_ang,b_tab)
2809 !      call construct_tab
2810 !      call output_tabs
2811
2812 !      call construct_ranges(phi_n,phi_start,phi_end)
2813 !      do i=0,phi_n-1
2814 !        print *,phi_start(i)*rad2deg,phi_end(i)*rad2deg
2815 !      enddo
2816
2817 !      call fix_no_moves(phi)
2818 !      print *,'NO MOVES FOUND, BEST PHI IS',phi*rad2deg
2819
2820       R(0,0)=0.D0
2821       R(1,0)=0.D0
2822       R(2,0)=0.D0
2823       R(0,1)=0.D0
2824       R(1,1)=-cos(28.D0*deg2rad)
2825       R(2,1)=-0.5D0-sin(28.D0*deg2rad)
2826       R(0,2)=0.D0
2827       R(1,2)=0.D0
2828       R(2,2)=-0.5D0
2829       R(0,3)=cos(30.D0*deg2rad)
2830       R(1,3)=0.D0
2831       R(2,3)=0.D0
2832       R(0,4)=0.D0
2833       R(1,4)=0.D0
2834       R(2,4)=0.5D0
2835       R(0,5)=0.D0
2836       R(1,5)=cos(26.D0*deg2rad)
2837       R(2,5)=0.5D0+sin(26.D0*deg2rad)
2838       do i=1,5
2839         do j=0,2
2840           R(j,i)=vbl*R(j,i)
2841         enddo
2842       enddo
2843 !      i=move_res(R(0,1),0.D0*deg2rad,180.D0*deg2rad)
2844       imov=2
2845       i=move_res(0.D0*deg2rad,180.D0*deg2rad,imov)
2846       print *,'RETURNED ',i
2847       print *,(R(i,3)/vbl,i=0,2)
2848
2849       return
2850       end subroutine loc_test
2851 #endif
2852 !-----------------------------------------------------------------------------
2853 ! matmult.f
2854 !-----------------------------------------------------------------------------
2855       subroutine MATMULT(A1,A2,A3)
2856 !      implicit real*8 (a-h,o-z)
2857 !      include 'DIMENSIONS'
2858 !el local variables
2859       integer :: i,j,k
2860       real(kind=8) :: A3IJ
2861
2862       real(kind=8),DIMENSION(3,3) :: A1,A2,A3
2863       real(kind=8),DIMENSION(3,3) :: AI3
2864       DO 1 I=1,3
2865         DO 2 J=1,3
2866           A3IJ=0.0
2867           DO 3 K=1,3
2868     3       A3IJ=A3IJ+A1(I,K)*A2(K,J)
2869           AI3(I,J)=A3IJ
2870     2   CONTINUE
2871     1 CONTINUE
2872       DO 4 I=1,3
2873       DO 4 J=1,3
2874     4   A3(I,J)=AI3(I,J)
2875       return
2876       end subroutine MATMULT
2877 !-----------------------------------------------------------------------------
2878 ! readpdb.F
2879 !-----------------------------------------------------------------------------
2880       subroutine int_from_cart(lside,lprn)
2881 !      implicit real*8 (a-h,o-z)
2882 !      include 'DIMENSIONS'
2883       use control_data,only:out1file
2884 #ifdef MPI
2885       include "mpif.h"
2886 #endif
2887 !      include 'COMMON.LOCAL'
2888 !      include 'COMMON.VAR'
2889 !      include 'COMMON.CHAIN'
2890 !      include 'COMMON.INTERACT'
2891 !      include 'COMMON.IOUNITS'
2892 !      include 'COMMON.GEO'
2893 !      include 'COMMON.NAMES'
2894 !      include 'COMMON.CONTROL'
2895 !      include 'COMMON.SETUP'
2896       character(len=3) :: seq,res
2897 !      character*5 atom
2898       character(len=80) :: card
2899       real(kind=8),dimension(3,20) :: sccor
2900       integer :: i,j,iti !el  rescode,
2901       logical :: lside,lprn
2902       real(kind=8) :: di,cosfac,sinfac
2903       integer :: nres2
2904       nres2=2*nres
2905
2906       if(me.eq.king.or..not.out1file)then
2907        if (lprn) then 
2908         write (iout,'(/a)') &
2909         'Internal coordinates calculated from crystal structure.'
2910         if (lside) then 
2911           write (iout,'(8a)') '  Res  ','       dvb','     Theta',&
2912        '     Gamma','    Dsc_id','       Dsc','     Alpha',&
2913        '     Beta '
2914         else 
2915           write (iout,'(4a)') '  Res  ','       dvb','     Theta',&
2916        '     Gamma'
2917         endif
2918        endif
2919       endif
2920       do i=1,nres-1
2921 !       if (molnum(i).ne.1) cycle
2922 !in wham      do i=1,nres
2923         iti=itype(i,1)
2924         if (((dist(i,i+1).lt.2.0D0 .or. dist(i,i+1).gt.5.0D0).and.&
2925        (iti.ne.ntyp1  .and. itype(i+1,1).ne.ntyp1)).and.molnum(i).eq.1) then
2926           write (iout,'(a,i4)') 'Bad Cartesians for residue',i
2927 !test          stop
2928         endif
2929 !#ifndef WHAM_RUN
2930         vbld(i+1)=dist(i,i+1)
2931         vbld_inv(i+1)=1.0d0/vbld(i+1)
2932 !#endif
2933         if (i.gt.1) theta(i+1)=alpha(i-1,i,i+1)
2934         if (i.gt.2) phi(i+1)=beta(i-2,i-1,i,i+1)
2935       enddo
2936 !el -----
2937 !#ifdef WHAM_RUN
2938 !      if (itype(1,1).eq.ntyp1) then
2939 !        do j=1,3
2940 !          c(j,1)=c(j,2)+(c(j,3)-c(j,4))
2941 !        enddo
2942 !      endif
2943 !      if (itype(nres,1).eq.ntyp1) then
2944 !        do j=1,3
2945 !          c(j,nres)=c(j,nres-1)+(c(j,nres-2)-c(j,nres-3))
2946 !        enddo
2947 !      endif
2948 !#endif
2949 !      if (unres_pdb) then
2950 !        if (itype(1,1).eq.21) then
2951 !          theta(3)=90.0d0*deg2rad
2952 !          phi(4)=180.0d0*deg2rad
2953 !          vbld(2)=3.8d0
2954 !          vbld_inv(2)=1.0d0/vbld(2)
2955 !        endif
2956 !        if (itype(nres,1).eq.21) then
2957 !          theta(nres)=90.0d0*deg2rad
2958 !          phi(nres)=180.0d0*deg2rad
2959 !          vbld(nres)=3.8d0
2960 !          vbld_inv(nres)=1.0d0/vbld(2)
2961 !        endif
2962 !      endif
2963       if (lside) then
2964         do i=2,nres-1
2965           do j=1,3
2966             c(j,nres2+2)=0.5D0*(2*c(j,i)+(c(j,i-1)-c(j,i))*vbld_inv(i) &
2967            +(c(j,i+1)-c(j,i))*vbld_inv(i+1))
2968 ! in wham            c(j,maxres2)=0.5D0*(c(j,i-1)+c(j,i+1)
2969           enddo
2970           iti=itype(i,1)
2971           di=dist(i,nres+i)
2972 !#ifndef WHAM_RUN
2973 ! 10/03/12 Adam: Correction for zero SC-SC bond length
2974           
2975           if (itype(i,1).ne.10 .and. itype(i,1).ne.ntyp1 .and. di.eq.0.0d0) &
2976            di=dsc(itype(i,molnum(i)))
2977           vbld(i+nres)=di
2978           if (itype(i,1).ne.10) then
2979             vbld_inv(i+nres)=1.0d0/di
2980           else
2981             vbld_inv(i+nres)=0.0d0
2982           endif
2983 !#endif
2984           if (iti.ne.10) then
2985             alph(i)=alpha(nres+i,i,nres2+2)
2986             omeg(i)=beta(nres+i,i,nres2+2,i+1)
2987           endif
2988           if (iti.ne.0) then
2989           if(me.eq.king.or..not.out1file)then
2990            if (lprn) &
2991            write (iout,'(a3,i4,7f10.3)') restyp(iti,1),i,vbld(i),&
2992            rad2deg*theta(i),rad2deg*phi(i),dsc(iti),vbld(nres+i),&
2993            rad2deg*alph(i),rad2deg*omeg(i)
2994           endif
2995           else
2996           if(me.eq.king.or..not.out1file)then
2997            if (lprn) &
2998            write (iout,'(a3,i4,7f10.3)') restyp(iti,1),i,vbld(i),&
2999            rad2deg*theta(i),rad2deg*phi(i),dsc(iti+1),vbld(nres+i),&
3000            rad2deg*alph(i),rad2deg*omeg(i)
3001           endif
3002           endif
3003         enddo
3004       else if (lprn) then
3005         do i=2,nres
3006           iti=itype(i,1)
3007           if(me.eq.king.or..not.out1file) &
3008            write (iout,'(a3,i4,7f10.3)') restyp(iti,1),i,dist(i,i-1),&
3009            rad2deg*theta(i),rad2deg*phi(i)
3010         enddo
3011       endif
3012       return
3013       end subroutine int_from_cart
3014 !-----------------------------------------------------------------------------
3015       subroutine sc_loc_geom(lprn)
3016 !      implicit real*8 (a-h,o-z)
3017 !      include 'DIMENSIONS'
3018       use control_data,only:out1file
3019 #ifdef MPI
3020       include "mpif.h"
3021 #endif
3022 !      include 'COMMON.LOCAL'
3023 !      include 'COMMON.VAR'
3024 !      include 'COMMON.CHAIN'
3025 !      include 'COMMON.INTERACT'
3026 !      include 'COMMON.IOUNITS'
3027 !      include 'COMMON.GEO'
3028 !      include 'COMMON.NAMES'
3029 !      include 'COMMON.CONTROL'
3030 !      include 'COMMON.SETUP'
3031       real(kind=8),dimension(3) :: x_prime,y_prime,z_prime
3032       logical :: lprn
3033 !el local variables
3034       integer :: i,j,it,iti
3035       real(kind=8) :: cosfac2,sinfac2,xx,yy,zz,cosfac,sinfac
3036       do i=1,nres-1
3037         do j=1,3
3038           dc_norm(j,i)=vbld_inv(i+1)*(c(j,i+1)-c(j,i))
3039         enddo
3040       enddo
3041       do i=2,nres-1
3042         if (itype(i,1).ne.10) then
3043           do j=1,3
3044             dc_norm(j,i+nres)=vbld_inv(i+nres)*(c(j,i+nres)-c(j,i))
3045           enddo
3046         else
3047           do j=1,3
3048             dc_norm(j,i+nres)=0.0d0
3049           enddo
3050         endif
3051       enddo
3052       do i=2,nres-1
3053         costtab(i+1) =dcos(theta(i+1))
3054         sinttab(i+1) =dsqrt(1-costtab(i+1)*costtab(i+1))
3055         cost2tab(i+1)=dsqrt(0.5d0*(1.0d0+costtab(i+1)))
3056         sint2tab(i+1)=dsqrt(0.5d0*(1.0d0-costtab(i+1)))
3057         cosfac2=0.5d0/(1.0d0+costtab(i+1))
3058         cosfac=dsqrt(cosfac2)
3059         sinfac2=0.5d0/(1.0d0-costtab(i+1))
3060         sinfac=dsqrt(sinfac2)
3061         it=itype(i,1)
3062
3063         if ((it.ne.10).and.(it.ne.ntyp1)) then
3064 !el        if (it.ne.10) then
3065 !
3066 !  Compute the axes of tghe local cartesian coordinates system; store in
3067 !   x_prime, y_prime and z_prime 
3068 !
3069         do j=1,3
3070           x_prime(j) = 0.00
3071           y_prime(j) = 0.00
3072           z_prime(j) = 0.00
3073         enddo
3074         do j = 1,3
3075           x_prime(j) = (dc_norm(j,i) - dc_norm(j,i-1))*cosfac
3076           y_prime(j) = (dc_norm(j,i) + dc_norm(j,i-1))*sinfac
3077         enddo
3078         call vecpr(x_prime,y_prime,z_prime)
3079 !
3080 ! Transform the unit vector of the ith side-chain centroid, dC_norm(*,i),
3081 ! to local coordinate system. Store in xx, yy, zz.
3082 !
3083         xx=0.0d0
3084         yy=0.0d0
3085         zz=0.0d0
3086         do j = 1,3
3087           xx = xx + x_prime(j)*dc_norm(j,i+nres)
3088           yy = yy + y_prime(j)*dc_norm(j,i+nres)
3089           zz = zz + z_prime(j)*dc_norm(j,i+nres)
3090         enddo
3091
3092         xxref(i)=xx
3093         yyref(i)=yy
3094         zzref(i)=zz
3095         else
3096         xxref(i)=0.0d0
3097         yyref(i)=0.0d0
3098         zzref(i)=0.0d0
3099         endif
3100       enddo
3101       if (lprn) then
3102         do i=2,nres
3103           iti=itype(i,1)
3104           if(me.eq.king.or..not.out1file) &
3105            write (iout,'(a3,i4,3f10.5)') restyp(iti,1),i,xxref(i),&
3106             yyref(i),zzref(i)
3107         enddo
3108       endif
3109  
3110       return
3111       end subroutine sc_loc_geom
3112 !-----------------------------------------------------------------------------
3113       subroutine sccenter(ires,nscat,sccor)
3114 !      implicit real*8 (a-h,o-z)
3115 !      include 'DIMENSIONS'
3116 !      include 'COMMON.CHAIN'
3117       integer :: i,j,ires,nscat
3118       real(kind=8),dimension(3,20) :: sccor
3119       real(kind=8) :: sccmj
3120 !        print *,"I am in sccenter",ires,nscat
3121       do j=1,3
3122         sccmj=0.0D0
3123         do i=1,nscat
3124           sccmj=sccmj+sccor(j,i)
3125 !C          print *,"insccent", ires,sccor(j,i) 
3126         enddo
3127         dc(j,ires)=sccmj/nscat
3128       enddo
3129       return
3130       end subroutine sccenter
3131 #if .not. defined(WHAM_RUN) && .not. defined(CLUSTER)
3132 !-----------------------------------------------------------------------------
3133       subroutine bond_regular
3134       use calc_data
3135 !      implicit real*8 (a-h,o-z)
3136 !      include 'DIMENSIONS'   
3137 !      include 'COMMON.VAR'
3138 !      include 'COMMON.LOCAL'      
3139 !      include 'COMMON.CALC'
3140 !      include 'COMMON.INTERACT'
3141 !      include 'COMMON.CHAIN'
3142       do i=1,nres-1
3143        
3144        vbld(i+1)=vbl
3145        vbld_inv(i+1)=1.0d0/vbld(i+1)
3146        vbld(i+1+nres)=dsc(itype(i+1,molnum(i)))
3147        vbld_inv(i+1+nres)=dsc_inv(itype(i+1,molnum(i)))
3148 !       print *,vbld(i+1),vbld(i+1+nres)
3149       enddo
3150       return
3151       end subroutine bond_regular
3152 #endif
3153 !-----------------------------------------------------------------------------
3154 ! refsys.f
3155 !-----------------------------------------------------------------------------
3156       subroutine refsys(i2,i3,i4,e1,e2,e3,fail)
3157 ! This subroutine calculates unit vectors of a local reference system
3158 ! defined by atoms (i2), (i3), and (i4). The x axis is the axis from
3159 ! atom (i3) to atom (i2), and the xy plane is the plane defined by atoms
3160 ! (i2), (i3), and (i4). z axis is directed according to the sign of the
3161 ! vector product (i3)-(i2) and (i3)-(i4). Sets fail to .true. if atoms
3162 ! (i2) and (i3) or (i3) and (i4) coincide or atoms (i2), (i3), and (i4)
3163 ! form a linear fragment. Returns vectors e1, e2, and e3.
3164 !      implicit real*8 (a-h,o-z)
3165 !      include 'DIMENSIONS'
3166       logical :: fail
3167       real(kind=8),dimension(3) :: e1,e2,e3
3168       real(kind=8),dimension(3) :: u,z
3169 !      include 'COMMON.IOUNITS'
3170 !      include 'COMMON.CHAIN'
3171       real(kind=8) :: coinc=1.0D-13,align=1.0D-13
3172 !el local variables
3173       integer :: i,i1,i2,i3,i4
3174       real(kind=8) :: v1,v2,v3,s1,s2,zi,ui,anorm
3175       fail=.false.
3176       s1=0.0
3177       s2=0.0
3178       do 1 i=1,3
3179       zi=c(i,i2)-c(i,i3)
3180       ui=c(i,i4)-c(i,i3)
3181       s1=s1+zi*zi
3182       s2=s2+ui*ui
3183       z(i)=zi
3184     1 u(i)=ui
3185       s1=sqrt(s1)
3186       s2=sqrt(s2)
3187       if (s1.gt.coinc) goto 2
3188       write (iout,1000) i2,i3,i1
3189       fail=.true.
3190 !     do 3 i=1,3
3191 !   3 c(i,i1)=0.0D0
3192       return
3193     2 if (s2.gt.coinc) goto 4
3194       write(iout,1000) i3,i4,i1
3195       fail=.true.
3196       do 5 i=1,3
3197     5 c(i,i1)=0.0D0
3198       return
3199     4 s1=1.0/s1
3200       s2=1.0/s2
3201       v1=z(2)*u(3)-z(3)*u(2)
3202       v2=z(3)*u(1)-z(1)*u(3)
3203       v3=z(1)*u(2)-z(2)*u(1)
3204       anorm=dsqrt(v1*v1+v2*v2+v3*v3)
3205       if (anorm.gt.align) goto 6
3206       write (iout,1010) i2,i3,i4,i1
3207       fail=.true.
3208 !     do 7 i=1,3
3209 !   7 c(i,i1)=0.0D0
3210       return
3211     6 anorm=1.0D0/anorm
3212       e3(1)=v1*anorm
3213       e3(2)=v2*anorm
3214       e3(3)=v3*anorm
3215       e1(1)=z(1)*s1
3216       e1(2)=z(2)*s1
3217       e1(3)=z(3)*s1
3218       e2(1)=e1(3)*e3(2)-e1(2)*e3(3)
3219       e2(2)=e1(1)*e3(3)-e1(3)*e3(1)
3220       e2(3)=e1(2)*e3(1)-e1(1)*e3(2)
3221  1000 format (/1x,' * * * Error - atoms',i4,' and',i4,' coincide.',&
3222        'coordinates of atom',i4,' are set to zero.')
3223  1010 format (/1x,' * * * Error - atoms',2(i4,2h, ),i4,' form a linear',&
3224        ' fragment. coordinates of atom',i4,' are set to zero.')
3225       return
3226       end subroutine refsys
3227 !-----------------------------------------------------------------------------
3228 ! int_to_cart.f
3229 !-----------------------------------------------------------------------------
3230       subroutine int_to_cart
3231 !--------------------------------------------------------------         
3232 !  This subroutine converts the energy derivatives from internal 
3233 !  coordinates to cartesian coordinates
3234 !-------------------------------------------------------------
3235 !      implicit real*8 (a-h,o-z)
3236 !      include 'DIMENSIONS'
3237 !      include 'COMMON.VAR'
3238 !      include 'COMMON.CHAIN'
3239 !      include 'COMMON.DERIV'
3240 !      include 'COMMON.GEO'
3241 !      include 'COMMON.LOCAL'
3242 !      include 'COMMON.INTERACT'
3243 !      include 'COMMON.MD'
3244 !      include 'COMMON.IOUNITS'
3245 !      include 'COMMON.SCCOR' 
3246 !   calculating dE/ddc1  
3247 !el local variables
3248        integer :: j,i
3249 !       print *,"gloc",gloc(:,:)
3250 !       print *, "gcart",gcart(:,:)
3251        if (nres.lt.3) go to 18
3252        do j=1,3
3253          gcart(j,1)=gcart(j,1)+gloc(1,icg)*dphi(j,1,4) &
3254            +gloc(nres-2,icg)*dtheta(j,1,3)       
3255           if ((itype(2,1).ne.10).and.&
3256           (itype(2,molnum(2)).ne.ntyp1_molec(molnum(2)))) then
3257           gcart(j,1)=gcart(j,1)+gloc(ialph(2,1),icg)*dalpha(j,1,2)+ &
3258           gloc(ialph(2,1)+nside,icg)*domega(j,1,2)              
3259         endif
3260        enddo
3261 !     Calculating the remainder of dE/ddc2
3262        do j=1,3
3263          gcart(j,2)=gcart(j,2)+gloc(1,icg)*dphi(j,2,4)+ &
3264          gloc(nres-2,icg)*dtheta(j,2,3)+gloc(nres-1,icg)*dtheta(j,1,4)
3265         if(itype(2,1).ne.10) then
3266           gcart(j,2)=gcart(j,2)+gloc(ialph(2,1),icg)*dalpha(j,2,2)+ &
3267           gloc(ialph(2,1)+nside,icg)*domega(j,2,2)
3268         endif
3269         if(itype(3,1).ne.10) then
3270           gcart(j,2)=gcart(j,2)+gloc(ialph(3,1),icg)*dalpha(j,1,3)+ &
3271           gloc(ialph(3,1)+nside,icg)*domega(j,1,3)
3272         endif
3273         if(nres.gt.4) then
3274           gcart(j,2)=gcart(j,2)+gloc(2,icg)*dphi(j,1,5)
3275         endif                   
3276        enddo
3277 !  If there are only five residues       
3278        if(nres.eq.5) then
3279          do j=1,3
3280            gcart(j,3)=gcart(j,3)+gloc(1,icg)*dphi(j,3,4)+gloc(2,icg)* &
3281            dphi(j,2,5)+gloc(nres-1,icg)*dtheta(j,2,4)+gloc(nres,icg)* &
3282            dtheta(j,1,5)
3283 !         if(itype(3,1).ne.10) then
3284           if ((itype(3,1).ne.10).and.&
3285           (itype(3,molnum(3)).ne.ntyp1_molec(molnum(3)))) then
3286            gcart(j,3)=gcart(j,3)+gloc(ialph(3,1),icg)* &
3287            dalpha(j,2,3)+gloc(ialph(3,1)+nside,icg)*domega(j,2,3)
3288          endif
3289 !        if(itype(4,1).ne.10) then
3290           if ((itype(4,1).ne.10).and.&
3291           (itype(4,molnum(4)).ne.ntyp1_molec(molnum(4)))) then
3292            gcart(j,3)=gcart(j,3)+gloc(ialph(4,1),icg)* &
3293            dalpha(j,1,4)+gloc(ialph(4,1)+nside,icg)*domega(j,1,4)
3294          endif
3295         enddo
3296        endif
3297 !    If there are more than five residues
3298       if(nres.gt.5) then                           
3299         do i=3,nres-3
3300          do j=1,3
3301           gcart(j,i)=gcart(j,i)+gloc(i-2,icg)*dphi(j,3,i+1) &
3302           +gloc(i-1,icg)*dphi(j,2,i+2)+ &
3303           gloc(i,icg)*dphi(j,1,i+3)+gloc(nres+i-4,icg)*dtheta(j,2,i+1)+ &
3304           gloc(nres+i-3,icg)*dtheta(j,1,i+2)
3305           if(itype(i,1).ne.10) then
3306            gcart(j,i)=gcart(j,i)+gloc(ialph(i,1),icg)*dalpha(j,2,i)+ &
3307            gloc(ialph(i,1)+nside,icg)*domega(j,2,i)
3308           endif
3309           if(itype(i+1,1).ne.10) then
3310            gcart(j,i)=gcart(j,i)+gloc(ialph(i+1,1),icg)*dalpha(j,1,i+1) &
3311            +gloc(ialph(i+1,1)+nside,icg)*domega(j,1,i+1)
3312           endif
3313          enddo
3314         enddo
3315       endif     
3316 !  Setting dE/ddnres-2       
3317       if(nres.gt.5) then
3318          do j=1,3
3319            gcart(j,nres-2)=gcart(j,nres-2)+gloc(nres-4,icg)* &
3320            dphi(j,3,nres-1)+gloc(nres-3,icg)*dphi(j,2,nres) &
3321            +gloc(2*nres-6,icg)* &
3322            dtheta(j,2,nres-1)+gloc(2*nres-5,icg)*dtheta(j,1,nres)
3323           if(itype(nres-2,1).ne.10) then
3324               gcart(j,nres-2)=gcart(j,nres-2)+gloc(ialph(nres-2,1),icg)* &
3325               dalpha(j,2,nres-2)+gloc(ialph(nres-2,1)+nside,icg)* &
3326               domega(j,2,nres-2)
3327           endif
3328           if(itype(nres-1,1).ne.10) then
3329              gcart(j,nres-2)=gcart(j,nres-2)+gloc(ialph(nres-1,1),icg)* &
3330              dalpha(j,1,nres-1)+gloc(ialph(nres-1,1)+nside,icg)* &
3331              domega(j,1,nres-1)
3332           endif
3333          enddo
3334       endif 
3335 !  Settind dE/ddnres-1       
3336 !#define DEBUG
3337 #ifdef DEBUG
3338           j=1
3339               write(iout,*)"in int to carta",nres-1,gcart(j,nres-1),gloc(nres-3,icg),dphi(j,3,nres), &
3340         gloc(2*nres-5,icg),dtheta(j,2,nres)
3341
3342 #endif
3343 !#undef DEBUG
3344
3345        do j=1,3
3346         gcart(j,nres-1)=gcart(j,nres-1)+gloc(nres-3,icg)*dphi(j,3,nres)+ &
3347         gloc(2*nres-5,icg)*dtheta(j,2,nres)
3348 !#define DEBUG
3349 #ifdef DEBUG
3350               write(iout,*)"in int to cartb",nres-1,gcart(j,nres-1),gloc(nres-3,icg),dphi(j,3,nres), &
3351         gloc(2*nres-5,icg),dtheta(j,2,nres)
3352
3353 #endif
3354 !#undef DEBUG
3355         if(itype(nres-1,1).ne.10) then
3356           gcart(j,nres-1)=gcart(j,nres-1)+gloc(ialph(nres-1,1),icg)* &
3357           dalpha(j,2,nres-1)+gloc(ialph(nres-1,1)+nside,icg)* &
3358           domega(j,2,nres-1)
3359 !#define DEBUG
3360 #ifdef DEBUG
3361               write(iout,*)"in int to cart2",i,gcart(j,nres-1),gloc(ialph(nres-1,1),icg)* &
3362           dalpha(j,2,nres-1),gloc(ialph(nres-1,1)+nside,icg), &
3363           domega(j,2,nres-1)
3364
3365 #endif
3366 !#undef DEBUG
3367
3368         endif
3369         enddo
3370 !   The side-chain vector derivatives
3371         do i=2,nres-1
3372          if(itype(i,1).ne.10 .and.  &
3373            itype(i,molnum(i)).ne.ntyp1_molec(molnum(i))) then   
3374             do j=1,3    
3375               gxcart(j,i)=gxcart(j,i)+gloc(ialph(i,1),icg)*dalpha(j,3,i) &
3376               +gloc(ialph(i,1)+nside,icg)*domega(j,3,i)
3377 !#define DEBUG
3378 #ifdef DEBUG
3379               write(iout,*)"in int to cart",i, gxcart(j,i),gloc(ialph(i,1),icg),dalpha(j,3,i), &
3380               gloc(ialph(i,1)+nside,icg),domega(j,3,i)
3381 #endif
3382 !#undef DEBUG
3383             enddo
3384          endif      
3385        enddo                                                                                                                                                    
3386 !----------------------------------------------------------------------
3387 ! INTERTYP=1 SC...Ca...Ca...Ca
3388 ! INTERTYP=2 Ca...Ca...Ca...SC
3389 ! INTERTYP=3 SC...Ca...Ca...SC
3390 !   calculating dE/ddc1      
3391   18   continue
3392 !       do i=1,nres
3393 !       gloc(i,icg)=0.0D0
3394 !          write (iout,*) "poczotkoawy",i,gloc_sc(1,i,icg)
3395 !       enddo
3396        if (nres.lt.2) return
3397        if ((nres.lt.3).and.(itype(1,1).eq.10)) return
3398        if ((itype(1,1).ne.10).and. &
3399         (itype(1,molnum(1)).ne.ntyp1_molec(molnum(1)))) then
3400         do j=1,3
3401 !c Derviative was calculated for oposite vector of side chain therefore
3402 ! there is "-" sign before gloc_sc
3403          gxcart(j,1)=gxcart(j,1)-gloc_sc(1,0,icg)* &
3404            dtauangle(j,1,1,3)
3405          gcart(j,1)=gcart(j,1)+gloc_sc(1,0,icg)* &
3406            dtauangle(j,1,2,3)
3407           if ((itype(2,1).ne.10).and. &
3408         (itype(2,molnum(2)).ne.ntyp1_molec(molnum(2)))) then
3409          gxcart(j,1)= gxcart(j,1) &
3410                      -gloc_sc(3,0,icg)*dtauangle(j,3,1,3)
3411          gcart(j,1)=gcart(j,1)+gloc_sc(3,0,icg)* &
3412             dtauangle(j,3,2,3)
3413           endif
3414        enddo
3415        endif
3416          if ((nres.ge.3).and.(itype(3,molnum(3)).ne.10).and.&
3417          (itype(3,molnum(3)).ne.ntyp1_molec(molnum(3)))) &
3418       then
3419          do j=1,3
3420          gcart(j,1)=gcart(j,1)+gloc_sc(2,1,icg)*dtauangle(j,2,1,4)
3421          enddo
3422          endif
3423 !   As potetnial DO NOT depend on omicron anlge their derivative is
3424 !   ommited 
3425 !     &     +gloc_sc(intertyp,nres-2,icg)*dtheta(j,1,3)  
3426
3427 !     Calculating the remainder of dE/ddc2
3428        do j=1,3
3429          if((itype(2,1).ne.10).and. &
3430            (itype(2,molnum(2)).ne.ntyp1_molec(molnum(2)))) then
3431            if ((itype(1,1).ne.10).and.&
3432               ((itype(1,molnum(1)).ne.ntyp1_molec(molnum(1)))))&
3433             gxcart(j,2)=gxcart(j,2)+ &
3434                                gloc_sc(3,0,icg)*dtauangle(j,3,3,3)
3435         if ((itype(3,1).ne.10).and.(nres.ge.3).and.(itype(3,molnum(3)).ne.ntyp1_molec(3))) &
3436          then
3437            gxcart(j,2)=gxcart(j,2)-gloc_sc(3,1,icg)*dtauangle(j,3,1,4)
3438 !c                  the   - above is due to different vector direction
3439            gcart(j,2)=gcart(j,2)+gloc_sc(3,1,icg)*dtauangle(j,3,2,4)
3440           endif
3441           if (nres.gt.3) then
3442 !           if ((itype(1,1).ne.10).and.&
3443 !              ((itype(1,molnum(1)).ne.ntyp1_molec(molnum(1))))) &
3444            gxcart(j,2)=gxcart(j,2)-gloc_sc(1,1,icg)*dtauangle(j,1,1,4)
3445 !c                  the   - above is due to different vector direction
3446            gcart(j,2)=gcart(j,2)+gloc_sc(1,1,icg)*dtauangle(j,1,2,4)
3447 !          write(iout,*) gloc_sc(1,1,icg),dtauangle(j,1,2,4),"gcart"
3448 !           write(iout,*) gloc_sc(1,1,icg),dtauangle(j,1,1,4),"gx"
3449           endif
3450          endif
3451          if ((itype(1,1).ne.10).and.&
3452          (itype(1,molnum(1)).ne.ntyp1_molec(molnum(1)))) then
3453           gcart(j,2)=gcart(j,2)+gloc_sc(1,0,icg)*dtauangle(j,1,3,3)
3454 !           write(iout,*)  gloc_sc(1,0,icg),dtauangle(j,1,3,3)
3455         endif
3456          if ((itype(3,1).ne.10).and.(nres.ge.3)) then
3457           gcart(j,2)=gcart(j,2)+gloc_sc(2,1,icg)*dtauangle(j,2,2,4)
3458 !           write(iout,*) gloc_sc(2,1,icg),dtauangle(j,2,2,4)
3459          endif
3460          if ((itype(4,1).ne.10).and.(nres.ge.4)) then
3461           gcart(j,2)=gcart(j,2)+gloc_sc(2,2,icg)*dtauangle(j,2,1,5)
3462 !           write(iout,*) gloc_sc(2,2,icg),dtauangle(j,2,1,5)
3463          endif
3464
3465 !      write(iout,*) gcart(j,2),itype(2,1),itype(1,1),itype(3,1), "gcart2"
3466        enddo
3467 !    If there are more than five residues
3468       if(nres.ge.5) then                        
3469         do i=3,nres-2
3470          do j=1,3
3471 !          write(iout,*) "before", gcart(j,i)
3472           if ((itype(i,1).ne.10).and.&
3473           (itype(i,molnum(i)).ne.ntyp1_molec(molnum(i)))) then
3474           gxcart(j,i)=gxcart(j,i)+gloc_sc(2,i-2,icg) &
3475           *dtauangle(j,2,3,i+1) &
3476           -gloc_sc(1,i-1,icg)*dtauangle(j,1,1,i+2)
3477           gcart(j,i)=gcart(j,i)+gloc_sc(1,i-1,icg) &
3478           *dtauangle(j,1,2,i+2)
3479 !                   write(iout,*) "new",j,i,
3480 !     &  gcart(j,i),gloc_sc(1,i-1,icg),dtauangle(j,1,2,i+2)
3481 !          if (itype(i-1,1).ne.10) then
3482           if ((itype(i-1,1).ne.10).and.&
3483           (itype(i-1,molnum(i-1)).ne.ntyp1_molec(molnum(i-1)))) then
3484
3485            gxcart(j,i)=gxcart(j,i)+gloc_sc(3,i-2,icg) &
3486       *dtauangle(j,3,3,i+1)
3487           endif
3488 !          if (itype(i+1,1).ne.10) then
3489           if ((itype(i+1,1).ne.10).and.&
3490           (itype(i+1,molnum(i+1)).ne.ntyp1_molec(molnum(i+1)))) then
3491           gxcart(j,i)=gxcart(j,i)-gloc_sc(3,i-1,icg) &
3492       *dtauangle(j,3,1,i+2)
3493            gcart(j,i)=gcart(j,i)+gloc_sc(3,i-1,icg) &
3494       *dtauangle(j,3,2,i+2)
3495           endif
3496           endif
3497 !          if (itype(i-1,1).ne.10) then
3498           if ((itype(i-1,1).ne.10).and.&
3499           (itype(i-1,molnum(i-1)).ne.ntyp1_molec(molnum(i-1)))) then
3500            gcart(j,i)=gcart(j,i)+gloc_sc(1,i-2,icg)* &
3501            dtauangle(j,1,3,i+1)
3502           endif
3503 !          if (itype(i+1,1).ne.10) then
3504           if ((itype(i+1,1).ne.10).and.&
3505           (itype(i+1,molnum(i+1)).ne.ntyp1_molec(molnum(i+1)))) then
3506            gcart(j,i)=gcart(j,i)+gloc_sc(2,i-1,icg)* &
3507            dtauangle(j,2,2,i+2)
3508 !          write(iout,*) "numer",i,gloc_sc(2,i-1,icg),
3509 !     &    dtauangle(j,2,2,i+2)
3510           endif
3511 !          if (itype(i+2,1).ne.10) then
3512           if ((itype(i+2,1).ne.10).and.&
3513           (itype(i+2,molnum(i+2)).ne.ntyp1_molec(molnum(i+2)))) then
3514            gcart(j,i)=gcart(j,i)+gloc_sc(2,i,icg)* &
3515            dtauangle(j,2,1,i+3)
3516           endif
3517          enddo
3518         enddo
3519       endif     
3520 !  Setting dE/ddnres-1       
3521       if(nres.ge.4) then
3522          do j=1,3
3523          if ((itype(nres-1,1).ne.10).and.&
3524        (itype(nres-1,molnum(nres-1)).ne.ntyp1_molec(molnum(nres-1)))) then
3525          gxcart(j,nres-1)=gxcart(j,nres-1)+gloc_sc(2,nres-3,icg) &
3526           *dtauangle(j,2,3,nres)
3527 !          write (iout,*) "gxcart(nres-1)", gloc_sc(2,nres-3,icg),
3528 !     &     dtauangle(j,2,3,nres), gxcart(j,nres-1)
3529 !         if (itype(nres-2,1).ne.10) then
3530          if ((itype(nres-2,1).ne.10).and.&
3531        (itype(nres-2,molnum(nres-2)).ne.ntyp1_molec(molnum(nres-2)))) then
3532        gxcart(j,nres-1)=gxcart(j,nres-1)+gloc_sc(3,nres-3,icg) &
3533           *dtauangle(j,3,3,nres)
3534           endif
3535          if ((itype(nres,1).ne.10).and.&
3536          (itype(nres,molnum(nres)).ne.ntyp1_molec(molnum(nres)))) then
3537         gxcart(j,nres-1)=gxcart(j,nres-1)-gloc_sc(3,nres-2,icg) &
3538           *dtauangle(j,3,1,nres+1)
3539         gcart(j,nres-1)=gcart(j,nres-1)+gloc_sc(3,nres-2,icg) &
3540           *dtauangle(j,3,2,nres+1)
3541           endif
3542          endif
3543          if ((itype(nres-2,1).ne.10).and.&
3544          (itype(nres-2,molnum(nres-2)).ne.ntyp1_molec(molnum(nres-2)))) then
3545             gcart(j,nres-1)=gcart(j,nres-1)+gloc_sc(1,nres-3,icg)* &
3546          dtauangle(j,1,3,nres)
3547          endif
3548           if ((itype(nres,1).ne.10).and.(itype(nres,molnum(nres)).ne.ntyp1_molec(molnum(nres)))) then
3549             gcart(j,nres-1)=gcart(j,nres-1)+gloc_sc(2,nres-2,icg)* &
3550            dtauangle(j,2,2,nres+1)
3551 !           write (iout,*) "gcart(nres-1)", gloc_sc(2,nres-2,icg),
3552 !     &     dtauangle(j,2,2,nres+1), itype(nres-1,1),itype(nres,1)
3553            endif
3554          enddo
3555       endif
3556 !  Settind dE/ddnres       
3557        if ((nres.ge.3).and.(itype(nres,1).ne.10).and. &
3558           (itype(nres,molnum(nres)).ne.ntyp1_molec(molnum(nres))))then
3559        do j=1,3
3560         gxcart(j,nres)=gxcart(j,nres)+gloc_sc(3,nres-2,icg) &
3561        *dtauangle(j,3,3,nres+1)+gloc_sc(2,nres-2,icg) &
3562        *dtauangle(j,2,3,nres+1)
3563         enddo
3564        endif
3565 !   The side-chain vector derivatives
3566 !       print *,"gcart",gcart(:,:)
3567       return
3568       end subroutine int_to_cart
3569 #if .not. defined(WHAM_RUN) && .not. defined(CLUSTER)
3570 !-----------------------------------------------------------------------------
3571 ! readrtns_CSA.F
3572 !-----------------------------------------------------------------------------
3573       subroutine gen_dist_constr
3574 ! Generate CA distance constraints.
3575 !      implicit real*8 (a-h,o-z)
3576 !      include 'DIMENSIONS'
3577 !      include 'COMMON.IOUNITS'
3578 !      include 'COMMON.GEO'
3579 !      include 'COMMON.VAR'
3580 !      include 'COMMON.INTERACT'
3581 !      include 'COMMON.LOCAL'
3582 !      include 'COMMON.NAMES'
3583 !      include 'COMMON.CHAIN'
3584 !      include 'COMMON.FFIELD'
3585 !      include 'COMMON.SBRIDGE'
3586 !      include 'COMMON.HEADER'
3587 !      include 'COMMON.CONTROL'
3588 !      include 'COMMON.DBASE'
3589 !      include 'COMMON.THREAD'
3590 !      include 'COMMON.TIME1'
3591 !      integer :: itype_pdb !(maxres)
3592 !      common /pizda/ itype_pdb(nres)
3593       character(len=2) :: iden
3594 !el local variables
3595       integer :: i,j
3596 !d      print *,'gen_dist_constr: nnt=',nnt,' nct=',nct
3597 !d      write (2,*) 'gen_dist_constr: nnt=',nnt,' nct=',nct,
3598 !d     & ' nstart_sup',nstart_sup,' nstart_seq',nstart_seq,
3599 !d     & ' nsup',nsup
3600       do i=nstart_sup,nstart_sup+nsup-1
3601 !d      write (2,*) 'i',i,' seq ',restyp(itype(i+nstart_seq-nstart_sup)),
3602 !d     &    ' seq_pdb', restyp(itype_pdb(i))
3603         do j=i+2,nstart_sup+nsup-1
3604           nhpb=nhpb+1
3605           ihpb(nhpb)=i+nstart_seq-nstart_sup
3606           jhpb(nhpb)=j+nstart_seq-nstart_sup
3607           forcon(nhpb)=weidis
3608           dhpb(nhpb)=dist(i,j)
3609         enddo
3610       enddo 
3611 !d      write (iout,'(a)') 'Distance constraints:' 
3612 !d      do i=nss+1,nhpb
3613 !d        ii=ihpb(i)
3614 !d        jj=jhpb(i)
3615 !d        iden='CA'
3616 !d        if (ii.gt.nres) then
3617 !d          iden='SC'
3618 !d          ii=ii-nres
3619 !d          jj=jj-nres
3620 !d        endif
3621 !d        write (iout,'(a,1x,a,i4,3x,a,1x,a,i4,2f10.3)') 
3622 !d     &  restyp(itype(ii)),iden,ii,restyp(itype(jj)),iden,jj,
3623 !d     &  dhpb(i),forcon(i)
3624 !d      enddo
3625 !      deallocate(itype_pdb)
3626
3627       return
3628       end subroutine gen_dist_constr
3629 #endif
3630 !-----------------------------------------------------------------------------
3631 ! cartprint.f
3632 !-----------------------------------------------------------------------------
3633       subroutine cartprint
3634
3635       use geometry_data, only: c
3636       use energy_data, only: itype
3637 !      implicit real*8 (a-h,o-z)
3638 !      include 'DIMENSIONS'
3639 !      include 'COMMON.CHAIN'
3640 !      include 'COMMON.INTERACT'
3641 !      include 'COMMON.NAMES'
3642 !      include 'COMMON.IOUNITS'
3643       integer :: i
3644
3645       write (iout,100)
3646       do i=1,nres
3647         write (iout,110) restyp(itype(i,1),1),i,c(1,i),c(2,i),&
3648           c(3,i),c(1,nres+i),c(2,nres+i),c(3,nres+i)
3649       enddo
3650   100 format (//'              alpha-carbon coordinates       ',&
3651                 '     centroid coordinates'/ &
3652                 '       ', 6X,'X',11X,'Y',11X,'Z',&
3653                                 10X,'X',11X,'Y',11X,'Z')
3654   110 format (a,'(',i3,')',6f12.5)
3655       return
3656       end subroutine cartprint
3657 !-----------------------------------------------------------------------------
3658 !-----------------------------------------------------------------------------
3659       subroutine alloc_geo_arrays
3660 !EL Allocation of tables used by module energy
3661
3662       integer :: i,j,nres2
3663       nres2=2*nres
3664 ! commom.bounds
3665 !      common /bounds/
3666       allocate(phibound(2,nres+2)) !(2,maxres)
3667 !----------------------
3668 ! commom.chain
3669 !      common /chain/ in molread
3670 !      real(kind=8),dimension(:,:),allocatable :: c !(3,maxres2+2)
3671 !      real(kind=8),dimension(:,:),allocatable :: dc
3672       allocate(dc_old(3,0:nres2))
3673 !      if(.not.allocated(dc_norm2)) allocate(dc_norm2(3,0:nres2+2)) !(3,0:maxres2)      
3674       if(.not.allocated(dc_norm2)) then
3675         allocate(dc_norm2(3,0:nres2+2)) !(3,0:maxres2)
3676         dc_norm2(:,:)=0.d0
3677       endif
3678 !
3679 !el      if(.not.allocated(dc_norm)) 
3680 !elwrite(iout,*) "jestem w alloc geo 1"
3681       if(.not.allocated(dc_norm)) then
3682         allocate(dc_norm(3,0:nres2+2)) !(3,0:maxres2)
3683         dc_norm(:,:)=0.d0
3684       endif
3685 !elwrite(iout,*) "jestem w alloc geo 1"
3686       allocate(xloc(3,nres),xrot(3,nres))
3687 !elwrite(iout,*) "jestem w alloc geo 1"
3688       xloc(:,:)=0.0D0
3689 !elwrite(iout,*) "jestem w alloc geo 1"
3690       allocate(dc_work(6*nres)) !(MAXRES6) maxres6=6*maxres
3691 !      common /rotmat/
3692       allocate(t(3,3,nres),r(3,3,nres))
3693       allocate(prod(3,3,nres),rt(3,3,nres)) !(3,3,maxres)
3694 !      common /refstruct/
3695       if(.not.allocated(cref)) allocate(cref(3,nres2+2,maxperm)) !(3,maxres2+2,maxperm)
3696 !elwrite(iout,*) "jestem w alloc geo 2"
3697       allocate(crefjlee(3,nres2+2)) !(3,maxres2+2)
3698       if(.not.allocated(chain_rep)) allocate(chain_rep(3,nres2+2,maxsym)) !(3,maxres2+2,maxsym)
3699       if(.not.allocated(tabperm)) allocate(tabperm(maxperm,maxsym)) !(maxperm,maxsym)
3700 !      common /from_zscore/ in module.compare
3701 !----------------------
3702 ! common.local
3703 ! Inverses of the actual virtual bond lengths
3704 !      common /invlen/ in io_conf: molread or readpdb
3705 !      real(kind=8),dimension(:),allocatable :: vbld_inv !(maxres2)
3706 !----------------------
3707 ! common.var
3708 ! Store the geometric variables in the following COMMON block.
3709 !      common /var/ in readpdb or ...
3710       if(.not.allocated(theta)) allocate(theta(nres+2))
3711       if(.not.allocated(phi)) allocate(phi(nres+2))
3712       if(.not.allocated(alph)) allocate(alph(nres+2))
3713       if(.not.allocated(omeg)) allocate(omeg(nres+2))
3714       if(.not.allocated(thetaref)) allocate(thetaref(nres+2))
3715       if(.not.allocated(phiref)) allocate(phiref(nres+2))
3716       if(.not.allocated(costtab)) allocate(costtab(nres))
3717       if(.not.allocated(sinttab)) allocate(sinttab(nres))
3718       if(.not.allocated(cost2tab)) allocate(cost2tab(nres))
3719       if(.not.allocated(sint2tab)) allocate(sint2tab(nres))
3720 !      real(kind=8),dimension(:),allocatable :: vbld !(2*maxres) in io_conf: molread or readpdb
3721       allocate(omicron(2,nres+2)) !(2,maxres)
3722       allocate(tauangle(3,nres+2)) !(3,maxres)
3723 !elwrite(iout,*) "jestem w alloc geo 3"
3724       if(.not.allocated(xxtab)) allocate(xxtab(nres))
3725       if(.not.allocated(yytab)) allocate(yytab(nres))
3726       if(.not.allocated(zztab)) allocate(zztab(nres)) !(maxres)
3727       if(.not.allocated(xxref)) allocate(xxref(nres))
3728       if(.not.allocated(yyref)) allocate(yyref(nres))
3729       if(.not.allocated(zzref)) allocate(zzref(nres)) !(maxres) 
3730       allocate(ialph(nres,2)) !(maxres,2)
3731       ialph(:,1)=0
3732       ialph(:,2)=0
3733       allocate(ivar(4*nres2)) !(4*maxres2)
3734
3735 #if defined(WHAM_RUN) || defined(CLUSTER)
3736       allocate(vbld(2*nres))
3737       vbld(:)=0.d0
3738       allocate(vbld_inv(2*nres))
3739       vbld_inv(:)=0.d0
3740 #endif
3741
3742       return
3743       end subroutine alloc_geo_arrays
3744 !-----------------------------------------------------------------------------
3745 !-----------------------------------------------------------------------------
3746       subroutine returnbox
3747       integer :: allareout,i,j,k,nojumpval,chain_beg,mnum
3748       integer :: chain_end,ireturnval
3749       real*8 :: difference
3750 !C change suggested by Ana - end
3751         j=1
3752         chain_beg=1
3753 !C        do i=1,nres
3754 !C       write(*,*) 'initial', i,j,c(j,i)
3755 !C        enddo
3756 !C change suggested by Ana - begin
3757         allareout=1
3758 !C change suggested by Ana -end
3759         do i=1,nres-1
3760            mnum=molnum(i)
3761          if ((itype(i,mnum).eq.ntyp1_molec(mnum))&
3762             .and.(itype(i+1,mnum).eq.ntyp1_molec(mnum))) then
3763           chain_end=i
3764           if (allareout.eq.1) then
3765             ireturnval=int(c(j,i)/boxxsize)
3766             if (c(j,i).le.0) ireturnval=ireturnval-1
3767             do k=chain_beg,chain_end
3768               c(j,k)=c(j,k)-ireturnval*boxxsize
3769               c(j,k+nres)=c(j,k+nres)-ireturnval*boxxsize
3770             enddo
3771 !C Suggested by Ana
3772             if (chain_beg.eq.1) &
3773             dc_old(1,0)=dc_old(1,0)-ireturnval*boxxsize
3774 !C Suggested by Ana -end
3775            endif
3776            chain_beg=i+1
3777            allareout=1
3778          else
3779           if (int(c(j,i)/boxxsize).eq.0) allareout=0
3780          endif
3781         enddo
3782          if (allareout.eq.1) then
3783             ireturnval=int(c(j,i)/boxxsize)
3784             if (c(j,i).le.0) ireturnval=ireturnval-1
3785             do k=chain_beg,nres
3786               c(j,k)=c(j,k)-ireturnval*boxxsize
3787               c(j,k+nres)=c(j,k+nres)-ireturnval*boxxsize
3788             enddo
3789           endif
3790 !C NO JUMP 
3791 !C        do i=1,nres
3792 !C        write(*,*) 'befor no jump', i,j,c(j,i)
3793 !C        enddo
3794         nojumpval=0
3795         do i=2,nres
3796            mnum=molnum(i)
3797            if (itype(i,mnum).eq.ntyp1_molec(mnum)&
3798               .and. itype(i-1,mnum).eq.ntyp1_molec(mnum)) then
3799              difference=abs(c(j,i-1)-c(j,i))
3800 !C             print *,'diff', difference
3801              if (difference.gt.boxxsize/2.0) then
3802                 if (c(j,i-1).gt.c(j,i)) then
3803                   nojumpval=1
3804                  else
3805                    nojumpval=-1
3806                  endif
3807               else
3808               nojumpval=0
3809               endif
3810               endif
3811               c(j,i)=c(j,i)+nojumpval*boxxsize
3812               c(j,i+nres)=c(j,i+nres)+nojumpval*boxxsize
3813          enddo
3814        nojumpval=0
3815         do i=2,nres
3816            mnum=molnum(i)
3817            if (itype(i,mnum).eq.ntyp1_molec(mnum) .and. itype(i-1,mnum).eq.ntyp1_molec(mnum)) then
3818              difference=abs(c(j,i-1)-c(j,i))
3819              if (difference.gt.boxxsize/2.0) then
3820                 if (c(j,i-1).gt.c(j,i)) then
3821                   nojumpval=1
3822                  else
3823                    nojumpval=-1
3824                  endif
3825               else
3826               nojumpval=0
3827               endif
3828              endif
3829               c(j,i)=c(j,i)+nojumpval*boxxsize
3830               c(j,i+nres)=c(j,i+nres)+nojumpval*boxxsize
3831          enddo
3832
3833 !C        do i=1,nres
3834 !C        write(*,*) 'after no jump', i,j,c(j,i)
3835 !C        enddo
3836
3837 !C NOW Y dimension
3838 !C suggesed by Ana begins
3839         allareout=1
3840         j=2
3841         chain_beg=1
3842         do i=1,nres-1
3843            mnum=molnum(i)
3844          if ((itype(i,mnum).eq.ntyp1_molec(mnum))&
3845            .and.(itype(i+1,mnum).eq.ntyp1_molec(mnum))) then
3846           chain_end=i
3847           if (allareout.eq.1) then
3848             ireturnval=int(c(j,i)/boxysize)
3849             if (c(j,i).le.0) ireturnval=ireturnval-1
3850             do k=chain_beg,chain_end
3851               c(j,k)=c(j,k)-ireturnval*boxysize
3852              c(j,k+nres)=c(j,k+nres)-ireturnval*boxysize
3853             enddo
3854 !C Suggested by Ana
3855             if (chain_beg.eq.1) &
3856             dc_old(1,0)=dc_old(1,0)-ireturnval*boxxsize
3857 !C Suggested by Ana -end
3858            endif
3859            chain_beg=i+1
3860            allareout=1
3861          else
3862           if (int(c(j,i)/boxysize).eq.0) allareout=0
3863          endif
3864         enddo
3865          if (allareout.eq.1) then
3866             ireturnval=int(c(j,i)/boxysize)
3867             if (c(j,i).le.0) ireturnval=ireturnval-1
3868             do k=chain_beg,nres
3869               c(j,k)=c(j,k)-ireturnval*boxysize
3870               c(j,k+nres)=c(j,k+nres)-ireturnval*boxysize
3871             enddo
3872           endif
3873         nojumpval=0
3874         do i=2,nres
3875            mnum=molnum(i)
3876            if (itype(i,mnum).eq.ntyp1_molec(mnum)&
3877               .and. itype(i-1,mnum).eq.ntyp1_molec(mnum)) then
3878              difference=abs(c(j,i-1)-c(j,i))
3879              if (difference.gt.boxysize/2.0) then
3880                 if (c(j,i-1).gt.c(j,i)) then
3881                   nojumpval=1
3882                  else
3883                    nojumpval=-1
3884                  endif
3885              else
3886               nojumpval=0
3887               endif
3888            endif
3889               c(j,i)=c(j,i)+nojumpval*boxysize
3890               c(j,i+nres)=c(j,i+nres)+nojumpval*boxysize
3891          enddo
3892       nojumpval=0
3893         do i=2,nres
3894            mnum=molnum(i)
3895            if (itype(i,mnum).eq.ntyp1_molec(mnum)&
3896              .and. itype(i-1,mnum).eq.ntyp1) then
3897              difference=abs(c(j,i-1)-c(j,i))
3898              if (difference.gt.boxysize/2.0) then
3899                 if (c(j,i-1).gt.c(j,i)) then
3900                   nojumpval=1
3901                  else
3902                    nojumpval=-1
3903                  endif
3904               else
3905               nojumpval=0
3906               endif
3907             endif
3908               c(j,i)=c(j,i)+nojumpval*boxysize
3909               c(j,i+nres)=c(j,i+nres)+nojumpval*boxysize
3910          enddo
3911 !C Now Z dimension
3912 !C Suggested by Ana -begins
3913         allareout=1
3914 !C Suggested by Ana -ends
3915        j=3
3916         chain_beg=1
3917         do i=1,nres-1
3918            mnum=molnum(i)
3919          if ((itype(i,mnum).eq.ntyp1_molec(mnum))&
3920            .and.(itype(i+1,mnum).eq.ntyp1_molec(mnum))) then
3921           chain_end=i
3922           if (allareout.eq.1) then
3923             ireturnval=int(c(j,i)/boxysize)
3924             if (c(j,i).le.0) ireturnval=ireturnval-1
3925             do k=chain_beg,chain_end
3926               c(j,k)=c(j,k)-ireturnval*boxzsize
3927               c(j,k+nres)=c(j,k+nres)-ireturnval*boxzsize
3928             enddo
3929 !C Suggested by Ana
3930             if (chain_beg.eq.1) dc_old(1,0)=dc_old(1,0)-ireturnval*boxxsize
3931 !C Suggested by Ana -end
3932            endif
3933            chain_beg=i+1
3934            allareout=1
3935          else
3936           if (int(c(j,i)/boxzsize).eq.0) allareout=0
3937          endif
3938         enddo
3939          if (allareout.eq.1) then
3940             ireturnval=int(c(j,i)/boxzsize)
3941             if (c(j,i).le.0) ireturnval=ireturnval-1
3942             do k=chain_beg,nres
3943               c(j,k)=c(j,k)-ireturnval*boxzsize
3944               c(j,k+nres)=c(j,k+nres)-ireturnval*boxzsize
3945             enddo
3946           endif
3947         nojumpval=0
3948         do i=2,nres
3949            mnum=molnum(i)
3950            if (itype(i,mnum).eq.ntyp1_molec(mnum) .and. itype(i-1,mnum).eq.ntyp1_molec(mnum)) then
3951              difference=abs(c(j,i-1)-c(j,i))
3952              if (difference.gt.(boxzsize/2.0)) then
3953                 if (c(j,i-1).gt.c(j,i)) then
3954                   nojumpval=1
3955                  else
3956                    nojumpval=-1
3957                  endif
3958               else
3959               nojumpval=0
3960               endif
3961             endif
3962               c(j,i)=c(j,i)+nojumpval*boxzsize
3963               c(j,i+nres)=c(j,i+nres)+nojumpval*boxzsize
3964          enddo
3965        nojumpval=0
3966         do i=2,nres
3967            mnum=molnum(i)
3968            if (itype(i,mnum).eq.ntyp1_molec(mnum) &
3969             .and. itype(i-1,mnum).eq.ntyp1_molec(mnum)) then
3970              difference=abs(c(j,i-1)-c(j,i))
3971              if (difference.gt.boxzsize/2.0) then
3972                 if (c(j,i-1).gt.c(j,i)) then
3973                   nojumpval=1
3974                  else
3975                    nojumpval=-1
3976                  endif
3977               else
3978               nojumpval=0
3979               endif
3980             endif
3981              c(j,i)=c(j,i)+nojumpval*boxzsize
3982               c(j,i+nres)=c(j,i+nres)+nojumpval*boxzsize
3983          enddo
3984         do i=1,nres
3985          if (molnum(i).eq.5) then
3986           c(1,i)=dmod(c(1,i),boxxsize)
3987           c(2,i)=dmod(c(2,i),boxysize)
3988           c(3,i)=dmod(c(3,i),boxzsize)
3989           c(1,i+nres)=dmod(c(1,i+nres),boxxsize)
3990           c(2,i+nres)=dmod(c(2,i+nres),boxysize)
3991           c(3,i+nres)=dmod(c(3,i+nres),boxzsize)
3992          endif
3993         enddo
3994         return
3995         end       subroutine returnbox
3996 !-------------------------------------------------------------------------------------------------------
3997       end module geometry