#!/bin/bash

# Author: Chuck Theobald, March 2012
# This script depends upon DCMTK's dcmdump program.
# It will copy a directory full of DICOM files into the
# given output directory with a sub-directory named for
# the ProtocolName group,element.  Alternative sortings
# may be had by judicious editing and modification of this
# script.

function usage {
  echo "Usage: $0 -D <DICOM directory>"
  echo "          -o Output directory"
  echo "          -h This page"
}

while getopts "hD:o:" flag
do
  case "$flag" in
    D)
      DICOMDIR=$OPTARG
      ;;
    o)
      OUTDIR=$OPTARG
      ;;
    h|?)
      usage
      exit 2
      ;;
  esac
done

if [ -z "${DICOMDIR}" ]; then
  echo "DICOMDIR is required"
  usage
  exit 2
fi

if [ -z "${OUTDIR}" ]; then
  echo "OUTDIR is required"
  usage
  exit 3
else
  mkdir ${OUTDIR}
fi

# Select each file in given DICOM directory.
for d in ${DICOMDIR}/*
do
  echo -n .
  ProtocolName=$(dcmdump ${d} | grep -e '^(0018,1030)' | sed -e 's/^(0018,1030).*\[\(.*\)\].*/\1/')
  DESTDIR=${OUTDIR}/${ProtocolName}
  if [ ! -d ${DESTDIR} ]; then
    mkdir ${DESTDIR}
  fi
  cp ${d} ${DESTDIR}/
done
ls ${OUTDIR}

