#!/usr/bin/perl -w
#==============================================================
#
#  Abs:  sets DV PV to 1 (linac upgrade/test PV) or 0 (not)
#        alarm handler tree
#
#  Name: changeGroupDVPVs.pl
#
#  Args: 1. alh group name
#        2. value to change to (should be 0 or 1)
#        3. top alh config file that will contain the tree
#           in question.  For example LCLS_All.alhConfig will
#           pick up everything.
#
#  Usage: called by script, or eventually some gui or other.
#
#--------------------------------------------------------------
#

use strict;
my @filelist;

my %alhGroups;

sub usage()
{
	print "Usage:\n";
	exit;
}

sub loadTree
{
# loads alarm tree into hash of arrays
	my ($fil, $parentGroup) = @_;
#        local *incFILE;

        local *INP; 	

        if (!open(INP, $fil)) {
                print "*** $fil: failed to read \n";
                return;
        }
	my @alhLines = <INP>;
	close INP;

        my $alhLine;

        my $channel;
        my $grp;
        my $record;
        my $count = 0;
        my $i;
        my $incChan; 
        my $incParent; 
        my $incGroup;
        my $memberExists;
        my $member;

        #print "START OF FILE $fil\n";

	foreach my $alhLine (@alhLines) {
                # remove leading whitespace
                $alhLine =~ s/^\s+//;
		if ($alhLine =~ /GROUP/) {
                        $count++;
                    
                        my ($chan, $parent, $group) = split/\s+/, $alhLine;
                        
                        # if the group is NULL, this is an INCLUDEd file
                        # need to set the parent from parameter list
                        if ($parent eq "NULL")
                           { $parent = $parentGroup; }

                       
                        # look to see if this subgroup has already been represented
                        $memberExists = 0;
                        foreach $member (@{$alhGroups{$parent}})
                           {
                           if ($member eq $group)
                              {
                              $memberExists = 1;
                              last;
                              } 
                           }
                        if ($memberExists == 0)
                           {   
                           #print "   -->GROUP:  pushing $group onto group $parent\n";
                           push @{$alhGroups{$parent} }, $group
                           }

		}
		elsif ($alhLine =~ /CHANNEL/) {
                        my ($chan, $parent, $channel) = split/\s+/, $alhLine;

                        # look to see if this subgroup has already been represented
                        $memberExists = 0;
                        foreach $member (@{$alhGroups{$parent}})
                           {
                           # print "member: $member  channel: $channel\n";
                           if ($member eq $channel."^cHan")
                              {
                              $memberExists = 1;
                              #print "$channel exists in $parent already\n";
                              last;
                              } 
                           }

                        if ($memberExists == 0)
                           {   
                           push @{$alhGroups{$parent} }, $channel. "^cHan";
                           #print "   -->CHANNEL:  pushing " . $channel. "^cHan onto group $parent\n";
                           #print "$channel NOT in $parent already\n";
                           }


                        # also add an element for a single channel, with itself as member
                        
                        if (!(defined @{$alhGroups{$channel} }))
                           {
                           push @{$alhGroups{$channel} }, $channel. "^cHan";
                           #print "      -->AND:  pushing " . $channel. "^cHan onto group $channel\n";
                           }


		}
		elsif ($alhLine =~ /INCLUDE/) {
                        $count++;
                    
                        my ($inc, $group, $fileName) = split/\s+/, $alhLine;

                        loadTree($fileName,$group);
		}
	}


	return;
}

sub changeGroupPVs
{
# caput 0 or 1 to the appropriate group of FORCEPVs in the tree
my ($groupName, $toWhat) = @_;

#print "***changing group $groupName to $toWhat\n";

my $groupMember;
#print "   members: \n";

foreach $groupMember (@{$alhGroups{$groupName}})
   { 
   # print "     $groupMember of $groupName\n"; 
   if ($groupMember =~ /\^cHan/)
      {
      #print "    ==processing chan here\n";
      
      my ($PVName, $label) = split/\^/, $groupMember;

      my $caputCommand = "caput " . $PVName . "DV " . $toWhat;
      # print "doing: $caputCommand\n";
      my $rc = system $caputCommand;
      if ($rc != 0)
         {
         print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"; 
         print "PROBLEM CAPUT-ing " . $PVName . "FP!\n"; 
         print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"; 
         }
      }
   else
      {
      changeGroupPVs($groupMember, $toWhat);
      }

   }
return;
}


##################################################

# code start

##################################################

my $pwd = `pwd`;
chomp $pwd;

%alhGroups = ();

if ($pwd !~ /\/$/) {
	$pwd .= '/';
}

my $sdir = $pwd;

if ($#ARGV < 0) { usage(); }

my $groupToSet = $ARGV[0];
shift @ARGV;

my $toWhat = $ARGV[0];
shift @ARGV;

my $topFile = $ARGV[0];

# load appropriate subset of the alarm handler tree groups for
# searching

loadTree($topFile, "Top");

#print "will change group $groupToSet here\n";

changeGroupPVs($groupToSet, $toWhat);

