#!/usr/bin/env perl
#
# svn $Id: cpp_clean 362 2009-07-02 21:48:48Z arango $
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# Copyright (c) 2002-2009 The ROMS/TOMS Group                           :::
#   Licensed under a MIT/X style license                                :::
#   See License_ROMS.txt                                                :::
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
#  This script is used to clean CPP files.  It removes:
#
#       1) Lines with '#' in column 1 (lines inserted by CPP).
#       2) Lines with '!#' in columns 1:2 (commented CPP definitions).
#       2) Lines with '!!' in columns 1:2 (double commented lines).
#       3) Lines with '!$!' in columns 1:3 (removes OpenMP directives).
#       4) Blank lines.
#       5) Fixes placement of trailing '&'
#

my $file = $ARGV[0];
my $slash = rindex($file,"/");
if($slash lt 0) {
   $root = ".";
}else {
   $root = substr($file,0,$slash);
}
my $tmp = "$root/tmp.$$";
open(FILE, "$file");
open(TMP, ">$tmp") || die "Can't open tmp file";

while (<FILE>) {
   next if /^#/;
   next if /^!#/;
   next if /^!!/;
   next if /^!\$\!/;
   next if /^\s*$/;
   $a=rindex($_,"&");
   if(/\&(\ )*$/ && $a!=72){
      $l=length();
      if($a<72){
	 $t=($a-1)-72;
	 $t2=-$t;
	 $sp="";
	 for($i=1;$i<$t2;$i++){
	    $sp=$sp . " ";
         }
	 substr($_,-2,-$t-1)="$sp&\n";
      }
      if($a>72){
	 $t=72-($l);
	 substr($_,$t,-$t-1) = "&";
      }
   }
   print TMP;
}
close(FILE);
close(TMP);

rename($tmp, $file);
