#!/bin/bash

#------------------------------
# isnum $1
#------------------------------
function isnum {
  if [ $# -ne 1 ]; then
    echo "[ERROR] isnum : invalid argument" 1>&2 # output stderr
    return 1
  fi
  echo $1 | egrep '^[0-9]+$' > /dev/null 2>&1
  if [ $? -eq 0 ]; then
    return 0
  fi
  return 1
}

#------------------------------
# left string length
#------------------------------
function left {
  # $1 : string
  # $2 : length
  if [ $# -ne 2 ]; then
    echo "[ERROR] left $* : invalid argument" 1>&2 # output stderr
    return 1
  else
    isnum $2
    if [ $? -ne 0 ]; then
      echo "[ERROR] left $* : invalid argument" 1>&2 # output stderr
      return 1
    fi
    if [ `expr length $1` -le $2 ]; then
      echo $1
      return 0 
    fi
    expr substr $1 1 $2
    return 0
  fi
}

#------------------------------
# right string length
#------------------------------
function rigth {
  # $1 : string
  # $2 : length
  if [ $# -ne 2 ]; then
    echo "[ERROR] right $* : invalid argument" 1>&2 # output stderr
    return 1
  else
    isnum $2
    if [ $? -ne 0 ]; then
      echo "[ERROR] right $* : invalid argument" 1>&2 # output stderr
      return 1
    fi
    if [ `expr length $1` -le $2 ]; then
      echo $1
      return 0 
    fi
    l=`expr length $1`
    p=`expr $l - $2 + 1`
    expr substr $1 $p $2
    return 0
  fi
}

#------------------------------
# TEST
#------------------------------
left HelloWorld 5
rigth HelloWorld 5
