#! /bin/csh -f
#
#  echo <value> for PBS memory limit, i.e. "-l mem=<value>" in a PBS job
#  submit command;
#
#  arguments:  $1 = desired memory *per processor*
#              $2 = desired #nodes
#              $3 = desired #processors per node
#
#  the script echos the resulting value string if successful, or "error" 
#  if not; there are no explanatory messages...
#
#  procedure:  (a) strip off trailing "mb", "kb", or "gb" from $1; extract
#    leading integer msize; (b) compute product with "@"; (c) re-attach
#    trailing "mb" "kb" or "gb"; (d) echo result
#
#  examples:
#
#     calc_memtot 2000mb 2 2  --> "8000mb"
#     calc_memtot 1900mb 8 4  --> "60800mb"
#     calc_memtot 1900 8 4  --> "error.." (1st arg needs trailing gb, kb or mb)
#     calc_memtot 1.9gb 8 4 --> "error.." (need integer value before mb/gb/kb)
#     calc_memtot a b c d   --> "error.." (wrong no. of arguments)
#
#        (actual error string contains suffix meant to be a hint as to the
#         cause of the trouble)
#

  if ( $#argv != 3 ) then
    # arg count error
    echo "error_arg_count"
    exit 1
  endif

  @ nnodes = $2
  if ( $status ) then
    # integer decode error
    echo "error_decode_2"
    exit 1
  endif

  @ ppn    = $3
  if ( $status ) then
    # integer decode error
    echo "error_decode_3"
    exit 1
  endif

  set mpernod = $1

  @ ier = 1
  set mtest_kb = `echo $mpernod | sed 's#kb$##'`
  set mtest_mb = `echo $mpernod | sed 's#mb$##'`
  set mtest_gb = `echo $mpernod | sed 's#gb$##'`

  if ( "$mtest_kb" != "$mpernod" ) then
    set munits = kb
    @ mnum = $mtest_kb
    if ( $status ) then
      # integer decode error
      echo "error_decode_1kb"
      exit 1
    endif
    @ ier = 0
  endif

  if ( "$mtest_mb" != "$mpernod" ) then
    set munits = mb
    @ mnum = $mtest_mb
    if ( $status ) then
      # integer decode error
      echo "error_decode_1mb"
      exit 1
    endif
    @ ier = 0
  endif

  if ( "$mtest_gb" != "$mpernod" ) then
    set munits = gb
    @ mnum = $mtest_gb
    if ( $status ) then
      # integer decode error
      echo "error_decode_1gb"
      exit 1
    endif
    @ ier = 0
  endif

  if ( $ier != 0 ) then
    # unrecognized memory units suffix
    echo "error_mem_units"
    exit 1
  endif

  @ mtot = $mnum * $nnodes * $ppn

  if ( $status ) then
    # arithmetic error
    echo "error_mem_product"
    exit 1
  endif

#  success...

  set mstr = ${mtot}${munits}

  echo $mstr
  exit 0
