#!/bin/bash

ansiColor[0]="\e[0m"
ansiColor[1]="\e[36m"
ansiColor[2]="\e[33m"

OLDIFS=$IFS
NEWIFS='
'
IFS="$NEWIFS"
sarch="story.tgz"
sfile="start.txt"

while [ 1 ]
do
	printf "\n"
	optcnt=0
	for LINE in `/bin/tar -zxf $sarch $sfile -O`;
	do
		case $LINE in
			~THEEND)
				printf "\nYour sad tale will not be remembered.\n\n"
				IFS="$OLDIFS"
				exit
				;;
			~WIN)
				printf "\nYour story will go down in history.\nThank you for playing!\n\n"
				IFS="$OLDIFS"
				exit
				;;
			~*~*.txt)
				IFS="~" read -r -a ropt <<< $LINE
				IFS="$NEWIFS"
				((optcnt++))
				optprompt[$optcnt]="$optcnt) ${ropt[1]}\n"
				options[$optcnt]="${ropt[2]}"
				;;
			*) printf "$LINE\n" ;;
		esac
	done

	printf "\n"
	for ((i=1;i<=optcnt;i++));
	do
		printf "${ansiColor[1]}${optprompt[$i]}${ansiColor[0]}"
	done

	# Input loop
	choice=""
	while [ "$choice" == "" ]
	do
		printf "\n${ansiColor[2]}What's your choice?${ansiColor[0]} "
		read choice
		case $choice in
			q)
				printf "\nThanks for playing.\n\n"
				IFS="$OLDIFS"
				exit
				;;
			''|*[!0-9]*)
				printf "\nThat's not even a number.\n"
				choice=""
				;;
			*)
				if [ $choice -lt 1 ] || [ $choice -gt $optcnt ]; then
					printf "\nThat's not an option.\n";
					choice=""
				else
					sfile="${options[$choice]}"
				fi
			;;
		esac
	done
done

IFS="$OLDIFS"
