#!/usr/bin/env perl
eval 'exec perl -x -wS $0 ${1+"$@"}'
  if 0;
#
#  Copyright (c) 1991-2025 by the GMT Team (https://www.generic-mapping-tools.org/team.html)
#  See LICENSE.TXT file for copying and redistribution conditions.
#
# gmt5syntax convert old GMT script to use new 'gmt <module>' syntax
# usage: gmt5syntax old_script > new_script

use strict;
use warnings;

# name of the main gmt executable
my $progname = 'gmt';

# words to prepend with $progname
my @modulenames = `$progname --show-classic`;
chomp (@modulenames);

# add more compatibility modules
my @compat_modules = split (";", "minmax;gmtdp;gmtstitch;grdreformat;ps2raster;originator");
push @modulenames, @compat_modules;

# Regexp::Assemble creates a single efficient regexp from multiple regexp
my $have_assemble = eval "use Regexp::Assemble; 1" ? 1 : 0;

my $re;
if ($have_assemble) {
  # build smart regexp from @modulenames
  my $ra = Regexp::Assemble->new(anchor_word_begin => 1, anchor_word_end => 1);
  $ra->add(@modulenames);
  #say $ra->as_string; # print assembled regexp
  $re = $ra->re;
}
else {
  # concatenate modulenames to '\b(backtracker|blockmean|blockmedian|...)\b'
  $re= '\b(' . (join '|', @modulenames) . ')\b';
}

# convert lines to new syntax
while (<>) {
  s{(^[^#<>]+)}{ # skip anything after comment or I/O redirection
    my $str = $1;
    $str =~ s/($re)/$progname $1/g unless /$progname ($re)/; # prepend $progname
    $str
  }eg;
  s{(^[# ]+[^<>]+)}{ # convert gmt commands directly following a comment
    my $str = $1;
    $str =~ s/^([# ]+)($re)/$1$progname $2/g unless /$progname ($re)/; # prepend $progname
    $str
  }eg;
  print;
}
