#!/bin/ash
#
# medelamer rev4.001
#
# http://www.seanster.com/lamer
#
# rev4 20110524 SDM lamer@seanster.com *4th release, *A-Z, *Decade, *Name, *movie.nfo support, *automatic first-shortcut collection, *config file tweaks
# rev3 20110508 SDM lamer@seanster.com *3rd release, *thumbgen support, *config file tweaks
# rev2 20110502 SDM lamer@seanster.com *second release 1st release, *top250, *config file tweaks
# rev1 20110323 SDM lamer@seanster.com *first release never released
#
# Copyright (c) 2011 Seanster All Rights Reserved. Licensed under the GNU GPLv3
# 

VERSION="ID	medelamer.conf	rev4"

# set -x outputs all commands to stder
# set +x normal does not output all commands to stder
#


OIFS=$IFS
NIFS="$(printf '\n')"
NTFS="$(printf '\n\t')"
RET="$(printf '\r')"
SPACE="$(printf ' ')"
TAB="$(printf '\t')"
PIPE="$(printf '|')"
NTPFS="$(printf '|\n\t')"


SCRIPT_NAME="$0"


# Log File Extensions

LOG_EXT=".log"
LOG_ERR_EXT=".err"

# Create default log file name
DEF_LOG="$SCRIPT_NAME$LOG_EXT"
DEF_LOG_ERR="$SCRIPT_NAME$LOG_ERR_EXT"

# redirect error output to DEF_LOG_ER
# exec 2>"$DEF_LOG_ERR"


# the default config file shall be a file of the same name as the progream

CONF_EXT=".conf"
CONF="$SCRIPT_NAME$CONF_EXT"


################## FUNCTION DEFNS ##########################
################## FUNCTION DEFNS ##########################
################## FUNCTION DEFNS ##########################
################## FUNCTION DEFNS ##########################


#
# GET INFO TYPE
#
# grep the file for some sort of marker to tell what format it is
# expected to return NULL if not recognized
#
# I suppose we could return FAIL if we wanted to really point out
# a bad situation, but the caller will need to have it's logic double-checked first
#
# INPUT: filepath
#
# OUTPUT: ID STRING (TGXML, SUM, DPXML, XML, etc)
#

get_INFO_Type () {

  f="$1"

  # should check these in order of most confident ID string

  if [ -n "$reg_TGXML" ] ; then
    g=`grep "$reg_TGXML" "$f"`
    if [ -n "$g" ] ; then
      echo "$ID_TGXML"
      return
    fi
  fi  

  if [ -n "$reg_DPXML" ] ; then
    g=`grep "$reg_DPXML" "$f"`
    if [ -n "$g" ] ; then
      echo "$ID_DPXML"
      return
    fi
  fi  

  if [ -n "$reg_SUM" ] ; then
    g=`grep "$reg_SUM" "$f"`
    if [ -n "$g" ] ; then
      echo "$ID_SUM"
      return
    fi
  fi  

  if [ -n "$reg_XML" ] ; then
    g=`grep "$reg_XML" "$f"`
    if [ -n "$g" ] ; then
      echo "$ID_XML"
      return
    fi
  fi  

  if [ -n "$reg_MXML" ] ; then
    g=`grep "$reg_MXML" "$f"`
    if [ -n "$g" ] ; then
      echo "$ID_MXML"
      return
    fi
  fi  
}



############# GET INFO FILES ####################
# 
# Given a directory, spit out a list of available INFO files and their specific formats
# BUT - only return the files in a certain order of preference 
# (the logic of which is known only to one man on the planet)
#

# INPUT: Directory Pathname

# OUTPUT: List of :  TYPE|Directory Pathname \n
#         NULL > if nothing found
#         TYPE 'FAIL' > if the only xml is an unrecognized style 
#         (or maybe we want to pass up to the caller a troublesome file name
#         but so far we dont, we are happy if one file is readable)
#
# Eventually we could add DIR style and use the actual directory/filename as a source of info,
# and the retured filepath could itself be parsed for goodies.
#

get_INFO_Files () {

  have_SUM=""
  have_TGXML=""
  have_DPXML=""
  have_XML=""
  have_MXML=""

  path=$*
  base=`basename "$path"`

# path /tmp/hdd/volumes/HDD1/Movies/2001 - A Space Odyssey (1968).tt0062622(84)
# base 2001 - A Space Odyssey (1968).tt0062622(84)

#  echo -e "path $path" >&2
#  echo -e "base $base" >&2

  #
  # look for the first available DVDPROFILER IMDB tt1234567.xml file
  #

 if [ -n "$ID_DPXML" ] ; then
    z=`find "$path" -name "$nam_IMDB" | head -n 1 -`

    if [ -e "$z" ] ; then

      # make sure it's dvdprofiler
      # otherwise let the catch-all *.xml find and ID it
      # so as to move that less-preferred file to the bottom of the list

      the_type=`get_INFO_Type "$z"`

    #  echo "x $the_type x"

      if [ "$the_type" == "$ID_DPXML" ] ; then

        have_DPXML="true"

        echo -e "$the_type|$z"
      fi
    fi


    #
    # look for the first available DVDPROFILER UPC 123456789012.xml file
    #

    z=`find "$path" -name "$nam_DPXML" | head -n 1 -`

    if [ -e "$z" ] ; then

      # make sure it's dvdprofiler
      # otherwise let the catch-all *.xml find and ID it
      # so as to move that less-preferred file to the bottom of the list

      the_type=`get_INFO_Type "$z"`

      if [ "$the_type" == "$ID_DPXML" ] ; then
        have_DPXML="true"
        echo -e "$the_type|$z"
      fi
    fi
  fi


  #
  # Look for summary.txt
  #

 if [ -n "$ID_SUM" ] ; then
    z="$path/$nam_SUM"

    if [ -e "$z" ] ; then

      # found the summary.txt file which has a special format

    #  echo -e "$SCRIPT_NAME:\t exist $z" >&2

      the_type=`get_INFO_Type "$z"`

      if [ "$the_type" == "$ID_SUM" ] ; then

        have_SUM="true"

        echo -e "$the_type|$z"
      else

        # weird.. found a summary.txt file but we don't recognize the format
        # sounds like something we should report to the error stream
        # but now that you can not define them we have to be a little smarter
        echo -e "$ID_FAIL|$z" >&2
      fi
    fi
  fi
  #
  # Look for movie.nfo
  #

 if [ -n "$ID_MXML" ] ; then
    z="$path/$nam_MXML"

    if [ -e "$z" ] ; then

      # found the file

    #  echo -e "$SCRIPT_NAME:\t exist $z" >&2

      the_type=`get_INFO_Type "$z"`

      if [ "$the_type" == "$ID_MXML" ] ; then

        have_MXML="true"

        echo -e "$the_type|$z"
      else

        # weird.. found a movie.nfo file but we don't recognize the format
        # sounds like something we should report to the error stream
        echo -e "$ID_FAIL|$z" >&2
      fi
    fi
  fi



  #
  # Look for whatever.nfo (and see if it is thumbgen)
  #
  # If some dumbass has multiple nfo files too damn bad for me cuz i had to code for it

  # *.nfo

  # important to have globbing flag on during this

  for file in $path/$nam_TGXML ; do

    if [ -e "$file" ] ; then

      # found the whatever.nfo file which may have a special format

      #  echo -e "$SCRIPT_NAME:\t exist $file" >&2

      the_type=`get_INFO_Type "$file"`

#was going to skip multiple TG files but F-it
#      if [ "$the_type" == "$ID_TGXML" ] && [ have_TGXML != "true" ] ; then

       if [ "$the_type" == "$ID_TGXML" ] ; then

        have_TGXML="true"

        echo -e "$the_type|$file"

      else

        # we found an NFO file but it is not thumbgen format.
        # It's likely there are tons of useless nfo files in a collection so we will ignore it.
        x=1
        #echo -e "$ID_FAIL|$file" >&2
      fi
    fi
  done



  #
  # look for "DIRNAME.xml"
  #

  z="$path/$base.xml"

  # test for the existence of <DIR>.xml

  if [ -e "$z" ] ; then

    # ok it exists and we will use it

    have_XML="true"

  #    echo -e "$SCRIPT_NAME:\t exist $z" >&2

  else

  #  echo -e "$SCRIPT_NAME:\t not exist"

    #
    # search for the first occurrence of something like DIR.CD2.xml
    #


    z=`find "$path" -name "$base*.xml" | head -n 1 -`

    # test it to be sure

    if [ -e "$z" ] ; then

  #    echo -e "$SCRIPT_NAME:\ta: exist $z" >&2
      have_XML="true"

    else
      # echo -e "$SCRIPT_NAME:\ta: not exist $z"

      #
      # look for the first occurrence of ANY xml file
      # unless we have a DPXML file, in which case  we need to exclude finding it again
      #

      if [ "$have_DPXML" == "true" ] ; then
        # invert grep for the DVD Profiler name format to exclude those from any results
        z=`find "$path" -name "*.xml" | grep -v "$nam_DPXML" | head -n 1 -`
      else  
        z=`find "$path" -name "*.xml" | head -n 1 -`
      fi

      # test the results to be sure

      if [ -e "$z" ] ; then

  #     echo "$SCRIPT_NAME:\t exist $z" >&2
        have_XML="true"

      else

        # we may have other acceptable files no need to bitch about it 
        #echo -e "s1b: not exist $z" >&2

        # cant find any acceptable info file so just give up

        have_XML="false"

      fi
    fi
  fi

  #
  # determine exactly what kind of XML we are dealing with
  #

  if [ "$have_XML" == "true" ] ; then

    the_type=`get_INFO_Type "$z"`

    if [ -n "$the_type" ] ; then

      # We don't care what the type is really, just that there is one
      echo -e "$the_type|$z"

    else

      # we found a file but couldn't read it or otherwise determine it's file type
      # I guess it's really only a problem if we have NO OTHER file

      # But someone would want to know that there's unparseable XML out there

      # But if we have already found readable INFO it's less of a concern
      # so lets compromise, and ignore it if we do have another file

      # if we don't have any other file we should I guess pass that info back to the caller
      # The caller should decide if it needs to be logged to STDERR (or at least stuff movie in OTHER genre)
      # Let's return it to the caller even though it will have to be handled

      if  [ "$have_TGXML" != "true" ] && [ "$have_SUM" != "true" ] && [ "$have_DPXML" != "true" ] && [ "$have_MXML" != "true" ] ; then

        echo -e "$ID_FAIL|$z"

      fi
    fi
  fi
}

############# END GET INFO FILES ####################



############# MAKE INFO LIST ####################

# Makes a list of the available information files (xml, nfo, txt, etc) for a directory
# INPUT: $COLLECTION_PATH
# OUTPUT "$LIST_INFO_INFO" (a file)

make_INFO () {

  echo -e "make_INFO\n"

  # create empty list

  cat /dev/null > "$LIST_INFO_INFO"

  IFS="$NTFS"

 
  # this find command will disallow symlinks as part of the movie collection
  # could be a good thing or could be a bad thing... dunno.

  # important to have globbing flag on during this

  for dir in $COLLECTION_PATH* ; do

  echo "Processing: $dir"

    if [ -d "$dir" ] ; then

      info_file=`get_INFO_Files "$dir"`

      if [ -n "$info_file" ] ; then

        echo -e "$info_file"

        echo -e "$info_file" >> "$LIST_INFO_INFO"

      fi
    else
      echo -e "" >&2
      echo "make_INFO: not a directory: $dir" >&2
      echo -e "" >&2
    fi
    echo -e ""
  done

  IFS="$NTFS"

}

############# END MAKE INFO LIST ####################




############# GET NAME ####################

# Given Type and Filename, extract the Movie Title from the file
#
# INPUT: TYPE, FILEPATH
# OUTPUT Movie Title

get_NAME () {

xthe_type="$1"
xthe_file="$2"

#echo -e "t[$xthe_type]T f[$xthe_file]F"
#echo -e ">>$IFS<<"

  case $xthe_type in

    # (always on the first line of the file after the brackets) HAS LINEFEED so EXTRA PERIOD before $
    # (1942)  Casablanca
    SUM) xthe_list=`sed -n -e '1 {s/^.*)\ \ \(.*\).$/\1/p}' "$xthe_file"`;;

    #    <title>Apocalypse Now</title>
    XML) xthe_list=`sed -n -e '/<title/,1 { s~\&amp;~\&~g ; s/.*<title.*>\(.*\)<\/title>.*$/\1/p }' "$xthe_file"` ;;

    #  <OriginalTitle>Terminator 2: Judgment Day</OriginalTitle>
    DPXML) xthe_list=`sed -n -e '/<OriginalTitle/,1 { s~\&amp;~\&~g ; s/.*<OriginalTitle>\(.*\)<\/OriginalTitle>.*$/\1/p }' "$xthe_file"` ;;

    #  <title>Dead Snow</title>
    TGXML) xthe_list=`sed -n -e '/<title/,1 { s~\&amp;~\&~g ; s/.*<title.*>\(.*\)<\/title>.*$/\1/p }' "$xthe_file"` ;;

    #  <title>Dead Snow</title>
    # sed range selection doesn't apply to a single line and wont work right if we used closing tag here
    MXML) xthe_list=`sed -n -e '/<title/,1 { s~\&amp;~\&~g ; s/.*<title.*>\(.*\)<\/title>.*$/\1/p }' "$xthe_file"` ;;

    FAIL) return;;
  
  esac

  echo "$xthe_list"
}

############# END GET NAME ####################



############# MAKE NAME LIST ####################

# INPUT: "$LIST_INFO_INFO" (a file)

# OUTPUT: "$LIST_NAME_INFO" (a file)
# OUTPUT: "$LIST_NAME_INFO_SORTED" (a file)

make_NAME () {


  # create empty list

  cat /dev/null > "$LIST_NAME_INFO"

  IFS="$NTPFS"

  while read -r qinfo_type qinfo_file ; do

#    echo -e "x $qinfo_line X"

    xname=""

    if [ -n "$qinfo_type" ] && [ -n "$qinfo_file" ] ; then
      
#      echo -e "X $xgenres $qinfo_type $qinfo_file X" >&2
      
      xname=`get_NAME "$qinfo_type" "$qinfo_file"`

      # Remove EVIL characters from anywhere in the filename
      # Would consider translating evil characters to some benign characters -need feedback
      # backticks require triple backslash escaping
      xname=`echo "$xname" | tr -d "\/\\\`\"|'<>:?*"`

      # remove any single or consecutive leading periods and other LEADING crap
      # would be easier to choose what is allowed
      xname=`echo "$xname" | sed -e '{s/^\([]~!@#$%^&*{}();:,.\ +|=[-]*\)//}'`

      # move leading 'the' and append to end as (The) -case insensitive and preserves original case
      xname=`echo "$xname" | sed -e '{s/^\(the\)\ \(.*\)$/\2 (\1)/I}'`
      
      if [ -n "$xname" ] ; then
        
        gdir=`dirname "$qinfo_file"`
        echo -e "$xname|$gdir" >> "$LIST_NAME_INFO"
      fi
    fi
  done < "$LIST_INFO_INFO"

  IFS="$NTFS"

  # Now take the list and SORT it, removing DUPLICATES, and numeric

  cat "$LIST_NAME_INFO" | sort -n -u > "$LIST_NAME_INFO_SORTED"
}

############# END MAKE NAME LIST ####################



############# BUILD NAME ####################

# INPUT: "$LIST_NAME_INFO_SORTED" (a file)
# OUTPUT: "$LIST_NAME_CMDS" (a file)

build_NAME () {

  cat /dev/null > "$LIST_NAME_CMDS"

  # now we go thru the list, simply creating links to the movie directories in entirety

  IFS="$PIPE"

  echo "echo \"#$SCRIPT_NAME $LIST_NAME_CMDS `date`\"" >> "$LIST_NAME_CMDS"
  echo -e "" >> "$LIST_NAME_CMDS"
  echo "if [ ! -d \"$CAT_ROOT_PATH$NAME_NAME\" ] ; then mkdir \"$CAT_ROOT_PATH$NAME_NAME\" ; fi;" >> "$LIST_NAME_CMDS"
  echo "ln -f -s \"$ICON_SRC_PATH$CAT_SET_PATH/$NAME_ICON\" \"$CAT_ROOT_PATH$NAME_NAME/folder.jpg\"" >> "$LIST_NAME_CMDS"
  echo -e "" >> "$LIST_NAME_CMDS"

  last_name="x"
  dupes=1
  
  while read -r xgen xdir ; do
    if [ -n "$xgen" ] ; then
      name="$xgen"
      fdir="$xdir"

      if [ "$name" != "$last_name" ] ; then
        dupes=1
      else
        dupes=$(($dupes+1))
      fi

      # we do kinda care if a movie is listed twice with two different folders... GIGO!
      echo -e "" >> "$LIST_NAME_CMDS"
      if [ "$dupes" != "1" ] ; then
        echo "ln -f -n -s \"$fdir\" \"$CAT_ROOT_PATH$NAME_NAME/$name -$dupes\"" >> "$LIST_NAME_CMDS"
      else
        echo "ln -f -n -s \"$fdir\" \"$CAT_ROOT_PATH$NAME_NAME/$name\"" >> "$LIST_NAME_CMDS"
      fi
      
      last_name="$name"
    fi
  done < "$LIST_NAME_INFO_SORTED"

  echo -e "" >> "$LIST_NAME_CMDS"
  echo "echo -e \"#EOF $SCRIPT_NAME $LIST_NAME_CMDS `date`\n\"" >> "$LIST_NAME_CMDS"
  
  
  IFS="$NTFS"
}

############# END BUILD NAME ####################




############# GET AZ ####################

# Given First Letter of a Movie Title, output the AZ category
# if titles have odd characters they should be translated down to something normal by the caller
#
# INPUT: 1st Character of Movie Title
# OUTPUT AZ Category

get_AZ () {

  xchar="$1"

# 0-9, A-B, C-D, E-F, G-H, I-K, L-M, N-O, P-R; S-T; U-W; X-Z

  case $xchar in

    [0-9]) echo "0-9" ;;

    [A-Ba-b]) echo "A-B" ;; 
    [C-Dc-d]) echo "C-D" ;; 
    [E-Fe-f]) echo "E-F" ;; 
    [G-Hg-h]) echo "G-H" ;; 
    [I-Ki-k]) echo "I-K" ;; 
    [L-Ml-m]) echo "L-M" ;; 
    [N-On-o]) echo "N-O" ;; 
    [P-Rp-r]) echo "P-R" ;; 
    [S-Ts-t]) echo "S-T" ;; 
    [U-Wu-w]) echo "U-W" ;; 
    [X-Zx-z]) echo "X-Z" ;; 

    *) echo "0-9" ;;

  esac

# not entirely sure why I chose to return a single line rather than a list

  echo "$xthe_list"
}

############# END GET AZ ####################


############# MAKE AZ LIST ####################

# INPUT: "$LIST_INFO_INFO"  (file)

# OUTPUT: "$LIST_AZ_INFO"  (file)
# OUTPUT: "$LIST_AZ_INFO_SORTED" (file)

make_AZ () {

  xname=""

  # create empty list of 'raw' genres 

  cat /dev/null > "$LIST_AZ_INFO"

  IFS="$NTPFS"

last_az="zyzzy"

  while read -r qinfo_type qinfo_file ; do

#    echo -e "x $qinfo_line X"

    if [ -n "$qinfo_type" ] && [ -n "$qinfo_file" ] ; then
      
#      echo -e "$qinfo_type $qinfo_file"
      

      xname=`get_NAME "$qinfo_type" "$qinfo_file"`

      # Remove EVIL characters from anywhere in the filename
      # Would consider translating evil characters to some benign characters -need feedback
      # backticks require triple backslash escaping
      xname=`echo "$xname" | tr -d "\/\\\`\"|'<>:?*"`

      # [ bracket causes a core dump anywhere in tr list -exploit
      #xname=`echo "$xname" | tr -d " \/\\\`\"|'<>;:?+&%!=*,.]()#^~-"`

      # remove any single or consecutive leading periods and other LEADING crap
      # would be easier to choose what is allowed
      xname=`echo "$xname" | sed -e '{s/^\([]~!@#$%^&*{}();:,.\ +|=[-]*\)//}'`

      # move leading 'the' and append to end as (The) -case insensitive and preserves original case
      xname=`echo "$xname" | sed -e '{s/^\(the\)\ \(.*\)$/\2 (\1)/I}'`

      # YES DO THIS AGAIN AFTER REMOVING 'THE'
      # remove any single or consecutive leading periods and other LEADING crap
      # would be easier to choose what is allowed
      xname=`echo "$xname" | sed -e '{s/^\([]~!@#$%^&*{}();:,.\ +|=[-]*\)//}'`

      # this is just plain sad
      xletter=`echo "$xname" | sed -n -e '1 {s/\(.\).*/\1/p}'`
      
      xaz=`get_AZ "$xletter"`

#      echo -e "X $xaz X" 

      if [ -n "$xaz" ] ; then
        gdir=`dirname "$qinfo_file"`
        echo -e "$xaz|$gdir" >> "$LIST_AZ_INFO"
      fi
    fi
    
  done < "$LIST_INFO_INFO"

  IFS="$NTFS"

  # Now take the genre - directory list and SORT it numeric, and removing DUPLICATES

  cat "$LIST_AZ_INFO" | sort -u -n > "$LIST_AZ_INFO_SORTED"
}

############# END MAKE AZ LIST ####################



############# BUILD AZ ####################

# INPUT: "$LIST_AZ_INFO_SORTED" (a file)
# INPUT: "$LIST_AZ_SECT" (a file of the AZ cropped out of the config file)
#
# OUTPUT: "$LIST_AZ_CMDS" (a file)

build_AZ () {


  cat /dev/null > "$LIST_AZ_CMDS"

  # now we need to go thru the list, doing lookups on GENRE
  # to get the genre info

  cur_genre=""

  IFS="$PIPE"

  echo "echo \"#$SCRIPT_NAME $LIST_AZ_CMDS `date`\"" >> "$LIST_AZ_CMDS"
  echo -e "" >> "$LIST_AZ_CMDS"
  echo "if [ ! -d \"$CAT_ROOT_PATH$AZ_NAME\" ] ; then mkdir \"$CAT_ROOT_PATH$AZ_NAME\" ; fi;" >> "$LIST_AZ_CMDS"
  echo "ln -f -s \"$ICON_SRC_PATH$CAT_SET_PATH/$AZ_ICON\" \"$CAT_ROOT_PATH$AZ_NAME/folder.jpg\"" >> "$LIST_AZ_CMDS"
  echo -e "" >> "$LIST_AZ_CMDS"


  while read -r xgen xdir ; do
    if [ -n "$xgen" ] ; then
      genre="$xgen"
      dir="$xdir"

      if [ "$cur_genre" != "$genre" ] ; then

        # output commands to generate the particular folder

        echo -e "" >> "$LIST_AZ_CMDS"
        echo "if [ ! -d \"$CAT_ROOT_PATH$AZ_NAME/$genre\" ] ; then mkdir \"$CAT_ROOT_PATH$AZ_NAME/$genre\" ; fi;" >> "$LIST_AZ_CMDS"
        
        # directly symlink the folder icon from the icon library 
        echo "ln -f -s \"$ICON_SRC_PATH$AZ_SET_PATH/$genre.png\" \"$CAT_ROOT_PATH$AZ_NAME/$genre/folder.jpg\"" >> "$LIST_AZ_CMDS"

        cur_genre="$genre"
      else
        v=1
      fi

      # output linkin cmd
      echo -e "" >> "$LIST_AZ_CMDS"
      echo "ln -f -s \"$dir\" \"$CAT_ROOT_PATH$AZ_NAME/$genre/.\"" >> "$LIST_AZ_CMDS"

    fi
  done < "$LIST_AZ_INFO_SORTED"

  echo -e "" >> "$LIST_AZ_CMDS"
  echo "echo -e \"#EOF $SCRIPT_NAME $LIST_AZ_CMDS `date`\n\"" >> "$LIST_AZ_CMDS"
  
  IFS="$NTFS"
}

############# END BUILD AZ ####################





############# GET YEAR ####################

# Given Type and Filename, extract the EYE M D BEE RATING Rating from the file
#
# INPUT: TYPE, FILEPATH
# OUTPUT rating 0-10

get_YEAR () {

xthe_type="$1"
xthe_file="$2"

#echo -e "t[$xthe_type]T f[$xthe_file]F"
#echo -e ">>$IFS<<"

  case $xthe_type in

    # (always on the first line of the file in brackets)
    # (1942)  Casablanca
    SUM) xthe_list=`sed -n -e '1 {s/^(\([0-9][0-9][0-9][0-9]\)).*$/\1/p}' "$xthe_file"`;;

    # allows index= or not
    #   <year index="Year_1970-79_1">1979</year>
    XML) xthe_list=`sed -n -e '/<year/,1 { s/.*<year.*>\([0-9][0-9][0-9][0-9]\)<\/year>.*$/\1/p }' "$xthe_file"` ;;

    #   <ProductionYear>1991</ProductionYear>
    DPXML) xthe_list=`sed -n -e '/<ProductionYear/,1 { s/.*<ProductionYear>\([0-9][0-9][0-9][0-9]\)<\/ProductionYear>.*$/\1/p }' "$xthe_file"` ;;

    # allows index= or not
    #   <year>2009</year>
    TGXML) xthe_list=`sed -n -e '/<year/,1 { s/.*<year.*>\([0-9][0-9][0-9][0-9]\)<\/year>.*$/\1/p }' "$xthe_file"` ;;

    # allows index= or not
    #   <year>2009</year>
    MXML) xthe_list=`sed -n -e '/<year/,1 { s/.*<year.*>\([0-9][0-9][0-9][0-9]\)<\/year>.*$/\1/p }' "$xthe_file"` ;;

    FAIL) return;;
  
  esac

# not entirely sure why I chose to return a single line rather than a list

  echo "$xthe_list"
}

############# END GET YEAR ####################


############# GET DECADE ####################

# Given Year, Output Decade
#
# INPUT: YEAR 1939
# OUTPUT DECADE 1930

get_DECADE () {

xthe_year="$1"

  if [ -n "$xthe_year" ]; then
    # yes.. brutal reliance upon strict integer math
    xthe_decade=$(($xthe_year/10))
    xthe_decade=$(($xthe_decade*10))
  else
    return;
  fi

  echo "$xthe_decade"
}

############# END GET DECADE ####################



############# MAKE DECADE LIST ####################

# INPUT: "$LIST_INFO_INFO" (a file)

# OUTPUT: "$LIST_DECADE_INFO" (a file)
# OUTPUT: "$LIST_DECADE_INFO_SORTED" (a file)

make_DECADE () {


  # create empty list

  cat /dev/null > "$LIST_DECADE_INFO"

  IFS="$NTPFS"

  while read -r qinfo_type qinfo_file ; do

#    echo -e "x $qinfo_line X"

    xdecade=""
    xyear=""

    if [ -n "$qinfo_type" ] && [ -n "$qinfo_file" ] ; then
      
#      echo -e "X $xgenres $qinfo_type $qinfo_file X" >&2
      
      xyear=`get_YEAR "$qinfo_type" "$qinfo_file"`
      xdecade=`get_DECADE "$xyear"`

      if [ -n "$xdecade" ] ; then
        
        gdir=`dirname "$qinfo_file"`
        echo -e "$xdecade|$gdir" >> "$LIST_DECADE_INFO"
      fi
    fi
  done < "$LIST_INFO_INFO"

  IFS="$NTFS"

  # Now take the list and SORT it, removing DUPLICATES, sorting in reverse (newest first) and numeric

  cat "$LIST_DECADE_INFO" | sort -n -r -u > "$LIST_DECADE_INFO_SORTED"
}

############# END MAKE DECADE LIST ####################



############# BUILD DECADE ####################

# INPUT: "$LIST_DECADE_INFO_SORTED" (a file)
# OUTPUT: "$LIST_DECADE_CMDS" (a file)

build_DECADE () {

  cat /dev/null > "$LIST_DECADE_CMDS"

  # now we go thru the list, simply creating links to the movie directories in entirety

  IFS="$PIPE"

  echo "echo \"#$SCRIPT_NAME $LIST_DECADE_CMDS `date`\"" >> "$LIST_DECADE_CMDS"
  echo -e "" >> "$LIST_DECADE_CMDS"
  echo "if [ ! -d \"$CAT_ROOT_PATH$DECADE_NAME\" ] ; then mkdir \"$CAT_ROOT_PATH$DECADE_NAME\" ; fi;" >> "$LIST_DECADE_CMDS"
  echo "ln -f -s \"$ICON_SRC_PATH$CAT_SET_PATH/$DECADE_ICON\" \"$CAT_ROOT_PATH$DECADE_NAME/folder.jpg\"" >> "$LIST_DECADE_CMDS"
  echo -e "" >> "$LIST_DECADE_CMDS"

  last_decade="x"

  while read -r xgen xdir ; do
    if [ -n "$xgen" ] ; then
      decade="$xgen"
      fdir="$xdir"

      if [ $decade != $last_decade ] ; then

        # output commands to symlink to the movie folder
        echo -e "" >> "$LIST_DECADE_CMDS"
        echo "if [ ! -d \"$CAT_ROOT_PATH$DECADE_NAME/$decade\" ] ; then mkdir \"$CAT_ROOT_PATH$DECADE_NAME/$decade\" ; fi;" >> "$LIST_DECADE_CMDS"

        # directly symlink the folder icon from the icon library 
        echo "ln -f -s \"$ICON_SRC_PATH$DECADE_SET_PATH/$decade.png\" \"$CAT_ROOT_PATH$DECADE_NAME/$decade/folder.jpg\"" >> "$LIST_DECADE_CMDS"

        last_decade=$decade
      fi

      # we don't really care if a movie is listed twice with two different decades... GIGO!
      echo -e "" >> "$LIST_DECADE_CMDS"
      echo "ln -f -s \"$fdir\" \"$CAT_ROOT_PATH$DECADE_NAME/$decade/.\"" >> "$LIST_DECADE_CMDS"

    fi
  done < "$LIST_DECADE_INFO_SORTED"

  echo -e "" >> "$LIST_DECADE_CMDS"
  echo "echo -e \"#EOF $SCRIPT_NAME $LIST_DECADE_CMDS `date`\n\"" >> "$LIST_DECADE_CMDS"
  
  
  IFS="$NTFS"
}

############# END BUILD DECADE ####################







############# GET RATING ####################

# Given Type and Filename, extract the EYE M D BEE RATING Rating from the file
#
# INPUT: TYPE, FILEPATH
# OUTPUT rating 0-10

get_RATING () {

xthe_type="$1"
xthe_file="$2"

#echo -e "t[$xthe_type]T f[$xthe_file]F"
#echo -e ">>$IFS<<"

  case $xthe_type in

    # IMDB: > 8.8 < with 165,991 votes (decimals, so just take the first one or two digits)
    SUM) xthe_list=`sed -n -e '/.*IMDB:/,1 {s/.*>\ \([0-9][0-9]*\).*$/\1/p}' "$xthe_file"`;;

    # 0-100 so divide by 10 sometime rating is -1 meaning no rating available, we will toss those into the zero category
    XML) xthe_list=`sed -n -e '/<rating>/,1 { s/.*<rating>\([1-9][0-9]*\)<\/rating>.*$/\1/p }' "$xthe_file"` ; if [ -n "$xthe_list" ] ; then xthe_list=$(($xthe_list/10)) ; fi ;;

    # 0-10 (decimals, so just take the first one or two digits)
    TGXML) xthe_list=`sed -n -e '/<rating>/,1 { s/.*<rating>\([0-9][0-9]*\).*$/\1/p }' "$xthe_file"`;;

    # 0-10 (decimals, so just take the first one or two digits)
    MXML) xthe_list=`sed -n -e '/<rating>/,1 { s/.*<rating>\([0-9][0-9]*\).*$/\1/p }' "$xthe_file"`;;

    FAIL) return;;
  
  esac

# not entirely sure why I chose to return a single line rather than a list

  echo "$xthe_list"
}

############# END GET RATING ####################



############# MAKE RATING LIST ####################

# INPUT: "$LIST_INFO_INFO" (a file)

# OUTPUT: "$LIST_RATING_INFO" (a file)
# OUTPUT: "$LIST_RATING_INFO_SORTED" (a file)

make_RATING () {

  xgenres=""

  # create empty list

  cat /dev/null > "$LIST_RATING_INFO"

  IFS="$NTPFS"

  while read -r qinfo_type qinfo_file ; do

#    echo -e "x $qinfo_line X"

    if [ -n "$qinfo_type" ] && [ -n "$qinfo_file" ] ; then
      
#      echo -e "$qinfo_type $qinfo_file"
      
      xgenres=`get_RATING "$qinfo_type" "$qinfo_file"`

#      echo -e "X $xgenres $qinfo_type $qinfo_file X" >&2

      if [ -n "$xgenres" ] ; then
        
        gdir=`dirname "$qinfo_file"`

        IFS="$NTFS"
        for genre in $xgenres ; do
          if [ -n "$genre" ] && [ "$genre" != "-1" ] ; then

            g=`echo $genre | tr -d "$RET"`

#            echo -e "$g|$gdir"
            echo -e "$g|$gdir" >> "$LIST_RATING_INFO"

          fi
        done
        IFS="$NTPFS"
      fi
    fi
    
  done < "$LIST_INFO_INFO"

  IFS="$NTFS"

  # Now take the list and SORT it, removing DUPLICATES, sorting in reverse (best first) and numeric

  cat "$LIST_RATING_INFO" | sort -n -r -u > "$LIST_RATING_INFO_SORTED"
}

############# END MAKE RATING LIST ####################



############# BUILD RATING ####################

# INPUT: "$LIST_RATING_INFO_SORTED" (a file)
# OUTPUT: "$LIST_RATING_CMDS" (a file)

build_RATING () {

  cat /dev/null > "$LIST_RATING_CMDS"

  # now we go thru the list, simply creating links to the RATING movie directories in entirety

  IFS="$PIPE"

  echo "echo \"#$SCRIPT_NAME $LIST_RATING_CMDS `date`\"" >> "$LIST_RATING_CMDS"
  echo -e "" >> "$LIST_RATING_CMDS"
  echo "if [ ! -d \"$CAT_ROOT_PATH$RATING_NAME\" ] ; then mkdir \"$CAT_ROOT_PATH$RATING_NAME\" ; fi;" >> "$LIST_RATING_CMDS"
  echo "ln -f -s \"$ICON_SRC_PATH$CAT_SET_PATH/$RATING_ICON\" \"$CAT_ROOT_PATH$RATING_NAME/folder.jpg\"" >> "$LIST_RATING_CMDS"
  echo -e "" >> "$LIST_RATING_CMDS"

  last_rating="x"

  while read -r xgen xdir ; do
    if [ -n "$xgen" ] ; then
      rating="$xgen"
      fdir="$xdir"

      # we don't really care if a movie is listed twice with two different RATING Ratings... GIGO!

      lrating="$(printf '%i' $rating)"
      trating=$(($lrating*10))	
	
      if [ $lrating != $last_rating ] ; then
        echo -e "" >> "$LIST_RATING_CMDS"
        echo "if [ ! -d \"$CAT_ROOT_PATH$RATING_NAME/$lrating\" ] ; then mkdir \"$CAT_ROOT_PATH$RATING_NAME/$lrating\" ; fi;" >> "$LIST_RATING_CMDS"
        
        # directly symlink the folder icon from the icon library 
        echo "ln -f -s \"$ICON_SRC_PATH$RATING_SET_PATH/rating_$trating.png\" \"$CAT_ROOT_PATH$RATING_NAME/$lrating/folder.jpg\"" >> "$LIST_RATING_CMDS"

        #echo "/bin/cp -a \"$ICON_SRC_PATH$RATING_SET_PATH/rating_$trating.png\" \"$CAT_ROOT_PATH$RATING_NAME/$lrating/.\"" >> "$LIST_RATING_CMDS"
        #echo "ln -f -s \"rating_$trating.png\" \"$CAT_ROOT_PATH$RATING_NAME/$lrating/folder.jpg\"" >> "$LIST_RATING_CMDS"

        last_rating=$lrating
      fi
      
      echo -e "" >> "$LIST_RATING_CMDS"
      echo "ln -f -s \"$fdir\" \"$CAT_ROOT_PATH$RATING_NAME/$lrating/.\"" >> "$LIST_RATING_CMDS"

    fi
  done < "$LIST_RATING_INFO_SORTED"

  echo -e "" >> "$LIST_RATING_CMDS"
  echo "echo -e \"#EOF $SCRIPT_NAME $LIST_RATING_CMDS `date`\n\"" >> "$LIST_RATING_CMDS"
  
  
  IFS="$NTFS"
}

############# END BUILD RATING ####################





############# GET TOP250 ####################

# Given Type and Filename, extract the EYE M D BEE Top250 Rating from the file

# INPUT: TYPE, FILENAME
# OUTPUT: 1-250 placement, or -1 or blank

get_TOP250 () {

xthe_type="$1"
xthe_file="$2"

#echo -e "t[$xthe_type]T f[$xthe_file]F"
#echo -e ">>$IFS<<"

  case $xthe_type in


    # so far only yammajamma includes this attribute
    # the value is (presumably) 1-250
    # otherwise, value is -1 (not in the 250)

	# <top250>89</top250>
	# between <top250> and </top250>
	# look for <top250>89</top250>
	# look for <top250>-1</top250>
    
    XML) xthe_list=`sed -n -e '/<top250>/,1 { s/.*<top250>\(.*\)<\/top250>.*/\1/p }' "$xthe_file"`;;

        
    FAIL) return;;
  
  esac

# not entirely sure why I chose to return a single line rather than a list

  echo "$xthe_list"
}

############# END GET TOP250 ####################



############# MAKE TOP250 LIST ####################

# INPUT: "$LIST_INFO_INFO" (a file)

# OUTPUT: "$LIST_TOP250_INFO" (a file)
# OUTPUT: "$LIST_TOP250_INFO_SORTED" (a file)

make_TOP250 () {

  xgenres=""

  # create empty list

  cat /dev/null > "$LIST_TOP250_INFO"

  IFS="$NTPFS"

  while read -r qinfo_type qinfo_file ; do

#    echo -e "x $qinfo_line X"

    if [ -n "$qinfo_type" ] && [ -n "$qinfo_file" ] ; then
      
#      echo -e "$qinfo_type $qinfo_file"
      
      xgenres=`get_TOP250 "$qinfo_type" "$qinfo_file"`

#      echo -e "X $xgenres X" 

      if [ -n "$xgenres" ] ; then
        v=1
        
        gdir=`dirname "$qinfo_file"`

        IFS="$NTFS"
        for genre in $xgenres ; do
          if [ -n "$genre" ] && [ "$genre" != "-1" ] ; then

            g=`echo $genre | tr -d "$RET"`

#            echo -e "$g|$gdir"
            echo -e "$g|$gdir" >> "$LIST_TOP250_INFO"

          fi
        done
        IFS="$NTPFS"
      fi
    fi
    
  done < "$LIST_INFO_INFO"

  IFS="$NTFS"

  # Now take the genre - directory list and SORT it, removing DUPLICATES

  cat "$LIST_TOP250_INFO" | sort -n -u > "$LIST_TOP250_INFO_SORTED"
}

############# END MAKE TOP250 LIST ####################



############# BUILD TOP250 ####################

# INPUT: "$LIST_TOP250_INFO_SORTED" (a file)
# OUTPUT: "$LIST_TOP250_CMDS" (a file)

build_TOP250 () {

  cat /dev/null > "$LIST_TOP250_CMDS"

  # now we go thru the list, simply creating links to the top250 movie directories in entirety

  IFS="$PIPE"

  echo "echo \"#$SCRIPT_NAME $LIST_TOP250_CMDS `date`\"" >> "$LIST_TOP250_CMDS"
  echo -e "" >> "$LIST_TOP250_CMDS"
  echo "if [ ! -d \"$CAT_ROOT_PATH$TOP250_NAME\" ] ; then mkdir \"$CAT_ROOT_PATH$TOP250_NAME\" ; fi;" >> "$LIST_TOP250_CMDS"
  echo "ln -f -s \"$ICON_SRC_PATH$CAT_SET_PATH/$TOP250_ICON\" \"$CAT_ROOT_PATH$TOP250_NAME/folder.jpg\"" >> "$LIST_TOP250_CMDS"
  echo -e "" >> "$LIST_TOP250_CMDS"

  while read -r xgen xdir ; do
    if [ -n "$xgen" ] ; then
      rating="$xgen"
      fdir="$xdir"

      # we don't really care if a movie is listed twice with two different TOP250 Ratings... GIGO!

      # output commands to symlink to the movie folder
      # but the trick will be that we insert the rating as the prefix to the directory name so it sorts accordingly
      
      # remains to be seen how VW sorts numerically
      # hopefully not some lame 1,10,14,2,3,4 forcing me to prefix with zeros in the rev3 that I will never bother making
      # {SIGH}

      tbase=`basename "$fdir"`
      
      lrating="$(printf '%03i' $rating)"
      
      echo -e "" >> "$LIST_TOP250_CMDS"
      echo "ln -f -n -s \"$fdir\" \"$CAT_ROOT_PATH$TOP250_NAME/$lrating $tbase\"" >> "$LIST_TOP250_CMDS"

    fi
  done < "$LIST_TOP250_INFO_SORTED"

  echo -e "" >> "$LIST_TOP250_CMDS"
  echo "echo -e \"#EOF $SCRIPT_NAME $LIST_TOP250_CMDS `date`\n\"" >> "$LIST_TOP250_CMDS"
  
  
  IFS="$NTFS"
}

############# END BUILD TOP250 ####################





############# GET GENRES ####################

# Given Type and Filename, extract the Genres from the file

# INPUT: TYPE, FILENAME
# OUTPUT: a list of Genres, separated by newline

get_GENRES () {

xthe_type="$1"
xthe_file="$2"

#echo -e "t[$xthe_type]T f[$xthe_file]F"
#echo -e ">>$IFS<<"

  case $xthe_type in

# sed -n -e 's/.*Genre:\ \(.*\)$/\1/p' summary.txt | sed s:,\ :\\n:g


	# Genre: Action, Suspense/Thriller
    # look between Genre:{space} and $ (eol) 
    # replaces .*Genre: with blank
	# replaces ", " comma space with newline
  
#    SUM) xthe_list=`$gen_SUM $xthe_file"`;;

    SUM) xthe_list=`sed -n -e '/Genre:\ /,1 {s~^.*Genre:\ ~~ ; s~,\ ~\n~gp}' $xthe_file"` ;;

# this one assumes all lines end with a linefeed and strip it off
# since we can't really assume, the caller will strip any BS linefeeds
#    SUM) xthe_list=`sed -n -e '/Genre:\ /,/$/ {s~^.*Genre:\ ~~ ; s~,\ ~\n~g ; s~.$~\n~gp}' $xthe_file"`;;
    

	#    <genres>
	#      <genre>Comedy</genre>
	#      <genre index="Genres_Comedy_1">Comedy1</genre>
	#    </genres>

    # between <genres> and </genres>
	# looks for <genre>Fantasy</genre>
    # or <genre index="Genres_Comedy_1">Comedy1</genre>

#    XML) xthe_list=`$gen_XML "$xthe_file"`;;

    XML) xthe_list=`sed -n -e '/<genres>/,/<\/genres>/ {s/^.*<genre>\(.*\)<\/genre>.*/\1/p ; s/^.*<genre index.*>\(.*\)<\/genre>.*/\1/p}' "$xthe_file"` ;;



	#  <Genres>
	#    <Genre>Action</Genre>
	#    <Genre>Suspense/Thriller</Genre>
	#  </Genres>
	# between <Genres> and </Genres>
	# look for <Genre>agenre</Genre>

#    DPXML) xthe_list=`$gen_DPXML "$xthe_file"`;;

    DPXML) xthe_list=`sed -n -e '/<Genres>/,/<\/Genres>/ {s/.*<Genre>\(.*\)<\/Genre>.*/\1/p}' "$xthe_file"` ;;



	#  <genre>
	#    <name>Comedy</name>
	#    <name>Fantasy</name>
	#    <name>Horror</name>
	#  </genre>
	# between <genre> and </genre>
	# look for <name>agenre</name> 	
	#

    TGXML) xthe_list=`sed -n -e '/<genre>/,/<\/genre>/ {s/.*<name>\(.*\)<\/name>.*/\1/p}' "$xthe_file"` ;;


                # <genre>Adventure / Drama / Thriller</genre>
                
    MXML) xthe_list=`sed -n -e '/<genre>/,1 { s~\ /\ ~\n~g ; s/.*<genre.*>\(.*\)<\/genre>.*$/\1/p }' $xthe_file"` ;;

        
    FAIL) return;;
  
  esac

  echo "$xthe_list"
}

############# END GET GENRES ####################



############# MAKE GENRE LIST ####################

# INPUT: "$LIST_INFO_INFO" mlist.info (file)

# OUTPUT: "$LIST_GENRE_INFO" mlist.genre (file)
# OUTPUT: "$LIST_GENRE_INFO_SORTED" mlist.genre.sorted (file)

make_GENRE () {

  xgenres=""

  # create empty list of 'raw' genres 

  cat /dev/null > "$LIST_GENRE_INFO"

  IFS="$NTPFS"

  while read -r qinfo_type qinfo_file ; do

#    echo -e "x $qinfo_line X"

    if [ -n "$qinfo_type" ] && [ -n "$qinfo_file" ] ; then
      
#      echo -e "$qinfo_type $qinfo_file"
      
      xgenres=`get_GENRES "$qinfo_type" "$qinfo_file"`

#      echo -e "X $xgenres X" 

      if [ -n "$xgenres" ] ; then
        
        gdir=`dirname "$qinfo_file"`

        IFS="$NTFS"
        for genre in $xgenres ; do
          if [ -n "$genre" ] ; then

			# remove extraneous linefeeds
            g=`echo $genre | tr -d "$RET"`

#            echo -e "$g|$gdir"
            echo -e "$g|$gdir" >> "$LIST_GENRE_INFO"

          fi
        done
        IFS="$NTPFS"

# WAS A BAD IDEA - wrong place for this if at all
#      else
#        # no genre found, toss it in the 'Other' genre
#        # this is a little bit BS.. if theres no info file at all then those movies will not be put in the other genre
#        echo -e "make_Genre_List: No genre found, substituting 'Other' for '$gdir'\n" >&2
#		echo -e "Other|$gdir" >> "$LIST_GENRE_INFO"
      fi
    fi
    
  done < "$LIST_INFO_INFO"

  IFS="$NTFS"

  # Now take the genre - directory list and SORT it, removing DUPLICATES

  cat "$LIST_GENRE_INFO" | sort -u > "$LIST_GENRE_INFO_SORTED"
}

############# END MAKE GENRE LIST ####################



############# BUILD GENRES ####################

# INPUT: "$LIST_GENRE_INFO_SORTED" (a file)
# INPUT: "$LIST_GENRE_SECT" (a file of the genres cropped out of the config file)
#
# OUTPUT: "$LIST_GENRE_CMDS" (a file)

build_GENRE () {


  cat /dev/null > "$LIST_GENRE_CMDS"

  # now we need to go thru the list, doing lookups on GENRE
  # to get the genre info

  cur_genre=""

  IFS="$PIPE"

  echo "echo \"#$SCRIPT_NAME $LIST_GENRE_CMDS `date`\"" >> "$LIST_GENRE_CMDS"
  echo -e "" >> "$LIST_GENRE_CMDS"
  echo "if [ ! -d \"$CAT_ROOT_PATH$GENRE_NAME\" ] ; then mkdir \"$CAT_ROOT_PATH$GENRE_NAME\" ; fi;" >> "$LIST_GENRE_CMDS"
  echo "ln -f -s \"$ICON_SRC_PATH$CAT_SET_PATH/$GENRE_ICON\" \"$CAT_ROOT_PATH$GENRE_NAME/folder.jpg\"" >> "$LIST_GENRE_CMDS"
  echo -e "" >> "$LIST_GENRE_CMDS"


  while read -r xgen xdir ; do
    if [ -n "$xgen" ] ; then
      genre="$xgen"
      dir="$xdir"

      if [ "$cur_genre" != "$genre" ] ; then

#        echo "old genre $cur_genre new genre $genre"

        # lookup the details for this genre
        # the genre list has alread been extracted from the config file to facilitate quicker lookups 

        IFS="$NTFS"
        p=`grep "^$genre$TAB" "$LIST_GENRE_SECT"`
        set -f -- $p
        name="$2"
        icon="$3"
        IFS="$PIPE"

		
        # If the Genre is missing, substitiute the "Other" genre (very likely until a lot of people feed back Genres)

        if [ -z "$name" ] ; then
          # this works fine but it can result in multiple attempts to recreate the Other folder etc. not an issue
          echo -e "build_Genres: Genre '$genre' is not configured, substituting 'Other'\n" >&2

          IFS="$NTFS"
          p=`grep "^Other$TAB" "$LIST_GENRE_SECT"`
          set -f -- $p
          name="$2"
          icon="$3"
          IFS="$PIPE"
        fi


        if [ -z "$name" ] ; then
          echo "build_GENRE: Genre \"$genre\" not defined in config file: \"Other\" is the cath-all for undefined genres.":
        else

          # output commands to generate the particular genre folder and symlink the icon into it

          echo -e "" >> "$LIST_GENRE_CMDS"
          echo "if [ ! -d \"$CAT_ROOT_PATH$GENRE_NAME/$name\" ] ; then mkdir \"$CAT_ROOT_PATH$GENRE_NAME/$name\" ; fi;" >> "$LIST_GENRE_CMDS"
          # directly symlink the folder icon from the icon library 
          echo "ln -f -s \"$ICON_SRC_PATH$GENRE_SET_PATH/$icon\" \"$CAT_ROOT_PATH$GENRE_NAME/$name/folder.jpg\"" >> "$LIST_GENRE_CMDS"

          # copy custom genre icon as the folder.jpg in the root folder for that genre
          # also make folder.png
          # echo "/bin/cp -a \"$ICON_SRC_PATH$GENRE_SET_PATH/$icon\" \"$CAT_ROOT_PATH$GENRE_NAME/$name/.\"" >> "$LIST_GENRE_CMDS"
          # as expected its only looking for folder.jpg but you can rename .png to .jpg and it still works
          # uncomment the line if this changes in the future (and the similar line above)
          # echo "ln -f -s \"$CAT_ROOT_PATH$GENRE_NAME/$name/$icon\" \"$CAT_ROOT_PATH$GENRE_NAME/$name/folder.png\"" >> "$LIST_GENRE_CMDS"
          # echo "ln -f -s \"$icon\" \"$CAT_ROOT_PATH$GENRE_NAME/$name/folder.jpg\"" >> "$LIST_GENRE_CMDS"
        fi

        cur_genre="$genre"
      else
	  v=1
      fi

      # output linkin cmd
      echo -e "" >> "$LIST_GENRE_CMDS"
      echo "ln -f -s \"$dir\" \"$CAT_ROOT_PATH$GENRE_NAME/$name/.\"" >> "$LIST_GENRE_CMDS"

    fi
  done < "$LIST_GENRE_INFO_SORTED"

# no need for this... there were other problems with the file. filenames just need quotes no other special escaping
#sed "-e 's|(|\\(|g' -e 's|)|\\)|g' -e 's|&|\\&|g' -e 's|'\''|\\'\''|g' $LIST_GENRE_CMDS" > clist

  echo -e "" >> "$LIST_GENRE_CMDS"
  echo "echo -e \"#EOF $SCRIPT_NAME $LIST_GENRE_CMDS `date`\n\"" >> "$LIST_GENRE_CMDS"
  
  
  IFS="$NTFS"
}

############# END BUILD GENRES ####################




############# DO CATEGORIES ####################
############# DO CATEGORIES ####################

# INPUT: "$LIST_INFO_INFO" (a file)
# OUTPUT: "$LIST_<whatever>_CMDS" (a file)

do_AZ () {

  echo -e "make_AZ\n"
  make_AZ

  echo -e "build_AZ\n"
  build_AZ

  chmod +x "$LIST_AZ_CMDS"
}


do_DECADE () {

  echo -e "make_DECADE\n"
  make_DECADE

  echo -e "build_DECADE\n"
  build_DECADE

  chmod +x "$LIST_DECADE_CMDS"
}


do_GENRE () {

  echo -e "make_GENRE\n"
  make_GENRE
 
  echo -e "build_GENRE\n"
  build_GENRE

  chmod +x "$LIST_GENRE_CMDS"
}


do_NAME () {

  echo -e "make_NAME\n"
  make_NAME

  echo -e "build_NAME\n"
  build_NAME

  chmod +x "$LIST_NAME_CMDS"
}


do_RATING () {

  echo -e "make_RATING\n"
  make_RATING

  echo -e "build_RATING\n"
  build_RATING

  chmod +x "$LIST_RATING_CMDS"
}


do_TOP250 () {

  echo -e "make_TOP250\n"
  make_TOP250

  echo -e "build_TOP250\n"
  build_TOP250

  chmod +x "$LIST_TOP250_CMDS"
}


############# END DO CATEGORIES ####################
############# END DO CATEGORIES ####################


############# GET SHORTCUTS ####################


# Make a list of all videowall shortcuts IN ORDER
#
# INPUT: "$VW_SHORTCUTS_LIST_FILE" (a file)
# OUTPUT: shortcut TYPE | shortcut PATH | shortcut

# contents of the file may look like this:
#  /tmp/ramfs/volumes/SYSTEM:/Name
#  //tmp/ramfs/volumes/F4UBCD:/Microsoft Streets And Trips (2011)
#  /tmp/netb/mnt/My Shortcuts/LT-A:sean/wftp

get_VW_Shortcuts () {

  # find all shortcuts that do NOT begin with double forward slash
  while read -r cut ; do

    typ=""
    paf=""
    
    #echo -E "xxx $cut"

    fake=`echo -E "$cut" | grep "^//"`
    
    net=`echo -E "$cut" | grep "^$VW_SHORTCUTS_NET_MOUNTS"`

    if [ -n "$net" ] ; then

      # Network mounted shortcut
      # this is pretty much okay as long as it is mounted when we use it!

      typ="smb"
      paf="$cut"

    elif [ -n "$fake" ] ; then

      # Fake shortcut
      # this is a shortcut that we created
      typ="FAKE"
      paf="$cut"

    else

      # NON-Network Bookmark
      # For these we need to find its label file

      # Extract the marker
      name=`echo -E "$cut" | sed -n -e 's~.*/\(.*\):.*$~\1~p'`

      # Also extract what's after the marker, so we can append that to the actual path
      xpath=`echo -E "$cut" | sed -n -e 's~.*:\(.*\)$~\1~p'`

      if [ -z "$name" ] ; then
        # there's no colon : in the path, it's not a conventional shortcut so maybe it's okay?
        typ="raw"
        paf="$cut"
      else

        # Find the label file that has our marker
        
        exp="\"^.${name}$\""

        # loop through the label files and find the first one that contains the marker
        # if there's more than one matching file I assume that's an error but we dont care
        for file in $VW_SHORTCUTS_LABELS* ; do

          fname=`grep -l "^.${name}$" "$file"`

          if [ -n "$fname" ] ; then
            break;
          fi
        done
        
        if [ -n "$fname" ] ; then
          # we found the matching file
          # the label file's name is the mount point, extract it
          mpoint=`basename "$file"`

          # get it's interface type sata,usb,???
          typ=`sed -n -e '3,3 p' "$file"`

          if [ -z "$typ" ] ; then
            typ="BAD"
          fi

          # output the complete path
          paf="$VW_SHORTCUTS_VOLUMES$mpoint$xpath"

        else
          # we can't find a label file but it has a colon in it
          # this is not good!
          typ="BAD"
          paf="$cut"
        fi
      fi
    fi
    
    # ok we now have type, path, and shortcut
    # as a last step, check the shortcut to see if it really exists as a directory (works ok for symlinks)
    if [ -d "$paf" ] ; then
      echo -E "$typ|$paf|$cut"
    else
      echo -E "MISSING-$typ|$paf|$cut"
    fi
    
  done < "$VW_SHORTCUTS_LIST_FILE"
}



############# ADD SHORTCUTS ####################


# INPUT: "$LIST_CAT_SECT" (a file)
# OUTPUT: "$LIST_CAT_CMDS" (a file)

do_CATEGORIES () {

  # loops through the enabled categories in the config file

  # creates moviewall shortcut and matching icon entry in the two config files
  # adds the root folder and icons

  # greps the shortcuts file to see if the shortcut is already there and intact
  # if it's there but NOT intact, or not there at all, it will be appeneded
  
  # JukeBoxPathL1.dat
  # /tmp/ramfs/volumes/SYSTEM:/Genre
  
  # and append the icon name to the other file
  
  # GenreList.dat 
  # All Movies by Name.png
  #

  echo -e "do_CATEGORIES"

  # empty the command file

  cat /dev/null > "$LIST_CAT_CMDS"

  cat=""

  echo "echo \"#$SCRIPT_NAME $LIST_CAT_CMDS `date`\"" >> "$LIST_CAT_CMDS"
  echo -e "" >> "$LIST_CAT_CMDS"

  IFS="$NTPFS"

  while read -r cat catname caticon ; do

    if [ -n "$cat" ] && [ -n "$catname" ] && [ -n "$caticon" ] ; then

      # echo -e "[$cat] [$catname] [$caticon]"

      echo -e "echo \"# INSTALL CATEGORY: [$cat] [$catname] [$caticon]\"" >> $LIST_CAT_CMDS

      # determine if the shortcut already exists
      # if not, append it to the moviewall shortcuts file, and add the icon too
    
      scut="$VW_SHORTCUTS_PREFIX$catname";
      addscut="\"$VW_SHORTCUTS_PREFIX$catname\" >> \"$VW_SHORTCUTS_LIST_FILE\""
      addicon="\"$caticon\" >> \"$VW_SHORTCUTS_ICONS_FILE\""

      echo "grep \"$scut\" \"$VW_SHORTCUTS_LIST_FILE\" ; if [ \$? != 0 ]; then echo -e $addscut; echo -e $addicon ; echo -e \"Category [$catname] installed\" ; else echo -e \"Category [$catname] already installed\" ; fi;" >> $LIST_CAT_CMDS 

      # grep "/tmp/ramfs/volumes/SYSTEM:/TOP-250" /usr/local/etc/dvdplayer/JukeBoxPathL1.dat ; if [ $? != 0 ]; then echo yes; else echo already installed; fi; 

      # make folder for the category just in case
      # individual categories do this themselves but I don't want to lock into a fixed order of operations
      # so you can run the schortcut commands before or after the category commands it wont matter
      # but ONLY this routine will add the shortcut icon to thbe videowall's resource folder

      echo "if [ ! -d \"$CAT_ROOT_PATH$catname\" ] ; then mkdir \"$CAT_ROOT_PATH$catname\" ; fi;" >> "$LIST_CAT_CMDS"

      # copy folder icon into videowall folder

      echo "/bin/cp -a \"$ICON_SRC_PATH$CAT_SET_PATH/$caticon\" \"$VW_SHORTCUTS_ICONS_PATH.\"" >> "$LIST_CAT_CMDS"
  
      # also copy the icon into the category's folder
      # (folder icon is not used in VW but lets do for other non-videowall views maybe)
  
#      echo "/bin/cp -a \"$ICON_SRC_PATH$CAT_SET_PATH/$caticon\" \"$CAT_ROOT_PATH$catname/.\"" >> "$LIST_CAT_CMDS"
      # as expected its only looking for folder.jpg but you can rename .png to .jpg and it still works
#      echo "ln -f -s \"$caticon\" \"$CAT_ROOT_PATH$catname/folder.jpg\"" >> "$LIST_CAT_CMDS"

      # directly symlink the folder icon from the icon library 
      echo "ln -f -s \"$ICON_SRC_PATH$CAT_SET_PATH/$caticon\" \"$CAT_ROOT_PATH$catname/folder.jpg\"" >> "$LIST_CAT_CMDS"

      echo -e "" >> "$LIST_CAT_CMDS"

    else
      echo -e "$SCRIPT_NAME:\t BAD CATEGORY DEFINITON in [$CONF]: [$cat] [$catname] [$caticon]" >&2
    fi

  # list the categories from the config file, exclude CAT BEGIN,END,PATH, and # commented lines

  done < "$LIST_CAT_SECT"

  IFS="$NTFS"

  echo "echo -e \"#EOF $SCRIPT_NAME $LIST_CAT_CMDS `date`\n\"" >> "$LIST_CAT_CMDS"

  chmod +x "$LIST_CAT_CMDS"
}


############# END ADD SHORTCUTS ####################


################# END FUNCTION DEFNS ###################
################# END FUNCTION DEFNS ###################
################# END FUNCTION DEFNS ###################
################# END FUNCTION DEFNS ###################
################# END FUNCTION DEFNS ###################




############# MAIN PROGRAM ####################
############# MAIN PROGRAM ####################
############# MAIN PROGRAM ####################
############# MAIN PROGRAM ####################
############# MAIN PROGRAM ####################



############# READ CONF ####################


# THIS IS voilla main(vanilda)


echo -e "### CONFIG FILE LOADING ###\n"

IFS="$NTFS"

# Use config file from command line, or use the default.
if [ -n "$*" ] ; then
  CONF="$*"
#  echo "CONF: $CONF"
else
#  echo "CONF: $CONF"
  v=1
fi


# Open Config File and Get Me Some Params

if [ ! -e "$CONF" ] ; then
  echo -e "$SCRIPT_NAME\t$CONF Hey tardbrain maybe a config file would help?\n"
  return 13 ;
fi


  # read config file parameters

CONF_VERSION=`grep "^ID$TAB" "$CONF"`

if [ "$CONF_VERSION" != "$VERSION" ] ; then
  echo -e "$SCRIPT_NAME: $CONF Hey doofus bad config version '$CONF_VERSION' Supported format(s): '$VERSION'\n"
  echo -e "Ensure that you have the correct version and that your files have no been polluted with linefeeds (CR-LF) - UNIX format only!\n"
  return 12 ;  
else
  v=1
  #    echo "$CONF_VERSION"
fi



# LOG INFO

p=`grep "^LOG_INFO$TAB" "$CONF"` 
set -f -- $p
LOG="$2"

p=`grep "^LOG_ERRORS$TAB" "$CONF"`
set -f -- $p
LOG_ERR="$2"

echo -e "DEF_LOG\t$DEF_LOG\nDEF_LOG_ERR\t$DEF_LOG_ERR\n"
echo -e "LOG\t$LOG\nLOG_ERR\t$LOG_ERR\n"


# CONF FILE INFO

p=`grep "^DATE$TAB" "$CONF"` 
set -f -- $p
CFG_DATE="$2"

p=`grep "^AUTHOR$TAB" "$CONF"`
set -f -- $p
CFG_AUTHOR="$2"

echo -e "CFG_DATE\t$CFG_DATE\nCFG_AUTHOR\t$CFG_AUTHOR\n"


# DEBUG FLAGS

ka="DEBUG"
kb="CONFIG"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
DEBUG_CONFIG="$3"
echo -e "DEBUG_CONFIG\t$DEBUG_CONFIG"

kb="COMMANDS"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
DEBUG_COMMANDS="$3"
echo -e "DEBUG_COMMANDS\t$DEBUG_COMMANDS\n"


# XML FETCHING VARIABLES

#ID_SUM	"SUM"
#ID_FAIL	"FAIL"
#ID_XML	"XML"
#ID_MXML	"MXML"
#ID_DPXML	"DPXML"

p=`grep "^ID_SUM$TAB" "$CONF"`
set -f -- $p
ID_SUM="$2"

p=`grep "^ID_FAIL$TAB" "$CONF"`
set -f -- $p
ID_FAIL="$2"

p=`grep "^ID_XML$TAB" "$CONF"`
set -f -- $p
ID_XML="$2"

p=`grep "^ID_MXML$TAB" "$CONF"`
set -f -- $p
ID_MXML="$2"

p=`grep "^ID_DPXML$TAB" "$CONF"`
set -f -- $p
ID_DPXML="$2"

p=`grep "^ID_TGXML$TAB" "$CONF"`
set -f -- $p
ID_TGXML="$2"

echo -e "ID_SUM\t$ID_SUM\nID_FAIL\t$ID_FAIL\nID_XML\t$ID_XML\nID_DPXML\t$ID_DPXML\nID_TGXML\t$ID_TGXML\n"


# nam_SUM	"summary.txt"

p=`grep "^nam_SUM$TAB" "$CONF"`
set -f -- $p
nam_SUM="$2"

# nam_MXML

p=`grep "^nam_MXML$TAB" "$CONF"`
set -f -- $p
nam_MXML="$2"

# nam_TGXML	"*.nfo"

p=`grep "^nam_TGXML$TAB" "$CONF"`
set -f -- $p
nam_TGXML="$2"

# rnam_DPXML	"[[:digit:]]\{12\}\.xml"
# nam_DPXML	"[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].xml"

p=`grep "^rnam_DPXML$TAB" "$CONF"`
set -f -- $p
rnam_DPXML="$2"

p=`grep "^nam_DPXML$TAB" "$CONF"`
set -f -- $p
nam_DPXML="$2"

echo -e "nam_TGXML\t$nam_TGXML\nnam_SUM\t$nam_SUM\nrnam_DPXML\t$rnam_DPXML\nnam_DPXML\t$nam_DPXML\n"


# reg_TGXML	"^<.*ThumbGen.*>"
# reg_DPXML	"^<!--DVD Profiler Collection Export-->"
# reg_XML	"^<details>"
# reg_SUM	".*ReportID assets1.frx.*"

p=`grep "^reg_TGXML$TAB" "$CONF"`
set -f -- $p
reg_TGXML="$2"

p=`grep "^reg_DPXML$TAB" "$CONF"`
set -f -- $p
reg_DPXML="$2"

p=`grep "^reg_XML$TAB" "$CONF"`
set -f -- $p
reg_XML="$2"

p=`grep "^reg_MXML$TAB" "$CONF"`
set -f -- $p
reg_MXML="$2"

p=`grep "^reg_SUM$TAB" "$CONF"`
set -f -- $p
reg_SUM="$2"

echo -e "reg_MXML\t$reg_MXML\nreg_TGXML\t$reg_TGXML\nreg_DPXML\t$reg_DPXML\nreg_XML\t$reg_XML\nreg_SUM\t$reg_SUM\n"


#sed script used to cull genre names from the info file

#gen_SUM sed -n -e '/Genre:\ /,/$/ { s~.*Genre:\ ~~ ; s~,\ ~\n~gp }        
#gen_XML sed -n -e '/<genres>/,/<\/genres>/ { s/<genre>\(.*\)<\/genre>.*/\1/p ; s/<genre index.*>\(.*\)<\/genre>.*/\1/p }        
#gen_DPXML   sed -n -e '/<Genres>/,/<\/Genres>/ { s/.*<Genre>\(.*\)<\/Genre>.*/\1/p }        
#gen_TGXML   sed -n -e '/<genre>/,/<\/genre>/ { s/.*<name>\(.*\)<\/name>.*/\1/p }        

p=`grep "^gen_TGXML$TAB" "$CONF"`
set -f -- $p
gen_TGXML="$2"

p=`grep "^gen_DPXML$TAB" "$CONF"`
set -f -- $p
gen_DPXML="$2"

p=`grep "^gen_XML$TAB" "$CONF"`
set -f -- $p
gen_XML="$2"

p=`grep "^gen_MXML$TAB" "$CONF"`
set -f -- $p
gen_MXML="$2"

p=`grep "^gen_SUM$TAB" "$CONF"`
set -f -- $p
gen_SUM="$2"

echo -e "gen_TGXML\t$gen_TGXML\ngen_DPXML\t$gen_DPXML\ngen_XML\t$gen_XML\ngen_SUM\t$gen_SUM\n"


# IMDB TT # regex & find command format
# rnam_IMDB	"tt[[:digit:]]\{7\}"
# nam_IMDB=	tt[0-9][0-9][0-9][0-9][0-9][0-9][0-9].xml"


p=`grep "^rnam_IMDB$TAB" "$CONF"`
set -f -- $p
rnam_IMDB="$2"

p=`grep "^nam_IMDB$TAB" "$CONF"`
set -f -- $p
nam_IMDB="$2"

echo -e "rnam_IMDB\t$rnam_IMDB\nnam_IMDB\t$nam_IMDB\n"

# END XML FETCHING VARIABLES


p=`grep "^COLLECTION$TAB" "$CONF"`
set -f -- $p
COLLECTION_NAME="$2"
COLLECTION_PATH="$3"
echo -e "COLLECTION_NAME\t$COLLECTION_NAME\nCOLLECTION_PATH\t$COLLECTION_PATH\n"

p=`grep "^CAT_ROOT$TAB" "$CONF"`
set -f -- $p
CAT_ROOT_NAME="$2"
CAT_ROOT_PATH="$3"
echo -e "CAT_ROOT_NAME\t$CAT_ROOT_NAME\nCAT_ROOT_PATH\t$CAT_ROOT_PATH\n"

ka="SET"
kb="BEGIN"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
SET_NAME="$3"
echo -e "SET_NAME\t$SET_NAME\n"

ka="CAT"
kb="PATH"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
CAT_SET_PATH="$3"
echo -e "CAT_SET_PATH\t$CAT_SET_PATH\n"

p=`grep "^ICON_SRC$TAB" "$CONF"`
set -f -- $p
ICON_SRC_NAME="$2"
ICON_SRC_PATH="$3"
echo -e "ICON_SRC_NAME\t$ICON_SRC_NAME\nICON_SRC_PATH\t$ICON_SRC_PATH\n"


# Videowall Shortcuts

ka="VW_SHORTCUTS"
kb="ENABLED"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
VW_SHORTCUTS_ENABLED="$3"

kb="PREFIX"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
VW_SHORTCUTS_PREFIX="$3"

kb="LABELS"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
VW_SHORTCUTS_LABELS="$3"

kb="VOLUMES"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
VW_SHORTCUTS_VOLUMES="$3"

kb="NET_MOUNTS"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
VW_SHORTCUTS_NET_MOUNTS="$3"

kb="LIST_FILE"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
VW_SHORTCUTS_LIST_FILE="$3"

kb="ICONS_FILE"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
VW_SHORTCUTS_ICONS_FILE="$3"

kb="ICONS_PATH"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
VW_SHORTCUTS_ICONS_PATH="$3"

echo -e "VW_SHORTCUTS_ENABLED\t$VW_SHORTCUTS_ENABLED"
echo -e "VW_SHORTCUTS_PREFIX\t$VW_SHORTCUTS_PREFIX"
echo -e "VW_SHORTCUTS_LABELS\t$VW_SHORTCUTS_LABELS"
echo -e "VW_SHORTCUTS_VOLUMES\t$VW_SHORTCUTS_VOLUMES"
echo -e "VW_SHORTCUTS_NET_MOUNTS\t$VW_SHORTCUTS_NET_MOUNTS"
echo -e "VW_SHORTCUTS_LIST_FILE\t$VW_SHORTCUTS_LIST_FILE"
echo -e "VW_SHORTCUTS_ICONS_FILE\t$VW_SHORTCUTS_ICONS_FILE"
echo -e "VW_SHORTCUTS_ICONS_PATH\t$VW_SHORTCUTS_ICONS_PATH\n"


# WORKING LISTS FILE NAMES

ka="LIST"
kb="ROOT"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
LIST_ROOT_PATH="$3"
echo -e "LIST_ROOT_PATH\t$LIST_ROOT_PATH"

kb="SECTION"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
LIST_SECTION="$3"
echo -e "LIST_SECTION\t$LIST_SECTION"

kb="INFO"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
LIST_INFO="$3"
echo -e "LIST_INFO\t$LIST_INFO"

kb="CMDS"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
LIST_CMDS="$3"
echo -e "LIST_CMDS\t$LIST_CMDS"

kb="SORTED"
p=`grep "^$ka$TAB$kb$TAB" "$CONF"`
set -f -- $p
LIST_SORTED="$3"
echo -e "LIST_SORTED\t$LIST_SORTED\n"

# these aren't part of the CAT List so we have to make them manually

LIST_CAT_SECT=$LIST_ROOT_PATH$LIST_SECTION".CAT"
LIST_CAT_CMDS=$LIST_ROOT_PATH$LIST_CMDS".CAT"

LIST_INFO_INFO=$LIST_ROOT_PATH$LIST_INFO".INFO"
#LIST_INFO_INFO_SORTED=$LIST_ROOT_PATH$LIST_INFO".INFO."$LIST_SORTED

# END WORKING LISTS FILE NAMES


p=`grep "^DEFAULT$TAB" "$CONF"`  
set -f -- $p
SET_NAME="$3"
echo -e "SET_NAME\t$SET_NAME\n"


  # Finally figured out how to set variable variables
  # read the list of categories and set variables for each enabled category

CAT_LIST=""

IFS="$NTPFS"

while read -r cat catname caticon ; do

  if [ -n "$cat" ] && [ -n "$catname" ] && [ -n "$caticon" ] ; then

    echo -e "ENABLED CATEGORY: [$cat] [$catname] [$caticon]"

    cname=$cat"_NAME"
    cicon=$cat"_ICON"

    CAT_LIST=$CAT_LIST$cat"|"

#    echo -e "X $cname $cicon X" >&2

    eval $cname='$catname'
    eval $cicon='$caticon'

#    echo -e "($cname) ($cicon)" >&2

    # Category Working Files
    eval "LIST_"$cat"_SECT"=$LIST_ROOT_PATH$LIST_SECTION"."$cat
    eval "LIST_"$cat"_INFO"=$LIST_ROOT_PATH$LIST_INFO"."$cat
    eval "LIST_"$cat"_INFO_SORTED"=$LIST_ROOT_PATH$LIST_INFO"."$cat"."$LIST_SORTED
    eval "LIST_"$cat"_CMDS"=$LIST_ROOT_PATH$LIST_CMDS"."$cat

    # Category Set Name
    kn=$cat"_SET_NAME"
    ka="_SET"
    kb="BEGIN"
    p=`grep "^$cat$ka$TAB$kb$TAB" "$CONF"`
    set -f -- $p
    katnam="$3"
    eval $kn='$3'

    # Category Icon Path
    kn=$cat"_SET_PATH"
    ka="_SET"
    kb="PATH"
    p=`grep "^$cat$ka$TAB$kb$TAB" "$CONF"`
    set -f -- $p
    eval $kn='$3'

    # if a  cat BEGIN-END is defined, extract it
    
    if [ -n "$katnam" ] ; then
      sed -n "/${cat}_SET.BEGIN/,/${cat}_SET.END/ { /^${cat}_SET.[BEP]\|^#\|^$/!p }" "$CONF" > $LIST_ROOT_PATH$LIST_SECTION.$cat
    fi


  else

    echo -e "$SCRIPT_NAME:\t BAD CATEGORY DEFINITON in [$CONF]: [$cat] [$catname] [$caticon]" >&2
  fi

done < `sed -n '/CAT.BEGIN/,/CAT.END/ { /^CAT.[BEP]\|^#\|^$/!p }' "$CONF" > $LIST_CAT_SECT ; echo $LIST_CAT_SECT`
echo -e "\n"


#echo -e "Categories Found:\n$CAT_LIST\n"
#echo -e $LIST_GENRE_CMDS_SORTED
#echo -e $LIST_GENRE_CMDS

IFS="$OIFS"

echo -e "### CONFIG FILE LOADED ###\n"

#important - global no-globbing flag ON
# we want it off during config file loading but otherwise we need it on

set +f


############# END READ CONF ####################


# THIS IS THE MAIN PROGRAM WAY DOWN HERE AT THE END


if [ -z "$DEBUG_CONFIG" ] ; then


  # Sort out the collection path and make sure it's readable
  
  if [ "$COLLECTION_PATH" == "USE_FIRST_SHORTCUT" ] ; then

    echo -e "AUTO Shortcut Selection..."

    COLLECTION_PATH=""
    
    # Dump shortcuts into a section file
    get_VW_Shortcuts > "$LIST_CAT_SECT.shortcuts"

    # Find the first workable shortcut and set that as our collection path

    IFS="$PIPE"

    while read -r styp spath sname ; do
    
      gtyp=`echo -E "$styp" | grep -v "^BAD\|^MISSING\|^FAKE"`

      if [ -n "$gtyp" ] ; then

        if [ -z "$COLLECTION_PATH" ] ; then
          echo "Selected collection: $styp $spath $sname"
          # ALWAYS ADD THE trailing slash.. shortcuts do not have one
          COLLECTION_PATH="$spath/"
        else
          echo "Alternate collection: $styp $spath $sname"
        fi
      fi
    done < "$LIST_CAT_SECT.shortcuts"

    if [ -z "$COLLECTION_PATH" ] ; then
      echo -E "No COLLECTION_PATH found with auto-discovery. Make sure your media is still mounted -ABORT!"
      return 15 ;
    fi

    echo -e ""
    
    IFS="$OIFS"
  fi

  
  # Double-check the collection path!
  if [ ! -d "$COLLECTION_PATH" ] ; then
    echo -E "COLLECTION_PATH \"$COLLECTION_PATH\" IS MISSING or NOT a DIRECTORY! ABORT!"
    return 14 ;
  fi


  # inventories entire collection for any files we can use to gain information
  make_INFO


  if [ -n "$AZ_NAME" ] ; then
    x=1
    do_AZ
  fi

  if [ -n "$DECADE_NAME" ] ; then
    x=1
    do_DECADE
  fi

  if [ -n "$GENRE_NAME" ] ; then
    x=1
    do_GENRE
  fi

  if [ -n "$NAME_NAME" ] ; then
    x=1
    do_NAME
  fi

  if [ -n "$RATING_NAME" ] ; then
    x=1
    do_RATING
  fi

  if [ -n "$TOP250_NAME" ] ; then
    x=1
    do_TOP250
  fi

  if [ "$VW_SHORTCUTS_ENABLED" == "TRUE" ] ; then
    # Build the videowall Shortcuts Files
    do_CATEGORIES
  fi

else
  echo -e "DEBUG ON: Only reading Config File - NOTHING EXECUTED!"
fi


# REMINDER: This script outputs all commands into these files
# "clist.*" - be sure to examine them before allowing this script to execute them automatically
# Don't forget to check your videowall shortcut files.
# If you used dummy files you can cut/paste their contents to your actual shortcut files.
#
# (the leading period means 'execute the file')


if [ -z "$DEBUG_COMMANDS" ] && [ -z "$DEBUG_CONFIG" ] ; then

  if [ -n "$AZ_NAME" ] ; then
  . "$LIST_AZ_CMDS"
  fi

  if [ -n "$DECADE_NAME" ] ; then
  . "$LIST_DECADE_CMDS"
  fi

  if [ -n "$GENRE_NAME" ] ; then
  . "$LIST_GENRE_CMDS"
  fi

  if [ -n "$NAME_NAME" ] ; then
  . "$LIST_NAME_CMDS"
  fi

  if [ -n "$RATING_NAME" ] ; then
  . "$LIST_RATING_CMDS"
  fi

  if [ -n "$TOP250_NAME" ] ; then
  . "$LIST_TOP250_CMDS"
  fi

  if [ "$VW_SHORTCUTS_ENABLED" == "TRUE" ] ; then
    echo -e "Creating Shortcuts Folders, Icons, Links, etc:\n"
    . "$LIST_CAT_CMDS"
    echo -e "Installing Shortcuts: Completed.\n"
  fi

else
  echo -e "DEBUG ON: COMMAND FILES NOT EXECUTED"
fi


echo -e "normal program exit\n"
return 0 ;

#//EOF
