#!/usr/bin/perl
($pwd) = $ENV{"PWD"};	# Current Working Directory
($job) = "sander";	# whether this is sander or sander.new
@arde_node = qw(01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23);
		# Arde Cluster names
$arde_no = 1;	# Which arde machine should we use?
$count = 0;	# Comparison parameter to choose whether there are 2 jobs
		# running in a arde machine
@files = <*>;	# Read the current directory
chomp (@files);

foreach $_ (@files) {
  if (/lambda_/ && -d $_) {
    /lambda_(.*)/;
    $lambda = $1;
    chdir ("$pwd/$_") || die "cannot chdir to ./$_: $!";
    open(INPUT, ">test.in") || die "cannot open test.in: $!";
    print INPUT <<EOF;
    0 ps simulation with lambda = $lambda - Test Run
     &cntrl
      imin=0,
      ntx=1,irest=0,
      ntpr=0,ntwr=0,ntwx=0,
      ntc=1,ntf=1,ntb=0,cut=10,
      igb=0,
      ntr=0,
      nstlim=0,dt=0.001,nscm=5000,nrespa=1,
      ntt=3,gamma_ln=1,tempi=300,temp0=300,ig=233,
      ntp=0,taup=1,pres0=1,
      icfe=1,clambda=$lambda,klambda=6
     /
EOF
    close(INPUT) || die "cannot close test.in: $!";
    chdir ($pwd) || die "cannot chdir to ./$_: $!";
  }
}

NODE:
foreach $_ (@files) {
  if (-d $_ && /lambda_/) {	# If the file is a
				# directory and if it has 'lambda' in it
	++$count;
	chdir ("$pwd/$_") || die "cannot chdir to ./$_: $!";
				# Change the directory to the 'lambda' directory
	@files_check = <*>;	# Read the files in this 'lambda' directory
	foreach $_ (@files_check) {	# Loop to assign the names of the
					# prmtop and rst files
		if (/prmtop/) {
			$prmtop = $_;	# Assign the prmtop file
		} elsif (/inpcrd/) {
			$crd = $_;	# Assign the restart file
		} elsif (/test.in/) {
			/(.*)\.in/;
			$out = $1;	# Assign the output file name
			$md = $_;	# Assign the .in file
		}
	}
	if ($count/$arde_no <= 3) {	# Test if there are 2 jobs running
					# in the arde machine
		system ("\\ssh arde$arde_node[$arde_no-1] "
			."\"cd $pwd/$_ ; "
			."$job -O -i $md -p $prmtop -c $crd -o $out.out "
			."-r $out.rst -x $out.mdcrd &\" &");
					# Run the job
	} else {	# If there are already 2 jobs running ...
		$arde_no++;
                if ($arde_no == 24) {last NODE};
                system ("\\ssh arde$arde_node[$arde_no-1] "
                        ."\"cd $pwd/$_ ; "
                        ."$job -O -i $md -p $prmtop -c $crd -o $out.out "
                        ."-r $out.rst -x $out.mdcrd &\" &");
					# Run the job
	}
	chdir ($pwd) || die "cannot chdir to ./: $!";	# Go to the original
							# directory
  }
}
print "All of the jobs are running right now in arde cluster.\n";
