#!/bin/bash

CDMOUNTPOINT=/cdrom
TARGETBASEDIR=/ct

TARGETDIR=${TARGETBASEDIR}/cd_$(date +%Y%m%d_%H%M%S)

function progress() {
	if [ "$DISPLAY" == "" ] ; then 
		echo -ne "$1/$2\015"
	else 
		echo -ne "Loading files:\012 $2 files scanned\012 $1 DICOM files found." | \
			xmessage -center -buttons "" -timeout 1 -file - &
	fi
}

function complain() {
	if [ "$DISPLAY" == "" ] ; then 
		echo "$@"
	else 
		echo "$@" | xmessage -center -buttons "OK" -timeout 10 -file - &
	fi
}

function complain_and_exit() {
	complain "$@"
	exit 1
}

umount "${CDMOUNTPOINT}" 2>/dev/null
mount "${CDMOUNTPOINT}" || complain_and_exit "Can't mount CD. None in drive?"
mkdir "${TARGETDIR}" || complain_and_exit "Can't create target directory. Check access rights."
cd "${TARGETDIR}" || complain_and_exit "Can't change into target directory. Check access rights."

COUNTALL=0
COUNTDICOM=0

find "${CDMOUNTPOINT}/." -type f | while read filename ; do
	COUNTALL=$((COUNTALL+1))
	file "${filename}" | grep -q DICOM || continue
	COUNTDICOM=$((COUNTDICOM+1))
	progress "${COUNTDICOM}" "${COUNTALL}"
	CDF=$(printf "%08d" "${COUNTDICOM}")
	cat <"${filename}" >"${TARGETDIR}/${CDF}"
done
umount "${CDMOUNTPOINT}" || complain "Can't unmount CD."
complain "Files copied. Converting - please wait.






"
eccet_convert_dicomstack
complain "Conversion completed."

exit 0
