#!/usr/bin/perl

#
# Script        : worldify.pl
# Task          : Adding a world to the default MCAM output in order that the geometry could be displayed in Moritz and Vised properly
# Execution     : ./worldify.pl fileName.mcn worldSize_inCentimeters
# Output        : fileName__worldified.mcn
# Author        : Mathieu Trocme (mathieu.trocme@ires.in2p3.fr)
# Date          : 21 September 2009
# Framework     : PhD thesis, CNRS/IPHC/DRS/RAMSES, Strasbourg, France
#

if ( @ARGV != 2 ) {	print ("\n!!! ERROR !!! \n\nUsage: ./worldify.pl fileName.mcn worldSize_inCentimeters \n\n") ; exit() ; }
$finName=$ARGV[0] ; 
$worldSize=$ARGV[1] ; 

# Making sure the input file permissions will allow to copy it
`chmod a+rw $finName` ; 

# Removing any file called foutName & creating the output file which is just a copy of the input file
$foutName = $finName ; $foutName =~ s/.mcn/__worldified.mcn/ ; 
`rm -f $foutName 2>/dev/null` ; 
`cp -f $finName $foutName && chmod a+rw $foutName` ; 

# Deleting all the empty last lines (necessary to append the last section without any white line)
`sed -i -e :a -e '/^\\n*\$/{\$d;N;ba' -e '}' $foutName` ;  # source: http://www.commentcamarche.net/faq/sujet-6699-sed-trucs-et-astuces

# Getting the number of cells
$nCells = `grep 'Cell(s)' $finName | awk '{print \$5}'` ; #printf("\nnCells = %d\n",$nCells) ;

# Generating the string of cells to be removed ("#1 #2 ..."), on several lines if necessary (adding a '&' at the end of each line)
$str_cellToBeRemoved = "" ;
for ($idx=1; $idx<=$nCells; $idx++) { 
	$str_cellToBeRemoved = $str_cellToBeRemoved." #".$idx ; 
	if ( $idx%10 == 0 && $idx!=$nCells ) { $str_cellToBeRemoved = $str_cellToBeRemoved." \\&\\n" ; }  # "\\" necessary to be properly copied in the file (see below)
}
$str_cellToBeRemoved = $str_cellToBeRemoved." \\&" ; #printf("\n%s\n",$str_cellToBeRemoved) ;

# Adding the world cells & surfaces in a compliant way to the MCAM "Read MCNP" function, which requires cells and surfaces to be in increasing order. 
`sed -i "s/^\$/c WORLD\\n998    0             999     IMP:N,P=0\\n999  999  -0.00125  -999 \\&\\n$str_cellToBeRemoved\\n IMP:N,P=1\\n/g" $foutName` ;
`echo -e "c WORLD\n999 rpp -$worldSize $worldSize -$worldSize $worldSize -$worldSize $worldSize\n" >> $foutName` ;

# Setting a random material (Pb) other than vacuum to all cells in order they can be seen
`sed -i "s/0   (/1 -11.35   (/g" $foutName` ;

# Adding a dummy data card
`echo "m999  7000 1."                  >> $foutName` ; 
`echo "m1 82000 1."                    >> $foutName` ; 
`echo "mode n"                         >> $foutName` ; 
`echo "sdef par=n erg=5. pos=0. 0. 0." >> $foutName` ; 
`echo "nps 1\n"                        >> $foutName` ; 
