#!/bin/sh
# consolidate DICOMDIR [CONSDIR] 
#
# Consolidates the directory structure of fragmented DICOM image, copying all the 
# images in the sub-sub-directories into a single sub-sub-directory.
# This was necessary because of the way DICOM files are saved at the VA.
# If CONSDIR is given, the DICOMDIR is first copied to CONSDIR and the
# consolidation is done in there.
#
#  Steve Lehar Jan 2010
#

# Check for command-line arg
if [ $# -eq 0 ] || [ $# -gt 2 ]; then
  echo 'Usage: consolidate DICOMDIR [CONSDIR] e.g. consolidate PRL045 PRL045C'
  exit 1
fi

# Check that arg1 is a directory
if ! [ -d $1 ]; then
  echo "ERROR consolidate: \"$1\" is not a directory!"
  exit 1
fi

# Convert $1 to absolute path
pushd $1 > /dev/null
prldir=`pwd`
popd > /dev/null

# Check that arg2 doesn't already exist
if [ $2 ]; then
  if [ -e $2 ]; then
    echo "ERROR consolidate: \"$2\" already exists"
    exit 1
  else
    mkdir $2
    echo "copy $1 to $2"
    cp -r $prldir/* $2
    cd $2
    prldir=`pwd`
  fi
fi

# Get the top directory and listing
echo "consolidate $prldir"
cd $prldir/DICOM
toplist=`ls`
#echo "toplist ="`ls`
firsttop='true'
for topdir in $toplist
do
  firstone='true'
  #echo "  topdir=$topdir"
  if [ $firsttop = 'true' ]; then
    firsttopdir=$topdir
  fi
  cd $prldir/DICOM/$topdir
  #echo "cd topdir pwd"`pwd`
  dirlist=`ls`
  
  for dir in $dirlist
  do
    #echo "    dir=$dir"

    #consolidate
    if [ $firstone = 'true' ]; then
      firstone='false'
      firstdir=$dir
      #echo "    firstdir=$firstdir"
    else
      #echo "cp $dir/* $firstdir"
      cp $dir/* $firstdir
    fi
  done

  #echo "Delete unused directories"
  for dir in $dirlist
  do
    if [ $dir = $firstdir ] && [ $topdir = $firsttopdir ]; then
      #echo "Don't delete $dir!"
      doNothing='true'
    else
      #echo "rm -r $dir"
      rm -r $dir
    fi
  done
  #echo "if topdir != firsttopdir"
  #echo "if $topdir != $firsttopdir"
  if [ $topdir != $firsttopdir ]; then
    #echo "rm -r $prldir/DICOM/$topdir"
    rm -r $prldir/DICOM/$topdir
  fi
  firsttop='false'
done




