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