#!/usr/bin/env perl
#
# -*- Perl -*-
#
# Copyright (c) 2005-2007 The ABINIT Group (Yann Pouillon)
# All rights reserved.
#
# This file is part of the ABINIT software package. For license information,
# please see the COPYING file in the top-level directory of the ABINIT source
# distribution.
#

use strict;
use warnings;

sub my_config_files (@)
{
 my @retval;

 foreach my $entry (@_)
 {
  push @retval, $entry if ($entry =~ /\.cf/);
 }

 return @retval;
}

my $my_name    = "make-build-examples";
my $my_cnfdir  = "./config/build-examples";
my $my_outdir  = "./doc/config/build-examples";
my $my_reffile = "./doc/config/build-config.ac";

opendir(DIR,$my_cnfdir) or die "Cannot read $my_cnfdir\n";
my @cnf_files = my_config_files(readdir(DIR));
closedir(DIR);

foreach my $cnf_file (@cnf_files)
{
   my %cnf_vars = ();

   # Read config file
   open(CNF,"<$my_cnfdir/$cnf_file") or die "Cannot read $cnf_file\n";
   while ( <CNF> )
   {
      chomp();
      my ($var,$val) = split(/\t+/,$_);
      $cnf_vars{$var} = $val;
   }
   close(CNF);

   # Read template and write output
   open(INP,"<$my_reffile") or die "Cannot read $my_reffile\n";
   open(OUT,">$my_outdir/".$cnf_vars{"filename"})
    or die "Cannot write to ".$cnf_vars{"filename"}."\n";

   while ( <INP> )
   {
      my $do_print = 1;

      foreach my $var (keys %cnf_vars)
      {
         if ( (/^#$var=/) || ((/^#fcflags_opt_/) && ($var =~ /^fcflags_opt_/)) )
         {
            print OUT "$var=\"$cnf_vars{$var}\"\n";
            $do_print = 0;
         }
      }

      if ( $do_print )
      {
         print OUT $_;
      }
   }

   close(OUT);
   close(INP);
}
