#!/usr/bin/perl

use strict;
use warnings;
#use lib "/ccvobs/satrad/rttov";
use Fortran90_stuff_interface;
use Data::Dumper;
use File::Basename;

$Data::Dumper::Indent = 1;

#use Devel::DProf; #dprofpp
#use Devel::SmallProf; #dprofpp

#my $PROJECT=$ENV{PROJECT} or die "PROJECT not defined ";

{
  our $study_called=0;
  my (@files);
  (@files) = @ARGV;
  &setup_parse();
  for (@files) {
    my (%vars,@unused_vars,%args,$var,%doctor_viols,$action);
    my (@inc_statements,@interface_block);
    my (%use_vars,@unused_use_vars,%prog_info,@line_hash);
    
# Read in lines from file
    my $fname = $_;
    my $dirname=&dirname($fname);
    $dirname=~s!.*/(.+)!$1!;
    next unless ($fname=~/\.F90$/ or $fname=~/\.h$/);

    $action='hook';
    #print "ACTION $action \n";
    my $modfile= "_$fname";
    print "insert_hook: $fname => $modfile\n";
      
    my @lines = &readfile($fname);

    #print @lines;

#   if($action eq 'all' or $action eq 'hook' ) {
# Some initial tidiyng to make the rest work smoothly
#     &pre_tidy(\@lines);
#   }
# Expand the macros INTEGER_M etc into Fortran
    &remove_macro(\@lines);

# Expand lines into statements
#   "@statements" is an array of hashes ultimately containing the statements themself and
#   different attributes of the statement,  expcont puts in the statements
    if($action eq 'all' or $action eq 'hook' ) {
      my @statements=(); 
      &expcont(\@lines,\@statements);

      if($fname=~/\.F90$/) {
# "Study" the statements and set attributes in @statements
	$study_called=0;
	&study(\@statements,\%prog_info);


	&process_include_files(\@statements,\%prog_info,\@inc_statements);
 
# Simple tidying (simple replacemnts .EQ. -> ==  etc.)
#   &tidy(\@statements);

# Tidy up declerations
#	&tidy_decl(\@statements);

# Rename some variables
      }
      if($action eq 'all' and $fname=~/\.F90$/) {
      
#	&change_var_names(\@statements);

# Get all locally declared variables and all USE, ONLY variables
	%vars=();
	%use_vars=();
	&getvars(\@statements,\%prog_info,\%vars,\%use_vars);

# Find variables declared but not used
	&find_unused_vars(\@statements,\%vars,\@unused_vars,
			  \%use_vars,\@unused_use_vars);
	&remove_unused_vars(\@statements,\@unused_vars,\@unused_use_vars);

      }
   
      if($fname=~/\.F90$/ and ($action eq 'all' or $action eq 'hook' and  $fname!~/codb_distribute\.F90/)){

 	unless($prog_info{is_module} and ! $prog_info{has_contain} and ! $prog_info{has_interface_block}){
 	  &various(\@statements,\%prog_info,\%vars); 
 	  &insert_hook(\@statements,\%prog_info,\%vars); 
 	}
      }
      if($fname=~/\.F90$/ and ($action eq 'all' or $action eq 'hook' )) {
    
# Get lines back from the statements
  	&cont_lines(\@statements,\@lines,\@line_hash);

      }
    }


# Restore protected !
    for (@lines) {
      s/Ł/!/g;
    }
# And write them out
    &writefile($modfile,\@lines);

  } # This file done
}

