#!/bin/bash

# Compare radiances in VIIRS SDR files (M-band, I-band, DNB)
# Liam.Gumley@ssec.wisc.edu 2012-03-16

# Check arguments
if [ $# -ne 2 ]; then
  echo "Usage: viirs_sdr_compare.bash dir1 dir2"
  exit 1
fi

# Get primary and secondary directory names
dir1=$1
dir2=$2

# Get list of VIIRS SDR files
list=$(find $dir1 -name SV???_npp_*.h5 | sort)

# Loop over each file
for file1 in $list; do

  # Get product type (SVM, SVI, SVD), dataset name (e.g., /All_Data/VIIRS-I4-SDR_All/Radiance) and data type
  prod=$(basename $file1 | cut -c1-3)
  if [ $prod == "SVM" ]; then
    band=$(basename $file1 | cut -c4-5 | bc)
    data='/All_Data/VIIRS-M'$band'-SDR_All/Radiance'
  elif [ $prod == "SVI" ]; then
    band=$(basename $file1 | cut -c4-5 | bc)
    data='/All_Data/VIIRS-I'$band'-SDR_All/Radiance'
  else
    data='/All_Data/VIIRS-DNB-SDR_All/Radiance'
  fi
  type=$(h5dump -H -d $data $file1 | grep DATATYPE | awk '{print $2}' | cut -c5-8)

  # Get name of secondary SDR file
  name=$(basename $file1 | cut -c1-28)
  file2=$(find $dir2 -name $name'*.h5')

  # Compare primary and secondary SDR files
  if [ "$file2" != "" ]; then

    echo
    echo File 1: $file1
    echo File 2: $file2

    if [ "$type" == "IEEE" ]; then

      # Floating point comparison: look for relative differences
      h5diff -p 0.000001 $file1 $file2 $data

    else
     
      # Integer comparison: look for absolute differences
      h5diff -d 1 $file1 $file2 $data

    fi

    # Print message if no differences were found
    if [ $? -eq 0 ]; then
      echo "No differences found"
    fi

  fi 

done

exit 0
