Wed, Apr
5 New Articles

Breathing New Life into Old Code

  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

I’ve seen some RPG code I’d rather forget. These programs used all 99 indicators and had loads of redundant code. Code such as this wastes both time and indicators and begs for conversion to RPG IV.

Here is a list of some good reasons to dump RPG II and RPG III (a.k.a. RPG/400). Figures 1 and 2 compare and contrast RPG III and RPG IV functions. Figure 3 shows additional RPG IV functions. You may want to refer to these figures as you review the list.

• The five-character op codes used by RPG II and RPG III make source code look cryptic.

• Using the Compile-time Data (CTDATA) command links a D-spec with the compile-time array data that follows the O-specs. No more trying to figure out what array goes with what dataset!

• Data structures and named constants are defined in the D-specs, which leaves the I-spec with just input fields.

• RPG IV lets you declare data structure subfields by relative positions. Of course, you can still declare subfields by absolute position.

• The cryptic IFxx op codes can be replaced by an IF condition. The condition can be a comparison (e.g., X > Y), an indicator, an expression (e.g., [X + Y] > Z), or a value returned by a subprocedure.

• Doing a complex math equation like (A + B)/(C + D) in RPG II and RPG III requires several lines of calculations, and that makes code harder to follow. One thing you will appreciate is EVAL. Thanks to EVAL, a complex mathematical expression is a breeze in RPG IV. This powerful free-format op code has the ability to replace MOVEL, Z-ADD, ADD, SUB, DIV, and MULT (see Figure 2). Of course, the C-spec also supports fixed- format calculations.

• A new type of function called a built-in function, or BIF, has given RPG IV abilities not imaginable before. There are many BIFs for string manipulation, such as %trim, which removes blank spaces. There are so many BIFs, in fact, that I recommend you get the ILE RPG for AS/400 Reference manual and check them out. For one example of how BIFs can make your life easier, take a look at the next bulleted point.

• I/O op codes don’t require resulting indicators. Instead, you can use BIFs. You heard right; such operations as CHAIN, READ, SETLL don’t need indicators. To check the results of a CHAIN operation, you would use an IF %Found; for SETLL, an IF %Equal; and for READ, an IF %Eof.

• Before the advent of the “prefix” keyword, I spent a lot of time renaming fields in files that had exactly the same field name to avoid overlaying each file with the same data. However, now the prefix keyword (which gets added to the F-spec) automatically adds a code of my choosing to the beginning of each field name, thereby eliminating the need to rename each field.

• You no longer need to worry about converting dates back and forth, because RPG IV’s enhanced MOVE op code, which has the ability to translate many date formats, will do it for you (see Figure 3).

• RPG IV has given you two new alternatives to the CALL op code: CALLB and CALLP. CALLB is a way of binding one or more separately compiled modules into a single program. You can think of the CALLP (Call a Prototyped Procedure) op code as a special kind of EXSR statement that can return one or many values and execute with nearly the speed of a subroutine.

• The most import reason of all to convert to RPG IV is that IBM stopped making enhancements to RPG III a while ago, which means that it will get harder and harder to find programmers who know how to maintain your old stuff.

It’s Strategy Time

I want to stop right here for a second to mention that you can’t cut and paste RPG II or III code into RPG IV. First, the record length of RPG IV is 100 bytes: 80 bytes for coding and 20 bytes for right-hand comments. The RPG III compiler reads only 80 bytes, and comments are included. Second, the C-spec has changed greatly. Only one detail-time conditioning indicator is allowed on a C-spec line. Additionally, Factor 1, Factor 2, the result field, and op code areas are larger under RPG IV. Some op codes, such as SETOF and SELEC, are no longer abbreviated. SEU has been modified to support the RPG IV syntax, and it seems to be even smarter than RPG III; for example, it delivers a warning should you accidentally repeat keywords in the F- or D-spec. SEU will also allow you to indent things in Factor 2.

There are three types of RPG conversion. The first type is conversion by application. In this scenario, you completely rewrite a group of related RPG III programs to take full advantage of RPG IV. What you gain by doing this is increased productivity through employing subprocedures that can be used by other programs; you also make performance gains from using activation groups. The disadvantage to this process is that you need to understand the application and isolate all of its parts, have the time available to do this, and have a good understanding of RPG IV and subprocedures.

A second type of conversion is also by application, but in this example, you don’t rewrite the code to take full advantage of RPG IV. Instead, you use IBM’s conversion tool, Convert RPG Source (CVTRPGSRC), to convert RPG III members to RPG IV. This means you need only a minimal understanding of RPG IV and not nearly as much time as

the first type of conversion. The disadvantages are that you still have to isolate the RPG programs responsible for the application, you’re not taking full advantage of RPG IV features, and you’ll have to maintain more than one version of RPG in your system.

The third type of conversion is one in which you convert only one (or maybe a few) programs at a time by using CVTRPGSRC. While the advantages and disadvantages are the same as the second type of conversion, you needn’t spend any time isolating the application programs; hence, the time to convert is minimal.

For both the second and third types of conversions, you could use a third-party source converter to let your source code have all D-spec-defined field names, indicators replaced with an IF *Inxx structure, and IF conditions to replace the converted Ifxx. Doing so would require minimal effort on your part and result in improved readability and function.

CVTRPGSRC will convert your RPG source code into an RPG IV member. The intent of this command is to map RPG to an RPG IV format. It will create some D-specs to take the place of I-spec data structures, but it will not define your C-spec-defined fields in the D-spec. This tool also doesn’t do such things as convert conditioning indicators to logical expressions or mathematical operations to arithmetic expressions.

Just Do It!

To initiate a conversion, key CVTRPGSRC at the command line and press F4 to prompt it. Then, press F9 to display all of the parameters and F11 to show the keywords. The FROM and TO parameters map the RPG code from one source member to another (the member names have to be different if you do your conversions in the same library/source file). The FROM parameter also allows *ALL or a generic name for mass conversions. The Expand copy (EXPCPY) parameter gives you the option of taking /COPY members source code and expanding it into the program you are converting. If you don’t use /COPYs or if you want to leave your /COPY as separate members, leave the default as *NO.

The Insert specification template (INSRTPL) parameter automatically inserts form specification templates into the appropriate specification sections as commented text. The LOGFILE parameter keeps track of what programs have successfully or unsuccessfully been converted.

The default file name QRNCVTLG keeps track of a wealth of conversion information, such as the conversion status. A status of 00 means that no errors were found, whereas a status of 30 or 40 means that a severe error occurred. Other information includes parameter options selected, the user doing the conversion, and so on. This type of information will be helpful if are performing mass conversions.

The file must exist before you use it; if it doesn’t, use the Create Duplicate Object (CRTDUPOBJ) command to duplicate the QARNCVTLG file in QRPGLE to a QRNCVTLG file in your library. The Conversion report (CVTRPT) parameter allows you to request a Conversion error report. This report contains not only error messages but also useful warnings such as a suggestion to change some of the CALL op codes to CALLB. There is a supplemental parameter to CVTRPT called the Second-level message text (SECLVL) parameter; specifying *YES means you want second-level help messages in your conversion report.

Look Out for the Troublemakers

Keep an eye out for problems with /COPY compiler directives. Those that have E, L, or I specification forms in them will convert to the appropriate D- or F-spec keyword, but their insertion in the program may cause a compilation error because I-specs come after D-specs in RPG IV.

Here is a typical way to handle /COPY. First, alter the source code to tell it where the new /COPY resides, because it doesn’t belong in QRPGSRC anymore. Second, compile the program; if you get a “form out of sequence” error, then you have to modify

the program to use the /COPY member or break up the /COPY member into other members, insert them into the appropriate places, and convert or compile again. It may be worth expanding the /COPY with the EXPCPY (*YES) parameter before you start, just to see what problems you may have.

The next items to look out for are the op codes FREE and DEBUG, which are no longer supported. Replacing DEBUG is easy, but removing the FREE op code could take a bit of redesign. FREE was removed from RPG IV because RPG IV is an ILE language and its objects remain active in an activation group until you issue a Reclaim Activation Group (RCLACTGRP) command. One way to replace the FREE op code is to create true ILE programs; that is, compile them into their own activation groups (see “Activation Group Fundamentals,” MC, March 1999) and use CL’s RCLACTGRP command.

With SQLRPG members, the continuation line column 74 could be a problem for you. If column 74 is not blank, you may wind up with all of the SQL code from that line to the /END-EXEC concatenated, filling up all 80 columns. It is best, then, to alter your source so that column 74 is blank before you convert. If you have an AUTORPG program, the converter will try to convert as much of it as possible by expanding the output from the Create Auto Report RPG Program (CRTRPTPGM) command. One thing that is removed by the converter that will not directly affect your code is the /TITLE lines.

Make Me Beautiful!

You can quickly achieve modern RPG IV code with the help of third-party conversion tools, which take your code and pretty it up. Fields that are defined in the C-specs are redefined in the D-specs. IFxx commands are translated to conditional expressions. Conditioning indicators may be translated to conditional expressions, depending on what kind of converter you’ve chosen. Such op codes as Z-ADD and SUB, among others, can be converted to EVAL operations with arithmetic expressions. While this capability does not take advantage of ILE, it does significantly improve the appearance of your code.

With third-party postconversion, your code is run through IBM’s CVTRPGSRC; you then execute a command to modernize your code, such as Brad Stone’s Convert ILE Format (CVTILEFMT) command (see “Programmer’s Toolbox: CVTILEFMT: A Beautician Specializing in RPG IV Source Code,” MC, March 1999). Third-party converters like ProData’s CVTRPGIV do it in one step, saving time. Postconversion gives you a chance to correct your code while it is still close to its original form; however, direct conversion is faster. Also, vendors of commercial converters will support their products, whereas you may not get any support with a freeware or shareware converter.

Most products give you the option to change arithmetic op codes such as Z-ADD, ADD, and MULT to EVAL, although you must exercise caution when selecting this option if you have fields that are not large enough to hold the result of an arithmetic expression. Unlike RPG III, which will truncate a numeric field that overflows, RPG IV gives a runtime error message. In addition, there may be cases in which you want a MOVEL rather than EVAL. EVAL differs from MOVEL in that it pads the resulting field with spaces.

In our shop, we converted programs one at a time or in a small group when it made sense. We also used the CVTILEFMT command to improve the readability of the code and to have all of the fields defined in the D-specs. My advice to you is to convert a handful of noncritical programs. That way, you can build up both your confidence and experience as you learn that converting old RPG code to RPG IV is well worth the effort.

References and Related Materials

• “Activation Group Fundamentals,” Mario Martinez, MC, March 1999
• ILE RPG for AS/400 Programmer’s Guide (SC09-2507)
• ILE RPG for AS/400 Reference (SC09-2508)
• Moving to Integrated Language Environment for RPG IV, Redbook (GG24-4358)
• ProData CVTRPGIV home page: www.prodatacomputer.com/ile.htm

• “Programmer’s Toolbox: CVTILEFMT: A Beautician Specializing in RPG IV Source Code,” Bradley V. Stone, MC, March 1999
• “RPG III-to-RPG IV Conversion Utility,” Doug Pence and Ron Hawkins, MC, January 1999

• “Subprocedures: A Step in the Right Direction!” Jim D. Barnes, MC, May 1998

* Example OF data structures, arrays, L-spec, and IF conditions,

* RPG style.




E ARR1 1 2 75

E COS 1 2 5 0


I 1 5 CODE

I 6 75 DESC



C DO 2 X 30












O 8 ‘CODE’





O COS,X 1 110


O TOTAL 1 110

House Ranch
Car No Description AVAILABLE



* Example of data structures, arrays, L-spec, and IF conditions,

* RPG IV style.

fqsysprt o f 132 printer

f oflind(*inof)

f FormLen(66)

f FormOFL(60)

d arr1 s 75 dim(2) ctdata perrcd(1)

d cos s 5 0 dim(2)

d ctdata perrcd(1)

d dsarr ds

d code 5

d desc 70

d total s 7 0

d x s 3 0

C Except Hdg

c Do 2 x

c move arr1(x) dsarr

c except detail

C if *INOF

C Except Hdg

C Eval *INOf = *off

C endif


c eval total = (total + cos(x))

Figure 1: Here are examples of RPG III data structures, arrays, L-spec, and IFEQ conditions.

c Enddo

c except totcst

c Eval *INLR = *On

Oqsysprt e HDG 2 01

O 8 ‘CODE’


o e detail 1

o code 8

o desc 85

o cos(x) 1 110

o e totcst 2 2

o total 1 110


House Ranch
Car No Description AVAILABLE

* Example : Converting dates stored in packed format

* : manipulating strings

D Isodate s d

* Date Format is ISO when no DATFMT keyword is specified.

D MDY# s 6 0

D CYMD# s 7 0

D FullName s 20 Inz(*blanks)

D Initials s 3

D FirstName s 10 Inz(‘John’)

D LastName s 10 Inz(‘Doe’)

D MDYString s 8

C Eval CYMD# = 1021101

* example of Date Converting

* convert 7 packed CYMD to a 6 Packed MDY result=110102

C *CYMD Move CYMD# IsoDate

C *MDY Move IsoDate MDY#

* convert 6 packed MDY to a 7 Packed CYMD result=1021101

C *MDY Move MDY# IsoDate

C *CYMD Move IsoDate CYMD#

* Add 13 months, result IsoDate = 2003-12-01

C Adddur 13:*M IsoDate

* example of string manipulation

* FullName = John Doe

* Initials = J D

C Eval Fullname = %trim(FirstName)

C + ‘ ‘

C + %trim(LastName)

C Eval Initials = %Subst(FirstName:1:1)

C + ‘ ‘

C + %Subst(LastName:1:1)

* create edited string from MDY#, MDYString result = 11/01/02

C Eval MDYString = %editc(MDY#:’Y’)

C eval *inlr = *On

Figure 2: Here are examples of RPG IV data structures, arrays, L-spec, and IFEQ conditions.

Figure 3: RPG IV can convert dates stored in packed fields and manipulate strings.



Support MC Press Online

$0.00 Raised:

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: