#! /usr/bin/env bash

# Convert time in format of H:MM or HH:MM (or possibly also including :SS), or even just H or HH, followed by AM/PM/am/pm
#    to 24 hour time without colon.
# Original time can be in $1 or multiple arguments due to possible use of spaces.

time=`echo $* | sed 's+^\([^:]*\)$+\1:00+' | sed 's+\(.*:.*\):.*+\1+' | tr -dc '[0-9]' | sed 's+^0*++'`

if [[ "$time" == "" ]]; then
  echo "X"
  exit
fi

suffix=`echo $* | tr -dc 'AMPMampm' | downcase`

if [[ $suffix != "" ]]; then
  # first if to catch times like 12:30 am
  if [[ $time -ge 1200 ]]; then
     time=$(($time-1200))
  fi
  if [[ $suffix == pm ]]; then
     time=$(($time+1200))
  fi
fi

echo `ndig 4 $time`
