#!/bin/bash 
#
# Bash shell script to read "grid.out" generated by PLUTO
# Depending on the input argument, it will print different information:
#
# -size:  print Nx,Ny (number of zones in the x- and y-direction)
# -xbeg:  print the second row of the file, containing the leftmost 
#         x-coordinate (xbeg)
# -ybeg:  print the row containing the beginning coordinate in the y-dir
# -xend:  print the row containing the rightmost coordinate in the x-dir
# -yend:  print the row containins the rightmost coordinate in the y-dir
#
# Last modified: Sep 7, 2012 by A. Mignone (mignone@ph.unito.it)
#

i=0
while read LINE; do      # read a line from grid.out

  if [ ${LINE:0:1} = '#' ]; then  # if the first character of the line
    continue                      # begins with '#' then do not increment i
  fi                              # and continue reading.

  if [ $i -eq 0 ]; then # 1 row after comment: number of zones
    Nx=$LINE            # in the x direction
  fi

  if [ $i -eq 1 ]; then # 2 rows (after comments) used to recover xbeg 
    if [ $1 = "-xbeg" ]; then 
      echo $LINE 
      exit 0
    fi
  fi

  if [ $i -eq $Nx ]; then  # nx rows (after comment) used to recover xend
    if [ $1 = "-xend" ]; then
      echo $LINE
      exit 0 
    fi
  fi

  let ybeg=Nx+1
  if [ $i -eq $ybeg ]; then
    Ny=$LINE
  fi

  let j=ybeg+1
  if [ $i -eq $j ]; then
    if [ $1 = "-ybeg" ]; then
      echo $LINE
      exit 0
    fi
  fi

  let j=ybeg+Ny
  if [ $i -eq $j ]; then
    if [ $1 = "-yend" ]; then
      echo $LINE
      exit 0
    fi
  fi

  let i=i+1
done < grid.out

if [ $1 = "-size" ]; then
  echo "Nx="$Nx";"
  echo "Ny="$Ny
else
  echo "Unrecognized flag"
fi
