#!/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;


{
  our $study_called=0;
  my ($file,$modi);
  ($file,$modi) = @ARGV;
  &setup_parse();
  for ($file) {
    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='modi';
    #print "ACTION $action \n";
    my $modfile= "_$fname";
    print "insert_use_modi: $fname => $modfile\n";
    my @lines = &readfile($fname);
# Expand the macros INTEGER_M etc into Fortran
    &remove_macro(\@lines);
# Expand lines into statements
    if($action eq 'all' or $action eq 'modi' ) {
      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);}
# Rename some variables
      if($fname=~/\.F90$/ and ($action eq 'all' or $action eq 'modi' 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_use_modi(\@statements,\%prog_info,\%vars,$modi); 
 	}}
      if($fname=~/\.F90$/ and ($action eq 'all' or $action eq 'modi' )) {
    
# 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
}
