#!/bin/bash
#! -*-perl-*-
eval 'exec perl -x -wS $0 ${1+"$@"}'
  if 0;
# $Id: gmt5syntax.in 12691 2014-01-01 09:41:00Z pwessel $
#
#  Copyright (c) 1991-2014 by P. Wessel, W. H. F. Smith, R. Scharroo,
#  J. Luis, and F. Wobbe
#  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@GMT_INSTALL_NAME_SUFFIX@';

# words to prepend with $progname
my @modulenames = qw( backtracker blockmean blockmedian blockmode dimfilter
filter1d fitcircle gmt2kml gmtconvert gmtdefaults gmtget gmtgravmag3d gmtinfo
gmtmath gmtselect gmtset gmtsimplify gmtspatial gmtstitch gmtvector gmtwhich
gravfft grd2cpt grd2rgb grd2xyz grdblend grdclip grdcontour grdcut grdedit
grdfft grdfilter grdgradient grdgravmag3d grdhisteq grdimage grdinfo
grdlandmask grdmask grdmath grdpaste grdpmodeler grdproject grdraster grdredpol
grdreformat grdrotater grdsample grdseamount grdspotter grdtrack grdtrend
grdvector grdview grdvolume greenspline gshhg hotspotter img2grd kml2gmt
makecpt mapproject mgd77convert mgd77info mgd77list mgd77magref mgd77manage
mgd77path mgd77sniffer mgd77track minmax nearneighbor originator project
ps2raster psbasemap psclip pscoast pscontour pscoupe pshistogram psimage
pslegend psmask psmeca pspolar psrose psscale pssegy pssegyz pstext psvelo
pswiggle psxy psxyz rotconverter sample1d segy2grd spectrum1d sph2grd
sphdistance sphinterpolate sphtriangulate splitxyz surface trend1d trend2d
triangulate x2sys_binlist x2sys_cross x2sys_datalist x2sys_get x2sys_init
x2sys_list x2sys_merge x2sys_put x2sys_report x2sys_solve xyz2grd );

# 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;
}
