#!/bin/bash -f
function usage {
echo "
   findscreen lists the edm screens that directly reference 
   a device, PV, or in fact arbitrary text such a label or title.

   For instance, it can be used to find a screen with a given title, or screens
   associated with a given MPS faulted device.

   Usage:
          findscreen [-ecmh] <string>  

   Options:
          -e launch edm in execute mode on all the sceens found.
             Give it time!
          -c Only find screens where the argument is in the name of a control PV
          -m Include MPS screens. These are normally excluded.
          -h Display this help

   Examples:
          findscreen BFW:UND1:1310      List screens that reference 
                                        BFW:UND1:1310 in any way.
          findscreen -c XCOR:LI21       Find screens that do control 
                                        of PVs with XCOR:LI21 in their name
          findscreen -e BFW:UND1:1310   Find and attempt to launch screens. 
                                        Launches are in the background. 
          findscreen -emc OTRS:IN20:465 Find and launch all screens, except MPS,
                                        that, reference the given device.            

   Auth: Greg White, 10-Feb-2011
"
}
#----------------------------------------------------------------
# Mod: Greg White, 11-Feb-2011
#      Added -eloc to edm launch. Closes manager when the last screen 
#      is closed.
#================================================================
if [ $# -eq 0 ]; then
   echo "No arguments, see findscreen -h for help"
   exit 1;
fi

# Set Defaults
excludeMPS='| awk ''!/mps/'''
launchedm=
control=""

while getopts ecmh opt; do
   case "$opt" in
       h) usage; exit 0 ;;
       c) control='controlPv.*' ;;
       m) excludeMPS='';; 
       e) launchedm='| xargs edm -x -eolc &'  ;;
       *) echo "Unknown Arguments, see findscreen -h"; exit 1;;
   esac
done
shift $((OPTIND-1))

pattern="${control}${1}"

cmd="printenv EDMDATAFILES | tr : '\n' "${excludeMPS}"| xargs -I{} find {} -name '*.edl' -maxdepth 1 | xargs egrep -ie "${pattern}" -l"${launchedm}   

eval $cmd
