#!/usr/bin/perl -w
# Display_hash
#    VERSION: Version 3 (25 November 2003)
#    PURPOSE: Prints out the keys and values of a stored hash
#    INPUT FILES: Must be stored using the store method of the module Storable
#          The key "|" has a special meaning of summing previous values
#    OUTPUT FILES: Output is to screen
#    DIFFERS FROM Version 2 in fixing bug in recognizing default file name

############## LIBRARIES AND PRAGMAS ################

  use strict;
  use Storable;

#################### CONSTANTS ######################

  my $LF = "\n";
  my $true = 1;
  my $false = 0;
  my $sum_symbol = chr(255);

#################### VARIABLES ######################

  my %model;

###################### FILES ########################
# Requests name of file using STDERR so as not to contaminate output to
#    STDOUT, in case you want to redirect it to a file

  print STDERR 'Enter file containing model (default = "Model.dat"):  ';
  my $input_file_name = <STDIN>;
  chomp $input_file_name;
  if ($input_file_name eq "") {$input_file_name = "Model.dat"}
  Get_Model($input_file_name);

################### MAIN PROGRAM ####################

  Print_keys ("", \%model);

#################### SUBROUTINES ####################

##### GET_MODEL (path to file containing model)
#     Reads model using retrieve method from module Storable
#     Retrieve stores model in a hash and gives the reference to $model_reference
#     Reference allows us to define %model
  sub Get_Model {
     my ($model_file_name) = @_;
     my $model_reference = retrieve $model_file_name;
     %model = %$model_reference; 
  }

##### PRINT_KEYS (previous keys, hash reference)
#     Recursive routine that prints out keys and value of a a hash of hashes
#        of indeterminate nesting
#     If a hash of hashes is received, keys are extracted and each
#        hash is sent back into subroutine
#     If a hash of values is received, those values are printed
  sub Print_keys {
    my ($old_keys, $hash_ref) = @_;
    my %hash = %$hash_ref;
    my $full_keys;
    my @full_keys;
    my @keys = sort keys %hash;
    my $first_time_through = $true;

    foreach my $key (@keys) {
       if ($key eq "") {$full_keys = $old_keys . " "} else {$full_keys = $old_keys . $key}
       if (ref($hash{$key}) eq "HASH") {Print_keys($full_keys, $hash{$key})}
       else {
          @full_keys = split("",$full_keys);
          if ($first_time_through == $true) {print "{", join("}{",@full_keys), "} "}
          elsif ($key eq $sum_symbol) {print "-" x (length($full_keys) + 13), " "}
#          else  {print "{", join("}{", ("-") x length($old_keys), $key), "} "}
          else  {print "   " x length($old_keys), "{", $key, "} "}
          print $hash{$key}, $LF;
          $first_time_through = $false;
       }
    }
  }
