#!/bin/bash
#---------------------------------------------------------------------
# Extract the files from the FireHawk disks
# Obs: Files beginning with "#" where deleted on the original disks
#      and this tool undeleted them.
#---------------------------------------------------------------------

DSKNAME=$1
#OUTDIR=`echo $DSKNAME | cut -f1 -d'.'`
#OUTDIR="${OUTDIR}_files"

OUTDIR="$2"

mkdir -p "${OUTDIR}"

for ((ENTRY=0x800; ENTRY<0x1200; ENTRY+=0x10 )) ; do
	
	USEDENTRY=$[`xxd -s $[$ENTRY] -l1 -g1 $DSKNAME |cut -f2 -d' '| sed -e"s/^/0x/"`]
	
#	if [ $USEDENTRY -gt 47 ] && [ $USEDENTRY -lt 123 ] ; then
	if [ $USEDENTRY -lt 123 ] ; then
		# Obtain the file entry on the directory table 

		if [ $USEDENTRY -gt 0 ] ; then
			FILENAM=`dd skip=$ENTRY bs=1 if=$DSKNAME count=8 2>/dev/null |cut -f1 -d' '`
		else
			FILENAM=`dd skip=$[$ENTRY+1] bs=1 if=$DSKNAME count=8 2>/dev/null |cut -f1 -d' '`
			FILENAM="#"${FILENAM}
		fi
		FILEEXT=`dd skip=$[$ENTRY+8] bs=1 if=$DSKNAME count=3 2>/dev/null`
		if [ "`echo $FILEEXT |cut -f1 -d' '`empty" != "empty" ] ; then
		FILENAM="$FILENAM.$FILEEXT"
		fi

		VALUES=`xxd -s $[$ENTRY+0xc] -l4 -g1 $DSKNAME |cut -f2-5 -d' '| sed -e"s/^/0x/;s/ / 0x/g"`
		eval VALUES="( $VALUES )"

		# Calculate the start sector
		C=$[${VALUES[2]}*2+((${VALUES[3]} & 0x10) >> 4 )]
		A=$[${VALUES[3]} & 0xEF]
		HL=$C
		DE=$[A+C-1]
		SECT=$[HL*8+DE]

		#Change FILENAM to all uppercase
		FILENAM=`echo $FILENAM | tr "[:lower:]" "[:upper:]"`	
	
		echo "${FILENAM}: sector=$SECT, size=${VALUES[0]}"
		dd bs=512 if=$DSKNAME of="${OUTDIR}/${FILENAM}" skip=$SECT count=${VALUES[0]}
		
	fi
	
done

if [ -f "${OUTDIR}/_" ] ; then
	mv ${OUTDIR}/_ ${OUTDIR}/STARTUP.COM
fi


 
