#!/bin/bash

TMPFILE=/tmp/tmp-cnv-bdm-$$

function progress() {
	if [ "$DISPLAY" == "" ] ; then 
		echo -ne "Files processed:$1\015"
	else 
		echo -ne "Converting DICOM files:\012Processing file $1." | \
			xmessage -center -buttons "" -timeout 1 -file - &
	fi
}


if [ "$1" != "" ] ; then
	cd $1
fi

COUNT=0

find . -type f -maxdepth 1 | while read filename ; do 

	COUNT=$((COUNT+1))
	eccet_dicom_to_P5 -H <"$filename" >"$TMPFILE"
	progress "${COUNT}"

	PATNAME=$(cat "$TMPFILE" | grep -a "Dicom/(0010,0010)" | sed -e"s/#.*: //" | tr -c "a-zA-Z0-9" "_")
	if [ "$PATNAME" = "" ] ; then
		PATNAME="Noname"
	fi
	SERUID=$(cat "$TMPFILE" | grep -a "Dicom/(0020,000E)" | sed -e"s/#.*: //")
	if [ "$SERUID" = "" ] ; then
		SERUID="None"
	fi

	DIRNAME="${PATNAME}/$SERUID"

	ZPOS=$(cat "$TMPFILE" | grep -a "Dicom/(0020,0013)" | sed -e"s/#.*: //")

	if [ "$ZPOS" = "" ] ; then
		continue;
	fi

	ZPOS=$( printf "%04d" "$ZPOS" )
	mkdir -p "${DIRNAME}"
	TARGET="${DIRNAME}/${ZPOS}.dcm"
	
	if [ -e "$TARGET" ] ; then
		echo "Can't move $filename to $TARGET."
		continue
	fi

	mv "$filename" "$TARGET" 2>&1
	chmod a-x "$TARGET"
	chmod ug+w "$TARGET"
done

rm -f "$TMPFILE"

exit 0
