#! /bin/bash

## 
## This script constructs a composite IT8.7/1 reference or measurement file 
## for use by lprof, as described by Hal Engel in the document at
##   http://www.colorreference.de/testdata/composit-profile.txt
## It is also compatible with Argyll CMS files.
##
##     Version 0.02   Most recent modification: 23 January 2011
##       Copyright © 2010,2011 Brendt Wohlberg <osspkg@gmail.com>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of version 3 of the GNU General Public License at
## http://www.gnu.org/licenses/gpl-3.0.txt
##

# Function to convert decimal ASCII code to character
chr() {
  printf \\$(printf '%03o' $1)
}

# Initialise file counter and strings
n=0
a=''
s=''
# Iterate over all input reference files
for f in $*; do
  # Extract basename of reference file
  b=`basename $f | sed -e 's/\.[^\.]*$//'`
  # Accumulate list of basenames
  a="$a $b"
  # Accumulate new serial text
  if [ "$s" = '' ]; then
    s="$b"
  else
    s="$s $b"
  fi
  # Construct temporary file name
  g="$b.tmp"
  # Determine prefix character to be inserted in data section
  nc=`expr $n + 65`
  c=`chr $nc`
  # Insert current prefix character in data section of current reference file
  # (first replacing DMIN and DMAX with GS0 and GS23 respectively, for 
  # measurement files)
  sed -e "/BEGIN_DATA/,/END_DATA/ {
            s/^DMIN/GS0/
            s/^DMAX/GS23/
            s/^\([[:graph:]]*[[:digit:]][[:digit:]]*\)/$c\1/
          }" $f > $g
  # Increment file counter
  n=`expr $n + 1`
done


# Iterate over all temporary modified reference files
dst=''
for f in $a; do
  # Construct temporary file name
  h="$f.tmp"
  # If output exists, insert data section from current temporary file before
  # END_DATA tag, otherwise copy entire current temporary file to initialise 
  # the output file
  if [ "$dst" != '' ]; then
    # Extract data section from current temporary file and replace newlines 
    # with "\n"
    data=`sed -n '/^BEGIN_DATA\($\|[^_]\)/,/^END_DATA/ { /^BEGIN_DATA/b; /^END_DATA/b; p }' $h | sed ':a { $!N; s|\n|\\\n|; ta }'`
    # Insert current data section before END_DATA of output
    dst=`echo "$dst" | sed -e "/END_DATA\($\|[^_]\)/i$data"`
  else
    # Compute NUMBER_OF_SETS value for composite file
    ns=`expr 288 \* $n`
    # Create initial output file with modified SERIAL and NUMBER_OF_SETS tags
    dst=`sed -e "s/^SERIAL.*/SERIAL \"Composite $s\"/" \
             -e "s/^NUMBER_OF_SETS.*/NUMBER_OF_SETS $ns/" $h`
  fi
  # Clean up temporary files
  rm -f $h
done

# Output concatenated file data
echo "$dst"

exit 0