* merge_large.inp
* For merging an arbitrarly large number of trajectory segments
* A number of intermediate segments are produced.
* These should be deleted with system calls.
*

set SYSDIR /my/dir/
set SYSNAME fnam

! X is the number of units to read at once
! F is the first unit to read on
! O is the output unit
set X = 80
set F = 11
set O = 1

if @?FIRSTN eq 0 stop
if @?LASTN eq 0 stop

calc MAX = @X * @X
calc OK = @LASTN - @FIRSTN + 1
if @OK ge @MAX stop

!read residue topology file
!read parameter file
!read in psf

set V = 1
set A = @FIRSTN
label OUTLOOP
calc Z = @A + @X - 1
if @Z gt @LASTN set Z = @LASTN
calc D = @Z - @A + 1
set U = @F
set N = @A

label INLOOP
open unit @U read unform name -
@SYSDIR@SYSNAME.@N.dcd
incr N by 1
incr U by 1
if @N le @Z goto INLOOP

open unit @O write unform name @SYSDIR@SYSNAME.cat@V.dcd
merge firstu @F nunit @D outputu @O

incre V by 1
incre A by @X
if @A gt @LASTN set A = @LASTN
if @Z lt @LASTN goto OUTLOOP

calc VMAX = @V - 1
set V = 1
set U = @F
label JOINLOOP
open unit @U read unform name -
@SYSDIR@SYSNAME.cat@V.dcd
incr V by 1
incr U by 1
if @V le @VMAX goto JOINLOOP

open unit @O write unform name @SYSDIR@SYSNAME.@FIRSTN-@LASTN.dcd
merge firstu @F nunit @VMAX outputu @O

STOP