No. 41 May/June 1988 $3.95 THE MICRO TECHNICAL JOURNAL

3-D Graphics / AI Theory Three-Dimensional Graphics, Part 1 page 8 Earl Hinrichs uses high performance graphics IC to create and display depth.

Neural Networks page 16 Modeling human reasoning is the first step in creating a useful robot.

The Logic Of Programming Languages page 22 Proving that a language is logically valid beats testing it for 10 years.

Applying Information Theory page 42 Calculating the maximum theoretical data compression and then applying it.

Plus:

Updating The C Reviews page 48

RS-232 Interfacing page 30

Button's Great Share", page 58

MarketiJ , H' ..of

AndMuc Mu

II 11 •• 1 .. 1.1 11111.111 III II I " VERY HIGH RESOLUTION The PC Tech COLOR and MONOCHROME video processor boards employ the TMS 34010 high performance graphics co·processor to insure the best possible video performance at reasonable prices. .

Color 34010 Video Processor: • Featured on the cover of Micro Cornucopia. • From 800 x 512 through 1024 x 800 resolution (depending on monitor and configuration). • 8 Bits per pixel for 256 simultaneous colors • Hardware support for CGA/MDA emulation. • PC, XT, and AT compatible

The PC Tech Color 34010 video processor is a superior 34010 native code and DGIS development tool. We support up to 4 megabytes of program (non-display) 34010 RAM as well as up to 76aK bytes of display RAM. Compare our architecture and prices to any other intelligent graphics board. Then choose the PC Tech Color 34010 Video Processor for your development engine and your production requirements as well. Color 34010 Video Processor ...... $1, 195.00 Price includes 512K display RAM, 1024K program RAM, and utility software. Monitor not included. Also available: DGIS, 34010 C compiler, assembler, 34010 fractal software, additional display and program memory, and various monitor options.

PC Tech Monochrome 34010 Video Processor and Monitor • 736 x 1024 resolution (other options available) • 2 bits per pixel for 4 hardware gray shades • Hardware support for CGA/M DA/Hercules emulation • PC, XT, and AT compatible • Full page 66 line text editing with many popular editors • Excellent windows 2.0 application development system The graphics and bit manipulation capabilities of the TMS 34010 make the PC Tech Monochrome 34010 Video Processor 66 line full page text and graphics display faster than many 25 line systems. The video processor is available separately or with the high resolution white phosphor monitor shown above. Monochrome 34010 Video Sub-System ...... $1,295.00 Price includes Monochrome Video Processor and monitor pictured above. Also available: DGIS, TI 34010 C compiler, TI assembler. Monochrome 34010 Video Processor also available separately. SOG SPECIAL! PC Tech will offer a 10% SOG DISCOUNT on all , Designed, Sold and Serviced By: 34010 based video products ordered within 1 week of SOGI Special pricing effective July 7-21, 1988 904 N. 6th St. Lake City, M N 55041 (612) 345·4555 (612) 345·5514 (FAX)

PC, XT, AT, DGIS, Hercules, and Windows 2.0 are trademarks or registered trademarks of their respective companies. Reader Service Number 3 DataDesk's New Turbo-lOl Enhanced Keyboard Bundle!

12 function keys Enlarged Dedicated Pause, with functional L-shaped Enter Key Scroll Lock, Print Fll & F12 Screen keys Switch-selectable for swallping Ctrl L and Caps Lock positions ' /.1 /- Extra-wide ,/.. , Shift keys ,i!/",,; . . /

~\ ~?,..OO "" ftt~~· C\~\,\\~ Positive-tactile, firm-feel keys Dedicated screen ~1.r\\\'\:~' ~'{',~."""~",,--~,,,,---- control and cursor keypad with O:f"''J'J ~.-- movement keys enlarged Enter key S __ ~~-"'"

You don't have to think twice. Get both - the best-selling Turbo! 01 T" Enhanced I(eyboard and ThinkTank;" the award-winning outline processor. For an unthinkable $149.95! Now Both You and Your PC can be State-of-the-Art The Turbo-lOl Enhanced Keyboard gives " Great typing touch ... there's only you all of the features of IBM's newest key­ You Don't Have one DataDesk Turbo-WI-the first board standard (see above photo). It's ideal To Be A Brain Surgeon keyboard to challenge IBM products for word processing with its traditional seriously. "Selectric" typewriter layout featuring To Understand This Special Offer. Jim Seymour enlarged Shift, Enter and Control keys. ThinkTank is already a best seller at $i95. PC Magazine, January 1988 " Spreadsheet entry couldn't be easier be­ So it's easy to figure out that getting both cause we give you both a separate Cursor the critically-acclaimed Turbo-lOi keyboard and the ThinkTank software for the price of and Numeric keypad eliminating the need " The Turbo-WI can satisfy all ... it's to constantly toggle Nums Lock. And the the keyboard alone-$149.95-is a deal that turbocharges your PC without flattening your a rock-solid product that does double­ Turbo-101 's exclusive tactile-feedback keys duty and then some. let you type faster with fewer mistakes than wallet. And that's not all, our USA-made Turbo-Wi keyboard is so well built it carries Robert Luhn ever before. PC World, October 1987 " ThinkTank is the world's most powerful out­ a full 2-year warranty-which is probably a ! liner and idea processor. It will introduce you lot longer than your PC's warranty! But just II step-by-step to a fascinating new way of in case you are not completely satisfied, organizing and managing your ideas, your you can always change your mind, ~-­ time, your business, and even your thinking. with our no-questions-asked ~ ... ..---- 30-day money-bac~/ And to get you up and running quickly and INTERNATIONAL guarantee...... ---- H' Wh t easily we even include 30 predefined Think­ - eres a 7651 HASKELL AVENUE Tank Productivity Templates. ThinkTank is the Experts Think ... considered by many to be one of the most VAN NUYS, (A 91406 important productivity enhancers on a micro­ (818) 780·1673 BOTH computer. It turns thoughts into reality and " I really prefer the feel of the Data­ TURBO·101 ENHANCED ideas into results! Desk Turbo-WI. The keys have tactile KEYBOARD AND THINKTANK feedback. No mush at all. SOFTWARE FOR ONLY: Instantly Upgrade Your Productivity Jerry Pournelle The Turbo-lOl and ThinkTank are both Byte Magazine, August 1987 " Please add ShiP. - O. ·.. designed to instantly streamline and improve pIng and handling.$1~ CAi;)(~TI LB·'/'- .® .... ·.QP residents must also your computing performance regardless of include $9,75 sales tax which model PC, XT, AT, Tandy or com­ " Don't plop down your simoleons for for each keyboard, LIMITED OFFER patible you use. With our Turbo-l0l­ a Keytronic or others ... for ingenuity of Nome ______~ ______~ ______ThinkTank bundle, you'll feel the design and sheer dollar-value those from difference from the tip of your Company ___---:.. ______DataDesk can't be beat. fingers to the center of ...... ·C~\.\. Curt Suplee your brain. dO.~~a Washington Post, May 1987 " ~'i~PS1lio Phone ______~ Models also available lor the Tandy 1000, AT&T, PCjr and all Computer Type MacIntosh computers. ' Credit Cord No, ____..;...-_-,::. ~O~)~;~\~ "Limited offer with purchase 01 Turbo-101 enhanced keyboard. Exp; ______---::; All DataDesk International products are registered trademarks or trademarks of DataOesk International, Inc. Other brand and product names are trademarks or registered trademarks of their respective holders, Copyright 1987 DataDesk International. ~ Reader Service Number 8 ~.~"""-" ~-" IT'S WHAT'S UNDER THE HOOD THAT COUNTS!

XT KIT WI 2 Floppy Drives. Includes: 0K RAM, Serial, parallel and game ports, clock/calendar, AT-Style keyboard, cabinet, power supply, mono graphics card and amber or green monitor. Keyboard switchable turbo. 80386 KIT- 8 mhz with lock, LED, Reset & Turboswitch ...... 579.00 10mhz with lock, LED, Reset & Turboswitch...... 599.00

XT KIT W 120MB Hard Drive. Includes: 0K RAM, Serial, parallel and game ports, clock/calendar, AT-Style keyboard, cabinet, power supply, mono graphics card and amber or green monitor. Keyboard switchable turbo. Includes: 0K RAM, 1.2 MB FD, 1 360K floppy 8 mhz with lock, LED, Reset drive and 40 MB Seagate St 251 hard drive, . & Turboswitch ...... 879.00* 6/1Omhz, serial, parallel and game ports, clock/ calendar, AT-style keyboard, cabinet, power 10mhz with lock, LED, Reset supply, monographics card, amber or green & Turboswitch ...... 899.00* monitor, keyboard switchable turbo. - Pictured keyboard is 5339 - *(For 30MB Miniscribe add $50.00) 1595.00 KIT OPTIONS *MS DOS 3.21 or 3.3 w/ CASES & GW Basic ...... 95.00 HARD DRIVES POWER SUPPLY *5339 Keyboard Sub ...... , 24.00 *Color Options: & CONTROLLERS 150 Watt Power Supply (XT) ...... 50.00 (Includes & monitor) AT 40 MB Seagate #251-1 ...... 495.00 200 Watt Power Supply (AT) ...... 80.00 CGA Color ...... 200.00 XT Slide Case ...... 34.00 CGA/EGA Color...... 410.00 AT Hard Drive & floppy controUer (WD) ...... 140.00 XT Flip Top or XT Slide CGA/EGAlVGA Color ...... 590.00 20 MB Miniscribe HD with Lock & LED...... 38.00 ASSEMBLY AND TESTING XT Systems ...... , 60.00 with controller ...... 349.00 AT with Lock & LED...... 65.00 AT /80386 Systems ...... 80.00 30 MB Miniscribe HD MONITORS with controller ...... 399.00 EGA/CGA (Auto Switch) ...... 452.00 VGA/EGA/CGA Color ...... 600.00 SOFTWARE CGA Color ...... 295.00 MOTHERBOARDS The Twin Spreadsheet...... 49.00 Amber 12" TTL ...... 89.00 Leading Edge Word XTITurbo 4.77/10mhz ...... 109.00 Green 12" TTL ...... , 89.00 Processor ...... 49.00 AT 6/10 mhz (4 layer) Choice of Ventura Desktop VIDEO CARDS Phoenix or DTK Bios ...... 350.00 Publisher by Xerox ...... 525.00 Color IGraphics/Parallel ...... 52.00 XT/Turbo 4.77/8 mhz Turbo C by Borland...... 89.00 256K EGA Graphics ...... 125.00 (2 layer) ...... 99.00 Turbo Pascal V4 ...... 89.00 Mono/Graphics/Parallel ... ,...... 49.00 803868/16 mhzlAward Bios & A T! Graphics Solution- 1MB RAM, made in U.S.A ..... 1595.00 ACCESSORIES Mono, Here. Color Emulation on For XT I AT memory ...... $Call 1200 Baud Modem - Internal Mono CGA ...... (List 299) 125.00 FLOPPY DISK DRIVES (Leading Edge Model L) AT! Wonder Auto Switch Mono, Here Hayes compatible...... 99.00 Any monitor, Any software, Auto conversion Fujitsu 360K ...... 89.00 2400 Baud Modem - Internal CGA, EGA, VGA ...... (List 499) 299.00 Toshiba 360K...... 99.00 (Leading Edge Model L) EGA, CGA, PGA (64Ox480) ...... 185.00 Teac 1.2 MB ...... 125.00 Hayes compatible ...... 219.00 Toshiba 3Y1" Drive Kit 720K ...... 125.00 EXPANSION CARDS 1200 Baud Modem - External Toshiba 3Y1" Drive 1.44mb ...... 145.00 Hayes compatible ...... 119.00 Clock Card ...... , 25.00 KEYBOARDS V20-8mhz ...... 14.00 Dual Floppy Disk Controller ...... 25.00 Memory Chips ...... (call for prices) Joystick ...... 25.00 5339 Professional XT-AT Gravis Analog Joystick...... 49.95 w/12 function key ...... 69.00 Game Port...... 19.00 5060 Keyboard AT Style ...... 55.00 BUILDING YOUR Multi-Function, 1 ser/par/clk/gamel KB 101 Keytronic ...... '" 6 7 .00 OWN CLONE ****FREE BOOKLET**** 2 floppy ...... 61.00 Free Instructions with Each System Parallel (printer) ...... 19.00 *90-day warranty/30-day money back Serial Port (RS232) 1 port ...... 29.00 (subject to restrictions) 640K RAM (0K installed) ...... 35.00 XT/AT RS232 MicroSphere, Inc. (4 port/2 installed) ...... 59.00 P.O. Box 1221 Bend, Oregon 97709 Prices are subject to change without notice. (503) 388.. 1194 '., Shipping CHARGES will be added. Hours: Monday.Friday ...... 9:00·5:30 Pacific Time 1IIiIiII.

2 MICRO CORNUCOPIA, #41, May-June 1988 THE MICRO TECHNICAL J OUR N A L MICRO CORNUCOPIA

MAY/JUNE 1988 - ISSUE NO. 41

Earl Hinrichs 48 C'ing Clearly 8 Graphics In 3-D (Part 1) Scott Ladd updates his review of C packages and then There's a lot more to three dimensions than gluing a updates us on memory model sizes. balsa-wood model to the face of your CRT. Earl tackles the nits and grits (mathematics and chip manipulation) required to give depth to your flat screen. 54 86 World Laine returns to the U.S. and celebrates by building a Diane Ingraham, Gurmail Kandola, Mark Pillon keyboard translator. 16 Neural Networks Making computers think the - 58 ShareWare way you think isn't as easy as you might think. 62 On Your Own Paul Voda 22 The Logic Of 66 Pascal Column Programming Languages If you can prove mathematically that a language works and 71 Culture Comer prove that the program is valid, then you've proven the results. Unfortunately many languages are unprovable. 85 Technical Tips Bruce Eckel 30 The Mysteries Of RS-232 If you need connections in the computer world, let Bruce put in a plug for you (so all your handshakes will be successful). 72 CP/M Notes Larry Fogg 36 Intel's 8088 Kaypro Column Larry exposes PC brains in this, 73 his last look at the monster chips in the MS-DOS machines. .... • n - :: :r ...... ~~ Ramachandran Bharath ~- --".r...- : 42 How Much ...... ;:. .. " 82 Tidbits Information Does A .... Message Contain? Know anything about 96 LastPage information theory? It's that stuffy theoretical stuff they teach in graduate school. Right? Well, it's not so stuffy and it's not just for students anymore. Cover illustration by Paul Leatherwood

MICRO CORNUCOPIA, #41, May-June, 1988 3 By David Thompson TH£ MICRO TECHNICAL JOURNAL MICRO CORNUCOPIA

Editor & Publisher David J. Thompson Museum Pieces

Associate Editors Gary Entsminger Cary Gatton

Technical Department Larry Fogg

Director of Advertising There's something magic about climbing into a Stin­ Laura Logan son, a fabric and frame tail-dragger that's pushing the ragged side of 40. And there's even more magic when I Accounting bring to life its cranky old Franklin engine, six giant Sandra Thompson cylinders, 165 horses, sounding every bit like 600. Order Department Forty years ago Stinsons were fast, but since then the Tammy Westfall rest of the world has more than caught up. They were once the most popular plane in the air. Now they're Graphic Design rare enough to be a curiosity and wherever one goes, a Carol Steffy group gathers. "A friend had one of these. Once."._ "1 built a model Stinson when I was in the fifth grade. Or was it the sixth grade? I've always dreamed of flying in one." "Do you still fly it?" MICRO CORNUCOPIA (ISSN 0747-587X) is Occasionally a burled hand gently presses the var­ published bi-monthly for $18 per year by Micro Cornucopia Inc. 155 NW Hawthorne, nished fabric. The hand remembers another Stinson, Bend, OR 97701. Second-class postage paid perhaps. at Bend, OR and additional mailing offices. The plane is quiet too. POSTMASTER: Send address changes to MICRO CORNUCOPIA, PO Box 223, Bend, "It used to have a wooden prop," I tell them: "But a OR 97709. rough landing shortened it a bit." That happened before the Stinson and I met, and I've often wondered how it flew with that hand-rubbed, SUBSCRIPTION RATES: 1 yr. (6 issues) ...... $18.00 wood-grained prop. Better, I think. 2 yr. (12 issues) ...... $34.00 You can tell the pilots from the non-pilots. Pilots 3 yr. (18 issues) ...... $48.00 know that props suffer occasionally and let it pass. 1 yr. (Canada & Mexico) ...... $26.00 1 yr. (Other foreign) ...... $36.00 Non-pilots glance at the gray-metal replacement and Make all orders payable in U.S. funds on a then, casually, move away. U.S. bank, please. They needn't worry, I'm not offering rides. CHANGE OF ADDRESS: Please send your I remember one afternoon. I was preparing to depart old label and new address. . from a wind-torn coastal airstrip and was trying to MICRO CORNUCOPIA wrestle the Stinson away from a fence when a gnarled P.O. Box 223 wisp of a man approached. Bend, Oregon 97709 "Could you use a hand?" "Great," I shouted against the gale, wondering if he CUSTOMER SERVICE: for orders & sub­ could really help. But together we moved it. Then, as he scription problems call 503-382-5060, 9 am to 5 pm, Pacific time, M - F. held the quivering frame I jumped in and cranked up the Franklin. For technical help call 503-382-8048, 9 am to noon, Pacific time, M - F. As the ancient bird and I rose from the runway I spotted the old man, standing alone by the fence, the RBBS - 24 hrs. 300-1200-2400 baud damp coastal wind whipping at his thin clothes. I 8 Bits, No Parity, 1 Stop Bit 503-382-7643 waved, the Stinson dipped a wing, and we were gone. I think he would have liked a ride. Metal prop or not. Copyright 1988 by Micro Cornucopia Inc. All rights reserved ISSN 0747-587X

(Continued on page 77)

4 MICRO CORNUCOPIA, #41, May-June 1988 Interlocking Pieces: ]ffin~n§e~Iffi@ 1funrrlb)(Q) JP~§(C~no

Whether you're a Turbo Pascal expert or a novice, you can benefit from using professional tools :, Turho P'CHVER SCREEN " $129.00 to enhance your programs. With Turbo POWER TOOLS PLUS™ and Turbo ASYNCH PLUS~ , NEW! General screen managemerit; paint:,' Blaise Computing offers you all the right pieces to solve your 4.0 development puzzle. :screens; blocknlodedata entrY or'fieJd·by~·: . . fieIdcontrol with instant screen access; Now, '. Compiled units (TPU files) are provided so each package is ready to use for Turbo Pascal 4.0, soon forC and llASIC.' . c, with Turbo Pascal 4.0. Both POWER TOOLS PLUS and ASYNCH PLUS ~~~.... use units in a clear, consistent and effective way. If you are familiar ,'T~rboC'TO()LSC,'-': , ' .. ,< $129.()(r "" (J:!.~~,.~~;;J with units, you will appreciate the organization. If you are just getting , Full spectrum of gerierarservice utility func- <,~; " , .... started, you will find the approach an illustration of how to construct tions including:windows;'rilenus; memorY ,:~.; resident applications; i'nterrupt service ': and use units. ~roll-::;" ~~ ,~.\...- lines; intervention code; and 'direct video,:', ':<'~~; " ~... ","'" ~ POWER TOOLS PLUS is a library of over 180 powerful functions , access for fast screen handling. I:orTurbo c,':;'; ;::"" ::: CJJ""'" .' and procedures like fast direct video access, general screen , ,", . ~ '. handling including multiple monitors, VGA and EGA 50-line ':":CTOOLSi~LU~r <-',$1~9.VO:\:::~~i<>: , :Windo.,ys;menusiJSRs; inierV~ntionc~de:', ::;"';::~~,~; (,: ~ .,":;'~ and 43-line text mode, and full keyboard support, including , ,screen handling and EGA 43-line tex{mode ": ~;'::' ':,: '. , .. " ~"""'"~ the 101II02-key keyboard. Stackable and removable win- , support; dire<;t screen access: DOSfile'hari~:.::: ~' :".'~; ,:' dows with optional borders, titles and cursor memory ,dling:and more. Specifically designedJor~;., 7, ,::, . complete windowing capabilities. Horizontal, ver­ ,:· C 5.0, andQ~ickC;:;;:. ',', :,.': ,',r' ~;", '.; ;,', ;:"~»:"':, ': , grid and Lotus-style menus can be easily incorporated ~', ',;,ASYNCH MANAGER: ':<·"'~${/5.00~,·(f;::~'~' ,?:. into your programs using the menu management routines. ,F,ull featured interrupt driVen $ttpport forthe:",.;,,:,:];,:,,: ::~ You can create the same kind of moving pull down menus ' r:':;'XMODE~file'transfe'r~for¥icro~6{iqand::'';;~,;::';,;;::';" Control DOS memory allocation. Alter the Turbo Pascal heap ;';:TurboCorMSPascat ':,,', ::":':..""t/,"" size when your program executes. Execute any program from within your program and POWER TOOLS PLUS automatically l.. '.. ·,:,'PASC~'TOOL~iTOOLS;2:':$i7{:drit~t;~;~;~;h· compresses your heap memory if necessary. You can even force ~. ,:'; Expaf!dedstringand screen hiu;'::; '::.; -,", 1;',,: "" ks rOiltinys; memorY mimageioent; generat:'",~';~;:',( : the output of the program into a windowf ; .' . ,'programconirol; DOSfilesupportandmore::,~;,'.';,:,~ ;" ,::-". Write general interrupt service routines for either hardware or software interrupts. Blaise Computing's unique intervention I;;': ;;:y~li:::~Cat\"~" '-.;:::~;:~t.~i~:;,;)~~;;)" code lets you develop memory resident (TSRs) applications ;',;.;,~"Super.::batch': program; Creat~:RatP)i ~Ilesi::.;;.:;\;i)'.<, that take full advantage of DOS capabilities. With simple pro­ i-;."" ,.which,can invokeprograrnsandprQvldeiJlP4t',;~,ir: ;;( ',> cedure calls, "schedule" a Turbo Pascal procedure to execute I" ',to tllem; ni~~l1Y program:~na~ieftded.;"c,r~a~e:1:>; ;;:;',;;~'l ;';:, either when pressing a "hot key" or at a specified time. f '. " . ,demo,nstratlon programs; analyt!!Keyboaru';:; .',;" ";,;,::+' ¢ASYNCH PLUS provides the crucial core of hardware interrupts needed to support asynchronous data communications. This package offers l:$~:1~d.':)·.•• )2)?~t;:%~:;~'1t¥W~Si~~~f~ simultaneous buffered input and output to both COM ports, and up to four t :::.': : 'NEW VERSION! Program~hainU)gexecu;:::';<;";~n:;::':' ( ports on PS/2 systems. Speeds to 19.2K baud, XON/XOFF protocol, hard­ n:::':"tive. ,Ch~jn' ~)fle p'rogram' fr~m;anqther:)ti: ~,'.\:';;::;:;~"j)~; ware handshaking, XMODEM (with CRC) file transfer and modem control :) '-;':,differentlanguages; 'specify:,c()mmimi data.':-:;·;~';:", ;':;./ are all supported. ASYNCH PLUS provides text file device drivers so you can use standard "Readln" and "Writeln" calls and still exploit interrupt-driven communication. t:;'~f.~~~i;~fl~JI]!~~~9i~~%~~~~~1 f>: ;~:inTurbO pascal: flexibl6prirlter cohh'Qt;:us~ The underlying functions of ASYNCH PLUS are carefully crafted in assembler ['::' :"d~fin~d \tiu~hiblesi!itldex'gerieraJiorii::~iia :f;t.ne:.~~:=o~~[d;':~ these functions directly to your application i::(i;e;~~;!~;IT' ~~:~ty, \, :,i}:Dl~IJ~1;~~~ Blaise Computing products include all source code that is efficiently crafted, :.,:' TO ORDER C.Att rrOI,;:ttF~t,E:' re~:~J~~~6~~ ~::~~~~~l:J~~~~~~ r:~~~ ~i~ ~~=~~ E,c'~c::·,j:/,Z;~:'·,;.':~~.9'·~~~;~.~~~i:~f:a;;' '~r c code fragments. Many complete examples and useful utilities are !;.:·:-'i;::'·:P".:;~TELEX~MJMBEii~~3r 'Jt .' included on the diskettes The documentation examples and I:'<~"':':;'<:':""":-:<;'"'J .•...... v;~.·~'" source code reflect the attention to detail and ~ommitment to ;,}: ;;";/;'~.;:<;/;'~'~'}~::::}:' ':'~;,:;;·,\':0::·:;:~~':";~'~~£';';-;;';:·"""'· technical support that have distinguished Blaise Computing over ~.::,:,;-':::}:::",~2.:,: 0;;~ ~:,;,;;,~~~';,;;'''' - ...... the years. 1,,':":" .><", '_-- . Designed explicitly for Turbo Pascal 4.0, Turbo _---.... --~~;~:c;s\ COllies d~~ POWER TOOLS PLUS and Turbo ASYNCH _--- ndtUetheng ior~ourllro 1\ 00 ior ~.' PLUS provide reliable, fast, professional routines- , ~£S\ S~ is $~niorrnat\on. orders add $ ~ir. ____ the right combination of pieces to put your Turbo Pascal\ Bnc\O~e send tne tn~ 'I~. Dotnlt~ress standard ) ___- puzzle together. Complete price is 8129.00 each. , 0 \' e . dents add S~ior federal l'Phone: ~______\ c~reS\'~lng,$10, .. ______.... l1li,. \ U\'Sshlllll . ___ 'LW· Date:~ ...... \ Natne: State. £~ll' :. ~JI!: \ ~ddr ' BLAISE COMPUTING INC. \ ~~~~or~S~~~~~l~%f' : 2560 Ninth Street, Suite 316 Berkeley, CA 94710 (415) 540-5441 \._.... ~~,~: ' .. /. l,{,(~r;fli:l,~~ad~I1JCI~~;(JI;B9r~aJ1.d.I!J'tf!r[l,f;I Reader Service Number 5 .. ,', ;,:{·;::,,:\j':::"<:,}:·,:T:~<~:~, :";:5'o;?~{;,~. /:,., "-,"_«: it,;};~;,;~;\~~:.,>".;:,<;~.~:<". ;,'~ __ ';. ~.

C Vs. Assembly Language - One yields the following assembly code C with CodeView, a fine debugger. This letter is in response to the article when compiled with Microsoft C Verso MSC sports 31-character symbol C vs. Assembly Language in Micro C issue 5.0 using "cl-Fa -Gs test.c": names, and an excellent optimizer #40. with automatic register allocation, On the whole, I agree with Mr. ;misc constant declarations loop optimization, intrinsic code for Isaacson's assertion that a program is _DATA SEGMENT more common functions (such as more efficient when written in assembly _iop_name DB '/dev/iopmem/8alXO*',OOH strlen) as well as the more common language than in any other language. _DATA ENDS optimizations that Mr. Isaacson finds Additionally, I agree it can take less _TEST SEGMENT so trivial. time to develop the assembly language ;pre 5.0 MASM setup stuff Well-written assembly code can be program than the C version of the same PUBLIC _main more efficient, and certainly more fun program-given that well-qualified _main PROC NEAR to write. But portability, availability of programmers are working on each mov BYTE PTR _iop_name+19,99 maintenance talent, and client team. ret paranoia often preclude its use-not I take issue, however, with his ab­ _main ENDP without good reason. surd example. He makes several state­ _TEST ENDS ments about the C language that show William E. Weinman he knows as much about C as those This is equivalent to Mr. Isaacson's 1800 S. Robertson Blvd., Ste. 206 who write unmaintainable assembly one line of assembly language. To Los Angeles, CA 90035 code do about 8086 assembly language. write code like this requires a good un­ Most glaring is his statement justify­ derstanding of the language. Editor's note: Thanks Bill. And, thanks ing the construct: He points at the common I/O func­ for agreeing to speak at SaG (a talk en­ tions defined as part of many lan­ titled "C Isn't The Devil's Own iopmem [strlen (iopmem) - 1] = c; guages but implemented as functions Language"). in C. He says this is a defect of C; I see He says: "Because of the limitations it as an advantage. The code isn't C V s. Assembly Language - Two of the C language, it's impossible at linked in unless necessary, and I don't Mr. Isaacson raises a few good compile time to determine the location use it very much in a large system points in his article, but I must point of the last element of the fixed-length where I'm likely to use my own I/O out a few incorrect and unduly harsh array... " library. items. In fact, the sizeof operator is a unary Mr. Isaacson points to the terse na­ First let me say that C compilers, operator that, according to ANSI section ture of this small, elegant language as especially for PCs, have been greatly 3.3.3.4, "yields the size (in bytes) of its a fault saying, "that cryptic, incom­ improved in the last couple of years. operand... When applied to an operand prehensible code becomes easy to The code generated by Mr. Isaacson's that has array type, the result is the write," and that K&R "give some ex­ compiler doesn't look like the code total number of bytes in the array." amples (with a tone of approval!) of that comes out of Microsoft C vS. 5.0. Hence the following code: atrocious C programming technique." MSC doesn't save SI or DI unless Is C more cryptic than assembly? Is they're used in the function. It also 'define iop_user it difficult to write "atrocious" assemb­ leaves values in registers if con­ (sizeof (iop_name) - 1) ly code? Is K&R the Devil's program­ venient, which happens often with volatile char iOp_ name [ ] ming guide? Well, isn't that special. I pointers that are used more than once. \ "/dev/iopmem/8alXO*"; think Mr. Isaacson is not a C-literate It may be true that Mr. Isaacson's I main() programmer. compiler limited him to seven-charac­ ) { In his summary, he states that lack ter names. But a Unix port I've used of a debugger, short symbol names, allowed 32 characters while the as­ and inefficient code make C a poor sembler had an eight character limit. choice for large efforts. I· use Microsoft (Continued on page 70)

6 MICRO CORNUCOPIA, #41, May-June 1988 LIST OURS TURBO PASCAL ADD·ONS ASCII TURBO GHOST WRITER STARTER NEW 99 89 COMPLETE NEW 289 259 FEATURED PRODUCTS ~o~~ire?~~~!~ci~~~.u;~s~:l~bt'!rg~~~~i:~:r f~\\:::pf:~~~~~i~~0~[FOii!RA~~77~i~h~:~rlrs. A Ph~~~~AS~r{fN~) assembly language. (Requires List: $595 Special Price: $545 SPINDRIFT LIBRARY - Collection of 150 ~~~!~~et~u~tNgo~J~b~stf{Ey~OlKlr~;J SCREEN. The windowing system allows an unlimited number of windows to be defined on the screen. each having its own color, cursor position and border type. Supports automatic wrap and/or scrolling. List: $149 Special Price: $129 ~!~t~I~;~~;;. ~C;d:~m~~~~~~~:tl!b;;~~u~r fields and windows. multi· line fields. horizontal and vertical field scrolling. menus. help boxes. and custom field validation. List: $495 Special Price: $389 Programmer's Paradise Gives You Superb Selection, ~~t~pre~~vJ;i~~~i~i~~x~fi'i~~o!;J~~~~r~~nsa~;r~es code on DOS systems. Storage. retrieval. tracking and branching text files are effectively managed. Personal Service and Unbeatable Prices! List: $189 Intro PrIce: $169 Welcome to Paradise. The microcomputer software source that caters to your programming needs. Discover the Many Advantages of Paradise ... AZATAR DOS TOOLKIT NEW 99 85 DOS/BIOS & MOUSE TOOLS 75 69 o Lowest price guaranteed o Huge inventory, immediate shipment 0 Special orders FLASH·UP 89 79 METRABYTE DATA ACQ. TOOLS 100 89 o Latest versions o Knowledgeable sales staff 0 30-day money-back guarantee SCREEN SCULPTOR 125 95 SYSTEM BUILDER 150 129 IMPEX 100 89 Over 500 brand-name products in stock - if you don't see it, call! REPORT BUILDER 130 115 T· PLUS V. 4.0 SPECIAL 45 39 W/SOURCE NEW 90 79 TURBO.ASM 99 69 TURBO ASYNCH PLUS 129 99 TURBO GEOMETRY LIBRARY NEW 100 89 LIST OURS LIST OURS LIST OURS TURBO HALO 99 85 386 SOFTWARE CLIBRARIES FILE MANAGEMENT TURBO MAGIC 99 89 386·TO·THE·MAX NEW 75 65 C ASYNCH MANAGER 175 135 BTRIEVE 245 185 TURBO POWER TOOLS PLUS 129 99 ADVANTAGE 386 C OR PASCAL 895 829 C·FOODSMORGASBORD 150 95 XTRIEVE 245 189 TURBO POWER UTILITIES 95 79 DESQVIEW 130 109 C TOOLS PLUS/5. 0 129 99 REPORT OPTION 145 109 TURBO PROFESSIONAL 4.0 99 79 FOXBASE+ 386 595 CALL C UTILITY LIBRARY 185 125 BTRIEVE/N 595 455 TURBO WINDOW/PASCAL 95 79 HIGH C·386 NEW 895 835 ESSENTIAL COMMUNICATIONS 185 125 XTRIEVE/N 595 459 MICRO PORT SYSTEM COMMUNICATIONS PLUS 250 189 REPORT OPTION/N 345 269 SCREENS/WINDOWS V/386 (COMPLETE) 799 679 GREENLEAF C SAMPLER 95 69 CBTREE 159 139 C·SCAPE 279 265 MSWINDOWS/386 SPECIAL 195 125 GREENLEAF COMM LIBRARY 185 125 C·TREE 395 315 CURSES W/SOURCE CODE 250 169 NDP C OR FORTRAN·386 NEW 595 545 GREENLEAF FUNCTIONS 185 125 R·TREE 295 239 GREENLEAF DATA WINDOWS 225 155 PHARLAP 386IASM/LINK 495 419 MULTI·C 149 135 C·TREE/R·TREE BUNDLE 650 519 W/SOURCE CODE 395 259 SCO SYS V 386 (COMPLETE) 1495 1195 PFORCE 295 215 D·TREE NEW 395 CALL HI·SCREEN XL 149 119 VM/386 SPECIAL 245 179 RESIDENT C W/SOURCE 198 169 DBClIl 250 169 jYACC FORMAKER 495 449 X·AM 595 535 TIMESLICER SPECIAL 295 269 DBC III PLUS 750 595 jYACC JAM 750 679 TURBO C TOOLS 129 99 DILVISTA OR DB_QUERY 195 CALL 99 65 ARTIFICIAL INTELLIGENCE SINGLE USER W/SOURCE 495 CALL MS WINDOWS DEVELOPMENT KIT 500 319 ARITY STANDARD 95 79 COBOL MULTIUSER 495 CALL PANEL PLUS SPECIAL 495 389 MULISP·87 INTERPRETER 300 199 E·ZPAGE 295 259 MULTIUSER W/SOURCE 990 CALL PANEL/QC OR /TC 129 99 MICRO FOCUS SCREENSTAR W/SOURCE 198 169 PC SCHEME 95 85 900 729 INFORMIX PRODUCTS CALL CALL TURBO PROLOG 100 69 COBOLl2 249 229 VITAMIN C SPECIAL 225 149 COBOL/2 TLSET 900 729 PHACT MANAGER TURBO PROLOG TOOLBOX 100 69 XQL 795 599 VC SCREEN 99 79 PC·CICS 1500 1189 VIEW MANAGER 275 199 LEVEL II COBOL 349 279 FORTRAN COMPILERS WINDOWS FOR DATA 295 CALL ASSEMBLERS/LINKERS 149 119 ADVANTAG E DISASSEMBLER 295 279 PERSONAL COBOL LAHEY FORTRAN F77L EM/16 695 625 W/SOURCE 590 CALL OTHERS CALL CALL LAHEY PERSONAL FORTRAN 77 95 89 MS MACRO ASSEMBLER 150 99 700 449 ADDITIONAL PRODUCTS OPTASM NEW 195 169 MICROSOFT COBOL MICROSOFT FORTRAN 450 285 MICROSOFT SORT 195 129 595 479 ADVANTAGE VCMS 379 329 PASM86 195 115 RM/FORTRAN BASTOC 495 399 495 279 OPT·TECH SORT 149 105 PJ..[NK86PLUS REALCICS 995 785 FORTRANLIBRARIESIUTILITIES REALIA COBOL 995 785 DIAGRAM'ER OR DOCUMENT'ER 129 115 BASIC W/REALMENU 1145 899 GRAFMATIC OR PLOTMATIC 135 119 DB/LIB 139 119 950 759 MAGUS NUMERICAL ANALYST 295 249 XENIXIUNIX SOFTWARE FINALLY! 99 89 RM/COBOL RM/COBOL·85 1250 999 MATHPAC 495 445 MICROPORT & SCQ PRODUCTS CALL CALL FLASH·UP SPECIAL 89 75 395 315 SPINDRIFT LIBRARY SPECIAL 149 129 ADVANTAGEC++ 695 625 MACH 2 75 59 RM/SCREENS SCREENIO 400 379 SSP/PC 350 269 BTRIEVE/N 595 455 MS QUICKBASIC 99 65 DIRECTORY SHELL (286) 349 315 QUICKPAK 69 59 COMMUNICATIONS GRAPHICS DIRECTORY SHELL (386) 495 445 QUICKWINDOWS W/SOURCE 99 89 ASCOMIV 195 175 ADVANTAGE GRAPHICS (C) 250 229 EPSILON 195 149 TRUE BASIC 100 79 CARBON COpy PLUS 195 159 ESSENTIAL GRAPHICS 250 189 FOXBASE+ 795 729 TURBO BASIC 100 69 CO·SESSION (2 USER) NEW 249 225 GSS GRAPHIC DEV. TOOLKIT 495 375 INFORMIX PRODUCTS CALL CALL TURBO BASIC TOOLBOXES 100 69 SUPPORT NEW 175 155 HALO 300 209 jYACC FORMAKER 895 809 APPLICATION NEW 125 115 HALO (5 MICROSOFT LANG.) 595 399 JYACCJAM 1350 1219 PTEL 50 45 METAWINDOW PLUS 275 229 KORNSHELL 145 115 SIDETALK 120 89 TURBOWINDOW/C 95 79 MICROSOFT LANGUAGES CALL CALL MOUSE PRODUCTS DEBUGGERS TURBO HALO (FOR TURBO C) 99 79 PANEL PLUS 795 675 LOGITECH SERIAL OR BUS MOUSE ADVANCED TRACE·86 175 119 MODULA·2 RM/COBOL 1250 949 W/PLUS, SOFTWARE 119 99 PERISCOPE I SPECIAL 345 269 LOGITECH MODULA·2 RMiFORTRAN 750 549 W/PLUS, LOGICPAINT 149 119 SPECIAL 175 135 WINDOWS FOR DATA 795 CALL PERISCOPE II COMPILERDEVELOPMENT KIT SYSTEM 24999 19979 .....______-.1 W/PLUS, LOGICADDMOUSE 189 149 PERISCOPE 1Il8 MHZ SPECIAL 995 789 W/PLUS, PUBLISHER MOUSE 179 145 PERISCOPE 1Il10 MHZ SPECIAL 1095 869 rom~T m m W/PLUS, PAINT, CADD 199 159 PFIX86 PLUS SPECIAL 395 199 SOLlDB+ TOOLBOX NEW 99 89 DAN BRICKLIN'S DEMO PROGRAM 75 59 W/PLUS, CADD PUBL.MOUSE 239 189 DEMO PROGRAM II 195 155 DISKIDOS/KEYBOARD UTILITIES STONYBROOKMODULA·2 195 169 W/PLUS, PAINT, PUBL.MOUSE 199 159 W/UTILITIES 345 299 DB2C 299 CALL W/PLUS, PAINT, CADD. PUBL. 253 205 ADVANCED NORTON UTILITIES 150 99 FLOW CHARTING II 229 205 LOGITECH SERIES 2 W/PLUS 99 79 COMMAND PLUS NEWV.2.0 80 69 OBJECT·ORIENTEDPROGRAMMING MAGIC PC 195 179 MICROSOFT SER OR BUS MOUSE 150 99 DISK OPTIMIZER 70 65 ACTOR 495 419 MKSTOOLKIT 139 115 W/EASYCAD 175 119 FETCH 55 45 ADVANTAGE C+ + 495 479 MKSRCS NEW. SPECIAL 189 169 WIMS WINDOWS 200 139 NORTON COMMANDER 75 55 PFORCE + + 395 215 MKS·SQPS NEW 495 469 PC MOUSE BUS W/PNT & POPUPS 179 129 PC TOOLS DELUXE NEW 80 69 SMALLTALKIV 100 85 NORTON GUIDES 100 65 PC MOUSE SER. W/PNT & POPUPS 159 115 PDISK 145 105 SMALLTALKIV286 NEW 200 169 PC·LINT SPECIAL 139 95 SUMMAMOUSE 119 99 VFEATURE 80 75 APPLICATION PACKS 50 45 POLYMAKE 149 129 EDITORS OPERATING SYSTEMS POLYTRON PVCS CALL CALL CCOMPILERS 195 CALL MICROPORT SYS V/AT 549 469 PRE·C 295 159 LATTICEC SOO 269 W/DBRIEF 275 CALL SCO XENIX SYSTEM V 1295 995 SOURCE PRINT 95 75 MICROSOFTC 450 285 EMACS 295 265 WENDlN·DOS 99 79 TREE DIAGRAMMER 77 69 QUICKC SPECIAL 99 65 EPSILON 195 149 OTHER MICRO PORT. SCO, TURBOC 100 65 KEDIT 12.5 99 WEND IN PRODUCTS CALL CALL MKSVi 75 69 CINTERPRETERS MULTI·EDIT NEW 99 89 PASCAL COMPILERS C·TERP 298 229 PC/EDT 250 229 MICROSOFT PASCAL 300 189 INSTANTC 495 379 PM ATE 195 115 PASCAL·2 259 CALL RUN/C 120 79 SPF/PC 245 185 TURBO PASCAL 100 69 RUN/C PROFESSIONAL 250 155 VEDITPLUS 185 129 TURBO PASCAL DEV. LIB. 395 289 BORLAND ADD·ONS CALL CALL Terms and Policies • We honor MC, VISA. AMERICAN EXPRESS No surcharge on credit card or C.O.D. Prepayment by check. New York State residents add applicable sale. 1-800-445-7899 :~~T.J. ::~~~:~Fe..il~~·r~:. UPS In NY: 914-332-4548 • Programmer's Paradise wiD match any current nation .. Customer Service: :~~~e~10fl~~ ~:bj~t~~!~:::n~:. • Hours 9AM EST -7PM EST 914332-0869 • We'U Match any NationaUy Advertised Price • Mall Orde" ,,,dude '0'" pIlo", ,.... "ber International Orders: ·Ask for details. Some manufacturers will not allow return$ once dis.k seals are broken. 914332-4548 Dealers and Corporate Buyers-'Call for Telex: 510-601-7602 A Division of Hudson Technologies, Inc. special discounts and benefits! 1Pou~" Reader Service Number ~8 42 River Street, Tarrytown, NY 10591 The 34010 is the fastest, smartest, most gung ho video controller ever devised (at Graphics In 3-D: least by TI). Since it's so smart and fast it may as well help with the chores-chores like creating 3-D images. Here's part one of Ray Tracing On The 34010 -, Part 1 a very significant two-part series.

hile ray tracing provides the motivation and examples, the W principles that follow apply to any three-dimensional computer gra­ phic program. I'll supply 34010 assembly language code which implements the geometric principles. Some if-then conditions will help you navigate through the paragraphs. If you're not at all interested in programming, you can easily skip the programming sections. I've separated each topic into theory and program-

8 MICRO CORNUCOPIA, #41, May-June 1988 By Earl Hinrichs - PC Tech P.O. Box 128 Lake City, MN 55041

ming parts, and the programming sec­ So let's get to it. the obvious choice for this project, but I tions can be skipped without losing the We can represent an arbitrarily com­ prefer 32-bit signed fixed point. Fixed continuity of the theory section. plex object as a collection of polygons, point arithmetic is much faster than If you are a programmer, you can and assign each object a color. floating point with the same number of use the 34010 examples as suggestions Pick a pixel (or dot) on the screen bits. Accuracy in either case depends on for creating a program on your favorite and draw a line from the eye to that the number of bits. CPU or in your favorite language. I as­ pixel. This type of line, defined by a Fixed point won't, however, let us sume you have no prior knowledge of starting point and a direction, is a ray. work on just any scale (floating point the 34010 and explain each 34010 in­ Extend the ray through the screen will), so the fixed point implementation struction I use in the examples. into space. Determine the first object I'm using here will only give valid This isn't a 34010 primer! The most that the ray intersects (see Figure 1). As­ results if all values stay within a 32-bit interesting programming instructions, sign the pixel the same color as that ob­ range. But 32 bits will be plenty. such as pixblt operations, XY address­ ject. Do this for every pixel on the Select a screen size which enables ing, and window violation interrupts screen. The resulting image will show each pixel to be about 1000 times larger are not used here. See the TMS34010 one view of the imaginary computer than the smallest number we can repre­ user's guide if you're serious about universe. sent. This will guarantee that any round learning 34010 programming. To create different views of the off error is far smaller than anything we If you're an experienced 34010 programmer, I don't want to hear about bugs in the code, or better ways to im­ Figure 1 - Representation of an object on the screen. plement these ideas. Part of my job is to convince my editors I'm an authority in OBJECT SCREEN EYE this area. I don't want any wisepersons messing up that myth. And don't give up on this article if you find the start too elementary. That will change before the end. Everyone, regardless of skill background, should find something of significance in here. PIXEL Ray Tracing Imagine an eye floating in space. If you draw a line from it, the first object it meets is the first thing you'd see if you looked along that line. The idea is so simple it's embarrass­ universe, move the eye and screen can display on the screen. ing. But it's important enough to stimu­ around. To make things more interest­ We place objects so that the typical late many interesting computer pictures. ing, you can move and alter objects or distance between them is on the order In our computer implementation, the make them reflective, so that rays of 1000 pixels. This means there are eye will be a point and the computer bounce off and continue on in other plenty of pixels to resolve the object, screen a rectangle in space. The com­ directions. The resulting game of light and the scene will fill the screen. puter universe will consist of a group of ray billiards generates even more fas­ So the size of the objects and the dis­ simple mathematical objects-spheres, cinating pictures. (Editors note: Earl tances between them are about planes, and rectangles. generated the graphic on the facing page 1/1000th of the largest number that can After you've learned the ropes, you using PC Tech's 34010 board.) be represented. And there's enough can add other kinds of objects to the room to avoid overflow errors. program (if you know the mathematical Arithmetic equation describing the object). Floating point arithmetic may seem

MICRO CORNUCOPIA, #41, May-June 1988 9 Fixed Point the form "Operation Source, Destina­ x = (x + a / x) / 2 In fixed point representation, we use tion." The source comes first then the If we run this long enough, x will be­ regular integers, but imagine a decimal destination. For example "add aO, al" come the square root of a. Figure 3 com­ point (binary point?) at some fixed loca­ adds aO to a1 and stores the result in a1. putes the square root. tion. The fixed point will be set to the This requires some adjustment for The push instruction has a strange right of bit 16 here. programmers used to Intel processors. name, mmtm. The first instruction in Thus we can represent numbers from We use double registers in the multi­ 16 16 Figure 3 is "mmtm sp, a4, a5, a6." This -65535 to +65535 (_2 to 2 ) with a ply and divide instructions. Double 16 instruction says to push registers a4, a5, resolution of 0.00002 (2- ). registers are even and odd pairs with and a6. mmtm stands for "move multi­ Let "A" be a real number, and sup­ the even register holding the most sig­ ple to memory." The pop instruction is pose "a" is the integer representation of nificant bits. For example "mpys aI, aO" mmfm for "move multiple from· "A" in the computer. Then "A" and multiplies a1 and aO and puts the top 32 memory." "a" are related by the simple formula- bits in aO and the bottom 32 bits in a1. ''btst'' is the bit test instruction. Figure 2 is the implementation of 32- 16 "dsjne" is the name TI gives to the loop A = a * 2 bit signed fixed point multiplication; 32- instruction; it stands for "decrement bit integer multiplication is one machine Suppose "B" and "b" are similarly skip jump not equal." instruction on the 34010. The result is 64 related, a representation of (A + B) be­ The instruction "dsjne a6, fs_OI" bits wide and is put into two 32-bit comes- near the end of Figure 3 will be skipped registers. 16 16 (A + B) = (a * 2 ) + (b * 2- ) 16 (a + b) * 2- Figure 2 - 34010 Fixed Point Multiplication and Division. So (a + b) is the fixed point repre­ sentation of (A + B). In other words, fxPt equ 16 idefine fixed point pOSition. fixed point addition is just simple in­ One equ 10000H iour representation of the number one. teger addition. Subtraction works the fxMu1tiply: same way. iOut: aO = aO * a1 For multiplication observe that- mpys a1, aO isigned integer multiplication sla 32-fxPt, aO iline up high order bits srl fxPt, a1 iline up low order bits 16 16 (A * B) = (a * 2- ) * (b * 2- ) or a1, aO i combine them 16 16 = (a * b * 2- ) * 2- rets Thus, the representation for (A * B) is fxOivide: iOut: aO = aO / a1 just (a * b) shifted right 16 bits. move a1, a2 isave divisor For division- move aO, a1 ibuild dividend in 64 bit register, iwith fxPt shift 16 16 sra 32-fxPt, aO ihigh order bits (A / B) (a * 2- ) / (b * 2- ) sll fxPt, a1 ilow order bits (a / b) 16 16 divs a2, aO isigned integer division b) * 2 ) * 2- «a / rets

So fixed point division is integer END or LISTING division followed by a left shift of 16 bits.

34010 Programming To get the fixed point result, the in­ if the result of the previous operation This will be the first time many teger result must be right shifted 16 bits. was zero. Otherwise it will decrement readers see 34010 program code, so I'll The 34010 doesn't have a double the a6 register and jump to fs_01 if a6 briefly summarize the 34010. register shift instruction, so separate isn't, zero. There are also "dsj" and The 34010 has 30 general purpose 32 shifts are done on each register. Then "dsjeq" instructions. bit registers, which are denoted AO - the results are combined with an OR. The first time I wrote 34010 code, I A14 and BO - B14. The shifts used provide 0 fill, so the un­ found myself drowning in registers. I The stack pointer can be denoted by used bits are effectively masked off. was used to Intel CPUs, which have a SP, A15 or B15. The division instruction in the 34010 relative shortage of registers. Some kind The B registers have special uses in takes a 64 bit double register and of convention on register usage has to the advanced graphic instructions. For divides it by a 32 bit divisor. The be adopted to successfully write a 34010 example, in the PIXBL T (pixel block quotient goes into a 32 bit register. program. transfer) instruction, the B registers con­ To avoid losing precision in the fixed The subroutines in this article use the tain the source and destination start ad­ point division routines, the shift is done following conventions. dress, the block size, and window first, then the division. The dividend is B registers are only used for the spe­ dimensions for clipping. left shifted 16 bits in the 64-bit register cial graphic operations. Subroutines When XY addresses are used, one of pair. The "sra" instruction is a sign ex­ return values in the low A registers, AO the B registers specifies the screen tending right shift. The register pair is A3. Arguments which can be origin. And when the source is a binary then divided by the 32-bit divisor. destroyed are sometimes passed in the array, the foreground and background Since that went so well, let's try a low registers. These registers are un­ colors are held in the B registers. square root, which we can compute defined when not used to return values. Instructions with two operands have with the iterative formula- Registers A4 - A7 are used as local

10 MICRO CORNUCOPIA, #41, May-June 1988 variables within a subroutine. They're are examples of vectors. always saved, and never used for pass­ You may have heard the expression P • Q = Px * QX + Py * Qy + pz * QZ ing arguments. that vectors have both length and direc­ The length of a vector, denoted I P I, AS - All are used to pass arguments tion. At first a point appears to have is defined by- to a subroutine. The values in AS - All neither length or direction. But the point are always preserved by the subroutine. gets a length and direction if we think IPI 2 = P • P = Px * Px + Py * Py A12 - A14 are used to pass argu;ments of it as being defined by the vector from + pz * pz which may change. The subroutine may the origin to that point. change the value of these registers, but We can add or subtract two vectors In other words, the Pathagorean not the meaning. by adding or subtracting their coor­ Theorem. For example, if a pointer is passed in dinates- The dot product can be used to com­ A12 to a subroutine, then the subroutine P + Q = (Px + QX, Py + Qy, pz + Qz) pute the angle between two vectors- The cos of angle between P and Q = (P • Q) / UPI * IQI) Figure 3 - Fixed Point Square Root As a consequence of this, we see that fxSqRoot: two vectors are perpendicular (at right icompute square root of a by iterating x = (x + a / x) / 2 angles) when P • Q = O. iout: aO = sqrt( aO ) mmtm sp, a4, as, a6 ;save registers which hold intermediate Informally, we represent direction by values. a vector. Sometimes mathematics and btst 31, aO ;test for negative argument computers require us to be exact about jrnz fs_OO ;if negative, refuse to compute square root. such things. In particular, since our movi 10, a6 ;Iteration limit, we'll be direction vector can have any length ;done long before this. there are an infinite number of vectors move aO, a4 ;Starting interation value move aO, as iRamember what number we're square which represent a given direction. rooting When forced to choose a particular one, fs_Ol: iStart of iteration loop move as, aO iGet a we'll choose the vector which has move a4, al ;and current x length one. We call vectors with length callr fxDivide ;aO = a / x one "unit vectors." add aO, a4 ;a4 = x + a / x sra 1, a4 ;a4 = ( x + a / x ) / 2 An arbitrary vector can be converted sub a4, aO ;compare with old x (sort of) to a unit vector by "normalizing"- sra 1, aO ;give or take a bit dsjne a6, fs 01 ;if not stable repeat move a4, aO- ;result to aO P = P / IPI fs 00: iimfm sp, a4, as, a6 ;restore soma registers. Given two vectors, P and Q, it's rets sometimes advantageous to break Pinto two components, one perpendicular to END or LISTING Q and one parallel to Q. We say the parallel component is the projection of Ponto Q. The condition of perpendicularity is the same as the dot may change the value of the pointer, P - Q = (Px - Qx, Py - Qy, pz - Qz) product being equal to zero. Two vec­ but the new value will still be a valid tors are parallel if one is a scalar multi­ If P and Q are points then P - Q is pointer. ple of the other. the vector which starts at Q and goes to These conventions are personal rules Mathematically, P. only. I present them here only as an ex­ Two types of multiplication are use­ planation of the register usage in this (1) P = Pl + P2 ful in vector arithmetic-one for multi­ article. You should adopt whatever con­ plying a vector by a number, the other where ventions fit your style of programming for multiplying two vectors. and the program you're writing. The first is called multiplication by a (2) Pl • Q = 0 scalar. Each coordinate of the vector is Three Dimensional Geometry Pl is the perpendicular component and multiplied by the number. The simplest object in geometry is a (3) P2 = c * Q point. An arbitrary point in the three c*P = (c*Px, c*Py, c*PZ) dimensional universe (called 3-space for for some number c. P2 is parallel to Q. short) is specified by three coordinates. Geometrically, this corresponds to The number c can be easily calcu­ = ( stretching or shrinking the vector. The We write P Px, Py, pz ) where P is lated, dot both sides of (1) with ~ the point and Px, Py, and pz are respec­ length of the vector changes but the direction does not. tively the x, y, z coordinates of P. P • Q = Pl • Q + P2 • Q We have to specify directions in 3- The second type of multiplication is o + (c * Q) • Q space. We can describe a direction by called the inner or dot product. Here = c * (Q • Q) D = ( Dx, Dy, Dz ), where Dx, Dy, and two vectors are multiplied and the So- Dz are the directions with respect to result is a scalar or number. The cor­ each axis. responding coordinates are multiplied c = (P • Q) / (Q • Q) Point and direction defined this way and the products are summed-

MICRO CORNUCOPIA, #41, May-June 1988 11 Thus, if P and Q are given, c can be FS = field size, 1 - 32 FE = extend option, 0 = zero fill, computed and so- 1 = sign extend F = field number, 0 or 1. P2 = c * Q I like to set the field sizes as follows: and SETF 16, 1, 0 P1 = P - c * Q SETF 32, 0, 1 The number c which arises in the Field 0 is 16 bit, sign extended; field above computations has an importance 1 is 32 bit. All the subroutines here as­ of its own. If Q is one of the standard sume these settings. Whenever the field unit vectors ( 1,0,0 ), ( 0, 1,0 ), or ( 0,0, size is changed, it's changed back to the 1 ) then c is just the x, y or z coordinate original setting as soon as possible. ofP. The 34010 move instruction has the A situation may arise where you form- need to change your frame of reference. If Q is one of the axis vectors in a non­ MOVE , , standard coordinate system, the value c where- Finally - is the Q coordinate of P. I like to think of Q as a measuring stick. I call the is the source operand Affordable Intelligence. process of extracting the number c, is the destination operand calibrating P with respect to Q. is the field operand F is either 0 or 1, if it's omitted zero TINY EINSTEIN Turning These Ideas Into A Program is assumed. Most of the move instruc- Since I chose a 32-bit fixed point rep­ The Expert System Shell resentation for numbers, we'll represent vectors by three such numbers. Figure 4 - Basic Vector Arithmetic • Create your own expert I chose not to pass vectors around in systems in minutes. registers. Instead vectors are always in . data memory and I pass memory pointers. A ;for intermediate values • With pulldown menus v'l'empO . space 60H and windows vector in memory consists of three 32- . text bit numbers in consecutive memory vMove: iOut: a9 = a8 • Context-sensitive locations. The pointer to the vector move *a8(px), aO, 1 points to the first number. move aO, *a9(px), 1 • Free example expert systems In the 34010, memory addressing is move a8(py), aO, 1 move aO, *a9(py), 1 • Tutorial by bits. So if a pointer is pointing to the move *a8 (pz) , aO, 1 x coordinate, then the y coordinate is at move aO, *a9(pz), 1 • Interactive full-screen offset 32, and the z coordinate is at off­ rets set 64 from the base. The following vAdd: definitions identify the individual com­ iOut: a10 = a8 + a9 • DOS access from shell move *a8(px), aO, 1 ponents- move *a9(px) , a1, 1 • Turbo Fast execution add a1, aO iPoint move aO, *a10(px}, 1 • Cluster, Trace, Explain px equ OOOOH move *a8(py) , aO, 1 py equ 0020H move *a9(py) , a1, 1 • For Diagnosing ... pz equ 0040H add a1, aO Simulating .. . move aO, *a10 (py) , 1 Memory references in the 34010 can move *a8(pz), aO, 1 Predicting .. . move *a9(pz), a1, 1 Planning .. . be made to any bit boundary, and can add a1, aO be for 1 to 32 consecutive bits. The move aO, *a10(pz), 1 Classifying .. . 34010 status register has two field size rets Training ... fields. The field size fields tell the 34010 vSub: and Monitoring systems. how many bits to read or write during iOut: a10 = a8 - a9 move *a8 (px) , aO, 1 memory accesses. move *a9(px) , a1, 1 When a memory value of less than sub a1, aO Only $49.951 (Plus $ 5 5/H) 32 bits is loaded into a 32-bit register, move aO, *a10(px), 1 move *a8(py), aO, 1 the 34010 will either zero fill the upper move *a9(py), a1, 1 Designed & implemented by bits or sign extend the value through sub a1, aO move aO, *a10(py) , 1 Gary Entsminger & Larry Fogg the upper bits. The SETF instruction sets move *a8(pz), aO, 1 the field size. move *a9(pz), a1, 1 Syntax is- sub a1, aO move aO, *a10(pz), 1 rets I"--c__ ~ _-I =1- SETF , , vDot: ACQUIRED INTELLIGENCE where- iOut: aO = a8 . a9 P.o. BOX 2091 • DAVIS. CA 95617 • (9161753·4704 mmt1II sp, a4

Reader Service Number 72 12 MICRO CORNUCOPIA, #41, May-June 1988 tions in the accompanying code involve Figure 4-Basic Vector Arithmetic, continued... 32-bit operations and so they end with ",1". Many addressing modes are pos­ move *a8, aO, 1 ;Multiply x components sible- move *a9, al, 1 calla fxMultiply R register move aO, a4 ;start accumulating sum *R indirect move *a8(py), aO, 1 *R+ post increment indirect move *a9(py), al, 1 -*R predecrement indirect calla fxMultiply ;Multiply y components Addr absolute add aO, a4 ;add to sum *R(disp) indirect with displacement move *a8(pz), aO, 1 move *a9(pz), al, 1 Here R is a register name, Addr is an calla fxMultiply ;Multiply z components add a4, aO ;return sum of products absolute memory address, and disp is a mmfm sp, a4 16-bit signed displacement. Nearly any rets combination of source and destination vScale: addressing modes is possible. ;Out: alO = a9 * a8 (a9=scalar, a8=vector) Figure 4 shows the 34010 implemen­ move *a8(px), aO, 1 move a9, al tation of vector arithmetic. The calla fxMultiply ;scale x component routine vMove makes a copy of a the move aO, *alO(px), 1 vector pointed to by as at the vector move *a8 (py), aO, 1 move a9, al pointed to by a9. calla fxMultiply ;scale y component v Adds adds as to a9 and stores the move aO, *alO(py), 1 results in al0. vSub subtracts a9 from as move *a8(pz), aO, 1 move a9, al and stores the result in a 10. Each coor­ calla fxMultiply ;scale z component dinate in a9 is added or subtracted from move aO, *alO (pz), 1 the matching coordinate in as, and the rets result is put into al0. vCalibrate: vDot returns the dot product of as ;Out: aO = a8 projected onto and calibrate by the unit vector a9 mmtm sp, a4, a8 and a9 in aO. as and a9 point to vectors callr vDot ;a9.a8 and aO is a number. vScale stores the move aO, a4 scalar multiplication of a9 and as in alO. move a9, a8 callr vDot ;a8.a8 a9 is a scaler, and as points to a vector. move aO, al vCalibrate returns the size of the move a4, aO calla fxOivide ;aO=(a9.a8)/(a8.a8) projection of as onto a9 as a multiple of mmfm sp, a4, a8 the length of a9. The result is returned rets in aO. vProjection puts the projection of vProjection: as onto a9 into the vector alO. v­ ;Out: alO = projection of a8 onto a9 Perpendicular puts the component of as mmtm sp, a8, a9 callr vCalibrate ;get projection multiplier perpendicular to a9 into alO. v­ move a9, a8 Normalize returns a normalized copy of move aO, a9 as in a9. callr vScale ;scale a9 mmfm sp, a8, a9 rets Compound Objects Now let's use vectors to build our vPerpendicular: ;Out: alO = component of a8 perpendicular to a9 descriptions of more interesting objects. mmtm sp, a4, a8, a9, alO A ray is half of a line; we define it by move alO, a4 movi vTempO, alO a starting point and a direction- callr vProjection ;temp = projection move alO, a9 Start S = (Sx, Sy, Sz) move a4, alO Direction D = (Dx, Dy, Dz) callr vSub ;subtract projection to get perpendicular mmfm sp, a4, a8, a9, alO I like to imagine a point starting at 5 rets and traveling out in direction D (see vNormalize: Figure 5). The position of this traveling ;Out: a9 = normalized as point at time t is given by- mmtm sp, a8, a9, alO move a9, alO move a8, a9 P = S + t*D callr vDot ;a8.a8 = square of size calla fxSqRoot ;size to aO where move aO, al movi One, aO calla fxOivide ;invert size t >= 0 is time. move aO, a9 callr vScale ; then scale In a strict mathematical setting, t is mmfm sp, a8, a9, alO just a number, and we say that t rets parameterizes the points on the ray. By END OF LISTING the way, if we also allow t

MICRO CORNUCOPIA, #41, May-June 1988 13 A Plane To the mathematician, anyone of The questions of intersection will be An arbitrary plane in space can be these is as good as any other. The answered by "when" rather than specified by designating a point on the programmer, however, will prefer the "where." The time parameter t will be plane, and a vector perpendicular to the last form. Imagine a rectangle in space in a plane. The point is the origin and is solving for t- standard orientation (see Figure 6), and denoted 0 = (Ox, Oy, Oz). The perpen­ t = (0 - 9 • H) I (D • H) suppose the edges are parallel to the X dicular vector is called the normal and is denoted N = (Nx, Ny, Nz). An arbitrary point P = (Px, Py, pz) Figure 5 -Ray Definition N lies on the plane if the vector, which starts at 0 and goes to P, is perpen­ dicular to N. The dot product can be used to determine when two vectors are per­ pendicular. A point P lies on the plane determined by the origin 0, and normal Nif- o

(P - 0) • H "" 0 A little algebra here will save us some time later on. The above formula will be the basis of a computerized test of whether a point lies on a particular plane. Consider the following equivalent forms- Figure 6 - Plane and Rectangle Definition (P - 0) • H = 0 P • H - 0 • H = 0 P • H = 0 • H o x _ee__ p and 6800/218/9 SOFTWARE SK*DOS - a powerful DOS for the 6809 ($75) or the 68000 ($140, incl. an editor, y assembler, Basic, utilities, code for a boot ROM, etc.) HUMBUG - a monitor/boot ROM, $50 - $75. OntER SYSTEM SOFT­ o and N are part of the definition of used to identify intersection. WARE including assem­ the plane. So the quantity 0 • N is fixed In ray tracing we want to know what blers, text formatters, editors, for any given plane. Set c = 0 • N, and object our ray intersects first. The time spell checkers, languages, then compute c when the plane is parameter answers this, so we often etc., all very reasonable. defined. don't need the actual point of intersec­ The test for whether a point lies on a tion. HARDWARE plane then becomes- Of course when we want to know A wide selection of single­ the point of intersection, we can easily board computers and sys­ P • H = 0 compute it from t. Just use the equation tems, from $275. for a point on a ray- The next question we ask is where COMBINATIONS does an arbitrary ray intersect the plane. P = 9 + t*D Package deals of fast and Recall that a ray is determined' by a powerful computer plus DOS starting point S and a direction D, and and more, from $350. the ray consists of all points P where- A Rectangle A plane is often too large an object. P = 9 + t*D Usually our flat objects will be rec­ tangles. A rectangle is embedded in a SOFTWARESYSTEMSCOR~ for some number t >= O. Thus we see a plane, so we add boundary information ray intersects a plane when- BOX 209· MT. KISCO, NY 10549 to the plane information to specify a 914/241-028~ rectangle .. (9 + t*D) • H = 0 Reader Service Number 40

14 MICRO CORNUCOPIA, #41, May-June 1988 and Y axes. Define the plane which em­ Second, the projection of the point beds the rectangle. onto the X extent must lie on the IItop" Locate C Bugs When we define a plane, the origin is side of the rectangle- arbitrary. Any point on the plane can before they Bite with serve as well as any other for the origin. (2) 0 <= «P - 0) • X) / (X • X) <= 1 This time pick the upper left comer of The same applies to the Y extent- the rectangle as the origin. Put a vector PC-lint on the top edge of the rectangle by (3) 0 <= «P - 0) • Y) / (Y • Y) <= 1 starting at the origin and going to the PC-lint will analyze your C top right side. Call this vector the X ex­ To find out whether a ray intersects programs (one or many modules) tent and define the Y extent along the a rectangle, first determine the point and uncover glitches, bugs, quirks, left side in a similar fashion. where the ray intersects the plane which and inconsistencies. It will catch A point, P, lies on the rectangle if it's contains the rectangle. Then ask subtle errors before they catch you. to the right of the origin but not farther whether the point of intersection lies on By examining multiple modules, to the right than the X extent, and the rectangle. PC-lint enjoys a perspective your below the origin and but not further compiler does not have. below than the Y extent. A Sphere : '.: ':::::. ~+: .. ::., . We can test this by verifying that the Representing a sphere is very numbers which come from calibrating straightforward. A sphere is given by a : .. :::::.::::::; .. ::: .. ,:. the vector from the upper left corner to center point, C, and a radius, r. We can ...... :.::;:; :. P with respect to both the X extent and use the dot product to measure dis­ ... :):(.: ...... the Y extent are between 0 and 1. tance. So a point P is on a sphere if- ::::::': A general rectangle isn't restricted to :':\: : ):': orientation with respect to the coor­ (P - e) • (P - e) = r2 ::: . :. ': .; ': : ': ... :: : :):.:' :. ::::::;::;;:".\.>:. ;:./:: H·:: : ::: •• '(:'r ;(» :<:: dinate axes. We can expand the descrip­ . Andrew Binstock, .The' C Gazette' tion of a rectangle in a standard posi­ By recalling the formula for a point on a ray we see that a ray intersects a tion in order to describe an arbitrary :':::';';:' :. rectangle. sphere at time t where- ::.: :~::.: .. U· :::: . First define the plane which embeds (S + t*D - e) • (S + t*D - e) = r2 the rectangle. We can no longer say ..... ".•.• ir .•••.•.•. '•.•.•••••••••••.•••••.••.•..•.•.••..••..•• which side of the rectangle is the top, so I'll spare you the details of the al­ just pick any comer to be the origin. gebra, but this can be put into the Connect two sides of the rectangle to standard form for quadratic equations- the point we picked for the origin; denote one the X extent and the other a*t2 + b*t + c = 0 the Y extent. :': .• :::.:::::: :: .. ;:L:::::::: :::::::: :;::':::::::: :.: :.:.':::::::: It doesn't matter which side you call where- Stephen D. Cooper, Blue Notes what, just remember to define the ex­ San Francisco PC Users Group a = D • D tents to start at the origin and go to the b = 2 * (D • (P - e» other comer on that side. The notion of c = (P - e) • (P - e) - r2 .. : '::::.:::-::::::::::;::::":::::::::': .. ' .. II.. :.':::::::). calibrating one vector with respect to so, another can be used to test whether a point extends beyond the X or Y ex­ 2 t = - b +/- (b - 4ac)1/2 tents. .' '...... In summary, we define a rectangle ~:/~:; ... '.: . by adding two vectors, the X extent and Part 2 I:;:;::;::::::::: Yextent- That's it for theory. In part two I'll .::\. get into the details of implementing Don Malpass, IEEE Software N, the normal vector, these ideas on the 34010. If you have 0, the origin, c, the plane constant (0 • N) questions that won't wait until next X, the X extent, and time, drop me a line (or two). @Q@i)~a ~@ffu\WJ~~ Y, the Y extent 3207 Hogarth Lane (The astute reader will observe that • • • Collegeville P A 19426 Nand c are redundant, in the sense that (215)584-4261 the rectangle could be fully defined from 0, X and Y. Nand c are carried PRICE: $139.00 first copy, $100 each along to simplify calculations.) additional, MC, VISA, COD, PA residents A point, P, lies in a rectangle if three add 6% sales tax, Outside USA add $15. conditions hold. First the point must lie Runs on MS-DOS, works with any C in the plane of the rectangle- compiler - direct support for 12 major C compilers including Microsoft 5.0, Turbo, (1) p. N = c C86+, Lattice, Datalight, Desmet PC-lint is a trademark of Gimpel Software.

MICRO CORNUCOPIA, #41, May-June 1988 15 Neural Networks Learning Systems Based On The Brain

clusions by associating many kinds of in­ processing, language acquisition, sequen­ During the edit I found myself talking formation. tial thought processing, and conscious­ with Diane Ingraham, one of the authors. A run-of-the-mill computer processes ness-far exceeds that of any known And during that discussion, talk turned to serially, yet more accurately and faster computer. the usefulness of the neural models. than a human being. It roars through cal­ What we've been talking about is a "We're using the model to help our culations at (often) amazing speeds while model, a simplified biological model, robot see." brains plod through simple math at a wherein the brain is a system of many in­ "I see." snail's pace. teracting parts whose overall state evol­ "For instance, the robot views a whole Though computers store knowledge ves (or changes) continuously. The way it desktop. We put an egg on the desk, then in megabytes, they can't draw on it evolves depends on the connections be­ replace the egg with a walnut. We tell the without specific instructions (i.e., a tween neurons. Not all neurons affect all robot what's unique about each scene. program). Meanwhile, given a few other neurons, and not all neurons which "Then we put the robot into a whole simple clues, a five-year-old child can affect each other, do so equally. new environment, put one of the objects recall relevant events quickly (by as­ Based on this model, work began in somewhere in the new scene, then ask it sociating). the 40's and 50's to model computing whether the new scene is more likely to con­ Human brain power-speech recogni­ devices around the neural network tain the egg or the walnut." tion, perception, vision, language theories. That work stalled in the mid- That's exciting. It's not that I'm espe­ cially into eggs or walnuts, but think about the possibilities for teaching machines to Figure 1- Small Neural Network & Neuron recognize objects, despite the fact that the objects may lie in new surroundings, or may make up only a tiny part of a scene. A SINGLE This is front edge stuff, folks. (Now, where's that egg illustration? Egg??? I think this computer's got its neurons on backwards.)

ach of us has a brain, a sophisti­ cated information processing sys­ Etem, which reads and interprets sights, sounds, smells, and feelings. Some computer scientists are trying to recreate this sophisticated "thinking" system by using brain cells (or neurons) to model devices. In our brain, billions of interconnected neurons communicate with each other via excitory and inhibitory electrochemi­ cal signals. This circuitry, (a network of seemingly simple cells) helps us see, hear, speak, learn, think, create, remem­ ber, and act. Although a human brain is a little slow (from a computer's perspective), it consumes little power and can process information in parallel. By parallel processing, our brains can draw con-

16 MICRO CORNUCOPIA, #41, May-June 1988 By Diane Ingraham, Gurmail Kandola, and Mark Pillon School Of Engineering Science/Simon Fraser University Burnaby, British Columbia Canada V5A 156

60's because of hardware and software working systems based on the simplest must learn by being taught. We can limitations. form of a brain's neural network. group the learning into two classes-as­ Computers simply weren't powerful In these artificial networks (or simula­ sociative learning and regularity dis­ enough to test the neural network tions) knowledge is stored in a pattern of covery. theories. (And, AI gurus Minsky and connections and weights which the net­ (1) Associative Learning-in which Papert were attacking the theories.) work uses for learning, processing, and the states of all visible units in a system Then, in 1982, John Hopfield showed generalizing from problems. are represented by a list of components that important problems could indeed be The nodes in an "artificial" neural (a pattern or vector) corresponding to the solved by neural networks. This led to a network represent processing elements, output of a unique visible unit. revival in neural network research and in and each can accept multiple inputs. The We train the system on a set of such the last three years there's been an ex­ operation of the nodes is determined by patterns by fixing or clamping the visible plosion of academic and commercial in­ differential equations (transfer functions) units to represent each pattern in tum. terest. Many companies are now funding which specify the change in output (with In the testing mode, we "show" part attempts to create neural networks in time) based on the input signals. The of a pattern to the neural net, and it com­ hardware as well as software. coefficients of these transfer functions can pletes the pattern by itself. For example, In this article, we'll briefly describe be modified following a '1earning" rule. suppose we teach the machine the pat­ how a neural network works, then go Although neural net models found in tern 1/10101" along with some other pat­ into the details of two useful models. the literature differ in the details of their terns. Then in the testing mode, it will structures, applications, and training pro­ reproduce the pattern, 10101, from a pat­ Neural Networks cedures, they all share the following: tern that uniquely defines it (for example, Neural networks are self-organizing • A set of processing units or "I 1 I"). systems of simple, interconnected neurons We can further classify associative processing units (See Figure 1). • An activation state, ai, on or off, learning into two categories depending One way to look at these units is to (high or low) of the system at on which part of the pattern we show the consider each as a representation of a time (t) determined by the states network in the testing phase: hypothesis about an input domain. The of all processing units (i) Auto-association-we show the hypothesis could be anything; but in its • An output rule to determine out­ system any sufficiently large set of ar­ simplest form, you might think in terms put, Oi, of a unit bitrarily chosen components of the pat­ of a two-state digital input/output sys­ • A pattern of connectivity among tern. Each pattern is then associated with tem (1s and Os). Neurons firing or not. all units showing both the connec­ itself, hence the name, "auto-association." The strength or weight of the connec­ tion and its associated weight, Wij For example, we could train a system tion between any pair of units could rep­ • An activation rule to find the new using a set of patterns representing resent the correlation between the two activation level' for a neuron photographs of our friends. hypotheses. based on its current state and the Then suppose that during the testing For example, if two neurons are con­ input it receives, Netij mode we show the system a picture of nected (can influence each other), we • A learning rule for modifying one of our friends now wearing sunglas­ give them a value of 1. If they aren't con­ weights ses. Ideally, the system will react, filling nected, we give them a value of O. • An operating environment in all the missing features of the picture Obviously, our brains are a bit more Each neuron or processing unit can (those covered by the sunglasses) and complicated than this, but even at this also be '1abelled" according to the role it come up with the right identification. level things can heat up fast. Fifteen plays: (ii) Pattern Association-where each neurons would require over 100 connec­ • Visible units-those that interface pattern is divided into two separate pat­ tions. Fifty neurons-well over a with the environment terns: the input pattern and the output thousand connections. • Hidden units-those that are un­ pattern. And our brain has billions of neurons! known to the environment The goal is to train the system to as­ Even a Cray wouldn't have a chance in a sociate input patterns with output pat­ brain-size network. So, naturally enough, How Do They Learn? terns. Then when we present an input researchers imagine smalli/artificial" net- Just like small children, neural nets pattern to the system in the testing mode,

MICRO CORNUCOPIA, #41, May-June 1988 17 it should generate the right output pat­ During the first phase, we supply an Unbelievable! tern. input pattern (for example, 110) to the (2) Regularity Discovery-where a input units, causing some output pattern machine learns regularities in the to appear at the output units. Unless input! output patterns. By building an in­ your neural net is a genius, the output ternal model of the environment, the net­ likely won't be the target pattern you work is able to recognize underlying want. structures. So, in the second phase, we calculate Creates commented source code and the difference between the target pattern listings from memory, COM or EXE files. Models and the output. (Using network jargon, Now that we've described neural net­ we say "calculation propagates back • CLARIFY UNDOCUMENTED works generally, we'll move into the from the output layer through the hidden CODE details of two simple neural net models layer to the input layer, modifying • EASILY MODIFY PROGRAMS that can be programmed on personal weights if necessary.") computers. The learning procedure alternates be­ SOURCERTM creates detailed com­ The first is a pattern associator which tween the first phase and the second mented listings and source code di­ can be trained to associate input patterns phase until the system learns to associate rectly suitable for assembly. Built in data the input pattern to the target pattern. analyzer and simulator resolves mul­ with output patterns. The second is a tiple data segments and provides Boltzmann Machine. (Hopefully, the thing converges.) detailed comments on interrupts and We can test the knowledge of the sys­ subfunctions, I/O ports and much more. Pattern Associator tem by looking at the input units of an Determines all necessary assembler The neural network in Figure 2 has an input pattern and verifying the output directives. Complete support for 8088 input layer, a hidden layer, and an out­ produced. through 80286, V20N30, 8087 and put layer. Each input neuron is con­ Units in any layer are updated 80287 instruction sets. No other prod­ nected to every hidden neuron and to synchronously. The equations we use uct comes close to the output quality of every output neuron. Each hidden during the first phase to calculate the net SOURCER. neuron is connected to every output input, the activation, and the output of neuron. each unit are as follows: In this version of the neural net The net input into an input unit i is

Figure 2 - A Three-layer Neural Net Used As A Pattern Associator.

INPUT OUTPUT PS/2 • AT • XT • PC • Clones LAYER LAYER • CHANGE & ADD FEATURES (VISIBLE) • CLARIFIES BIOS INTERFACES INPUTS OUTPUTS • SPECIFIC TO YOUR MACHINE FROM THE TO THE ENVIRONMENT ENVIRONMENT The bios pre-processor to SOURCER provides the first means to obtain ac­ , curate legal source listings for any bios! Identifies entry points with full explana­ tions. Resolves PS/2's multiple jumps ~ NEURON : for improved clarity. Provides highly de­ scriptive data labels such as "video_ mode" and "keybd_q_head," and much more. Fully automatic.

NEURON SOURCER $ 99.95* SOURCER w/BIOS Pre-Processor $139.95* model, there are no interconnections given by- ('OUTSIDE USA. ADD $15 SHIPPING; CA RES. ADD SALES TAX) within any layer. (Though the theory All our products come with a 30 day doesn't exclude these connections.) Neti (t) = Ii (t) + Bi money back satisfaction guarantee. Not The hidden neurons try to capture copy protected. To order or receive "higher-order" features characteristic of where Ii(t) is the ith component of the additional information just call! the inputs and outputs. These charac­ input pattern, and Bi is the bias of the ith 800-538-8157 x 811 800-672-3470 x 811 teristics cannot be extracted using simple input unit. (outside Calif.) (inside Calif.) pairwise connections between inputs and The total input into any hidden unit V COMMUNICATIONS outputs. and/ or output unit Ui is- 3031 Tisch Way, Suite 200, Dept. MC San Jose, CA 95128 A Learning Algorithm Neti (t) = I:(Wji * OJ (t)} + Bi j (408) 296-4224 The training rule for this model works

PS/2. AT. XT and PC are trademarks of IBM Corp. in two phases. where Wfi is the weight of the connection

Reader Service Number 62 18 MICRO CORNUCOPIA, #41, May-June 1988 from unit i to unit j, and OJ(t) is the actual pattern, say made up of three elements, temperatures iI:t the schedule can be output produced by unit j at a time t 101 for example. Then the model is help­ changed after every phase + using- when a particular input pattern is shown less if you input only 10_ or _01 or 1_1. to the net. One of the beauties of our own brains [energy of undamped units in phase-] The activation value of any unit is cal­ is that we can make inferences about Ti =------______culated by the logistic function- missing information. The Boltzmann [# undamped units inphase-](3/4)i-(3/20)] Machine is a version of neural net model 1 which can recognize patterns even (a relation that we find works). though the data is faulty or incomplete. It Learning Procedure: (1 + exp[-Neti(t»)) can "guess" what the missing elements 1. Set the Annealing Schedule are! In fact, it can even be trained using 2. PHASK - The Teaching Phase (O < adt) < 1} incomplete data. (Similar to human train­ (a) Clamp the input elements to the input ing.) neurons and the output elements to the The output function is simply a output neurons. threshold function- Background (b) Randomize the states of all the un­ Some background first: In 1982, John clamped (hidden) neurons. Odt) = 1 if adt) > 0.5 Hopfield proved that a network of sym­ (c) For each temperature Ti (not the equi­ =-1 otherwise metrically interconnected units would librium temperature) in the Annealing operate by the same mathematical rules Schedule, run the Boltzmann machine for The net input into any hidden or out­ as a ball rolling around on a bumpy sur­ t time units. After every time unit, update put unit is found from the following face. The network tends to settle into one the state of each undamped neuron k equation- of many stable energy states (where the using the probability decision rule: potential energy function has a local min­ Neti (t) = Wij (t) * OJ (t) + Bi imum) in much the same way as the ball 1 would settle into a dimple on the surface, Pk = If the output O(t) isn't equal to the tar­ refusing to move until someone or some­ get T(t), then the difference T(t)-O(t) thing gives it a poke. propagates through the system according This network is essentially a model of (Because we assumed that Boltzmann's to the following equations during the associative memory where each local energy distribution applies to our neural second phase. minimum in the energy function cor­ network behavior.) The error signal Oi(t) for each of out­ responds to an association being stored At low temperatures, the system tends put signal is determined by- in the network. to converge into the global minimum, A Boltzmann Machine is nothing but the time required to stabilize is very Ih (t) = [Ti (t) - Oi (t») * more than one of these Hopfield net­ long. On the other hand, at high adt) * [1 - adt) ) works that uses a special kind of poke temperatures it is more willing to make called "Simulated annealing" to get out uphill jumps so it reaches a stable state where Ti(t) is ith component of the target of local minima in order to settle into the faster. pattern T(t). globally minimum state, (or close to it). The best compromise is to start at a The weight for each connection into The trick is in how the interconnection high temperature and gradually reduce it output unit i is changed by- weights are updated. as the machine approaches "thermal To program a Boltzmann Machine equilibrium," a process known as simu­ Wij (t) = f * Ih (t) * OJ (t) you must set up an "Annealing lated annealing. (Annealing comes from Schedule" and then run through the the art of crystallizing metal-to get the where f is the learning rate (typically 0 < f Learning Procedure. best crystallization you alternately heat < 1). First the Annealing Schedule: and cool the metal until it hardens. Here, The error signal for a middle unit i is The Annealing Schedule is a set of you're alternately increasing and decreas­ found from- "temperatures" T and time units t as ing the activity of the model, trying to shown in the box below. reach the global minimum.) odt) = adt) * [1 - adt») * Bkk * (d) Now run the machine at the equi­ Wki(t) Annealing Schedule librium temperature Tq and update the Run the model for ti time units at units as in (c) above, except this time where 0 varies for all output units. modify the weights after each update The weights for all connections into Tq (decreasing) using: middle unit i are changed by- tq (increasing)

Wij (t) = f * Oi (t) * OJ (t) temperature Ti. The Tq is the equilibrium temperature. Initially the schedule might where Si is the state of unit i, and 0 is a Boltzmann Machine look like the one shown below. "small" positive real number, for example The first neural net pattern associator As the learning progresses, the 0=0.005. is an interesting model, but it is not of (e) Repeat 2 for the next pair of inputs much use unless you know all the ele­ and outputs (sometimes called the ments of the input and output patterns. 9.2 5.3 3.2 1.8 0.5 "vector"). What happens if some of the elements 2 2 4 6 10 3. PHASE+ - The Testing Phase are missing? That is, if you have an input (a) Clamp a part of the vector onto the

MICRO CORNUCOPIA, #41, May-June 1988 19 input units. (equilibrium temperature) be at which Fun Reading Suggestions (b) Same as 2(b) annealing is terminated? Amari, S., & M.A. Arbib (eds.), Com- (c) Same as 2(c) (4) Can the annealing schedule be petition and Cooperation in Neural Nets, (d) Same as 2(d) except now the weight modified after each learning cycle? lecture Notes in Biomathematics, Springer­ change is: Verlag, Berlin, 1982 Potential Applications Forsyth, R., & R. Rada, Machine Learn­ like a new wonder drug, neural nets ing Applications in Expert Systems and In­ have been suggested for solving an formation Retrieval, Ellis Horwood, J.Wiley 4. Repeat from 1. until the machine amazing array of problems, including, & Sons, 1986 learns; that is, when the output units pos­ but not limited to: Hinton, G., Learning in Parallel Net­ sess the expected states for several time • Exploration in space-planetary works, BYTE, April 1985 units in phase+. rover autonomous path selection, Hinton, G., T. Sejnowski, & D. Ackley, The process will alternate between the recognition of signals from ex­ Boltzmann Mnchines: Constraint Satisfaction 1/+" and "_" phases until the network has traterrestrials, teleoperator con­ Networks that Learn, Carnegie-Mellon found the global minimum. trols for building things in space, Technical Report: CMU-C5-84-119, 1984 (For those hardy souls who are inter­ space flight assistance, design of Hinton, G., T. Sejnowski, & D. Ackley, ested, the Appendix, pp.315-317, at the large space structures like space A Learning Algorithm for Boltzmann end of Chapter 7 in Rumelhart, et al, stations, pattern recognition, Mnchines, Cognitive Science, Vol. 9, pp 1986, actually derives the learning rule image compression (vector quan­ 147-169, 1985 for the Boltzmann Machine.) tization), atmospheric modeling, Hoppensteadt, F.c., An Introduction to Some interesting questions can be in­ fast threat assessment, damage­ the Mathematics of Neurons, Cambridge vestigated in programming a Boltzmann tolerant space-based computers University Press, Cambridge, 1986 Machine: • Military applications-battIe man­ lindsay, P. H., & D. A. Nonnan, (1) What should the temperature be at agement, target identification and Human Information Processing, Academic which annealing begins? recognition, self-guided tor­ Press, New York 1977 (2) How gradually is the temperature pedoes, submarine communica­ McClelland, J.L., D.E. Rumelhart & to be reduced? tions, autonomous spacecraft, the PDP Research Group, Parallel Dis­ (3) What· should the temperature cruise missile navigation, surveil­ tributed Processing Explorations in the lance Microstructure of Cognition Volume 2: • Civilian applications-vision, ro­ Psychological and Biological Models, A botic control, adaptive control, Bradford Book, MIT Press, Cambridge, prosthesis, fingerprint identifica­ MA,1986 tion, voice recognition, telecom­ McCorduck, P., Machines WIw Think, N£L!RRL munications, pattern recognition, W.H. Freeman & Co., New York, 1979 man-machine interfaces, associa­ Minsky, M. & S. Papert, Perceptrons, tive memory, robust or fault MIT Press, Cambridge, MA 1968 NET tolerant computers, complex Rumelhart, D.E., J.L. McClelland, & Netwurkz models a neural net in a simulations of physical, chemical, the PDP Research Group, Parallel Dis­ tutorial level program with source biological systems, language, opti­ tributed Processing Explorations in the you can change. It demonstrates cal computing, data processing Microstructure of Cognition Volume 1: an associative memory finding We don't know yet whether neural Foundations, A Bradford Book, MIT Press, nearest match to input word. Limit nets simulated in software or built-in Cambridge, MA, 1986 of 1000 neurons max. hardware actually think, but something Torras i Genis, c., Temporal-Pattern awesome occurs when you watch one learning in Neural Models, Lecture Notes in Netwurkz includes a complete work. Biomathematics, Springer-Verlag, Berlin, copy of PUD, the compiler 1985 language it is written in. PUD is easy to learn, offers control not in • • • C, and is faster.

Netwurkz $79.95 Neural Net emulator with source, Come See Micro C PUD compiler, and printed (At The West Coast Computer Faire) manuals. Add $75 for source of PUD. PC, XT, AT compatible with We're having a Micro Cornucopia booth at the West Coast Computer 256K. Faire A'pril7-10 at the Moscone Center in San Francisco. St

20 MICRO CORNUCOPIA, #41, May-June 1988 UAITE:n I I.

DISPLAY PAGING RECEIVER PC-LabCard FOR IBM AT IXT Designed for use in a nation-wide paging system • Dual conv. superhet 450 MHz crystal controlled receiver Multi-Lab Card...... $295.­ module (plug in modulel) (12 bit) NO + D/A + 010 + Counter • Twenty character alpha-numeric LED display (ASCII Encoded, ANSI character set) Super-Lab Card..... $495.­ • RCA COP 1802 Processor based display/mode controller (14 bit) AID + D/A + 010 + Counter Piezoelectric "beeper" unit APPLICATIONS: Digital 110' & Receiver module may be removed for other uses .. . Counter Card ...... $175.- Receiver could be recrystaled for Ham Radio Use .. . Possible to use for original application on Ham Bands ... Relay Actuator & Terrific source of parts ... Isolated Oil Card.. $239.- UNITS ARE COMPLETE BUT UNTESTED & SOLD "AS IS" Prototype 95 INCLUDING $19 SHIPPING Development Card .. $74.-

L1nON PROJECT BOX W/FAN RS-232 BREAK OUT BOX TRACKBALL • 31/2" x 71/2"x 9" • SWITCHABLE LINES • 250 CYCLES PER REVOLUTION • LED INDICATORS • 5 VDC OPERATION • 3" Fan • PATCH TERMINALS &JUMPERS • SPEC. SHEET INCLUDED • Perfect for mounting power • COMPACTSIZE $31 95 supplies or building projects 95 • Black Wrinkle Finish COMPUTER JOYSTICK $39. (IBM/APPLE COMPATIBLE) XEBEC 1410 SASI HARD DISK 95 95 CONTROLLER. $9. $1. 1995 $ 89.00 W/Fan W/OFan

AT/XT 4 SLOT MOTHER BOARD EXPANDER IEEE-488 HARD DRIVE INCLUDES: CONTROLLER HALF HEIGHT EXTERNAL • 4 SLOT XT MOTHERBOARD • ST506/412 Compatible DRIVE ENCLOSURE • Manufadured by Xebec • Attractive Low Profile • OPTIONAL AT CONNECTORS Chassis 19x15x2 3A • Great for the Experimentor • Fits nicely directly under PC • CABLING • Standard IBM Colors • Bezel for 511.' and 311z" Drive • CASE NOT INCLUDED $69 95 • GREAT FOR R&D ,95 $29

3 CONVENIENT LOCA TlONS: 3060 COPPER RD., SANTA CLARA 95051 WE SHIP C.O.D. HSC Electronic Supply of Santa Rosa HSC Electronic Supply 'A IL ORDERS Store Hours: 6819 S. Santa Rosa Ave. 5549 Hemlock St. _ M14 Mon·Fri 8:00·7:00 Cotati, CA Sacramento, CA ... (707) 792·2357 (916) 338·2545 Call NOW! (40B}732-1573 I added to cen .... cne<: •. I1I... donotsendcasl\.SOmellemshmlledtostockonhand. Reader Service Number 11

MICRO CORNUCOPIA, #41, May-June 1988 21 The Logic Of Programming Languages Proving The Compiler

The computer interprets the object x :=2; n :=5; Paul's an academic. He needs to prove program q in a way specified by the rela­ that something will work before he creates tion Evall. To trace the execution of the program it. After he carefully made the point that he This behavior can be captured in is simple enough, but ifs much harder to could prove, mathematically, that Trilogy terms of source programs by the relation deduce that the program computes the works, I asked him to do an article on prov­ Eval, which we can define as-Eval(p,i,o) value xl\n into the variable y provided n ing languages in general. Here it is. holds if and only if we have >= o. The underlying algorithm is called Compile(p,q) and Evall (q,i,o) for the ob­ a logarithmic exponentiation, and is the ject program q fastest way of computing integer powers. na broad sense, a program is a se­ The relation Eval (see Figure 4) quence of symbols used to control a Classical Procedural Programs specifies the formal semantics of L in the Imachine. The symbols can be charac- Now I'll formally describe a simple notation used first by Smullyan and later ters on a sheet of paper, holes punched procedural language called L, which con­ adopted for the programming language into cardboard, bits in a computer, a se­ tains assignment, if, and while state­ Prolog. quence of keystrokes, etc. ments. Figure 1 shows the syntax of the It goes like this. You can read a The computing "machine" can be a language, L, in the so-called Backus nor­ clause-- human performing computations on a mal form. sheet of paper, an automatic loom con­ We're not building a parser for L here A <- B, C, D trolled by a Jacquard card, an electronic so we can ignore the fact that our gram­ computer, or a hand-held calculator. mar is ambiguous. We've also omitted as "in order to establish the relation A, es­ We can use a mathematical conjecture the obvious definitions of variables and tablish the relations B, C, and D." Prolog called the Church Thesis to capture the numbers. programmers should have no trouble un­ meaning of programs for a specific com­ Consider the simple program L in derstanding the definition of Eva!. puting machine by means of a comput­ Figure 2. Figure 3 gives the result of trac­ Although you can visualize the defini­ able relation- ing the execution of the program with tion as a Prolog program, you really need input- know nothing about Prolog's computa- Eval (p, i, 0) Figure 1 - The Syntax of the Language L in BNF where p is a suitable encoding of a program, i is an input to the machine, and Expr :: = Variable I Number I Expr Oper Expr I (Expr) o is the output. Oper ::= + I - I * I / I < I = The relation Eval(p,i,o) holds if and Stats ::= Empty I Stat Stats Stat ::= Variable := Expr; I only if the machine obeys the instructions if Expr then Stats end; I of p by consuming the data i and halting if Expr then Stats else Stats end; with the output o. while Expr do Stats end;

Our programming languages are EJII) or LISTING based on variables, which are used in ex­ pressions, which are part of statements, which are grouped into subroutines. Figure 2 - A Program to Compute the Function Exp The relation Eval defining the mean­ ing of a program can be directly imple­ y := 1; mented in a computer in the form of an while n > 0 do interpreter, or in a decidable relation- n1 := n I 2: if 2*n1 < n then y := y*x; Compile (p, q) end; n := n1i x := X*Xi end: which holds whenever the object program q is obtained from the source program p EJII) or LISTING by a process called compilation.

22 MICRO CORNUCOPIA, #41, May-June 1988 By Paul 1. Voda - CompIete Logic systems Inc. 741 Blueridge Ave. N. Vancouver, B.C. V7R 2J5 Canada

tion method (called SLD-resolution). In using it in the process of establishing and only if) the program, liS," executed short-we instantiate a rule by replacing relationships. under the variable bindings given by all of its variables by constants before The Eval(s,bi,bo) relation holds iff (if ''bi'' stops with, possibly new, variable bindings, ''bo.'' We use a string representation of Figure 3 - A Trace of Program Exp Execution programs to emphasize that a program is a sequence of symbols. Strings are whiles executed & Y & x & n & nl decomposed with the help of "high­ powered" but obvious string pattern­ 1 & 1 & 2 & 5 & - 2 & 2 & 4 & 2 & 2 matching constructs. Alternatively, we 3 & 2 & 16 & 1 & 1 could have used lists to encode programs 4 & 32 & 256 & & ° ° in the so-called abstract syntax. Variable bindings are lists of variables END or LISTINQ coupled with their current values. For example-

Figure 4 -Eval. Definition [('x',2), ('y',l), ('n',S)]

Val('N',b,v) <- Number ('N' ,v) Editor's note: The symbols, [ and] enclose Val('V',b,v) <- Select(b,'V',v) Val('El + E2' ,b,vl+v2) <- Val('El' ,b,vl), Val('E2' ,b,v2) a list. Val('El - E2' ,b,vl-v2) <- Val('El' ,b,vl), Val('E2',b,v2) The relation Select(b,var,val) holds iff Val('El * E2' ,b,vl*v2) <- Val('El' ,b,vl), Val('E2',b,v2) the variable var is associated with the Val('El / E2',b,vl/v2) <- Val('El',b,vl), Val('E2',b,v2) Val('El = E2',b,1) <- Val('El',b,vl), Val('E2' ,b,v2), vl = v2 value val in the bindings b. The relation Val('El = E2' ,b,O) <- Val('El' ,b,vl), Val('E2' ,b,v2), vl v2 Newb(bi,var,val,bo) holds iff the bind­ Val('El < E2' ,b,l) <- Val('El' ,b,vl), Val('E2' ,b,v2), vl v2 Val('El < E2' ,b,O) <- Val('El' ,b,vl), Val('E2',b,v2), vl = v2 ings in bo are like bi but with the value val associated with the variable var. This Number ('D' ,v) <- Dig('D' ,v) relation obviously captures the effect of Number('ND',lO*v+d) <- Dig('D',d), Number('N',v) Dig('O' ,0) <- the assignment var := val. Dig(' l' ,1) <- The relation Val(exp,b,val) holds iff the value of expression exp computed Dig('9',9) <- under bindings b is val. Select ( [('V' ,v) It),'V' ,v) <- The meaning of programs in L is Select ( [('W' ,w) It], 'V' ,v) <- 'V' <> 'W', Select(t, 'V' ,v) given indirectly by the relation Eval. Eval('V := E; S' ,bi,bo) <- Nevertheless, this is a perfectly valid ap­ Val('E',bi,v), Newb(bi,'V',v,bb), Eval('S',bb,bo) proach and the programs are amenable Eval('if E then Sl else S2 end; S',bi,bo) <­ Val('E',bi,O), Eval('S2',bi,bb), Eval('S',bb,bo) to mathematical analysis. We can prove Eval('if E then Sllelse S2 end; S',bi,bo) <­ facts about the relation Eval. Val('E',bi,l), Eval('Sl',bi,bb), Eval('S',bb,bo) For example, let's denote by P the Eval('if E then Sl end; S',bi,bo) <- Eval('if E then Sl else end; S',bi,bo) while loop of the program in Figure 2. Eval('while E do Sl end; S',bi,bo) <- By using induction on the variable n Eval('if E then Sl while E do Sl end; end; S',bi,bo) we can easily prove that- Newb([('V',w) It), 'V', v, [('V',v)lt) <- Newb([('W',w) It), 'V', v, [('W',w) Itt)) <- 'W' <> 'V', If n >= ° and p is the smallest Newb(t, 'V' ,v,tt) number of the form p = 2 A k such that p >= n then, END or LISTINQ

Eval( & 'P', & [('y',y), ('x',x), ('n',n),

MICRO CORNUCOPIA, #41, May-June 1988 23 ('nl' ,nl) J, Declarative Languages logic and efficiency, say at the level of & [('y',y \times xA{n}), We can assign meaning to programs Pascal. The programming language C ('x' ,XA{p}), ('n' ,0), ('nl' ,O)J)' independent of a computation machine will probably stay with us ;'Is a system only if we restrict ourselves to a special implementation language, but we're con­ Thus the program y:=l; P computes kind of programming language called a vinced that most a pplications can be y = xAn. declarative language. We can interpret written in declarative style. declarative programs as functions or as Trilogy is a new declarative program­ Schools Of Semantics relations. ming language in which we've combined Our definition of semantics for L is In the former case we obtain function­ our theoretical research experience in the called definition by an abstract machine al languages (for instance Lisp), in the area of programming language semantics giving the operational semantics. la tter case we obtain logic languages (for with the practical experience of compiler A school of semantics called the instance Prolog, Trilogy). Functions and writing. denotational semantics was very influen­ relations are legal mathematical objects Trilogy is a language firmly based on tial a decade ago and claimed that opera­ treatable by methods of mathematical predicate calculus. Its programs are col­ tional semantics isn't a proper semantics logic. Declarative programs obtain their lections of predicates (relations). Trilogy because it tells us only what a program meaning via the standard logical method combines the areas of procedural, does without telling us what the of interpretations. database, and logic programming within program actually is. Declarative languages have a great a simple language of only eight con­ structs. To illustrate the procedural part of Figure 5 - Tail Recursive Exponentiation in Trilogy Trilogy, let's consider the predicate Expl (see Figure 5). proc Expl(x:I) iff (comm: n >= 0 & y = xAn * a Expl computes the exponential func­ if n = 0 then y = a tion by the logarithmic method. The ar­ else guments x, n, and a are declared as input if n mod 2 = 1 then al = x*a else al = a end & Expl(x*x,n/2,al,y) integer arguments, n is restricted to the end non-negative interval. When we call the predicate Expl, the END or LISTING input arguments will have the ap­ propriate values. The value of the integer output argument y will be computed by Figure 6 - Proving Theorems the call. Note the "iff" word saying that the predicate Exp1(x,n,a,y) holds if and Expl(x,O,y,y) only if the formula in its body holds. n >= 0 & Expl(x * x,n,x * a,y) -> Expl(x,2 * n+l,a,y) n >= 0 & Expl(x * x,n,a,y) -> Expl(x,2 * n,a,y) From the definition of Expl, we can easily prove the theorems in Figure 6. END or LISTING By a straightforward induction on n, we then obtain:

Denotational semanticists were cer­ advantage over procedural languages in Expl(x,n,a,y) <-> y = xA{n} * a tainly right. By giving the evaluation that they're free of side effects. The com­ predicate (or re~ation) Eval, we specify munication between programs is through Hence the call to Expl with the third the computations. A program is mere parameters only. As a consequence, the argument set to 1 computes the exponen­ data to the computing machine and programs can be relatively easy to prove tial function for a non-negative n: generally doesn't have a meaning per se. correct. Since the programs don't depend However, after criticizing the machine on any hidden assumptions, they're Expl(x,n,l,y) <-> y = xA{n} approach most of the denotationalists easier to maintain and more rugged. proceeded to define a so-called meaning The great computer scientist Tony There's even a simpler method of in­ function mapping programs into a com­ Hoare once observed that "Algol was an troducing Exp into the Trilogy code putational mechanism known as lambda improvement over all programming lan­ given in Figure 7. Both Exp and Expl use calculus. True, the lambda functions pos­ guages succeeding it." We can the same fast logarithmic exponentiation. sessed perfect meaning in the so-called paraphrase him and say that- The predicate Exp requires a true models of lambda calculus, but the The semantics of logic is a real improve­ recursion whereas the recursion in Expl meaning function was nothing but the ment over the denotational semantics is a "tail recursion." Tail recursion is relation Eval in disguise. which came fifty years later. recognized by the Trilogy compiler and The mistake of denotationalists was The declarative languages used to is automatically optimized to a loop, as their belief that computations can be have quite inefficient implementations. in Figure 2. described by models instead of machines. The mainstream programmers could thus They have somehow forgotten that the claim that they are just academic toys Logic Programming notion of computability can be defined and that real programmers use C. For­ We've seen that we can introduce only through computing machines, be it tunately, declarative languages have Expl as a predicate. It's interesting to by the schemas of recursive functions or come of age (although not all C program­ note that this predicate can be simulated by Turing machines. mers have). in Pascal by defining a procedure with It's now clear that we can have sound the following heading-

24 MICRO CORNUCOPIA, #41, May-June 1988 ADD TO THE POWER OF YOUR PROGRAMS WHILE YOU SAVE TIME AND MONEY! CBTREE does it all! Your best value in a B+tree source! Save programming time and effort. Access any record or group of records by: You can develop exciting file access programs quickly and easily because o Get first • Get last CBTREE provides a simple but powerful program interface to all B+tree o Get previous • Get next operations. Every aspect of CBTREE is covered thoroughly in the 70 page o Get less than • Get less than or equal Users Manual with complete examples. Sample programs are provided on o Get greater than • Get greater than or equal disk. o Get sequential block • Get partial key match o Get all partial matches • Get all keys and locations Gain flexibility in designing your applications. o Insert key and record • Insert key CBTREE lets you use multiple keys, variable key lengths, concatenated keys, and any data record size and record length. You can customize the o Delete key and record • Delete key B+tree parameters using utilities provided. o Change record location Increase your implementation productivity. Your programs will be using the most eHicient searching techniques. CBTREE is over 6,000 lines of tightly written, commented C source code. CBTREE provides the fastest keyed file access performance, The driver module is only 20K and links into your programs. with multiple indexes in a single file and crash recovery utilities. CBTREE is a full function implementation of the industry Port your applications to other machine environments. The C source code that you receive can be compiled on all popular C standard B+tree access method and is proven in applications compilers for the IBM PC and also under Unix, Xenix, and AmigaDos! No since 1984. royalties on your applications that use CBTREE. CBTREE supports multi- user and network applications. CBTREE IS TROUBLE-FREE, BUT IF YOU NEED HELP WE PROVIDE FREE PHONE SUPPORT. ONE CALL GETS YOU THE ANSWER TO ANY QUESTION! . CBTREE compares favorably with other software selling at 2,3 and 4 times our price. Sold on unconditional money-back guarantee. YOU PAY ONLY $159.00 - A MONEY-SAVING PRICE! TO ORDER OR FOR ADDITIONAL INFORMATION ~PEACOCK SYSTEms. inC CALL (703) 356-7029 or (703) 847-1743 OR WRITE Peacock Systems, Inc., 2108-C Gallows Road, Vienna, VA 22180

Reader Service Number 20

A Powerful Procedural, Database, and Declarative Language.

SPEED - Where Prolog must backtrack, Trilogy can A TRUE COMPILER - Trilogy is an interactive often solve the problem logically. Trilogy takes advan­ compiler which produces native code for the 8086/8087. tage of logic constraints (they constrain the search to LOGICAL PURITY - Trilogy was designed from possible solutions) which either eliminate backtracking scratch as a simple language with a completely logical or reduce millions of backtracks to a very few. foundation. Trilogy's speed results from its design, not SYNTAX - Trilogy uses an intuitive, Pascal-like, pro­ from added commands. (Prolog's assert, cut, var, and gram structure. retract, are not logical parts of that language. They INTEGRATION - Trilogy is complete. It's the only were added to improve performance.) language you need for writing Pascal-style routines, DATABASE SUPPORT - Trilogy supports: varia­ database handlers, and Prolog-style programs. ble size records, records with arbitrary values (lists, re­ MODULARITY - Trilogy is modular language, very cursive trees); plus record insertion, deletion, and modif­ similar to Modula-2. ication. (Anywhere in the file.) Files are relations and ENVIRONMENT - A complete programming envi­ can be queried from within the language. ronment, you get editor, library, linker, loader, error PRICE - Only $99.95 postpaid, U.S. funds. Plus $5.00 handling, automatic make, and contextual help. Plus, shipping & handling. Or $12.00 shipping & handling you get modules for: math, string handling, file manipu­ outside North America. Check, money order or lation, windows . . . VISA accepted.

Order 741 Blueridge Ave. From: r-fl-,...... •..• ... . fg~1~L[:Yr: North Vancouver BC Canada V7R 2J5 DBSVSY!:::r;JS (604) 986-3234

MICRO CORNUCOPIA, #41, May-June 1988 25

------.---- procedure Expl (x: integer; n: integer; persons such that- which seems to us slightly counterintui­ a: integer; var y: integer); ... (1) no two persons share the same ini­ tive. tial, The types of the first and last name and by replacing the ampersand "\&" by (2) nobody has the initials BF, initials are defined in Trilogy as a semicolon ";'. (3) the last name of A is before the last enumerated types. The predicate Names At the level of logic programming name ofB. is satisfied by an array n correlating the there is no direct translation into the pro­ There are 3! (3 factorial = 6) possible first names (indices) to the last names cedural Pascal. At this level Trilogy combinations. (values). should be compared with Prolog. Trilogy Notice that the only initials satisfying The double arrow "-»" says that the values of the array are all different. Tril­ ogy derives the solution a = 0, b = E, c = Figure 7 - Truly Recursive Exponentiation in Trilogy F without a single backtrack just by find­ ing the unknown array n satisfying the proc Exp(x:I) iff { n >= 0 & y = xAn } if n = 0 then constraints. y = 1 The "initials" problem is of course an else artificially simple one. A medium-size Exp(x,n/2,a) & ( a = xA(n/2) } if n mod 2 = 1 then y = a*a*x else y = a*a end logic problem has typically a search end space of about 1.5 million candidates. A declarative Prolog program must END OF LISTING generate all candidates before finding the ones satisfying the constraints. Such a Figure 8 - Generate & Test in Prolog: .A=d, B=e, C=f program typically executes for about 90 minutes (Turbo-Prolog on an XT). names (A,B,C) <- The same Trilogy program is shorter permute ( [d, e, f), [A, B, C) ) , because the clues can be directly trans­ B <> f, less (A,B) . lated almost word by word from English. less(d,e). less(d,f). less(d,f). What is even more important, the Trilogy program will generally execute under permute ([), [) . permute(T, [HIT2) <- delete(H,T,Tl), permute(Tl,T2). two seconds with only about five back­ tracks. delete(H, [HIT),T). Really big problems (billions of can­ delete(H,[H1IT),[H1IT1]) <- delete (H,T,Tl) . didates) cannot be even contemplated in <- names (A,B,C) . Prolog by the generate and test method. Trilogy can do them within minutes. END OF LISTING

Prolog As A Procedural Language Figure 9 - Constraints in Trilogy. The query is all Names([a,b,c» The implementers of Prolog were quite aware of the exponential blowout First = A I B I C of the generate and test method and in­ Last = DIE I F troduced a number of new "features" pred Names(n::First-»Last) iff such as cuts, asserts, retracts, vars, etc. n(B) <> F & n(A) < n(B) The features were introduced after im­

END OF LISTING plementers realized that they could cleverly utilize the insides of a Prolog en­ gine to shortcut the search. That they also shortcut the logic didn't matter. can deal with the same data structures as the constraints are AD, BE, and CF. The We now solve the puzzle of initials Prolog and can also perform backtrack­ Prolog program (see Figure 8) must using Prolog constructs called var and ing to compute non-deterministic predi­ generate all 6 permutations before it can nonvar. The Prolog engine always knows cates. find the correct one by a satisfaction test. whether a variable has a value or not. But unlike Prolog, Trilogy is the only Note that the Prolog test B<>f cannot The implementers made this visible to available logic programming language be executed until the variable B has be­ the programmer. The construct var(X) offering constraint satisfaction. Con­ come instantiated by the predicate per­ succeeds if X has no value. It fails other­ straints eliminate blind backtracking by mute. wise. nonvar is the negation of var. solving systems of equations and ine­ In Trilogy there are no such restric­ The constructs are called extra-logical qualities. tions, the above is simply remembered as since X=2, var(X) fails whereas var(X), I can illustrate the constraints of Tril­ a constraint on the solution. You can see X=2 succeeds. Hence, there is no way to ogy with an example which I have inten­ from the program in Figure 9 that there's give a logical meaning to var(X). tionally simplified to the bare essentials. no need for explicit generation .of can­ Nevertheless, programmers quickly didates for solutions. realized that by using var they could A Small Puzzle Note that variables in Trilogy start draw the same inferences as humans do Given three first name initials "A", with small letters, whereas constants, when solving this kind of problem. "B", "C", and three last name initials being proper names, are capitalized. Imagine a 3 by 3 matrix of zeros and "0",''E'', "F", find the initials of three Prolog uses just the opposite convention ones with first initials as rows and last

26 MICRO CORNUCOPIA, #41, May-June 1988 PerFormance and versatility For your CP/M or MS-DDS computer -(JPIM------Kaypro ------IBM PC----- CP/M by MICROCode Consulting KayPLUS ROM Set by MICROCode Consulting Fed up with the message "BDOS error: RIO"? With QP/M, you'll Want more performance and flexibility from your Kaypro? With CP/M, NorthStar, Macintosh, Apple II, never lose another file because you changed a diskette. QP/M the KayPLUS ROM set you can have the advantages of a Kaypro MS·DDS, and PS/2· Don't let offers full CP/M 2.2 compatibility with outstanding performance 4 or 10, even on your Kaypro 2. and more commands WITHOUT eating up precious program • Install up to four floppies and two hard drives incompatible diskette Formats get space. Get such features as automatic disk relogging, simple • Boots from floppy or hard disk you down, read them all with your PC. drive/user selection using either a colon or semi-colon, 31 user • Supports 96 TPI and 31f2" disk drives areas, drive search path, multiple program command line, archive • Can use any ST506 type hard drive - 5 to 64 Meg • 32 character type-ahead keyboard buffer UniForm·PC by MlcroSolutlons bit maintanence, and transparent time/date stamping; all in the How often have you wished you could use your CP/M diskettes same space as CP/M 2.2. Installs from aconvenient customization • Automatic screen blanking (not avail. on 83 series) • 12 disk formats buill-in, unlimited configurable on your PC? Now you can access your CP/M disks and programs menu, no software assembly required. Bootable disks available on your MS-DOS computer just as you would a standard MS-DOS with CBIOS for Kaypro, Xerox (8" or 5V4", -1 or -2), & BBI. • Full automatic disk relogging with QP/M • Internal real-time clock support diskette. Once the UniForm driver is installed, you can use QP/M , bootable -specify system .... $ 64.95 • No software assembly required standard DOS commands and programs right on your original QP/M without CBIOS (installs on any Z80 system) ..... $ 49.95 Includes manual, format, configuration, diagnostics, sysgen, diskette without modifying or copying your files. UniForm-PC diskette customization utility, AND hard disk utilities. Available allows you to read, write, format, and copy diskettes from over --Networks ----- for '83 and '84 series Kaypros. 275 CP/M and MS-DOS computers on your PC, XT, or AT. With UniForm-PC and the Compaticard, you can use 5%" high CP/M Network File System by MICROCode Consulting KayPLUS ROM Set, specify model ...... $ 69.95 density, 96TPI, dual format 31f2" (720kl1.44 meg.- PS/2), and QP/M Network File System is an efficient local area network KayPLUS ROM Set with QP/M ...... $125.00 allowing up to seven CP/M computers to share peripherals and even 8" drives. data resources. UniForm-PC by MicroSolutions ...... $ 64.95 • Transparent operation at speeds up to 11,000 bytes/second Parts and accessories for the Kaypro Uniform for Kaypro and other machines ...... $ 64.95 in syncronous mode Kaypro 2X Real-time Clock parts kit ...... $ 29.00 • Speeds of up to 1,920 bytes/second in asyncronous mode Kaypro 2X Hard disk interface parts kit ...... $ 16.00 CompatlCard by MlcroSolutlons • Local/remote disk drive and printer support Kaypro 10 or '84 series Hard Disk host board ..... $ 49.00 Meet the CompatiCard, THE universal disk drive controller card. • Remote peripheral support for modems and real-time clocks Kaypro four drive floppy decoder board ...... $ 35.00 This half card will let you run up to 16 disk drives (4 per Compati­ • All stations need not be on the network even though connected Complete parts and repair services available Card) on your PC or XT, including standard 360K, 96 TPI, high • Local drive access protection and control density (1.2 meg, dual speed), 8" single or double sided (SD or • Simple menu oriented configuration utility DD), and dual format 3V2" drives (720kl1.44 - PS/2). The combi­ • Extended DOS calls are provided for addition of custom net- --Xerox 82D---- PLUS2 ROM and X120 Double Density Board by nations are almost unlimited. Comes with its own MS-DOS driver work utilities. MICROCode Consulting and Emerald Mlcroware and format program for high density and 3V2" diskettes. Use it Works with interrupt driven Z80 systems such as Xerox 820, About had it with single density diskettes on your Xerox 820-1? with UniForm-PC for maximum versitility. 8" adaptor and addi­ Kaypro (KayPLUS & Advent ROMs), Eagle, and other computers Get unsurpassed versatility with our X120 Board and PLUS2 tional cabling available. running QP/M, or CP/M 2.2 ROM package. CompatiCard Board ...... $169.95 QP/M Network File System ...... $ 39.95 • Run up to four floppy disk drives at once CompatiCard with UniFORM-PC .. * * Special * * .. $225.00 • Mix 8" and 5W' at the same time CompatiCard with UniFORM-PC & high density or --Hard Disks ---- • Software compatible with Kaypro and Xerox 820 31f2" drive ...... * * * Special * * * ...... $350.00 Need more speed and storage on your system? • Buill in drivers for most serial and parallel printers Improve the productivity of your Z80 computer with a hard disk. • Get mini-monitor functions and auto-boot capability MatchPoint·PC by MicroSolutions • 19 built in disk formats, including Xerox and Kaypro The MatchPoint-PC board for the PC/XT/AT works with your HDS Host Board • Includes custom disk format definition program standard controller card to let you read and write to NorthStar This daughter board provides a convenient interface for connect­ • Banked ROM BIOS for more space in your TPA hard sector and Apple II diskettes on your PC. INCLUDES a copy ing a Western Digital WD1002-05 hard disk controller to your • Composite video adaptor on X120 board of the UniForm-PC program, as well as utilities to format disks, computer. • Runs 48 TPI diskettes on 96 TPI drives copy, delete, and view files on Apple DOS, PRODOS, and Apple • Plugs into the Z80 socket, no other wiring required • Supports real time clock from Z80-CTC CP/M diskettes. • 40 pin interface for a WD1002-05 (or HDO) controller board • Works on the Xerox 820-1 and Big Board I MatchPoint-PC Board ...... $169.95 • Switch selectable I/O port addressing • Both ROM and X120 board are required for operation • Comes as bare board or assembled & tested MatchMaker by MicroSolutions . • Kaypro '84 host board also available PLUS2 ROM Set and X120 Board A&T ...... $114.95 PLUS2 ROM Set and X120 Bare Board ...... $ 49.95 Now you can copy your Macintosh diskettes right on your PCIXT/ Winchester Connection by MICROCode Consulting PLUS2 ROM Set only ...... $ 39.95 AT with the MatchMaker. Just plug your external Macintosh drive The most simple and comprehensive hard disk software package 120 Bare Board only ...... $ 15.00 into the MatchMaker board and experience EASY access to your available for CP/M. * * * Special * * * 2 boards for $25, 5 for $50 31f2" Mac diskettes. Includes programs to read, write, initialize, • Designed for use with the WD1002-05 controller board Other kits, parts, and packages available and delete files on your single or double sided Mac diskettes. • Works with one or two hard disks - 5 to 64 meg MatchMaker Board ...... $139.95 • Menu installed, no software to assemble MatchMaker w/External Mac Drive ...... $325.00 • Complete hardware tests and error handling Parts and accessories for the Xerox 820 • Automatic swap, for warm boots from hard drive Xerox 820-2 CPU Board - new ...... $ 75.00 • Software drivers install above or below CP/M Xerox 820-2 Floppy Controller board - new ...... $ 65.00 Frustrated because your PC • Allows custom partition sizes and mixed drive types Xerox 820-2 CPU board w/ Floppy Controller .... " $125.00 can't speak CP/M? • Independent block and directory sizes on each partition Xerox 820-1 CPU board - new ...... " ...... $ 75.00 • Includes manual, format, test, park, and swap utilities UnlDOS by Micro Solutions Xerox 820 complete high profile keyboard ...... $ 65.00 Run CP/M programs on your PC? Of course. UniDOS is a Winchester Connection Software only ...... $ 39.95 Xerox 820 bare high profile keyboard - new ...... $ 25.00 memory resident program that can use the NEC V20 CPU chip HDS Board with Winchester Connection Software ..... $ 79.95 Xerox 820 5W' drive cable ...... $ 9.00 to actually RUN your favorite 8080 programs. Use UniDOS with HDS Bare Board with software ...... $ 59.95 Xerox internal video cable w/brightness control .... $ 9.00 UniForm-PC, and automatically switch to CP/M mode as you HDS Board, WD1002-05, and software ...... $245.00 Xerox 820 power supply ...... $ 35.00 log on your CP/M diskette. Switch to emulation mode to run Z80 Call or write for other priCing options Power connector, specify board or cable ...... $ 2.50 code programs or for systems without a V20. UniDOS directly Xerox parallel printer interface cable ...... $ 35.00 converts video and keyboard emulation for Kaypro, Xerox 820, WD1002-05 HARD DISK CONTROLLER BOARD by Western Dual Half Height 5%" Disk Drives - DSDD, Digital Morrow, Osborne, VT100, and eight other displays. All standard in cabinet with standard Xerox cable ...... $265.00 CP/M system calls are supported. Note: The NEC V20 CPU is • Standard ST506 drive interface Complete parts and repair services available • Same size as standard 5W' drive a fast, low power, CMOS replacement for the 8088 CPU chip • 40 pin interface to host computer that includes a full 8080 instruction set as well as the standard • WD2797 floppy disk controller interface on board 8088 set. Systems using an 8086 may substitute a V30 chip. • Can control up to three hard drives r EMERRLD 1 UniDOS by MicroSolutions ...... $ 64.95 • Direct replacement for Kaypro 10 controller UniDOS w/UniForm and V20-8 chip ...... $135.00 WD1002-05 Controller Board .... '" ...... $185.00 ~ MICRONRREj Other Western Digital boards available UniDOS zao Board by MlcroSolutlons P.O. Box 1726, Beaverton, OR 97075 Thi.s a Mhz. ZaOH half-card will run your Z80 and 8080 code Prices subject to change without notice. VISA and Mastercard programs at LIGHTNING speed on your PC or AT. Functions accepted. Include $5.00 shipping and handling, $7.50 for COD, just like the UniDOS program, except NO V20 or emulation mode UPS-Blue or RED Label additional according to weight. Please El (503) 641-0347 1\1 is required to run your programs. Now includes UniForm-PC! include your phone number with all correspondence. 30 day money back guarantee on all products. UniDOS Z80 Coprocessor Card ...... $169.95

Reader Service Number 10 initials as columns. The element BE of the This almost unreadable program We think the hacks shouldn't have matrix is set to one only if there is a per­ seems to be a terrible overkill for such a happened. The designers should have in­ son with such initials. simple problem. Unfortunately, the use sisted on the purity of both languages. Obviously, if a value in the matrix is of var and nonvar to simulate constraints But perhaps it couldn't have been set to one, all other values in the same is the only feasible way of solving large helped. After all Lisp was designed al- row and column must be zeros. Vice versa, if two values in the same row or column are zeros the third value must be Figure 10· Extralogical Use of Prolog a one. Figure 10 shows a Prolog program names([AD,AE,AF], [BD,BE,BF], [CD,CE,CF]) <- BF = 0, %second clue using var. The query names(Mat) is (AD = 1; AE = 1, BD = 0), %third clue answered by finding the matrix Mat. infer([AD,AE,AF], [BD,BE,BF], [CD,CE,CF]). %draw all inferences Note the help given to Prolog by encod­ novar(AD),novar(AE),novar(AF),novar(BD),novar(BE),novar(BF), ing the third clue. It says that either AD novar(CD),novar(CE),novar(BF). %see that all is set is an initial or else AE must be (and then infer([AD,AE,AF], [BD,BE,BF],[CD,CE,CF]) <- BD is not). ( rcinf(AD,AE,AF,A); rcinf(BD,BE,BF,A); rcinf(CD,CE,CF,A); rcinf(AD,BD,CD,A); rcinf(AE,BE,CE,A); rcinf(AF,BF,CF,A); A=ok),!, After the constraints have been set, ( A=inferred, infer([AD,AE,AF], [BD,BE,BF], [CD,CE,CF]); the "predicate" infer is repeatedly called A=incons, fail). as long as there is at least one row or rcinf(X,Y,Z,A) <- var(X), !,inf(X,Y,Z,A). column inference. This is achieved with rcinf(X,Y,Z,A) <- var(Y), !,inf(Y,X,Z,A). the help of another extra-logical feature rcinf(X,Y,Z,A) <- var(Z), !,inf(Z,X,Y,A). called cut, "!". rcinf(X,Y,Z,incons) <- X+Y+Z<>l. Where there's a cut, the program will inf(l,Y,Z,inferred) <- nonvar(Y), nonvar(Z), Y=O, Z=O, !. not backtrack past the cut to find alter­ inf(O,Y,O,inferred) <- nonvar(Y), Y=l, !. inf(O,O,Y,inferred) <- nonvar(Y), Y=l, !. nate solutions. The row and column in­ inf(_,Y,Z,incons) <- nonvar(Y), nonvar(Z), Y=l, Z=l. ferences are done in the "predicate" rcinf. When the inferences saturate the END 01' LISTING matrix, we must still check that all initials have been set. problems with millions of possibilities in most 30 years ago and Prolog more than Prolog. 15 years ago. Perhaps it was then impos­ Not only are the programs un­ sible to achieve efficiency without readable, but any connection to logic is sacrificing logic. lost. Such programs can be explained Today, however, there is no justifica­ only in a procedural way by a sequence tion for hacks in declarative languages. OVERSTOCK & DEMOS of changes to bindings of variables. Once Efforts to standardize Lisp and Prolog by COMPUTERS again a relation Eval is the only way to . including features violating logic are mis­ ACCESSORIES assign meaning to Prolog programs. guided. The programming language Trilogy is Why The Logic Was Lost uncompromising in its logic. Trilogy is KAY PRO 2, 2X & 4 Both Lisp and Prolog were originally very efficient but it obtains the efficiency $150 - $200 designed as nice and tidy languages without violating the logic. This was standing firmly on mathematical founda­ achieved by a tight control over the im­ tions. Lisp was designed by McCarthy at plementation. Whenever we had an im­ Z-80 CO-PROCESSOR MIT. Prolog was designed by Col­ plementation problem or whenever we BOARDS merauer at Marseilles. Unfortunately, have seen that we can improve the ef­ neither of the designers watched closely ficiency, we have always asked the ques­ BABY BLUE $50 over the implementations. tion of how to do it within the logiC. In a dubious quest for quick efficien­ The efficiency of Trilogy in non-deter­ TURBO SLAVE $100 cy, the implementers at MIT (Lisp), and ministic cases is achieved by constraints in Marseilles as well as in Edinburgh which eliminate blind backtracking. The (Prolog), added "features" to both lan­ use of types and modes by the Trilogy USED 3M DC 300 XL guages. compiler helps to generate Pascal-like TAPE CARTRIDGES The features increased the efficiency code quality in deterministic cases. $5.00 but unfortunately added the (euphemisti­ cally called) meta-logical features. In • • • All plus shipping charges plain English, the logic of Lisp and PROJECT DATA Prolog is gone. Both languages are mere procedural languages where the bindings SYSTEMS, INC. to the variables must be done in an exact 1050 Northgale Dr. #200 sequence. San Rafael, CA 94903 The extra-logical features of Lisp are (415) 492·1840 the dynamic binding, the association lists, rplaca, setq....

28 MICRO CORNUCOPIA, #41, May-June 1988 D LOGITECH Modula-2 V. 3.0 Compiler Pack Compiler in overlay and fu\1y linked form. Linkable Library. Post Mortem Debugger. Point Editor D LOGITECH Modula-2 V. 3.0Toolkit Library sources. Linker. Run Time Debug­ ger. MAKE. Decoder. Version. XRef. Formatter D LOGITECH Modula-2 $249 V. 3.0 Development System Compiler Pack plus Toolkit D Thrbo Pascal to FREE Modula-2 Translator With Compiler Pack or Development System D Window Package $49 Build true windowing into your Modula-2 code. D Upgrade Package Ca\1 LOGITECH for information or to receive an order form.

Add $6.50 for shipping and handling. California residents add applicable sales tax. Prices valid in U.S. only. Total Enclosed $ ____ o VISA 0 MasterCard 0 Check Enclosed

Card Number Expiration Date

Signature

Name

Address

City State The Mysteries Of RS-232 Success In This Field Requires Connections

With A Parallel Port" in Micro C #39) byte is beginning. Asynchronous serial communication is there are two signals: data and clock. Be­ To insure it wasn't just a noise glitch, definitely one of the weirder parts of per­ cause of the clock (which tells the receiv­ the receiving device (the 8250 on a PC) sonal computing. Although RS-232 is a ing end when the next bit is valid) there's rechecks the signal by sampling it several "standard" interface, you can't just plug no need to pause between bytes to reset times. things together and expect them to work. both the sender and receiver. (Thus there After the last data bit, some extra in­ are no stop or start bits.) formation arrives. If you have parity In asynchronous communication (by turned on, then the 8250 adds a 1 or 0 to n this article, I'll discuss my strategy far the most common mode) only the make the number of 1 bits in the charac­ for cabling problems, talk about RS- data is sent. First, both ends have to ter even or odd. (Even or odd parity.) I232 on the IBM PC and its clones, try agree on how fast the data is sent (the If one of the bits was received incor­ to dispel some of the mystery of com­ baud rate). Then, there's a pause between rectly then the receiving end would munications protocols, and otherwise characters (the start bit at the beginning notice that the number of ones was no entertain you. of the character and 1, 1.5, or 2 stop bits longer correct. If two bits changed, then at the end). parity checking wouldn't catch the What's Serial? By keeping track of the start and stop problem. In serial communication, you force all bits, and by knowing how fast data is The stop bits arrive last; you can use the information through a single wire, being sent, the receiver knows when to 1, 1.5, or 2. The stop bits return the line to one bit at a time. Sounds strange, doesn't look for each of the 8 (or 7) data bits that its marking state. They allow thereceiv­ it? Instead of each bit (in a byte) having come between. ing system some time to take care of its own wire, as on a parallel printer port, Figure 1 shows how a byte is trans­ things before the next byte starts. each bit has to wait its tum on a single ferred. The ones and zeros are "logical"; The most common configuration wire. they don't reflect the voltage values on you'll probably use is: eight bits, no There are two methods for com­ the RS-232 lines (more about that later). parity, one stop bit. This means ten bits municating serially, synchronous and When quiet, the line is in a marking con­ are transmitted for each byte. So, if you asynchronous; dition (it's marking time). The first edge divide your bit rate (also known as baud In synchronous communication (see of the signal (transition from mark to rate) by ten, the result will tell you ap­ "Controlling Synchronous Serial Chips space) notifies the receiver that a new proximately how many bytes per second

Figure l-RS-232 Data

IDLE STATE OPTIONAL PARITY BIT

START STOP BIT BITS

I" DATA BITS MARK --.. -----, ~-...---.---,.----.--...---.--~--,.-----.l SPACE ------1~~ II I '-----'-_--'-_~.-J'--__'__--'-_ _'_____'___ __' I .. FRAME ------1·~I~~~------FRAME

30 MICRO CORNUCOPIA, #41, May-June 1988 By Bruce Eckel - Eisys Consulting 1009 N. 36th Street , WA 98103

you will move. zeros through these lines. is represented by a signal between +5 For example: at 9600 bits/sec (9600 The physical connection is most often and +15 Volts, a logical one is repre­ baud), you'll move approximately 960 made through either a DB-25 (traditional) sented by a signal between -5 and -15 bytes per second. This number is only or DB-9 connector (on some PC adap­ volts. (As you might guess, there is also approximate, since most file transfer ters). Check out the pinout and line an R5-232B. It uses voltages between +25 protocols (described later) add bytes to names in Figure 2. and -25V). the beginning and end of each data On RS-232A transmit and receive lines It's worth noting that the standard RS- block. (pins 2 and 3; Tx and Rx), a logical zero 232 driver chip (1488) and receiver chip After a byte has arrived, the 8250 places it in a temporary storage register and sets some flags. If there were an un­ Figure 2-RS-232 Pinout (DB-25) read byte in the register when the new one came in (destroying the old one), the overrun flag is set If parity is on and • • • • • • • • • • • parity isn't right (indicating a noise glitch 2 3 4 5 6 7 8 9 10 11 12 on the line), the 8250 sets the parity error • • • • • • • • • • • • flag. 14 15 16 17 18 19 20 21 22 23 24 25 If you've set up the system for inter­ rupts (this is performed in software by your communications program), a PIN SIGNAL NAME PIN SIGNAL NAME received byte forces an interrupt Then EARTH GROUND 14 SECONDARY TRANSMITIED DATA the interrupt service routine must grab 2 TRANSMITIED DATA (Tx) 15 TRANSMIT CLOCK the byte before it's overrun. 3 RECEIVED DATA (Rx) 16 SECONDARY RECEIVED DATA 4 REQUEST TO SEND 17 RECEIVER CLOCK

Lotsa Wires 5 CLEAR TO SEND 18 UNA~SIGNED There are only three really important 6 DATA SET READY 19 SECONDARY REQUEST TO SEND wires in serial communication: a line to 7 LOGIC GROUND 20 DATA TERMINAL READY transmit from you to the other guy, a line 8 CARRIER DETECT 21 SIGNAL QUALITY DETECT to receive information back, and a 9 RESERVED 22 RING DETECT ground line. You can transmit and 10 RESERVED 23 DATA RATE SELECT receive at the same time; the lines are 11 UNASSIGNED 24 TRANSMIT CLOCK completely independent 12 SECONDARY CARRIER DETECT 25 UNASSIGNED You may notice there are usually 25 13 SECONDARY CLEAR TO SEND pins on your serial connector. That's more than three. To understand why, some history is in order. • • • • • 2 3 4 5 History The EIA RS-232C (Electronic In­ • • • • 6 7 8 9 dustries Association Recommended Stan­ RS-232 Pinout (DB-9) dard 232C) was developed solely to con­ nect Data Terminal Equipment (DTEs are PIN SIGNAL NAME PIN SIGNAL NAME computers, terminals, printers and other like machines) to Data Communication CARRIER DETECT 6 DATA SET READY Equipment (DCE; i.e., a modem). It con­ 2 RECEIVED DATA 7 REQUEST TO SEND sists of the definition of a set of lines 3 TRANSMITIED DATA 8 CLEAR TO SEND through which this communication takes 4 DATA TERMINAL READY 9 RING INDICATE place, and the voltage levels for ones and 5 SIGNAL GROUND

MICRO CORNUCOPIA, #41, May-June 1988 31 Figure 3-Connecting Devices using RS-232

THE TRANSMITIED SIGNAL AT THIS END,

BECOMES THE RECEIVED SIGNAL AT THIS END. 0 - o ) l Tx " Tx ,..------, ,..------, Tx •• B Rx Rx Rx "

COMPUTER MODEM MODEM COMPUTER (DTE) (MODULATOR­ (DTE) DEMODULATOR) (DC E)

"MODULATED" SIGNAL (BITS ARE TURNED INTO SOUNDS)

WHEN YOU CONNECT TWO COMPUTERS DIRECTLY, WITH NO ("NULL") MODEM:

THE TRANSMITIED SIGNAL AT THIS END

MUST STILL BE THE RECEIVED SIGNAL

AT THIS END. 0 - 0 . ) l ) l Tx " Tx •• •• B Rx " Rx B

COMPUTER COMPUTER (DTE) (DTE)

WHEN YOU CONNECT A COMPUTER TO SOMETHING ELSE:

IF THE OTHER DEVICE IS: USEA:

DCE STRAIGHT CABLE

DTE CROSSED CABLE

(1489) don't work reliably at + or -5 volts. naling rate is 20K bits per second (this is it won't work. Either your computer or (The Commodore 64 contains simple why 19.2K baud is a common limit). your device (or both) do not use the" transistor level shifters in place of the Editor's note: In the last cpuple of years standard as it was originally intended. 1488 and 1489. The Commodore's RS-232 we've seen the maximum rate move to 56K The biggie is this: the transmit line of the interface doesn't work with all serial baud (and higher). terminal was meant to be connected to devices.) the transmit line of the modem, and the The other (handshake and clock) lines The NON-Standard receive line to the modem receive line. on the RS-232 interface use the same volt­ It's a tribute to human ingenuity to When the terminal became a PC and age levels as the data lines but their sense see how many non-modem things people the modem was replaced by, say, a is backwards. On these lines, a positive found to hang on to an RS-232C port. printer, some bright printer designer voltage represents a logic one and a Trouble was, as soon as one released the realized that the printer was actually negative voltage represents a logic zero. constraint of the modem, there was no receiving the data which the computer Signal generators assume they'll be reason to use the lines as if they were was sending, so the TRANSMIT line of driving 3K-7K ohms. Thus they have to talking to a modem. Since no standard the computer should go to the RECEIVE supply between 2 and 5 rnA. Most line existed on how to use the lines for non­ line of the printer, and the TRANSMIT drivers and receivers are capable of sup­ modem purposes, designers used them line of the printer should go to the plying between 10 and 20 rnA. as they saw fit, and the RS-232C NON­ RECEIVE line of the computer. The maximum recommended cable standard was born. Data wise, the standard computer-to­ length for RS-232C is 50 feet (without So, when you connect a device to modem cable wouldn't work. repeaters). The maximum standard sig- your computer's RS-232 port, chances are

32 MICRO CORNUCOPIA, #41, May-June 1988 Hardware Handshaking Universal RS-232 Cable (Ha Ha) RS-232 On The PC Another insidious line is Clear To Figure 4 shows the solution I usually Clones support two serial ports, Send (CfS). Printers and other devices use when I make upan RS-232 cable. It's generally referred to as COMl and which are much slower than a computer hard to test whether you need a crossed COM2. Each of these ports has its own need some way of saying: "wait, I've cable; it's easiest to try both ways and see interrupt. received enough, I'll let you know when which one works. To save hassles, I just You may find, when configuring your I need more." wire in a double-pole, double-throw serial card (via jumpers or dip switches), This pause can be handled in (DPDT) switch so I can pop it back and that you can also make the ports COM3 hardware or in software. forth to cross and uncross Rx and Tx. and COM4. Selecting these options places The hardware method usually uses The other wiring shown will satisfy any the ports in an unused I/O area. There is the CIS line. When the printer pulls this hardware handshaking. no interrupt or operating system support line low (0£0, the computer is supposed I've used a cable like this to transfer for COM3 or COM4 and the lack of inter­ to stop and wait until the printer raises files from one computer to another using rupts severely limits their usefulness. the line. a public domain communication Editor's note: On PCs, COMl lies at This is a good idea, and there are no program (almost anyone will work, as 3F8h - 3FFh (data at 3F8h), it uses interrupt wires to cross (as with Rx and Tx). But long as the same protocol is used on both eCho COM2 lies at 2F8h - 2FFh (data at there are two problems. ends). 2F8h), it uses interrupt eBh. First, there is no guarantee the com­ Programs access the serial ports by puter has the hardware to sense the sig­ nal (or the sense to sense the signal). For­ tunately, PCs do. The only thing you can Figure 4 - Universal RS 232 Cable always assume about an RS-232C port is that it will have Tx and Rx. CONNECTOR CONNECTOR OPOT SWITCH TO CROSS APINS SPINS You can't even assume that pin 1 OR UNCROSS Rx & Tx (frame ground) will work as a signal (OS-25) ... -... ----- ... _-----, (OS-25) I I ground. Pin 7 (signal ground) is the only I I safe bet. Second, even if the circuits are in the computer, software must watch for the I I signal (or the 8250 must generate an in­ I terrupt). This isn't always simple, espe­ IL_ ... ______cially if the programmer is using BASIC or isn't an engineer. In the end, if you're designing a device which you want to interface to any computer, it's best to avoid using the CTS line. (In the PC world, CTS is the standard handshake.)

Software Handshaking The second solution to the "flow control" problem is via software. Two special characters are defined: with XON­ XOFF flow control, these are CONTROL­ S to stop the flow, and CONTROL-Q to RS-232 Cable with Handshaking restart it. When the computer receives the STOP character (via its Rx pin), it stops sending TO TO information until it receives the START RO RO character. The computer can also send out STOP and START characters to con­ RTS RTS trol data coming from a remote device. CTS CTS The advantage of software flow con­ OSR OSR trol is that you make no assumptions COMMON COMMON about hardware. OCO OCO Designers also use many of the other lines for hardware handshaking, often OTR 20 20 OTR with frustrating results. RI 22 22 RI For a simple-to-use, generic interface, it's best if you use only the Tx, Rx, and ground lines, with XON-XOFF flow con­ trol.

MICRO CORNUCOPIA, #41, May-June 1988 33 CLONE SYSTEMS reading and writing locations in the I/O space. The PC can access, via the (One YEAR guarantee on system) microprocessor's address lines, memory Turbo Mother Board 4.77 and 10 MHz cells or I/O (input/output) cells. I/O ad­ 640 K Ram installed 6n board dressing has different timing and hand­ Serial, Parallel, Game Ports shaking than memory addressing. I/O devices generally respond more slowly Clock/Calendar AT Style Keyboard than memory (as far as I can recall). Color (CGA) or Monochrome Video Board Not all microprocessors do this. The 150 Watt Power Supply Flip Top Case Motorola 68000 family, used in Macs, ABOVE WITH 2 FLOPPY DISK DRIVES $ 599.00 Ataris, Amigas, and many Unix WITH 1 FLOPPY AND 20 MEG $ 859.00 machines, puts all of its I/O in the WITH 2 FLOPPY AND 20 MEG $ 899.00 memory space (this is called "memory­ Assembled and Tested for 24 Hours mapped I/O"). The 68000 has special handshake lines for slow memory or AT TURBO SYSTEM peripherals. AT COMPATIBLE MOTHER BOARD WITH BIOS The status pins on the 80X86 or 8088 microprocessor tell the rest of the system 8 MEG AND 12 MEG SWITCHABLE SPEED whether the next access will be memory 512K RAM INSTALLED UP TO 1024 ON BOARD or I/O. WA2 HARD DISK/FLOPPY DISK CONTROLLER High-level languages also have some MONOCHROME GRAPHICS VIDEO WITH PRINTER method of specifying I/O. BASIC uses 1.2 MEG OR 360 K FLOPPY the IN and OUT commands. Turbo Pas­ 220 WATT POWER SUPPLY AT CASE cal uses the port array. Turbo Prolog uses AT KEYBOARD SET UP DISK the portbyte predicate. Microsoft C uses ONE YEAR WARRANTY ON SYSTEM $1195.00 inpO and outpO. Turbo C uses inportO /outportO for EGA UPGRADE FOR ABOVE $ 75.00 word I/O which allows an I/O instruc­ 512K UPGRADE (1024 INSTALLED) $ 130.00 tion to use the maximum word size of 5339 KEYBOARD UPGRADE $ 30.00 the processor's data bus (8 bits on the 8088, 16 bits on the 8086/80286, and 32 bits on the 80386) or inportbO /outportbO HARD DRIVES FOR XT AND AT for byte I/O. ST-225 KIT FOR XT (20 MEG) $ 259.00 The 8250 chip occupies a block of ST-238 KIT FOR XT (RLL 30 MEG) $ 279.00 eight addresses in the I/O space. ST-251 FOR AT (40 MEG) $ 405.00 Switches on the serial card determine the base (starting) I/O address. MONITORS Well-behaved programs find out Color Monitor RGB (CGA) $ 255.00 which I/O base address is supposed to Color Monitor RGB (EGA) $ 355.00 be COM1 and which is COM2 by read­ Monochrome TTL (Green) .$ 95.00 ing the BIOS data area. Base:offset Monochrome TTL (Amber) $ 95.00 0040:0000 holds COM1 and 0040:0002 EGA Color Video Card $ 129.00 holds COM2. This way you can switch the ports without rewiring; simply change the data. Many programs don't bother reading this data, however, so it CITIZEN PRINTERS isn't very useful. MODEL 120D 120 CPS 9" $ 179.00 MODEL 180D 180 CPS 9" $ 199.00 Communication Protocols MODEL MSP-15E 160 CPS 15" $ 359.00 When a communication program at­ MODEL MSP-40 240 CPS 9" $ 319.00 tempts to transfer a large amount of data MODEL MSP-45 240 CPS 15" $ 439.00 (for instance, a file) over a serial link, it MODEL MSP-50 300 CPS 9" $ 419.00 runs a risk. MODEL MSP-55 300 CPS 15" $ 499.00 It's not unusual for noise or other problems to change bits as they sail across the line. For file transfer to be de­ CASCADE ELECTRONICS, INC. pendable, the transfer program must be ROUTE 1 BOX 8 able to (1) determine whether there's an RANDOLPH, MN 55065 error and if so, (2) correct it. 507-645-7997 Most file transfer protocols (FTPs) Please ADD Shipping on all Orders break files up into blocks or packets. This way, you don't need to retransmit an en­ COD Add $3.00 Credit Cards ADD 5% tire file if there's an error. Limited to Stock on Hand Subject to change Data is usually surrounded by infor- Reader Service Number 15

34 MICRO CORNUCOPIA, #41, May-June 1988 mation which says, "a packet's coming, KERMIT negotiates with the other this is it's number, here's the data." end to establish the communication Finally, some sort of check value is sent. parameters. This is clever since it allows One of the earliest microcomputer extensions to the protocol without dis­ protocols is Ward Christensen's turbing existing installations. XMODEM. XMODEM divides a file into Two extensions have already been packets containing (1) the SOH (Start-Of­ made to speed KERMIT up-but it still Rafting Header) character (an ASCII 01) to indi­ assumes computers can only handle cate the beginning of a packet, (2) the se­ printable ASCII characters. This is one of 8arbeque quence number of the packet, both nor­ the things which make it portable, but it mal and in one's complement, (3) 128 runs like a turtle (not a frog) compared to Computer tech talk bytes of file data, and (4) one byte of XMODEM. As a rule of thumb, use checksum or the checkvalue, which is XMODEM whenever you can, and KER­ calculated by simply adding all the data MIT when you can't. SOGVII bytes together as they come in (throwing away the carries). Someday July 14 -July 16 Although by no means perfect, There's a lot more to writing a com­ XMODEM is probably the most com­ munication program than I can cover Bend, Oregon monly used protocol. An early flaw (a here (check out Joe Campbell's superb C checksum can miss errors) has been rec­ Programmer's Guide to Serial Communica­ Leave city life behindl tified with the addition of a cyclic-redun­ tions, Howard W. Sams & Company, dancy check (CRC) for the checkvalue. 1987), but I plan to do some kind of ex­ CRCs are more complicated but much periment with it in the coming months. more reliable. But you must often specify Stay tuned. XMODEM checksum or XMODEM CRe. The stand-alone XMODEM program only transfers one file at a time. This was • • • improved in the MODEM7 program, which will move groups of files. MODEM7 usually generates either check­ sum or CRC automatically. The YMODEM transfer has its own protocol, but will use XMODEM if that's what the other end is using. ZMODEM, WXMODEM, and others keep popping up. Usually, what's best is whatever the other machine uses. I've looked at a number of public domain/shareware communications programs, and I think my favorite is Shareware's Procomm-it's mature, it seems bug-free, it supports most popular (formerly Turbo GhostWriter) file-transfer protocols, it emulates a Perfect for creating complex business applications! VT100 terminal (convenient for connect­ Ideal for BASIC programmers who find TPascal too tough! ing to minis and mainframes), and it's Spec your customer in the morning - Show a demo in the afternoon! easy to use. You can find it on most Features More features BBS's and on Micro C disk #38. • screen editor and painter • automatic B-tree indexing • automatic programmer • consistent user interface Muppet Protocol documentation • automatic context -sensitive The only problem with most of these • automatic data help protocols is they were developed on checking/validation • relational model to show • plenty or "hooks" for customizing microcomputers, so many of them can customizing • 30 day money-back gaurantee only be found on microcomputers (al­ • unlimited technical support (less $14 shippinglhandling) though XMODEM is often found on UNIX systems). Columbia University set No questions to answer. Just draw your screens the way you want out to smash the communications them to appear, tell Turbo Programmer how to set up the indexes protocol bug once and for all with KER­ and that's it ... Running 4.0 code in 6 seconds with no MIT (the name of a famous frog, that's programming. Regular pnce $450. all). Now Only $289 Orders & Info 800 227-7681 KERMIT is designed to work on all computers without regard to size. This ASCII 3239 Mill Run, Raleigh, NC 27612-4135 was an ambitious project, but it seems to work; and it helps that all the source code is public domain. Reader Service Number 48

MICRO CORNUCOPIA, #41, May-June 1988 35 Intel's 8088 A Tour Through The Brains Of The PC

more. Inside that one piece of silicon lay goes back to thinking. Larry's finally done it. He's traversed his most of the smart chips I've discussed way through the primary players (we're talk­ over the past year. Intel also added a 8088/8086 Registers ing 40 pins here) in the IBM XT and its number of new instructions. Both processors make use of the same clones. He's finishing up with the kingpin, The 286 took the 8086 family in 14 two-byte registers. The four data the heart and soul, the chip without whom another direction with the capability to registers (AX, BX, CX, and OX) can be ac­ there would be no others... (Do I hear· a create multi-user and multi-tasking sys­ cessed in two ways: as a single 16-bit bull.. .. from the crowd?) tems. It could generate a 24-bit address register (AX), or as two separate 8-bit (16 MBytes) though it remained a 16-bit registers (AH and AL). "H" and "L" refer processor. to the high and low bytes in the AX ack in Micro Cornucopia Issue #35, A full 32 bits of address and data and register. I began this series on the pC's in­ 32-bit internal architecture make the 386 a Although you can use most of the Bnards with a look at the 8253 true 32-bit processor. As such, it could deal registers for several purposes, some programmable interval timer. This article with its entire address space (four registers must be used with certain in­ caps the series by covering the iAPX gigabytes) as one contiguous block. No structions. For example, port I/O requires 88/10 (or 8088 to the less snooty among more segments! However, ifs quite use of AX for words and AL for bytes. . us). happy in a segmented configuration like The four pointer and index registers I'll also talk briefly about some of the Intel's earlier processors. can only be accessed as words (16 bits), differences between the 8088 and other The 8088 remains the most prevalent but they have most of the general pur­ members of the 8086 family of CPUs­ member of the family and we'll be con­ pose capabilities of the data registers. NEC's V20 included. We'll finish up by centrating on it. But some of the discus­ While they can be used for math and following a keystroke from keyboard to sion will apply, at least loosely, to the logic operations, they usually serve other screen to see how all these smart chips other processors. purposes. conspire to perform something simple. The stack pointer (SP) and base The 8088 pointer (BP) support stack functions. All In The Family Intel divides the 8088 into two major String functions often use the source In 1978 Intel introduced the father of sections: the execution unit (EU) and the index (51) and destination index (01) for the 8086 family, named (appropriately bus interface unit (BID). These units manipulating strings. enough) the 8086. The following year saw operate independently with the EU ex­ When the 8088 needs to find the next the first of the soon to be ubiquitous ecuting instructions while the BIU instruction of a program, it uses the in­ 8088s. The two processors were nearly prefetches the next instructions and trans­ struction pointer (IP). A programmer identical-the main difference being the fers data to and from memory and I/O can't get at the IP directly-probably a size of their data busses. The 8086 trans­ space. good thing. The flag register holds infor­ ferred 16 bits of data at a time while the In rough terms, the EU thinks and the mation on the status of arithmetic and 8088 could deal with only 8 bits. BIU talks. The EU is almost completely logic operations, as well as control flags. However, object code compatibility be­ isolated from the rest of the system. When And the code segment (CS), data seg­ tween the two processors was complete the 8088 executes a program, the BIU ment (OS), stack segment (55), and extra and IBM's choice of the 8088 for use in prefetches instructions from memory and segment (ES) registers provide part of the their PC assured Intel of a huge market. loads them into the 8088' s 4-byte instruc­ addressing information. The 8086 and 8088 were followed by tion queue. The EU fetches· instructions There are, in addition, several the 80186, 80188, 80286, and, most recent­ from the queue and executes them. "temporary" and "internal ly, the 80386 CPU-all compatible with During execution of an instruction, the communication" registers inaccessible to the 8086. That means the whole family BIU happily prefetches more instructions the outside world. But I've never seen can execute 8086 code. to fill up the queue. If the current instruc­ these documented very well so I can't tell The 186 (16-bit data I/O) and 188 (8- tion requires port or memory I/O, the you anything about them. bit) added on-board clock, direct memory BIU finishes up with its prefetch (if any) access (DMA), interrupt control, and does the I/O. It then resumes instruc­ Execution Unit counter /timer, chip select logic, and tion prefetching (if needed) and the EU The EU includes the general purpose

36 MICRO CORNUCOPIA, #41, May-June 1988 La~Fogg Micro C SEan

registers, flags, and arithmetic/logic unit debugger to single step through your rupt return, or any of the jump instruc­ (ALU). code in search of those nasty glitches. tions. The flags live in a single 16-bit (See Micro C's Issue #40 C Column for In each of these situations, sequential register. (See Figure 1.) Six flags contain more on debuggers.) prefetch breaks down. The next instruc­ operation status information-did the tion in memory is not the next instruction operation result in a carry or a borrow, The Real Brains to be executed. So the queue gets did the result overflow the capacity of its If you want to isolate one part of the dumped, the BIU begins to refill it start­ destination, was the result positive or 8088 that really has some smarts, it's the ing at the jump destination, and we've negative, what was the parity of the ALU. Everything else supports this one lost some of the queue's benefit. You can result, was the result zero? section. The ALU performs all arithmetic see that code which jumps around a lot The other three flags perform the 8088 operations and logical comparisons. will be slower than sequential code. control functions. Setting the direction Most of us like to think of assembly The queue and its maintenance il­ flag makes string instructions process programming as the bottom line. But lustrate one of the differences between strings from high to low addresses. how does the ALU know what to do the 8088 and 8086 processors. The 8088 Resetting the flag reverses the processing with an instruction? contains a 4-byte queue which the BIU direction. Microcode. tries to refill as soon as a single byte has Microcode isn't little, tiny code writ­ been fetched by the ED. Since the 8088 ten by stunted programmers. The folks at has an 8-bit data path, it prefetches one Figure 1 - 8088 Flags Register Intel use microcode to translate the com­ byte at a time. plex set of object instructions into the The 8086, on the other hand, has a 6- Bit Function much smaller set the hardware under­ byte queue. And, since it does 16-bit data o car%y stands. I/O, and can therefore prefetch two bytes 1 unused at a time, the 8086 waits until two bytes 2 parity 3 unused Bus Interface Unit of the queue have been fetched by the 4 auxilia::y caX"%y The rest of the registers (segment EU before attempting to prefetch another 5 unused registers and the instruction pointer), a two bytes from memory. 6 zero 7 8ign 20-bit address generator, the instruction 8 trap queue, and bus control logic live in the 110 9 interrupt enable 10 direction BIU. The BIU also handles I/O chores for 11 overflow The BIU has three main tasks. First, it the EU. Whenever an instruction calls for 12-15 unused prefetches instructions from memory in either memory access or port I/O, the EU an attempt to always have instructions requests a bus cycle from the BIU. A bus waiting in the instruction queue. Execu­ cycle usually consists of four clock cycles, tion speed increases dramatically if the or T-states (unless we're talking to a slow EU doesn't have to wait while its next in­ device). More on this later. For now, let's With the interrupt enable flag set, the struction is fetched. just be aware that any time the EU needs 8088 recognizes external interrupt re­ Ideally, there will always be some­ to talk to the outside world, it does so quests. On the PC, external interrupts thing waiting in the queue for the EU to through the BID. come in from the 8259 interrupt control­ digest. No such luck. Two factors As it turns out, the BIU ends up ler and can be initiated by a real time decrease the efficiency of the queue. A spending some of its time idling. This clock tick, a keypress, or some other few fast instructions in a row can empty can happen when a coprocessor (perhaps hardware event. Resetting the interrupt the queue, but this doesn't happen all an 8089 I/O coprocessor or the 8087 flag disables these interrupts. The CLI that often. math chip) takes over the bus, or when and STI instructions take care of clearing The more common queue problem oc­ the EU has to grind through a compli­ (resetting) and setting this flag. curs when a program calls for any kind cated instruction. Finally, the trap flag causes the 8088 of branch. The branch could be a proce­ It only takes four bus cycles, or 16 T­ to generate an interrupt after execution of dure call, a return from a procedure, a states, to completely fill the queue-as­ each instruction. This flag allows a loop instruction, an interrupt, an inter- suming no interruptions by the EU for

MICRO CORNUCOPIA, #41, May-June 1988 37 I/O. (Why does this make me want to (See C'ing Clearly in this issue for more of T3. If it sees a low on READY, the BIU say E-I-E-I/O?) But some of the more on memory addressing.) inserts wait states (Tw) between T3 and complicated instructions take well over Segmented memory does add to T4 until the I/O device signals its readi­ 150 T-states to execute. So the Bill gets a programmers' confusion. But it's really ness by releasing the READY line. breather and usually ends up with some­ not that much of a hassle and it gives us thing waiting in the queue for the EU. all an excuse for Intel-bashing. Bus Control The third task of the BIU has to do How does the rest of the system know with ... 8088 Pinout whether there's address or data on the The 8088 lives in a standard 40-pin multiplexed bus? An 8288 bus controller Segmented Memory DIP package. (5ee Figure 2.) Nothing lets everyone know. "Ooooh, he said those nasty words." mysterious about A8 through A15. These Throughout the bus cycle the proces­ The main complaint most folks have pins provide eight bits of address which sor sends information to the 8288 via SO, against Intel processors is their use of a are valid throughout the entire bus cycle. segmented memory addressing scheme. The rest of the address lines share Using only its 16-bit registers, the 8088 their space with either data (ADO could directly address only 64 KBytes of through AD7) or status (A16/53 through memory. We need four more bits for a A19/56) signals. complete 20-bit address into 1 MByte of ''Time multiplexing" allows this shar­ RAM. ing of a pin (and a bus) by two signals. The BID contains a dedicated adder Let's look at ADO. which constructs the 20-bit address. It During the first (Tl) of the four or does this by combining the contents of more T-states in a bus cycle, ADO holds one of the 16-bit segment registers with a AO. T2 gives time to set the direction of 16-bit offset. Think of the segment ad­ the transfer, and the BIU reads or writes dress as the beginning of a block of a valid DO for the rest of the bus cycle.

51 and 52. The 8288 decodes these status lines according to Figure 3 and generates control signals for the rest of the system. For example, the following sequence would write a byte to memory. During Tl the 8088 outputs a full 20 bits of ad­ dress to the system. At the same time, it drives 50 low and leaves 51 and 52 high. The 8288 decodes this combination of status signals and generates an address latch enable (ALE). An LS373 takes care of the demul­ tiplexing chores for AO through A7. It responds to ALE by latching (storing) the lower eight bits of address. Another LS373 latches the upper eight bits of ad­ dress in response to the same signal. One more main board signal effects address generation, the address enable (AEN). Several system states can restrict access to the bus. Lock, hold, and wait conditions all hold AEN high. When any of these conditions occur, AEN keeps the 8288 from issuing any signals. Then, when the bus again becomes available, the system sends a low out on AEN, ena­ bling the 8288' s command outputs. AEN also enables the output of both LS373s before ALE triggers the address latching. In addition, it latches A8 memory and the offset as an index into If the I/O deals with a slow device, through All into an LS244. So now we that block. the device may pull the 8088' s READY have all 20 bits of address safely out on We get 20 bits by shifting the segment line low, telling the processor that the the address bus. address four bits to the left. Adding the device hasn't had time to place (or read) At the end of the ALE pulse, a new resulting 20-bit number to the offset gives data on the bus. combination of outputs on the 8088's an address within the 1 MByte space. The 8088 looks at READY at the end status lines brings another 8288 signal

38 MICRO CORNUCOPIA, #41, May-June 1988 If You Don't Have WindowDOS 2.0, You're Wasting Time!!

" When Baba Ram Dass said "Be here now, remember," designers of hard disk utilities should have paid heed. A powerful manager like XTREE can track files and subdirectories and execute DOS commands, but it isn't mem­ ory resident. Handy pop-up DOS commanders like PopDOS may be here now, but they lack the power of a ful/­ fledged disk manager. After much meditation, the developers of WindowDOS 2.0 have come up with the best answer yet to the guru's paradox. Until now, the closest thing to a real RAM-resident disk manager was version 1.0 of WindowDOS. If offered a ful/­ screen pop-up menu and could rename, copy, and delete files. But it couldn't move files, format disks, or rename subdirectories-which XTREE can. Now version 2.0 is here, and its a winner. Its RAM resident (using less than 50K) but offers all the power of a nonresident disk manager." -Patrick Marshall, WindowDOS 2.0 Product Review, PC World, May, 1987 Once you've experienced the convenience of instant access to DOS commands, you'll never be satisfied with returning to DOS to list files, format disks, or copy, rename, or erase files. Nor will you be happy with a DOS shell, because shell programs are just as inaccessible as DOS when you are using an application program. Only one program combines memory-residency with the power of a full-featured disk manager: WindowDOS Version 2.0.

Features Not Found In DOS • Sort directories in 8 ways--or not at ~~~:a~~~s~h~:;~~a~t~~~)i·· i. j .; ...... ·.··~~.i:l .• · all .··C· •. .•..•.•...... ,);' ... . ·.. ··.······/i • Copy, erase, and move groups of : ~~~:, ~~~a%~~~~~b~~~t~~~~s files • Copy files to printer or COM ports : : .••. ::::;::::: :: ::.:: :{:: {:...... '.' >:::

• Find any file in seconds • Display disk free space and other Ii:':j':':::::·:·j.·!>:l:"}:·.::.! :j::::i::::j::j: ·:0··~5~~~~:~:Q. :.::::~~:< ::>:.: ..... • Display default directory of any media information .<.:';.: ::i::!::.:·;:- :': :::::: . <:.;:;.:., drive with a single keystroke • Display graphic tree • Global copy & erase commands • Copy function prompts you to insert another disk when necessary • Display hidden files and subdirecto­ DOS functions whatever your : .. ". ::> . .;:." ries current task. Easily saves 10 or . : ':.; '.:~.:y .=

• Display file contents in various for­ more minutes a day. i,:.;::.•.•. !:.';:.:..• :.· .• :·.. ·.· .. ·: :.::: ::::: :: :.: <;::?:) <::: :.:: mats and page forward/backward • Comprehensive-Broad range of ':(::'~~l~m~::';~·:"::·~···I~r~.:.',~:>~::: ::!:~I~~::~: .~: :1~~~::~:1:f\~I: :,~>:~l:!:I:1 • Display Wordstar files in readable commands, including many notEI: ::: : .:'/:> format d f b th d d d . :: JI .q • Unique RAM Environment function supplied by DOS. Satisfies the 1'(1::1':1::1:1:1:::::1':::;::1:':'1:: II ~::rs~ 0 0 new an a vance 1::I:::I::/I·:·:·i(I::·:I}~I·:I::I:C:>I::'. I.t: •••. : y:::.':: :.••••. :I~~I' :.• : .•.• I~: shows name, size, location, and interrupts of every program in • Simplifies DOS-No need to · : .·US:7. )r.;g .. memory remember exact DOS commands.:.:::::: .><:: ::::> ..<: <:: ::?:::\X:) • Rename subdirectories for instant Intuitive interface and "point and reorganization shoot" design saves keystrokes and Other Information prevents mistakes. Group file • Hide and unhide subdirectories • Not copy protected ''tagging'' avoids the drudgery of • See and change file attributes • Uses only 51 K of memory repetitive commands. • Send control codes to printer • Supports EGA & Hercules • Security-Capability to hide/un­ • Switch default printer • Runs memory-resident or as a hide subdirectories, password • Password "lock" your system stand alone program "lock" a computer, and check for u n­ • Set AT Real-Time Clock • Uninstall command wanted programs in RAM helps • 5-minute screen-blanking function • PC/XT/AT/100 % Compatibles secure data and prevent unauthor­ • Input response macros • Order Today--Only $49.95 ized access. WindowDOS Associates· Box 300488-C· Arlington, Tx 76010 • 817-467-4103

Reader Service Number 14

MICRO CORNUCOPIA, #41, May-June 1988 39 into play. Data transmit/receive (DT /R) 8087 Coordination enable flag is set, the interrupt sequence controls the direction of an LS245 octal The queue status outputs (QSO and begins. If not, the 8088 continues execut­ bus transceiver. QSl) provide information about use of ing code until interrupts are reenabled. The LS245 provides' the multiplex­ the instruction queue. (See Figure 4.) If Nonmaskable interrupts (NMI) are ing/demultiplexing and I/O functions your system has an 8087, it uses this in­ caused by any of three error conditions: between the 8088 and the data bus. The formation to help route instructions to memory parity errors, I/O bus errors, or 8288 is now sending a high on DT /R tell­ the coprocessor. interrupts from the 8087. In each case, the ing the LS245 that this will be a write Two request/grant pins (RQ/GTO processor automatically executes inter­ operation, and we're into T2. and RQ/GTl) let request rupt 2, the NMI handler. This ROM code We have an address and we know use of the bus. The PC implements only tries to locate the source of error, prints a we'll be writing, but where and what? At the second of these for communication semi-informative message on the screen, the beginning of T2, SO-S2 cause the 8288 between the 8088 and the 8087. Both the and halts the system. to send a memory write (MEMW) com­ request and grant are active low pulses. Actually, "nonmaskable" is a lie. Sys­ mand. And, finally, the processor in­ When the 8087 needs the bus, it yanks tem configuration switches can be set to itiates a data enable (DEN), again RQ/GTllow for one clock cycle. disable both parity and I/O error mes­ through the 8288. DEN enables the LS245 Assuming a LOCK condition doesn't sages. Or you can totally disable NMIs and DO through D7 chug out onto the exist, we're not in the middle of accessing by resetting bit 7 of the NMI mask data bus. For most of the rest of the bus cycle we have a valid address, valid data, and '""\i \ :> :.'> an active MEMW. Voila, a complete memory write.

More Pins "'., On the 8088, A16 through A19 are \< \\' multiplexed with four more status sig­ >.ii..) nals. The PC ignores S3 through S6, but .\ ::,:<: ,:("':\" they deserve at least a mention. S3 and 54 provide information on which seg­ a word of memory, and we're not at the register (port OAOh) to zero. (Nonmask­ ment register is currently in use for data beginning of an interrupt acknowledge able interrupt mask sounds government access. S5 shows the status of the inter­ sequence, the 8088 finishes its current bus inspired-like the Department of Redun­ rupt enable flag and S6 does nothing. cycle (if any) and responds with another dancy Department.) Situations arise where a programmer one clock pulse on RQ/GTl. This grant To reset the 8088 the RESET pin must needs to ensure that the bus won't be pulse tells the 8087 that the 8088 has be held high for at least four clock cycles. grabbed by another processor in the sys­ released the bus. After four clocks a falling RESET signal tem. For example, in a multiprocessor When the 8087 finishes using the bus, triggers the reset sequence. During the system, several processors may share it sends a one-clock pulse to the 8088 tell­ space of about seven clock cycles, the common resources-data, buffers, per­ ing the processor that it can reclaim the 8088 zeros the DS, ES, SS, and IP haps a printer. In order to avoid conten­ bus on the next clock cycle. During the registers and sets the CS register to Offffh. tion, each processor checks a 8087' s bus activity, the BIU naps. It goes With reset accomplished, the 8088 "semaphore" before accessing the into an inactive state (Ti). When it wakes comes back to life and begins executing resource. up, it goes to T4 and we're off and run­ code at address OffffOh. In the PC this However, since the exchange (XCHG) ning again. location lies at the end of the ROM BIOS. instruction used to inspect and update a Another important pin in 8087 sys­ It holds a jump to RESET (the routine semaphore does two memory accesses, it tems is the TEST pin. The 8087 and 8088 which does power on self test) and we're would be possible for another processor can operate concurrently. But often we back in action (we hope). to hom in between the two accesses and want the 8088 to wait for the results of an Finally, the 8088 needs a heartbeat wreak havoc. To guard against this 8087 operation before continuing. The as­ and some power. The heartbeat comes in problem, we lock other processors out of sembly instruction "wait" forces the 8088 the form of an asymmetric square wave the bus. into an idling condition. It idles until it from the 8284 clock generator. The two­ An assembly instruction prefix of sees a low on TEST. This pin connects thirds low, one-third high nature of CLK "lock" forces the 8088 to pull its LOCK directly to the 8087' s BUSY output. So, as optimizes the 8088' s internal timing. And output low for the duration of the in­ soon as the 8087' s done, the 8088 can the power is a healthy 2.5 Watts of 5 struction. LOCK can then be used by the continue. Volts DC (at 0.5 Amps). system to restrict bus access during "Wait" instructions also show up semaphore updates. But the PC doesn't before most 8087 instructions. This MinimumfMaximum Modes need semaphores and uses LOCK in a guarantees that the 8087 will be finished This discussion has dealt only with different manner. with its last task before getting a new the 8088 in a maximum configuration. During a locked instruction, the PC one. The MN /MX input alters the functions of refuses to acknowledge hold requests nine processor pins and provides two from the DMA controller. I'm not sure Interrupts, Etc. modes of operation for the 8088. what purpose this serves. If anyone has A high on the interrupt request Maximum means a large, complex made use of the lock prefix in 8088 as­ (lREQ) line during T4 means a hardware configuration where the 8088 needs help sembly code, I'd like to hear from you. interrupt needs service. If the interrupt with system control. It also needs to be

40 MICRO CORNUCOPIA, #41, May-June 1988 able to handle coprocessors. programmable peripheral interface (PPI) there are plenty of topics we didn't even In a minimum configuration, the 8088 and an interrupt request 1 goes out to the discuss. How about the instruction set? generates its own bus control signals in­ interrupt controller (PIC). And what does microcode really look stead of using SO-52 as discussed above. If there aren't any higher priority in­ like? These extra control signals take the place terrupts waiting to be serviced, the PIC I could easily have filled this whole of the processor status, queue status, raises the 8088' s INT pin requesting in­ issue but Dave (and our advertisers) lock, and request/grant lines necessary terrupt service for the keystroke. If the would have me strung up. If you're for coprocessor control. So a system 8088' s interrupt flag is set (enabling inter­ hankerin' for more, take a wade through using the minimum configuration, like rupts), it finishes its current task and some of the following. the PCjr, cannot have coprocessors. pulls all of its status lines low. This causes the 8288 bus controller to Sources The V20 generate an interrupt acknowledge for This series in Micro Cornucopia in­ A few years back, NEC came out with the PIC. When the PIC sees that it has the cludes issues: an 8088 replacement called the V20. The processor's attention, it loads an 8-bit chip has proved to be very popular for a pointer onto the data bus. The 8088 reads • #35-8253 Counter /Timer couple of reasons. this pointer and uses it to index into a • #36-8259 Interrupt Controller First, it executes the 8080 instruction table of 256 4-byte vectors in the bottom • #37-8237 DMA Controller set. Quite exciting for the CP/M world at of the PC's address space. • #40-8255 Programmable Peri­ first, but interest in this feature seems to These vectors point to the interrupt pheral Interface have dwindled. And for good reason: handler code for each interrupt. For the And a bit more light reading: why cripple your clone with foreign keyboard interrupt, the 8088 gets a • IBM's Technical Reference for the software when an abundance of good pointer of 9 from the PIC. So the 8088 PC-XT. software exists that takes advantage of jumps to the address contained in the • Intel's 8086 Family User's Manual, the native system. ninth 4-byte vector. If no memory resi­ Component Data Catalog, and A better reason exists for using the dent programs are out there gobbling up Microsystem Components Handbook. V20. It's fast. Fast because of: keystrokes, the jump will be into the • Murray Sargent and Richard L. ROM BIOS. Otherwise some protected Shoemaker's The IBM Personal • Use of two data busses in the EU. area of RAM will contain the interrupt Computer From the Inside Out. • Faster address generation in the handler. • David C. Willen and Jeffrey I. BIU. In either case, the 8088 now processes Krantz's 8088 Assembler Language • Two extra 16-bit registers for mul­ the keystroke according to the code in Programming: The IBM Pc. tiplication/ division and shift/ro­ the interrupt handler and returns to tate instructions. whatever it was doing before the • Special prefetch pointer. This keystroke. pointer shows the location to be accessed next and reduces the loss Interrupted Interrupts of time due to jumps in code. The 8088 won't be able to deal with • New instructions for bit the keystroke without interruption. It has manipulation and BCD opera­ to contend with memory refresh, real tions. Interesting, but not that use­ time clock ticks, plus any memory resi­ ful. I doubt that many folks take dent code that's watching the clock. advantage of these because the Every 15 microseconds the DMA con­ software would be incompatible troller sees a pulse from counter 1 of the with the 8088. 8253 timer chip on its highest priority DMA request input. The DMA controller Use of CMOS technology gives sub­ requests a hold from the 8088 which stantial power savings over the 8088. The finishes up with its current task, grants V20 uses 0.5 Watts to the 8088's 2.5. The the hold, and sits back while the DMA V20 also enters a low power standby controller refreshes part of RAM. mode whenever it sees a halt instruction. The other periodic interrupt also !Rgfting originates in the 8253. Counter 0 gooses Tying It All Together the PIC's highest priority interrupt re­ 'Bar6 eque Over the past year we've talked about quest line about 18.2 times a second. the PC's five smart chips, one at a time. These "ticks" cause the 8088 to execute Computer tecli ta{~ But the PC is a system. So let's try to the time of day interrupt handler and make some sense of the interrelationships keep the time updated. which make the PC function. We'll keep it simple and just watch how a keystroke The End SOGVII ends up as a character on the screen. Well, that's it. We've looked at all the July 14 - July 16 Assuming an idling state with the cur­ smarts in the Pc. sor hanging out next to the DOS prompt, There's an amazing amount going on Bend, Oregon a keypress leads to the following events. in the 8088's little head. Although we've See you tfierell First, the scan code generated by the gone through a lot of detail, other levels keypress gets loaded into port A of the of obscurity exist below this one. And

MICRO CORNUCOPIA, #41, May-June 198~ 41 How Much Information Does A Message Contain? An Introduction To Information Theory

So What's In A Message? formation we've received is the resolu­ Who the heck cares about information When we receive a message (or a con­ tion of uncertainty associated with 32 theory? If we wanted theoretical stuff, we'd firmation that one of the possible mes­ outcomes. If we use the symbol H{N) for call ourselves Micro Theoretician. Micro C sages has materialized-let's say at a the amount of uncertainty associated is for practical solutions to real problems: modem), we can say we've received with N outcomes, we could describe the like the following. Enjoy. some information. race uncertainty this way- It also seems reasonable to say that the higher the uncertainty before we got H(32) = H(4) + H(8) the message, the higher the "quantity of information" that has been conveyed by This argument is perfectly general, so he mathematical theory of com­ the message. In other words, we can we can say that- munication developed by Claude measure the amount of information by TE. Shannon in 1948 is regarded as the amount of uncertainty resolved by H(m * n) = H(m) + H(n) one of the intellectual landmarks of this the message. century. Like many other great theories But how do we measure it? where m and n can be any numbers. (e.g., Newton's Three Laws Of Motion Take the extreme case where there's In other words, the quantity of infor­ or Einstein's principle that no material only one possibility. The outcome is cer­ mation conveyed by messages is addi­ body can travel faster than light), it's tain, so the uncertainty is zero. And any tive. based on seemingly simple but message confirming this already certain profound insights. outcome conveys absolutely zero infor­ Logarithms & Uncertainty At the heart of Shannon's theory is the mation. But this still doesn't let us Shannon showed that the only mathe­ idea that in all communication processes, measure uncertainty precisely. Recall the matical function which has this additive messages are sent to resolve uncertainty. race: how much more uncertainty is property is the logarithm. (The logarithm Each message (received) is one out of a there in 32 than in 8 outcomes? of any number A to a particular base B is set of possible messages which might If you guessed 4 times as much, you the power to which the base B should be have been sent. Let's look in detail at the guessed wrong. Is there 8 times as much raised to get the number A.) implications of this insight. uncertainty with 8 outcomes as with 1 For example, since 1000 = 10 raised to outcome? No. With 1 outcome, the un­ the power 3, the logarithm of 1000 to the Uncertainty certainty is a, and clearly it's unsatisfac­ base 10 is 3; and similarly since 32 is 2 Consider a situation where any of tory to say that with 8 outcomes, the un­ raised to the power 5, the logarithm of 32 several outcomes have the same pos­ certainty is 8 times a, or a as well. to the base 2 is 5, and so on. sibility. For example, take a horse race Let's reconsider the race. Instead of a Two other important properties of with no favorite, no dark horse, and an message telling us which of the 32 horses logarithms are- equal number of sorry nags, each with an has won, suppose we group the horses (1) the logarithm of 1 to any base is a identical chance of losing. into four groups: A, B, C, and D. We then (2) log (a/b) = log{a) -log(b) We "feel" intuitively that the larger get a first message telling us which of the If a message has one possible out­ the number of possibilities, the greater groups the winner is in, followed by a come, there is no uncertainty; so H(1) is the uncertainty of the outcome. That the second message telling us which of the 8 a, and the logarithmic measure fits in uncertainty of a tossup race of 32 horses horses in that group is the winner. with this as well. is greater than the uncertainty of a tossup The first message resolves our uncer­ The uncertainty H could be measured race of only 8 horses. tainty among 4 possible outcomes, and using any base for the logarithms, but

Let's examine this IIgeneral case" the second resolves our uncertainty there are considerable advantages in (where the alternative possibilities are all among 8 possible outcomes. We could using 2 as the base, as we'll see presently. identical) in some detail. Afterwards, say that the information we've received So from now on we'll use '10g" to mean we'll explore the modifications we need is the sum of the uncertainty associated "logarithm to the base 2." to extend our analysis to cases where with 4 outcomes plus the uncertainty as­ One advantage in using 2 as the base some outcomes are more probable than sociated with 8 outcomes. works like this-the uncertainty as­ others. But we could also say that the total in- sociated with 8 outcomes is log (8) = 3,

42 MICRO CORNUCOPIA, #41, May-June 1988 By Ramachandran Bharath - Mgmt., Mktg., & CIS Dept. Northern Michigan University Marquette, MI 49855

since 2 raised. to the power 3 is 8. We However, we should keep in mind We think generally of 2 raised to the could think of this 3 as the number of that when we talk bits here, we're think­ power 1 or 2 or 3 or 4 as meaning 2 mul­ characters we need for representing 8 dif­ ing of the least number of bits necessary tiplied by itself 1, 2, 3, or 4 times. What ferent alternatives if we use a character to represent the alternatives. To em­ then is 2 multiplied by itself 2.32 times? 2 set which has only 2 characters. phasize this, I'll use the word s_bits (for raised. to the power 2.32 =5. For example, if we use only the two Shannon bits) when referring to the What if we raised. 5 to the power 100 characters a and 1, we know we can have measure of uncertainty. This will distin­ (i.e., multiply it by itself 100 times)? That the 8 alternative codes: 000, 001, ala, all, guish it from the bits used. for holding would be the same as multiplying 2 lOa, 101, 110, and 111. More generally, the information in a computer. raised. to the power 2.32 by itself 100 with a string of K characters, each of The simplest case is 2 alternatives, times. This should give us 2 raised to the which is a a or a 1, we can have 2 raised. which we can associate with the uncer­ power 2.32 + 2.32 + ... a hundred. times to the power K alternative patterns. tainty of log(2) = 1 s_bit of information. (i.e., 232, a whole number). (Incidentally, The first character can be a a or 1, and Shannon used. the name "entropy" to both of these are pretty close to 17 fol­ corresponding to this, the second can be refer to the amount of uncertainty in an lowed. by 37 zeros). a a or 1, giving us 2 * 2 possible patterns. outcome, since the logarithmic formula With 3, we can have 2 * 2 * 2 possible he developed. was very similar to one Coding Blocks patterns, and so on, until we get 2 raised. which had been used. in the field of ther­ From the viewpoint of information to the power K patterns for K characters. modynamics. (fhe thermodynamics for­ theory, the implication is: if we code the So the amount of uncertainty with 2 mula was used. to measure a similar messages selected. from 5 alternatives, we raised. to the power N alternatives is N situation where there were a large num­ need. 3 characters to code each of them. units. Now we can say that the amount ber of possible configurations.) As we saw above, we're wasting some of of uncertainty in a situation with N alter­ In the examples above, I've con­ the capacity of these strings. But if we try natives is the minimum number of sidered cases where there are 8, 16, or 32 to pool sets of such messages, we may be characters required to code a different alternatives, all powers of 2. So, when we able to cut down the waste. message to represent the different alter­ take the logarithm to base 2, we get natives, using a two-character alphabet (0 whole numbers like 3, 4 or 5. Thi~ is the An Example and 1) for coding. number of a's and l's we need to repre­ Suppose we consider 100 messages The word "minimum" above is im­ sent the number of alternatives uniquely. with 5 alternatives each. portant. If we have two alternatives, the But what if the number of alternatives is, The number of alternative patterns we minimum string length we need for rep­ say,S? have is 5 * 5 * 5 .... or 5 raised to the resenting the two alternatives is just 1, If we look in a table of logarithms, we power 100. However, since 5 raised. to since we can say that a stands for alterna­ find the logarithm of 5 to the base 2 is the power 100 is the same as 2 raised to tive one, and 1 for alternative two. We 2.32(193). It doesn't seem to make sense the power 232, it means we should be could be wasteful and use longer strings, to say that we need a minimum of 2.32 able to code a block of 100 messages and say 00000 stands for the first alterna­ a's and l's to uniquely represent 5 pos­ using just 232 characters, and not 300 tive and 11111 for the second and so on, sibilities. characters as we must if we coded. them but we're thinking of the most economi­ First, we can see in a general way individually. cal way of distinguishing between the al­ why it comes out as more than 2 but less We could economize some by using ternatives. than 3. With two characters, we can rep­ smaller blocks. Suppose we have 3 such When data is represented. in a resent only 4 possibilities (which is not messages. The number of alternatives is 5 computer's memory using a's and l's, enough), and with 3 we can represent 8 * 5 * 5, or 125. If we code them in­ the on/off switches which we use to rep­ possibilities (which is more ~n we dividually, we have to use 3 characters resent the information are usually need.). for each, or 9 for the whole set. But if we described as holding one ''bit'' of infor­ However, we can go further than this. take the 3 messages as one then we need. mation each. So, we can say that the un­ If we try to code a message distinguish­ only 7 characters (a's or l's) to handle certainty or information content of a mes­ ing among 5 alternatives, we're forced. to 128 alternatives. sage selected. from N alternatives is use 3 characters, even though it's more So 7 characters would be sufficient to 10g(N) bits. than we need. represent the 125 alternative patterns

MICRO CORNUCOPIA, #41, May-June 1988 43 we're concerned with. And the block of 3 which uses a string of 7 D's and l's to sociated with each of the messages is messages needs only 7 characters (or 2.33 provide 2 to the power 7, or 12B alterna­ l/B. From this point of view, we can say characters per message). tives to represent the letters, numbers, that the uncertainty resolved by each By using even longer blocks, we move special symbols, etc. message is 10g{1/probability of the mes­ down to the limit of 2.32, which the So each character is a message with sage). This viewpoint allows us to extend measure of information/uncertainty tells about 7 units of uncertainty. And since the theory to a case where the messages us is the minimum number of characters uncertainty is additive, we can think of are not equally possible. required. the uncertainty in a long piece of text as the sum of the uncertainty in each of the Unlikely Messages Practical Examples strings of 7 D's and l's used. Let's consider a case with two alterna­ I've already talked about a number of Now let's look at the measure of un­ tives-"A" which has a probability of alternative messages. Now, in practice, certainty from a slightly different angle, 4/5, and "B" which has a probability of we don't send messages by having a set which will help in considering the case 1/5. We can say that the uncertainty of codes for each of the possible alterna­ where the alternatives aren't identically resolved by receipt of alternative "A" tives. We construct them by using a possible. is- series of characters from some alphabet. We saw that if there are, for example, For example, a message may be made B identical possibilities, the uncertainty 109(1/(4/5» = 109(5/4) = .322 s_bits up of letters of the English alphabet, plus associated with the situation is 10g(B) punctuation marks, numbers, and so on. s_bits. and the uncertainty resolved by receipt of But the analysis above can easily handle So, when we receive a message con­ alternative ''B'' is similar- this. firming anyone of the B, the amount of Think of each character in the mes­ information conveyed is log (B), and since 109(1/(1/5» = 109(5) = 2.322 s_bits. sage as a "mini-message" selected from a they're equally possible it makes sense to set of alternatives, since we could have say that the average amount of informa­ We could also say that, in a long chosen anyone of the characters of the tion conveyed by the receipt of a series of series of messages, on the average "A" alphabet. different messages selected from this set would be received 4/5 of the time, and We know that computers store or is also 10g(B). "B" 1/5 of the time. So, the average un­ transmit information coding the letters of Another way of looking at this is to certainty resolved by messages from this the alphabet using strings of D's and l's. say that since there are B equally possible set of two messages is a weighted The most widely used code is ASCII, messages, the chances or probability as- average--

4/5 * 0.322 + 1/5 * 2.322 = 0.722 MAILBASE SYSTEM™ s_bits. Productivity Software Now this brings up some interesting for DBase/Wordstar/Ventura Publisher issues. What does it mean to say that the • Letters/forms/contracts • Production • Record keeping • Grouped/repeated uncertainty is less than 1 s_bit, both in work, variations. Secretarial or professional use • Meeting management. Desktop the case of the message with probability input • dBASE file organizer. Develop your own specialized system with no pro­ 4/5 and for the weighted average? gramming • Constant or on-the-fly formatting • Stackware with standard programs Let's first look at the uncertainty as­ Painless construction of general letters, customized contracts, tabbed tables for sociated with alternative A, which we Ventura Publishers, etc; from dBASE II or III files. Use any version dBASE & Wordstar / MM. know is log(5/4), which (from the Track meeting participants; contracts; business letters; automatically make action properties of logarithms) is the same as summaries. Over 5 years of practical development. Never again type anything twice. log(5) -log(4). MS/PC-DOS, but also an Apple II CPM-Softcard version (not 7), 5114 disks. From the viewpoint of uncertainty, --FEATURES -- this tells us that the uncertainty has been I. Use any dBASE file & fields up to 214 (characters or numeric); reduced from a situation of 5 equally 2. Automatically track outgoing multl-copy letters &variants; possible alternatives to one of 4 equally 3. Select any fields at run time for latter Integration, adjacent fields for block text; 4. Branch to alternate letters In a single mallmerge pass then summarize regional actions; possible alternatives, and so is not much 5. Copy any fields to subsequent records, either old or newly appended, for letter/contract production; of a reduction in uncertainty. 6. Make consistent "structure extended" data dictionaries In dB format for transparent systems management Since "A" has a probability of 4/5 7. Produce correctly tabbed 2, 3, or 5 col. tables for Ventura Publisher from any dB file; 8. Other dB file management & production utilities; 2 col. Harvard Publisher tables, (other wp's on request); and "B" has a probability of 1 /5, we can 9. On-disk documentation: manual; tutorial; examples; letter/contract skeletons. Hardcopy manual $12 extra; think of the selection as being from a bag 10. Use to customize Invoicing systems, meeting management operations without programming. in which there are four pieces of paper • NOT COPY PROTECTED .. • Mail order only, $10 secondary sales rebate marked IIA" and one marked "B." So, • Money order or personal check (allow ten days to clear). when "A" materializes, it only means SEND TO: that one of the four A's has been picked. HARGER I.N.T. ONLY But even though we are technically P.O. Box 20, Grand Central Station "uncertain" which of the four A's was JKT Pouch picked, it doesn't really matter. For our New York, New York 10163 $45 purposes the four A's are equivalent. So dBASE II & dBASE III are trademarks of Ashton Tate, Wordstar & Mailmerge are trademarks of MicroPro. Apple II is a trademark of this residual "uncertainty" of log(4) isn't Apple Computer Inc. Softcard, MS-DOS & Microsoft are trademarks of Microsoft Corporation, CPIM is a trademark of Inc. PC DOS is a trademark of International Business Machines Corporation. Ventura Publisher is a trademark of Univation important, although it explains why the Inc. Harvard Publisher is a trademark of Softward Publishing Corporation. formal reduction in uncertainty comes Reader Service Number 26

44 MICRO CORNUCOPIA, #41, May-June 1988 out as a low figure when something has achieve are a direct result of Shannon's UNINTERRUPTABLE a high probability like 4/5. formula. POWER SOURCE More interesting is the conclusion we If we use one symbol for each mes­ have come to that the average uncertain­ sage, we would actually be using more ty is 0.722 s_bits. In terms of our previous symbols than we need. A situation like interpretation, this means we should on this, in which the uncertainty per symbol the average need a string of O's and l's is less than the maximum which can be whose length is less than 1 character. But handled (as we know, we can handle 1 with two alternatives, how do we use an s_bit of entropy using a two-character average length of less than 1 character, set), is said to exhibit redundancy. when at least 1 character is needed to While normally one would want to represent 2 alternatives? cut out redundancy, it has important Again, the answer lies in coding uses. For example, we can use it to MICRO blocks of messages, rather than in­ counter the distortion or "noise" of a SOLUTIONS protects your equipment and your data from power outages and dividual ones. Let's consider the mes­ message. brownouts. Our power systems provide sages in blocks of two. There are four the fastest switching speed in the in­ possibilities, AA, AB, BA or BB. The rela­ Noise dustry (2 ms± 1). tive frequencies with which we will get The most significant contribution of these sequences are in Figure 1. Shannon's work was a result known as EMI/RFI filtering and surge/spike protec­ tion all in one affordable unit. 1 year war­ Since the entropy calculations tell us Shannon's Second Theorem. (The First ranty on all units. Available in a size to that, on the average, the message A Theorem says it should be possible, by suit your needs - should require a string of less than one using block coding, to use a string of bi­ character, we try to economize on the nary characters whose length equals the 200 watts $290.00 350 watts $360.00 AA's by using just one character, say 0, entropy). 550 watts $410.00 to represent them. We want to make the The second theorem says that even if 800 watts $610.00 four messages uniquely decodable, so we messages get corrupted in transmission, 1000 watts $710.00 shouldn't use 0 as the start for any of the it's always possible to counteract this by Includes shipping to your door in the con­ sending a somewhat longer message. tinental U.S .. As specialists in overseas This is a remarkable result, and is at first systems, we can supply 220 volt units. Figure 1 - Relative Frequencies sight somewhat counter intuitive. Let's Call or write for details. consider a specific example. AA 4/5 X 4/5 - 16/25 or 0.64 prob. AD 4/5 X 115 - 4/25 or 0.16 prob. Let's say we have a message in which SOfTWARE SPECIAL SA 115 X 4/5 a 4/25 or 0.16 prob. the two symbols 0 and 1 are sent with BB 115 X 115 - 1/25 or 0.04 prob. equal probabilities 0.5. We know that BROOKLYN BRIDGE with 2 equally possible alternatives, the The BROOKLYN BRIDGE supplies the uncertainty or entropy is log(2) or 1 s_bit. link between the new PS/2 IBM com­ others. So we represent AB by 10, and If the messages are transmitted accurate­ puters or laptops that use 3.5" diskettes then for similar reasons, we represent BA ly, the information conveyed is 1 s_bit for and the rest of the MS-DOS world still using 5111" drives. The cable supplied will by 110 and BB by 111 (see Figure 2). each character transmitted. allow you to transfer files and software We see that the average number of O's Now suppose there is random distor­ between the two computers FAST. Simple and l's we would use for two messages tion, so that when a 1 is sent, 80% of the to use and reliable. Get it now for only is: time it's received as a I, but 20% of the $99.00 time it's corrupted into a O. Similarly, 0.64 * 1 + 0.16 * 2 + 0.20 * 3 = 1.56 when a 0 is sent, 80% of the time it's (or 0.78 per message) received correctly, but 20% of the time, it r.!Asher becomes a 1. ASHER TECHNOLOGY PUTS FAX ON There are various theoretical con­ Now, from the receiver's viewpoint, YOUR DESKTOP OR YOU CAN TAKE IT siderations regarding how best to code when a 1 is received, there is some WITH YOU ON YOUR LAPTOP FOR residual uncertainty. Was it a 1 sent LESS THAN $500. We have found the which has been received correctly, which answer to every small business's need for Figure 2 - Two-cltaracter Strings. FAX at a price they can afford, and that happens .5 * .8 (or .4 of the time), or was works. Get in on this exciting new Meaaage Code Length Probability it a corrupted 0 which happens .5 * .2 (or technology. Call for free demo disk! Al. 0 1 0.64 .1 of the time)? AD 10 2 0.16 SA 110 3 0.16 In other words, when a 1 is received, BB 111 3 0.04 the receiver has 4 to 1 odds, or .8 to .2, Iiiiii;'I RON ANGERT S that it's a correct 1 or a distorted I, and L!!!!J~ could compute the entropy of the mes­ _SOLUTIONS messages to make them uniquely sage as: decodable (while trying to reach the min­ . 8 * log (1/ . 8) + . 2 * log (1/ .2) = 0 .72 P.O. Box 166 Riner, VA 24149 imum limit indicated by entropy calcula­ 1-800-323-4829 (703) 382-6624 tions). I won't go into this branch of The same would hold if a 0 is call 24 hours - 7 days a week knowledge, known as Coding Theory. received, so the average entropy at the Visa MasterCard C.O.D. However, the economy and efficiency receiving end is 0.72. In contrast, with no that coding theory has been able to corruption the entropy at the receiving We Ship Worldwide Dealers Supported Reader Service Number 24

MICRO CORNUCOPIA, #41, May-June 1988 45 end is 0, since the receiver knows that of course, is that we're resolving uncer­ transmission of messages by telegraph, what is received is what was sent. Shan­ tainty at a lower rate, 0.28 per symbol telephone, and so on, its general scope non called the residual entropy the sent instead of 1 per symbol in a noise­ has led to continuing extensions of its ap­ Equivocation in the message. less channel. plications (see references below). So, the "noisy channel," instead of I won't go into the details of the proof In particular, it applies not just to resolving the uncertainty of 1, has only of this theorem, but let's consider why transmission of information, but to resolved 1 - 0.72 = 0.28. This figure is it's important. storage as well. You can think of storage said to be the Capacity of the channel of Shannon's theorem didn't tell us how of information as transmission, with a transmission. to resolve uncertainty. It simply showed delay between recording (sending) the us the minimum number of symbols message and retrieving it. Reducing Errors To Zero needed to reduce uncertainty to o. It's up By associating the quantity of infor­ On the face of it, it looks as if there to code theorists to come up with the mation in a message with the uncertainty may not be any recourse for remedying solutions. which a message resolves, Shannon was this uncertainty. How can the receiver This result is remarkable because it able to develop a simply brilliant field of know whether the 1 or 0 received was shows that something that seems intui­ knowledge which has led to deeper un­ sent as such or was received after distor­ tively impossible, is possible. And this derstanding of what information is and tion? theoretical reassurance has stimulated the how it can be best handled. The remarkable and powerful result development of coding methods which Of course, the theory has some limita­ which Shannon proved is this: it should try to get the equivocation as near 0 as tions in that it considers the number of be possible to find a way of coding the possible. possible messages as the key quantity. messages by using long blocks rather In practice, once the equivocation is We would say from our human perspec­ than coding the messages individually. very low, there may not be an advantage tive that a set of two messages ("you'll So the error rate is reduced to 0, in lowering the rate through longer get a million dollars"; "you won't get it") provided we don't try to reduce entropy blocks. Even if we repeat a message over isn't the same as the set ("you'll get one at a rate higher than the capacity. and over again, we can't be absolutely dollar"; "you won't get it"), although In other words, if we use an average sure there will be no errors (but based on each has an entropy of 1 s_bit. We think of 1/0.28 = 3.6 characters for reducing Shannon's theorem it is possible). of the first set as being more one unit of uncertainty, instead of the 1 "meaningful" or having greater "seman­ character we would use in a noiseless That's It tic significance." channel, it would be possible to reduce Though the theory of information was Shannon carefully pointed out in his the equivocation to O. The price we pay, developed in specific relation to the book that the "semantic aspects of com­ munication are irrelevant to the engineer­ ing problem." However, in the years since the theory was developed, there have been continu­ ing efforts to incorporate the semantic I use angle as well. Reference (3) in particular is an excellent source for an overview of Show Me! this aspect of the theory of information. References (1) Shannon, C. E. and Weaver, W.: all day long. The Mathematical Theory of Communication (Urbana, IL: University of Illinois Press, 1964). (2) Usher, M. J.: Information Theory for ".. . it's great!" Technologists (London, UK.: Macmillan Publishers, 1984). Show Me!, the pop-up multi-window file viewer, (3) Campbell, J.: Grammatical Man allows you to browse, print, search, and paste from (New York, N.Y.: Simon and Schuster, any file. New Version/II adds EMS and LAN support, 1982). multi-file -text search, and more! Our customers (4) Bharath, R.: Information Theory swear by Show Me! You will too! (BYTE, December 1987, pages 291-298) Escape••• through the windows of Show Me! • • • Call for your FREE demo disk (800) 634-3122 Single user version $59.95; unlimited user network version $119.95. Add $5 shipping & handling. Visa & Mastercard accepted. Unconditional 90 day satisfaction guarantee. Serengeti Software • P.O. Box 27254 • Austin, Texas 78755

Reader Service Number 27 46 MICRO CORNUCOPIA, #41, May-June 1988 New, Lower Prices fQr CP/M • VEDIT Version 1.40 ...... $49 (Single file, no windows) • VEDIT PWS Version 2.32 ...... $79 (Multiple file, no windows) • VEDIT PWS Version 2.33 ...... $95 (Current version with windows)

PROGRAMMABLE EDITOR

FREE Fully Functional Demo Disk *

Stunning speed. Unmatched performance. Total flexibil­ ity. Simple and intuitive operation. The newest VEDIT PLUS defies comparison. Call for 286 I XENIX Version Try A Dazzling Demo Yourself. Fully Network Compatible The free demo disk is fully functional - you can try all features yourself. Best, the demo includes a dazzling • Simultaneously edit up to 37 files of unlimited size. menu-driven tutorial - you experiment in one window • Split the screen into variable sized windows. while another gives instructions. • 'Virtual' disk buffering simplifies editing of large files. The powerful 'macro' programming language helps you • Memory management supports up to 640K. eliminate repetitive editing tasks. The impressive • Execute DOS commands or other programs. • MS-DOS pathname support. demo/tutorial is written entirely as a 'macro' - itshows that • Horizontal scrolling - edit long lines. no other editor's 'macro' language even comes close. • Flexible 'cut and paste' with 36 'scratch-pad' buffers. Go ahead. Call for your free demo today. You'll see why • Customization - determine your own keyboard layout, create VEDIT PLUS has been the #1 choice of programmers, your own editing functions, support any screen size. writers and engineers since 1980. • Optimized for IBM PC/XT/AT. Color windows. 43 line EGA. Available for IBM PC, Tandy 2000, DEC Rainbow, MS­ EASY TO USE DOS, CP/M-86 and CP/M-80. (Yes! We support windows • Interactive on-line help is user changeable and expandable. on most CRT terminals, including CRT's connected to an • On-line integer calculator (also algebraic expressions). IBM PC.) Order direct or from your dealer. $185. • Single key search and global or selective replace. • Pop-up menus for easy access to many editing functions. • Keystroke macros speed editing, 'hot keys' for menu Compare features functions. and speed BRIEF Norton PMATE VEDIT FOR PROGRAMMERS Editor PLUS • Automatic IndentlUndent for 'C', PUI, PASCAL, etc. 'Off the cuff' macros No No Yes Yes • Match/check nested parentheses, i.e. T and '}' for 'C'. • Automatic conversion to upper case for assembly language Built-in macros Yes No Yes Yes labels, opcodes, operands with comments unchanged. Keystroke macros Only 1 No No 100+ • Optional 8080 to 8086 source code translator. Multiple file editing 20+ 2 No 20+ Windows 20+ 2 No 20+ FOR WRITERS Macro execution window No No No Yes • Word Wrap and paragraph formatting at adjustable margins. Trace & Breakpoint macros No No Yes Yes • Right margin justification. Execute DOS commands Yes Yes Yes Yes • Support foreign, graphic and special characters. Configurable keyboard • Convert to/from WordStar and mainframe files. • Print any portion of file; selectable printer margins. Layout Hard No Hard Easy 'Cut and paste' buffers 1 1 1 36 MACRO PROGRAMMING LANGUAGE Undo line changes Yes No No Yes • 'If-then-else', looping, testing, branching, user prompts, Paragraph justification No No No Yes keyboard input, 17 bit algebraic expressions, variables. On-line calculator No No No Yes • Flexible windowing - forms entry, select size, color, etc. Manual size / index 250/No 421No 469/Yes 380/Yes • Simplifies complex text processing, formatting, conversions and translations. Benchmarks in 120K File: • Complete TECO capability. • Free macros: • Full screen file compare/merge • Sort mailing 2000 replacements 1 :15 min 34 sec 1 :07 min 6 sec lists. Print Formatter. Menu-driven tutorial Pattern matching search 20 sec Cannot Cannot 2 sec Pattern matching replace 2:40 min Cannot Cannot 11 sec

~~~e~:~~ ~°tTn~~~:re~rrn~~~~~~~ :!a~~~~~k~a~~ ~~~~~~~i~ f~~~~~l~gl~;'L~~!Wo~~o~ Editor is a trademark of Peter Norton Computing Inc . CompuView • Demo Disk is fully functional. but does not readily write large files. Reader Service Number 7 1955 Pauline Blvd., Ann Arbor, MI 48103 (313) 996-1299, TELEX 701821

MICRO CORNUCOPIA, #41, May-June 1988 47 A C Compiler Update And Secrets Of MS-DOS

By Scott Robert Ladd statements embedded in loops. The compile P.o. Box 61425 Scott updates his C review from last issue and will fail with an "out of heap space" error. I Denver, CO 80206 then looks closely at C's near pointers, far pointers, still haven't figured out why some switch state­ 303) 322-7294 model sizes ... ments are a problem, while others aren't. The problem only occurs in the small and medium models, when the lOa or lOx switches are hew! I'm glad that C compiler used. . review is over with - that was a lot Microsoft is working on a new (5.1) release of compiling and linking and com­ of MSC. It will have an editor, a new linker, Wpiling and linking and compiling and will work with both MS-DOS and OS/2. It and linking and ... what? The UPS man? With will be possible to create dynamically-linkable another compiler? More than ONE?! Well, I libraries with the new version. All known bugs guess I'll sign for it ... will be fixed. Also coming from Microsoft are A current table of benchmark results is new versions of Macro Assembler (MASM), available on the Micro Cornucopia BBS, at (503) Pascal, Fortran, and a business BASIC compiler. 382-7643. For example, it now contains figures All of these new compilers will work with both for Datalight Optimum-C v3.14, Turbo C loS, MS-DOS and OS/2. A new OS/2 Software Mark Williams Let's C v4.0.12, and MIX Power Developer's Kit, with a $350 price tag, will also C vl.0.0. be announced. My arm is getting sore filling Let's start with an update on the compilers out update forms ... reviewed last issue. Speaking Of OS/2 ... OOPS Lattice will soon be releasing a new version Somehow, a line got dropped somewhere in of their C compiler which will support OS/2 my comments about Quick C in issue #40. development. The new compiler will run under Quick C DOES use standard libraries CLIB both MS-DOS and OS/2. A global optimizer files). The integrated version uses just the and a symbolic debugger will be included. standard Quick Libraries, unless told otherwise in a Program List (used to build a MAKE con­ Datalight Optimum-C trol file). The Quick Library provided excludes The folks at Datalight are up to version 3.14 such things as math and graphics functions. To now; it seems almost as though they're running add functions not present in the default Quick the version-of-the-month club. I appreciate Library you must either create a new Quick Walter Bright's (the author of Datalight C) at­ Library, or include the Medium model library titude: if there's a bug, he wants the users to (MLlBCE.L1B) in a Program List. get the fix as soon as possible. Although this means the compiler constantly changes, it also Microsoft Update means a better and better compiler. Datalight Early versions of Quick C would cause a has a subscription BBS (for $60 per year), where hard disk crash when used with a specific type you can get the absolutely latest version of the of old Western Digital controller. This was a compiler at any time; otherwise, you can up­ bug in the controller, not in Quick C. You can date to the current version for $20. either upgrade your controller ROM (by con­ Performance with Optimum C 3.14 has im­ tacting Western Digital), or get a modified ver­ proved, especially in the area of floating-point sion of Quick C from Microsoft (call (800) 426- calculations. Code size has increased just slight­ 9400). ly (approx. 200 bytes) from version 3.12. I still Microsoft's Optimizing C (which I ab­ don't recommend this compiler to beginners breviate as MSC) version 5.00 will not compile (poor documentation), but an expert can't go some programs containing complex switch wrong with Optimum-Co

48 MICRO CORNUCOPIA, #41, May-June 1988 Borland Turbo C vl.S The 8086/8088 microprocessor seg­ (code) segment, while the DS register I mentioned Turbo C vl.5 in the ments its memory, whereas chips such contains the current data segment. review, pointing out that you would see as the older Z80 think of memory as A near address is faster because the it by the time the review appeared in being "flat." In a flat memory space, ad­ processor doesn't have to load a new print. True enough, Turbo C 1.5 has ar­ dresses are linear. The Z80 uses 16 bits value into a segment register. However, rived, and it looks good. An object­ to indicate an address, which translated a near address can only range over a module librarian and a GREP utility are into 64K, or 65,536 bytes of memory. 64K area, while a far address reaches now included. The compiler itself hasn't To expand memory addressing any location within a megabyte. changed much; in fact, it generates beyond 64K, Intel added four more bits slightly larger (800 - 1000 bytes) ex­ of address. That 20 bits meant the 8086 Memory Models ecutables than before, due to an increase family could access 1 meg (64K X 16). There are several ways of using seg­ in the size of some library modules. One Since twenty bits don't fit into a single mented memory when creating a surprising difference is in the speed of 16-bit word (without data compression), program, and this is where the concept disk access, where the time with version Intel used two words to specify a of "memory models" was born. 1.5 is 25% more than with 1.0. memory location, one called the "seg­ Many compilers let you select from All Borland languages (Turbo C, ment," the other the "offset." six models. Turbo C supports all six Turbo Pascal, etc.) support a graphics Editor's note: I used to wonder why models; Turbo Pascal only supports the library called the "Borland Graphics Intel didn't just paste the two addresses Large model. Figure 1 shows the Interface", or BGI. It supports nearly together as a 32-bit total. Then it could ad­ various models. every PC graphics adapter I've heard of, dress lots and lots of memory, make life Sometimes data needs a single un­ including Hercules and EGA cards. It easier for new programmers, and compete broken space larger than 64K. The huge can automatically sense which type of with Motorola's 68000. But I suppose that model pastes together segments to adapter is installed, allowing you to was too obvious. create a larger single space. write programs which will run on mul­ To generate a 20-bit address, the seg­ tiple adapters. ment word is shifted 4 bits to the left Pointers (multiplied by 16) and then added to Most programming languages have a MixPowerC the offset. This gives the 20-bit linear data type called a "pointer" which con­ This compiler is being heavily adver­ tains a memory address. The size of a tised as a competitor to both Turbo C and MSC. In the past, MIX has Figure 1 - Memory Model Sizes produced a non-standard compiler (known as MIX C), and was generally Memory Model Code Addresses Data Addresses considered an excellent choice for learn­ Tiny (Compact) code and data share one segment ing C. Power C is an ANSI compatible, Small near near optimizing compiler, and sells for the Medium (Program) far near amazing low price of $19.95. What do Compact (Data) near far you get for such a small amount of Large far far money? Huge far huge Power C has a huge library (400+ functions) which is a superset of the MSC v4.0 library. There seems to be a function for every occasion, including address. Two different segment and of­ pointer depends on the memory model. simple graphics and support for CGA, fset pairs can point to the same memory In the Medium model, pointers to EGA, and Hercules graphics cards. The location. procedures and functions (code) are two source for the library is available for There are 65,536 possible segments, words long, containing a far address. $10.00. each 16 bytes apart. We call these 16- The data pointer is only one word long, The performance claims on the back byte chunks "paragraphs." MS-DOS containing a near address. Thus, the cover of the manual look awfully good. aligns its memory areas on paragraph Medium model is very efficient for Are they true? Well ... there are bugs in boundaries and allocates memory in 16- programs with large amounts of code, the release (1.0.0) I received. For in­ byte multiples. but relatively small amounts of data. stance, even following MIX's sugges­ Some compilers offer "mixed model" tions, I couldn't get Power C to compile Near And Far programming. This lets you declare any programs which contain recursion. Due to the complex nature of pointers far and near (or far and wide). I'll wait for the "fixed" version they're memory, addresses come in two types: Now that you (hopefully!) under­ sending me. As soon as I can compile near and far. stand the concept of memory models all the benchmarks, I'll add Power C to A near address is a single 16-bit and pointers, let's begin dissecting the the master charts. word, containing an offset within the special (and largely undocumented) current 64K segment. A far address con­ ways MS-DOS uses the PC's memory. Memory Models and Pointers sists of two words, one a segment, the If you're going to do intricate or sys­ other an offset. Memory Control Blocks tem-level programming under MS-DOS, Near addresses don't change the seg­ One function of an operating system you'll need to understand how the ment (usually stored in one of the is to regulate the use of memory. MS­ microprocessor and MS-DOS handle processor's segment registers). The CS DOS must organize space for its own memory. Let's take a quick look. register contains the current executable code, device drivers, TSRs, normal

MICRO CORNUCOPIA, #41, May-June, 1988 49 programs, and data. The Memory Con­ Figure i-Format· Of TIt.!! r\.iemory Control Block trol Block, or MCB, is DOS's primary tool for memory management. An MCB takes up 16 bytes (one paragraph), of which only the first five bytes are sig­ nificant. These five bytes have the for­ mat shown in Figure 2. (Note: I use a trailing "h" to designate hexadecimal values.) 3h The Block Size specified in the memory control block tells how many paragraphs of memory are in the block controlled by the MCB. An MCB's block of memory follows immediately. Byte Byte The MCBs are organized as a con­ Offset Length . Purpose tiguous chain. If the chain byte is an OOh 2 ~eSOS8instruction.. INT .20h •. 1. program can "M," it's a member of the chain; other­ jumpto.this.iristruction to exit •. Calling wise, it's the last block in the chain. MS­ function 4Ch .of INT 21h is considered to be DOS function 48h allocates a new . the proper way of exiting,tho1l9h. . memory block, function 49h deletes a 02h 2 Segment address of .. the top of allocated. block, and function 4Ah attempts to memory. change the size of a block. 04h 1 Unknown •..•. ~eserved by· MS":':DOS . Undocumented function 52h will return a segment in the ES register and OSh S A far call to the MS~DOS function dispatcher I equivalent·. to executing an INT an offset in BX; subtracting 2 from BX 21h. will give you the address (in ES:BX) of a word containing the segment of the first OAb 4 The previous INT22h (DOS Terminate) address. MCB. I'm not sure what this function OEh 4 The previousINT'23h (CTRL-BREAK) address. actually points to, but it works for find- 12h 4 The previous tNT 24h (Critical Error) address •.

16h 2 PSP segment of parent program. UNDOCUMENTED~ CIRCUIT BOARDS lSh 20 MS-DOS file handle table. UNDOCUMENTED. 2Ch 2 The segment of this program's copy of the PCB-Edit ... creates multi-layered environment. UNDOCUMENTED. PCB's with ease. Included are solder 2Eh 34 Unknown. Reserved bY.MS.:-DOS. mask and legend ink support, plotter and printer drivers, and one of the SOh 3 INT 21h and far RET instructions. This is fastest CAD artwork layout packages definitel~NOT a recommended way of for the IBM access1ngINT 21h.

Only ...... $99.95 . S3h 2 Unknown. Reserved by MS~DOS. Demo Disk .... $10.00 55h 16 Default File Control Block (FCB) number 1. MS-DOS parses the first command line parameter into .. this area, . making. the PCB-Shop ... will build your double assumption .. that it's a file name~ sided, plated thru holes circuit boards from PCB-Edit files, or your 6Sh 16 Defaulti'il.e c()ntrol Block (FCB) . number . 2. artwork for only $1.00 per square inch MS:-DOSparses the .first command line parameter.intothis . area, . making the .. in single quantity. No set up charges assumption that it '.s a. file name.

Call or write for more information. ANALOGIC Phone(602)45~4065 P.O. Box 3228 Sierra Vista, Arizona 85636

Reader Service Number 38

50 MICRO CORNUCOPIA, #41, May-June 1988 ing the first MCB in versions 2.11, 3.1, Figure 4 - Accessing The and 3.2x of MS-DOS. Several programs, most notably the #inc1ude "stdio.h" public domain MAPMEM from Turbo­ #include ".h" Power Software, examine the chain of extern unsigned ~sp; 1* declare the ~sp variable *1 MCBs, using them to discover what is currently in memory. After finding the 1* define the PSP structure *1 first MCB, subsequent ones can be lo­ struct PSP ( cated with the following formula: char fi111[10]; void far *old INT 22; Next MCB segment = void far *old-INT-23; void far *old-INT-24; 16 * (Current MCB Size + 1) unsigned int par;nt seg; unsigned char handles[20] ; unsigned int environ seg; If the chain of MCBs is broken, MS­ char fi112 [82] ; DOS will eventually crash with a unsigned char tail len; "Memory Allocation Error." Only the char cmd_tail [127] ; }; last block of memory in the chain can be deleted safely; this is why you're in /* declare a pointer to a PSP structure *1 trouble if you remove a TSR from struct PSP far *PSPdatai memory when it's followed by other maine) programs and/or TSRs. { unsigned char i;

Program Segment Prefix (PSP) /* make a far pointer to the PSP *1 Each MCB has a pointer to the PSPdata = (struct PSP far *)MK_FP(~sp,O)i Program Segment Prefix, or PSP, of the /* print the command tail */ program which owns it. The PSP is 256 for (i = 0; i < PSPdata->tail len; ++i) bytes long, and as its name implies, it putchar(PSPdata->cmd_tail[i])i resides in memory as a prefix to the /* with a final CR *1 program it is associated with. The PSP putchar('\n'); } is rather fascinating, containing some very handy and interesting information. Figure 3 shows the format of the PSP, including several undocumented fields. Many programming languages im­ plement a special, reserved variable which points to the segment address of As you can see, my structure doesn't mand line. C, for example, has argc (ar­ the PSP. In most C compilers, the vari­ define every field in the PSP. Some of gument count) and argv (an array of able is called _psp, and is declared in the information in the PSP just isn't ter­ command line component strings), the header file DOS.H. ribly usefuL For example, the hard­ which are passed to mainO as Turbo Pascal calls it PrefixSeg, and coded places which execute interrupts parameters. Turbo Pascal has the it's part of the DOS unit. Turbo also has and jumps are holdovers from MS­ ParamCount and ParamStr procedures. a pair of DOS functions which provide DOS's early days when it tried to emu­ While very useful, these built-in the PSP of the currently executing late CP/M. The same thing goes for the functions assume that items on the com­ program. two FCB blocks; FCBs have been sup­ mand line are separated by spaces and Calling the DOS function dispatcher planted by 1/0 functions which use file tabs. Sometimes it's necessary to ex­ (INT 21h) with the AH register set to handles. amine the command line directly, pars­ either 62h or 51h will get you the cur­ The program in Figure 4 accesses ing it according to your own rules. rent PSP in the BX register. Why there what is generally the most useful item A word of warning: certain DOS are two identical functions (in MS-DOS in the PSP-the "command tail," begin­ functions store the data they retrieve in 3.21, they execute exactly the same ning at offset B1h. DOS takes the com­ a location known as the Disk Transfer code!), no one knows. Function 62h is mand line which executed the program, Area, or DTA. The initial DT A address documented, while 51h is not. But 62h strips off the name of the program, and is set to offset BOh within the PSP, right is only available in DOS 3.x or higher. stores the remainder in this area. where the command tail is stored. Function 51h worked in my tests for I/O redirection and pipe operators The FCB file and the directory search DOS versions 2.1 and later. «, >, and I) are also removed from the functions use the DTA. Very, very few To access the PSP, a program should line before storage. The length of the compilers use the FCB functions for file define a far pointer to a structure (or resulting string is stored in the PSP at 1/0, preferring the more flexible and record in Pascal) which is formatted like offset BOh. A carriage return (not in­ modern "handle" I/O functions intro­ the PSP. Then, using the PSP segment cluded in the length) terminates the duced with DOS version 2. If you do and an offset of 0, the pointer can be as­ string. use a function which puts its data in the signed to address the PSP data area. DTA, such as the directory search func­ Figure 4 shows this technique using Accessing The Command Line tions 4Eh and 4Fh, use function 1Ah to Turbo C. It will display the command Most programming languages sup­ set a new DTA address, or save the tail contained in the PSP. port functions for accessing the com- command tail in your own buffer.

MICRO CORNUCOPIA, #41, May-June, 1988 51 The stored interrupt vectors can be will have from 8 to 255 entries, depend­ handy, too. These are used by MS-DOS ing on the FILES= entry in your CON­ to restore the previous vectors upon FIG.SYS configuration file. Am~TheC program termination, in case the When a program starts up, the first program changes them. five entries in the PSP handle table are When capturing one of these inter­ automatically assigned (in order) to the Store,. rupts in a memory-resident program, values found in Figure 5. you need to change the associated vec­ Any value other than FFh in a hand­ EVERYTHING FOR tors in the PSP to point to your Inter­ le indicates that it is open to a file or THE C PROGRAMMER rupt Service Routines (ISRs). Do this device. As you can see, this system FREE SHIPPINGI before executing the Terminate and Stay gives MS-DOS great flexibility in assign­ PL US FREE SOFTWAREI Resident (TSR) function. Otherwise, ing a program's I/O to files and LATTICE C COMPILER Ver 3.2 $229 DOS will restore the original vectors, devices. Since MS-DOS treats a device The classic DOS development environment. and any ISRs you may have installed the same way it treats a file, it can do MICROSOFT C COMPILER Ver. 5.0 $269 will no longer be attached. I/O redirection (the >, <, and I com­ Innovative CodeView~ debugger, "make", more. mand line operators) merely by chang­ TURBO C COMPILER Ver. 1.5 $69 File Handle Table ing the internal handle in the program's Fast, full development environment bargain. The file handle table (once again, un­ PSP handle table. INSTANT C INTERPRETER Ver. 3.0 $379 documented by Microsoft) explains Instant linking, execution and debugging! Directly link Microsoft, lattice libraries. some things about MS-DOS file han­ Finally

C·TERP C INTERPRETER Ver. 3.0 $229 dling. When using the UNIX-like I/O I hope the information above gives Virtual memory support, versions for all compilers. functions (which appeared with MS­ you plenty of room for thought and ex­ PC LI NT Ver. 2.10 $99 DOS 2), files are referenced by a one perimentation. In the next issue, I'll ex­ Shake out C bugs before compiling; neat! byte "handle." plain how the MS-DOS environment PANEL PLUS Ver. 1.0 (w/source) $379 DOS uses this number as an index works, and how to manipulate the Complete screen I/O development, no royalty. into the table stored in the PSP, which master copy of the environment. I'll also WINDOWS FOR C Ver. 4.14 $149 contains what I call the "internal keep you updated on new develop­ WINDOWS FOR DATA Ver. 2.06 $229 Flexible, fast, high quality windowing system. handle" of the given file. The internal ments in C compilers and tools. See ya handle is an index into the primary then! GREENLEAF LIBRARIES: Functions Ver. 3.10 $129 table of DOS file handles, stored deep Communications Ver. 2.10 $129 down inside MS-DOS. The internal table Data Windows Ver. 2.10 $159 • • • Data Windows/With Source $269 Seasoned, reliable library leader of the pack.

CTREE Ver. 4.1 $299 RTREE Ver. 1.1 $229 CTREE/RTREE Package $499 Figure 5 - Automatic Assigments In The PSP One of the fastest B-trees, handles networks.

BTRIEVE Ver. 4.1 $179 Table Entry Handle Name Value (Device) XTRIEVE Ver. 3.02 $179 XTRIEVE report opt/on Ver. 3.02 $99 o Standard input 01 (CON- console) Innovative performer, fault tolerant B-tree. 1 Standard .. output 01 (CON- console) dbVISTA with Source Ver. 2.21 $389 2 Standard·error 01 (CON- console) dbQUERY with Source Ver. 1.0 $389 3 Standard auxiliary 00 (AUX- serial port) Very fast portable B-tree, Sal query option. 4 Standard" printer 02 (PRN~ printer) 5 thru 20 Open handles FFh NORTON GUIDE: C Ver. 1.0 $69 NORTON GUIDE: C/ASM Twin Pack Ver. 1.0 $110 Online help and reference when you need it.

THE BEST QUALITY C PRODUCTS AT THE BEST PRICES!

ORDER TOLL FREE: (800) 356-0909 THE COMPLETE COMPUTER RECIPE SYSTEM Use your personal computer to plan your weekly meals, IN NEW YORK CAll: parties and special Holiday meals. Includes 75 basic (800) 341-1950, EXT. 889 recipes and 500 recipe references from 5 popular cookbooks. Easy to use screens to help you set up your • FREE! PC-Write V2.71 complete word own recipes and categories. Add up to 200 of your own processor or Spectacular Two Player, recipes, up to 1200 recipe references. Has a unique . Real-Time SPACEWAR V1. 71 with feature to help you create a cross reference index of every order! • FREE! No charge for UPS Ground. recipes, giving the recipe name, book or magazine and page number. Has fast, easy to use software to help you - No surcharge for VISA or Mastercard. with your recipe selections. Adjust ingredients from (1-99) - 24 hour 1200 Baud order line! (914) 241-9324. - Customer/Technical Support (914) 666-8119. servings. Print recipes for friends and kitchen use. Prints - No APO, FPO or international orders. the shopping list too! $39.50 - 30 day money back guarantee on unused items with intact seals. Apple lillie/lie, one disk drive ...... Order 523A Lori & Nick's Enterprises IBM PC/JR/XT/AT & compatibles, 128KB, 1 disk dr ...... 5231 The C Store, Suite 277 57 Bridge Street • Box 392-A Add $2 for shipping & handling. Send check or Money Order. 487 East Main Street, Mt. Kisco, NY 10549·0110 Hillsboro, New Hampshire 03244 SATISFACTION GUARANTEED Reader Service Number 53 52 MICRO CORNUCOPIA, #41, May-June 1988 C CODE FOR THE PC source code, of course C Source Code Bluestreak Plus Communications (two ports, programmer's interface, terminal emulation) $400 CQL Query System (SQL retrievals plus windows) ...... $325 GraphiC 4.1 (high-resolution, DISSPLA-style scientific plots in color & hardcopy) ... . $325 Barcode Generator (specify Code 39 (alphanumeric), Interleaved 2 of 5 (numeric), or UP C) $300 Greenleaf Data Windows (windows, menus, data entry, interactive form design) ...... $295 Aspen Software PC Curses (System V compatible, extensive documentation) ...... $250 Vitamin C (MacWindows) ...... $200 Essential resident C (TSRify C programs, DOS shared libraries) ...... $165 Essential C Utility Library (400 useful C functions) ...... $160 Essential Communications Library (C functions for RS-232-based communication systems) . $160 Greenleaf Communications Library (interrupt mode, modem control, XON-XOFF) . . . $150 Greenleaf Functions (296 useful C functions, all DOS services) ...... $150 OS/88 (U**x-like operating system, many tools, cross-development from MS-DOS) $150 Turbo G Graphics Library (all popular adapters, hidden line removal) .... . $135 American Software Resident-C (TSRify C programs) ...... $130 CBTree (B+tree ISAM driver, multiple variable-length keys) ...... $115 Minix Operating System (U**x-like operating system, includes manual) . . . . $105 PC/IP (CMU/MIT TCP/IP implementation for PCs) ...... $100 B-Tree Library & ISAM Driver (file system utilities by Softfocus) ...... $100 The Pro filer (program execution profile tool) ...... $100 Entelekon C Function Library (screen, graphics, keyboard, string, printer, etc.) . . $100 Entelekon Power Windows (menus, overlays, messages, alarms, file handling, etc.) $100 Wendin Operating System Construction Kit or PCNX, PCVMS 0 IS Shells .. . $95 Professional C Windows (windows and keyboard functions) ...... $80 JATE Async Terminal Emulator (includes file transfer and menu subsystem) $80 MultiDOS Plus (DOS-based multitasking, intertask messaging, semaphores) $80 ME (programmer's editor with C-like macro language by Magma Software) $75 WKS Library (C program interface to Lotus 1-2-3 program & files) . . . . $65 Quincy (interactive C interpreter) ...... '...... $60 EZ-ASM (assembly language macros bridging C and MASM) ...... $60 PTree (parse tree management) ...... $60 HELP! (pop~up help system builder) ...... $50 Multi-User BBS (chat, mail, menus, sysop displays; uses Galacticomm modem card) $50 Heap Expander (dynamic memory manager for expanded memory) ...... $50 Make (macros, all languages, built-in rules) ...... $50 Vector-to-Raster Conversion (stroke letters & Tektronix 4010 codes to bitmaps) $50 Coder's Prolog (inference engme for use with C programs) ...... $45 C-Help (pop-up help for C programmers ... add your own notes) ...... $40 Biggerstaff's System Tools (multi-tasking window manager kit) ...... $40 CLIPS (rule-based expert system ~en~rator, Version 4.0) ...... $35 TELE Kernel or TELE Windows (Ken Berry's multi-tasking kernel & window package) $30 Clisp (Lisp interpreter with extensive internals documentation) ...... $30 Translate Rules to C (YACC-like function generator for rule-based systems) $30 6-Pack of Editors (six public domain editors for use, study & hacking) . . . $30 ICON (string and list processing language, Version 6 and update) ...... $25 LEX (lexical analyzer generator) ...... $25 Bison & PREP (YACC workalike parser generator & attribute grammar preprocessor) $25 AutoTrace (program tracer and memory trasher catcher) ...... $25 C Compiler Torture Test (checks a C compiler against K & R) ...... $20 Benchmark Package (C compiler, PC hardware, and Unix system) ...... $20 TN3270 (remote login to IBM VM/CMS as a 3270 terminal on a 3274 controller) $20 A68 (68000 cross-assembler) ...... $20 List-Pac (C functions for lists, stacks, and queues) ...... $20 XLT Macro Processor (general purpose text translator) ...... $20 Data WordCruncher (text retrieval & document analysis program) ...... $275 DNA Sequences (GenBank 52.0 including fast similarity search program) ...... $150 Protein Sequences (5,415 sequences, 1,302,966 residuals, with similarity search program) . . . $60 Webster's Second Dictionary (234,932 words) ...... $60 U. S. Cities (names & longitude/latitude of 32,000 U.S. cities and 6,000 state boundary points) $35 The World Digitized (100,000 longitude/latitude of world country boundaries) ...... $30 KST Fonts (13,200 characters in 139 mixed fonts: specify '!EX or bitmap format) . $30. USNO Floppy Almanac (high-precision moon, sun, planet & star positions) .. $20 NBS Hershey Fonts (1,377 stroke characters in 14 fonts) $15 U. S. Map (15,701 points of state boundaries) .... $15 The Austin Code Works Voice: (512) 258-0785 11100 Leafwood Lane [email protected] BBS: (512) 258-8891 Austin, Texas 78750-9409 USA Reader Service Number 4 FidoNet: 1:982/12 Free shipping on prepaid orders For delivery in Texas add 7% MasterCard/VISA

Reader Service Number 4 Building A Fancy Keyboard Translator Around Int 16h

Laine Stump Benchmark Blues PC Tech Indomitable Laine is willing to try anything. They've done it again. I don't know how it P.O. Box 128 When he isn't jeeping about in Turkish mountains happens, but every time somebody tries to Lake City, MN 55041 or rafting virgin rivers, he's braving the vicious publish some benchmarks, they end up with winters in ... No it can't be. an inaccuracy somewhere. I've heard of privation, but Lake City? Think of Take, for example, the running saga in the culture shock. (Is there nothing Laine won't at­ "Tidbits" of the Standard Deviation function tempt?) which mysteriously runs faster in Prolog than it does in C. Well, I have no idea why, whether, or how, that might be, but when I bet you're expecting to hear some story saw the row in the benchmark spreadsheet about fighting off wild hippos from a reed showing a 10 Mhz 286 running approximately canoe while floating down the Blue Nile. Or 7 times faster than an 8 Mhz 186, I simply had Imaybe rappelling from 5,000 foot cliffs into to investigate. a neo-Shangri La filled with dark-skinned Since I'm now working in a shop full of beauties. Well, I hate to disappoint you, but 186 based machines (X16Bs), and since the I've become suddenly, but temporarily, a nor­ machine at my desk is a 10 Mhz 0 wait 286- mal, boring guy. on-a-card (more about that later), I'm set up I've been wishing for a snowy winter for well to check Gary's results. I did. And I came three years (ever since I left Montana) and now up with slightly different results. I've got my wish. Maybe more than I bargained Compiling with Turbo C, version 1.0 and for. I just moved to Minnesota; talk about cul­ all optimizations on, including 186/286 code ture shock! generation, using compact model, I got 17.4 I decided that just reading about these great seconds for an 8 Mhz 186 and 8.2 (not, I new 80386s, 34010s, and all those other 5-digit repeat, not 2.5) on the 286. (I think I've met numbers (and all those acronyms, too-PC­ the guy you bought your watch from, Gary; MOS, OS/2, MTV ... ), just wasn't enough. So I fortunately the tour guide warned me before I called up Dean and Earl at PC Tech in Lake gave him any money.) City and made a deal to come work for them Even after the inaccuracy is removed, the during Istanbul's rainy season. result is still quite interesting. The differences I'll be playing with high tech toys for the in the 186 vs. 286 I mean; I don't give a hoot next few months while I wait for the return of about Prolog-it's too hotsy totsy and high warm weather on the Med (and while I stock brow for me. For that matter, I don't give a up on paddles, life jackets, and CDs of deca­ hoot about standard deviations either. (The dent rockabilly bands). only reason I passed my Engineering Statistics class when I was in college was because my Topic Of The Month Topic favorite CS instructor was teaching Stats that If you recall from last issue, we were talking quarter due to a staff shortage.) about keyboard interrupts (9 and 16h). I A difference in timings between two lan­ covered number 9 (the hardware interrupt, not guages on the same machine is explainable. the Beatles song) last issue and will deal with So is a difference in timing between two dif­ interrupt 16h (the software service interrupt) ferent processors. But the 186 microcode is the this time. same as the 286, the only immediately ob­ But before I get down to business, I might as vious advantage that the 286 has is that it well get a few things off my mind, as well as does memory accesses in 2 cycles compared to tell you about the great new "stuff" I'm using the 186's 4 cycles. these days. But in an instruction mix with a high per-

54 MICRO CORNUCOPIA, #41, May-June 1988 centage of arithmetic instructions, espe­ Anyway, Windows doesn't quite fit cially multiplies, that shouldn't make the bill right now. It's overkill. All I real­ much difference. Somebody wanna ly need is a multi-window editor that trace through the code this sucker's I've been wishing can integrate with my compilers. Oh, tossin' out? I might do it someday, but and it must be able to recognize the I'm too busy with "real" things right for a snowy winter extra 41 lines on my full page display. now. And it's gotta be cheap. Wait a Minute! I don't even believe for three years in benchmarks. Why am I bothering Looking For Mr. Good-Editor with all this??? (ever since I left Let's see. Everyone's first answer to Gary's note: Thanks, Laine. I'm still that is probably "Get Brief, you klutz!" confused about why we're getting this Montana) and now Maybe. Brief does automatically recog­ variation (oops, I used that statistical word) nize my 34010 Mono's full screen mode. in our benchmark, but I assure you all our I've got my wish. And its macro language can integrate it benchmark feedback has been from readers' with just about any compiler that spits testing on "their" machines. Maybe when out error messages. Earl uses Brief every you're finished doing "real" things, you can day and thinks it's ludefisk soup (hey, give this one a little more thought and get this is Minnesota!). But Brief only has back to us. tiled windows (Yuck. Overlapped is where it's at) and besides, it's too expen­ 80 What? 86 sive for my blood. And what was that I said about a 10 What else is there? Vedit? Nah. I still Mhz (12 Mhz, actually) 286 with up to 4 have bad memories of old Vedit that Megs of 0 wait state RAM, all normal have held over to my impression of new AT-type CPU support, a clock, Vedit. It uses tiled windows anyway. keyboard port, all on a single Compaq And it's expensive, too. 386-like (extended AT) card? Sorry. What about Express? Much as I hate That's a secret. to give up such a faithful friend, the times have changed and neither Cecil Macho Video nor I have had the chance to change Ex­ I always liked the idea of a graphics press with them. It may be fast, and it based, multi-windowing . does configure right up for a 64 line The idea, I said. The realization was screen with no hiccups or growls, but way beyond my means. Graphics made it'll only edit a single file at a time. And any machine I could afford too slow to lately I'm just too schizophrenic to cope bear, and there just wasn't enough with that. room on the screen to show any more than a single window without feeling The Solution? claustrophobic. I haven't found the solution to this Well, the price of macho video is still dilemma yet, but I do have a good can­ higher than the cost of myoid Big­ didate. It's an editor called Point from Board, but then I'm not a student Logitech. If any of you own Logitech anymore, either (although I do still Modula version 3.0 or a recent Logitech dress, live, and act like one). My main Mouse, you already own Point-it's in­ system at the office in bustling cluded with the "Plus" software pack­ downtown Lake City, as well as con­ age that comes with most of their mice taining the 286 board (sshh!), has a PC (as well as with Modula). Tech 34010 Mono Graphics Board As far as I know, they don't sell it hooked up to a CPT full page monitor separately, but even if you buy the with a resolution of 800 x 1024 at 2 mouse (or Modula) just to get Point, bits/pixel. So much for the you're still spending less than to buy claustrophobia. What about speed? just Brief, or just Vedit. And you get a What about 6 MIPs?? (And that 10 (three times the dots of a Herc), I think great little mouse (or one of the most Mhz 286 doesn't hurt, either). maybe it'd be okay. If someone would complete Modula development systems I never thought I'd consider using just port over a good editor (the Win­ around), too. And Point has OVER­ Microsoft Windows as a development dows NOTEPAD editor sucks) and an LAPPED WINDOWS (Hubba, Hubba!!). environment. Now I'm not sure. When I assembler and C and Modula compilers Like I said though, it's just a can­ first tried Windows, it was version 1.03 (all communicating with the editor, of didate. It has a few drawbacks. So far, I on a Hercules card. Slow, awkward, course) maybe I'd do it. can only make it go up to 43 lines (the tiny little tiled windows. I know you all think I'm crazy-only PC Tech 34010 Mono can easily be made Now that I've got Windows 2.03 a fool would develop his software to recognize many programs' 43 line with its new overlapping windows run­ under an environment so bugridden as "EGA" mode while keeping its normal ning in native mode on the PC Tech Windows. But come on guys, that was 9 x 14 character font). 34010 going into a full page display version 1, this is version 2! Then there's the problem that Point

MICRO CORNUCOPIA, #41, May-June, 1988 55 uses the mouse heavily. That would be I guess, before we rip it apart, a short use the input services provided by DOS okay if the keyboard commands were definition of what it does and how it's (INT 21h function 6, 7, and etc.) unless also full featured, but unfortunately normally used is in order. Very short­ you really must have the extra informa­ they make you simulate the mouse by you can get that kind of information tion provided by INT 16h (i.e., scan doing two keypresses for each mouse from any book about the IBM pc. For codes, shift status, a prior knowledge of button. If they'd just take a good look at example, The Pink Shirt Book by that guy what the next key will be). Microsoft WORD. It may be huge (and Norton. What we're going to talk about, expensive) but the keyboard vs. mouse By the way, this discussion is going though, is not how to use INT 16h, but thing is handled very well. to be in assembly, hex, and binary, (and how to change it. We want to change it And I have found a few serious Turkish) so all you pansies who only so that it will translate certain (crash causing) bugs. (I can recover by know how to program in 123 macros or keystrokes into different keystrokes for quitting and restarting.) I'm sending a (shudder) QuackBasic should go back to us. Kind of like Superkey, only list of these off to Logitech so maybe cutting paper dolls or turn on the friendlier (to other programs, not neces­ they'll soon be fixed. Peewee Herman show for awhile. sarily to the user). Otherwise, Point is great. Extremely fast (oh, did I forget to mention fast as INT 16h Services Method one of my requirements? Silly me ... ), Through INT 16h, the ROM BIOS We'll change INT 16h by writing a multi-level undo, very configurable. It provides client programs (applications Terminate and Stay Resident (TSR) goes one step further than a macro lan­ or operating systems) with three func­ program that saves the original INT 16h guage. tions related to the keyboard-get an vector and replaces it with our own. You can load in complete programs input key, check the availability of Then, every time there's a request for written in a "real" language (Logitech input, and determine the pressed/un­ keyboard input, we'll call the original Modula, of course) which integrate with pressed state of .all "shift-type" keys INT 16h to get a key and then translate the editor; that's how they integrate it (control, alt, etc.). it into another key according to a with their Modula compiler and linker. These functions are accessed by ex­ lookup table. Simple enough. Now if they'd just explain the details of ecuting an INT 16h instruction with AH I always thought the best way of un­ the interface so we could roll our own ... set to a function code of 0 - 2. See derstanding a program was to look at Point also lets you assign any com­ Figure 1 for a more detailed description the code, which you can find on Micro mand to any key, or (and here's the as well as examples of using each. By C's RBBS or get on the Issue #41 disk neat part) to any combination of mouse the way-I recommend that you always ($6 to subscribers, $8 to non-subscribers buttons or mouse buttons combined with directional movement of the mouse. For example, you can assign right button combined with a flick left to mean "DELETE TO SCRAP" while right button with right motion is "COpy FROM SCRAP." Wild idea. Oh yeah, and you can also define your own menus of editor commands that will either pop up wherever you are on the screen or pull down from the top bar. Still just a candidate, though. I'm very opinionated when it comes to text editors. But I really like the concepts behind Point. I'm even going so far as to use it to write this column. It's great being able to pop up the code that I'm writing about while I'm writing about it. (And without squeezing the window this text is in, down to nothing.) I'll be playing around more, hopeful­ ly discovering how to make it go to a full 66 lines (or even more with a smaller font). More later.

Down To Business "How about some substance in this silly column?" you ask. Okay, I'm easy (at least that's what rumor says). Let's talk about programming. In particular, let's talk about INT 16h, the keyboard software interrupt.

56 MICRO CORNUCOPIA, #41, May-June 1988 and foreign). If you're so inclined, check handling of the ALT key. The rewrite of out the code for the listing of ShiftStatFunction will only show AL T as TURKKEYS.ASM (that's Turk Keys, not being pressed if CTRL is also pressed. Turkeys). After you've taken a look at Use INT 16h if The modification to ShiftStatFunction the code, come back here so I can ex­ was necessary because Microsoft plain a few of the fine points (i.e., weird your purpose is to WORD was overriding the character parts) of the code. code if it saw that the alt key was translate pressed. It would see AL T down and ig­ Explanation nore the character value in AL, using You may notice some similarities be­ keystrokes into the extended code in AH instead. tween this program and the program in I also check in KeyXlate and only do issue #39 which intercepted printer out­ other keystrokes. If a translation if my newly modified put on INT 17h, the ROM BIOS printer ShiftStat shows ALT as not down. In output function. That's because they you want to other words, holding down CTRL dis­ have a lot in common. ables the translation and gives you the The initialization routine is identical activate another original keystroke instead. If I want to, I except for the difference in procedure can now redefine all of the AL T + combinations without losing the same basic sequence of events to install original keys. And they always told you any TSR. You just print a message, save keypress, watch that you couldn't have your pizza and a vector, install a replacement vector, eat it too ... then Terminate and Stay Resident. INT 9. Usage A Few Details Now don't get all excited and think The similarities stop there, though. that you're going to write a popup The service routine we've installed for Returning Status In The Flags program that looks to INT 16h for the the keyboard is translating input, not We run into another "return hotkey. I've seen programs that do that, output. So instead of translating and problem" in ConStatFunction. It's called but they end up with a "warmkey," not then chaining to the original service by an INT instruction (the call from the a hotkey. routine, we must chain first, then trans­ application program to NewKbdlnt), INT 16h is only activated when the late. which saves the flags on the stack current application asks for input, so Because we have to get control back before calling. An IRET in the calling sometimes nothing happens for quite after the ROM BIOS has its say, we procedure would then restore the flags some time (several milliseconds at can't simply jump to the original, we from before the INT, destroying that Z least). A hotkey should hook up to INT must call it. But the routine we are call­ flag we worked so hard to set up. 9, that way it will be informed the in­ ing returns with an IRET instruction, That's why in ConStatFunction I stant a key is struck. In general, use INT which expects three items on the stack return to the calling program with a 16h if your purpose is to translate (offset, segment, flags) while a far ·call RET 2 instead of IRET. RET 2 does the keystrokes into other keystrokes. If you instruction only puts two items on the same thing as a normal RET. But after want to activate another program upon stack (offset, segment). What to do ... popping the return address off the a particular keypress, watch INT 9. There are a couple of possible solu­ stack, it adds an extra 2 to the stack tions. The most obvious is to do an INT pointer, effectively popping the old Extensions instruction instead of a CALL. After all, flags without ruining the new flags. A simple way to extend the it puts everything we need onto the Also notice that I declared ConStat­ functionality of TURKKEYS (the first stack just perfect for an IRET. Function as a FAR procedure. This was thing to do is change its name) is to That's peachy, dear, but we've just necessary to force the assembler to replace the second word in each pair in taken the routine we want to call out of generate a FAR return (returning to a the translation table with a pointer to a the interrupt table and stored it in a different segment) instead of a NEAR longer, null terminated translation pointer variable. "So install it some­ return (return to a point in the same string. Then keep track of where you where else in the vector table!" Well, segment). are in the replacement string during maybe, but then what happens if 367 This isn't necessary for the other sub­ subsequent calls. programs all decide to chain onto INT functions (ConinFunction and ShiftStat­ Another way of doing the same 16h. What if there aren't any free vec­ Function) since they do IRETs, and thing would be to use that pointer to tors when our program runs? there's only one kind of IRET. I could point to a subroutine to execute instead I've adopted a much more trouble­ have declared all the other procedures of just pointing to a string. free method of chaining interrupts. I in the program as NEAR or FAR, but Then you could hook it up to a just push the flags, then do an indirect putting in a PROC declaration takes a "hotkeyed" user interface (through INT far call through the pointer that stores matching ENDP line, and I'm lazy. 9) which would let the user define new the address of the original routine. keys, and save and recall files full of That's why I have all those PUSHF in­ The ALTKey macros. Then give it a name... like ... structions without the corresponding The only other aspect of TURKKEYS uh... QuickKey! Yeah. That's the ticket. POPFs; The IRET instruction in the that bears explaining (other than "Why Let me get back to you on that one, called routine takes care of POPping the would anyone in Minnesota want to be huh? Fs. typing Turkish text?") is the special • • •

MICRO CORNUCOPIA, #41, May-June, 1988 57 ButtonWare, Tour '88 Coming Soon To A Users Group Near You

"They started feeding me requirements," he Anthony Barcellos In January Tony sat through two presentations said. P.o. Box 2249 by Jim Button. Now he's writing about Button­ Without realizing it, he had gone into the Davis, CA 95617-2249 (916) 756-4866 Ware. Am I surprised? Are you? Is ButtonWare software business. As his program passed hand really interesting? Sure. to hand, Jim found himself getting update re­ quests from people he didn't even know. Soon updates were no longer a matter of dropping a im Button was on the road. Two major disk onto a colleague's desk-he was laying out users groups in three days. San Francisco cash for mailers and postage. Inspiration on Monday and Sacramento on Wednes­ struck. Jday. His routine has been honed by many prior appearances, but his message hasn't User-Supported Software Is Born changed. He just wanted to say thanks. "I began including a message asking for a Over the past year, Button has descended $10 contribution from people who were really upon practically every notable users group­ serious about getting updates," he said. Button both at home and abroad. "He has traveled put it quite simply: His hobby had to become literally all over the world," says DeeDee self-supporting, or he would have to discon­ Walsh, ButtonWare's public relations and ad­ tinue mailing out disks. Button's wife calmly vertising specialist. informed him that he was "crazy" if he thought anyone would send him money. The California Swing Almost immediately he discovered that Jim was spreading the word about someone else had had the same idea. A friend shareware's success, and users were eager to came back to Button with a disk bearing a hear it. In Sacramento alone over five hundred program by Andrew Fluegelman called PC­ people were on hand to listen to him. The Talk. Said Button's acquaintance, "Fluegelman father of user-supported software was telling is doing the same thing you're doing, but it his half of the shareware story, and he was looks like he's doing it a lot more professional­ talking to people who had helped to make it ly." happen. Audiences laugh when Button tells this story "All good programming projects never come on himself, but it was a turning point in to an end," he said, describing how his "little shareware's history. Fluegelman'S "experiment label program" blossomed into the flagship of in economics" was called Freeware (a term he ButtonWare's fleet of shareware products. PC­ trademarked; Button was calling it "user-sup­ File started its life as an AppleSoft BASIC ported software" and Quicksoft's Bob Wallace program running on an Apple 11+. It stored, later coined "shareware"). He packaged his sorted, and printed labels. Gradually, however, disk with a nicely written pitch for people to it began to look more like a database. participate in this alternative marketing When IBM announced its PC in 1981, Jim scheme. Now you could "try before you buy." Button lined up with his fellow Big Blue employees for a new microcomputer. Unable to ButtonWare's First Price Hike meet the immediate demand, IBM advised But­ Button sent Fluegelman a copy of his ton that a PC would be his in only nine database program and the two were soon col­ months. Undaunted, Jim began using his lunch laborating. "He told me I was making him look hours at work to convert his label program to like a skinflint by only asking $10," said But­ the Pc. ton. "I suggested that he come down in his Jim casually shared his program with his price. He suggested that I come up to $25. His colleagues, all of whom were eager for some­ arguments were more persuasive than mine. thing to run on their PCs. Then it happened. That was my first price hike."

58 MICRO CORNUCOPIA, #41, May-June 1988 Fluegelman also talked Button into the Big Three of shareware were repre­ programs. In addition to sharing adopting a name similar to that of PC­ sented in our collection, which then was graphics features, PC-Calc+ and PC­ Talk. Button had been calling his only five disks!) File+ understand each other's file for­ program Easy File; now it became PC­ By the time the Buttons had cleared mats sufficiently to share data. In par­ File, the name under which it became away the backlog, Jim had his wife and ticular, PC-Calc+ can create spread­ famous. The nomenclature became a son working for ButtonWare full-time. sheets from PC-File+ databases. standard for many later shareware products, including ButtonWare's entire A Selection Of Greatest Hits list of applications programs: PC-Type, Stories have been circulating that PC-Calc, PC-Graph, PC-Stylist, and PC­ ButtonWare will move into the in­ Dial. With each tegrated software market with a The software libraries of PC clubs be­ program called Medley. Medley lives, came one of shareware's major outlets. iteration, Button but not in its originally envisioned Figures show that 19% of ButtonWare's form. Instead of an integrated package, customers learned of the products at adds new features. Medley has become an "integrator" for users groups. Another 38% learned of ButtonWare's database, word processor, ButtonWare from a friend. Thus user­ Newly released and spreadsheet. supported software is truly user-sup­ "That's in the VICIOUS rumor ported, with over half of the activity PC-Calc+ and category," jokes DeeDee Walsh. "In coming directly from user-to-user inter­ fact, we're already using Medley in our action. version 2.0 of office. We're thinking of bundling it with PC-File, PC-Type, and PC-Calc as "How Did I Get Into This Mess?" PC-File+ can a business package./I Jim recounted his reluctant transition However, no release date. has yet from IBM employee to shareware generate business been set for Medley and its three com­ entrepreneur. The returns from his panions. Testing continues at Button­ hobby, however, finally so over­ charts from Ware. shadowed his salary that he jumped, "In 1984 I left IBM and my wife spreadsheets or On The Road Again stopped talking to me./I Jim Button is preparing another Communications resumed shortly databases. swing into Europe, carrying the thereafter, as it became clear that Jim shareware message to more enthusiastic had made the right move. audiences. The co-inventor of the user­ Button's departure from Big Blue supported software concept is at the came one year after ButtonWare Over the next four years, ButtonWare peak of his form. Keep on trucking, Jim. received a major boost from PC World grew to a twenty-employee company, magazine. Doug Clapp's rave review of with annual revenues exceeding two The Local Library PC-File III appeared in the September, million dollars. Button's wife eventually The quickest source of shareware for 1983, issue and the small company's agreed that her husband's idea was not the interested computer user continues mailbox overflowed. so crazy. to be the local users group software library or electronic bulletin board sys­ Aloha, Success Biggest And Best? tem. Look around. ButtonWare is al­ But Jim wasn't there to witness the Today ButtonWare offers one of the ways nearby. You can also obtain event. PC World appeared on the most complete collections of shareware ButtonWare products directly via their newsstands while the Button family productivity programs, covering all of toll-free order line, 1-800-JBUTTON. The was flying to Hawaii for a vacation. the major PC applications. None of the software prices listed above were cur­ After a few days, Button called home to software exceeds $70 for a registered rent as of February, 1988. check with the high school student who copy. For the list, see the table which For more information on Jim Button was collecting their mail. follows: and shareware, check out David "Where do you want me to put the Thompson's interview in issue #37 of bags?/I asked the desperate boy. He Current Roster Of ButtonWare Micro Cornucopia (Sept./Oct. 1987). eventually filled the basement with Software Editor's note: Micro C has the Button grocery sacks full of mail. collection. Disk MS45 contains PC-File+ (It was right at the end of 1983 that PC-File+ 2.0 (database) ...... $69.95 (Version 1.0 with built-in doc. only), MS46 PC-File entered the software library of PC-Type+ 1.0 (word processor) ...... 69.95 contains PC-Type, MS47 contains the writ­ the Sacramento PC Users Group, as it PC-Calc+ 1.0 (spreadsheet) ...... 69.95 ing analyzer and dictionary, MS48 contains probably did the libraries of many other PC-Dial 1.0 (communications) ...... 59.95 PC-Dial and PC-Graph, MS49 contains computer clubs: It was the last volume PC-Stylist (style checker) ...... 29.95 PC-Calc and DOS helper, and MS50 con­ prepared by my predecessor as software PC-Tickle (tickler/calendar) ...... 29.95 tains the Calendar Reminder and a pair of librarian. Fluegelman's PC-Talk was al­ XD (Extended DOS; shell) ...... 29.95 Button Games. ready part of the library-though later Bakers Dozen (misc. utilities) ...... 59.95 Disks are $6 each, postpaid, for u.s. withdrawn at the author's request. subscribers-$8 each, postpaid, for non-sub­ When I included Bob Wallace's PC­ Meanwhile, Button has been working scribers and foreign. Call 1-800-888-8087 to Write as my first addition to the library, toward "loose integration" of his order.

MICRO CORNUCOPIA, #41, May-June, 1988 59 TURBO C QUICK C LET'S C DESMET C DATALIGHT C ECO-C LATIICE C MICROSOFT C AZTEC C COMPUTER INNOVATIONS C IS NOTHING

NEW --- Limited time offer. SACRED?

Peacock System's CBTREE Now the FULL source code for TURBO Pascal is avail­ Object library for only $491 able for the IBM-PC! WHAT, you are still trying to debug Our FULL COMMERCIAL VERSION of CBTREE in object library without source code? But why? Source Code Generators format is being offered for the amazingly low price of $49. (SCG's) provide completely commented and labeled ASCII source files which can be edited and assembled CBTREE provides you with easy to use functions that maintain key and UNDERSTOOD! indexes on your data records. These indexes provide you with fast, keyed access, using the industry standard B+tree access method. SCG's are available for the following prod­ "The darndest thing I ucts: ever did see ... " Everything you need to fully utilize CBTREE in your applications is _ TURBO Pascal ver 3 (IBM-PC)* ..$67.50 Pournelle, BYTE _ TURBO Pascal ver 3 (Z-80)* . . . .$45.00 included. The CBTREE source code can be purchased later at any "I have seen the original _ CP/M 2.2 ...... $45.00 time for the difference. Example source programs and utilities are source and yours is _ CP/M 3 ...... $75.00 included FREE. much better!" *A fast assembler is included free! Anonymous, SOG VI CBTREE source library $159 The following are general purpose disassem- Object library only $ 49 biers: t _ Masterful Disassembler (Z-80) ...$45.00 ~ , This limited time offer is simply too good to refuse. Peacock's standard _ Masterful Disassembler (IBM-PC) .$47.50 ROYALTY FREE, UNCONDITIONAL MONEY BACK GUARANTEE, - UNREL (relocatable files) (8080) .$45.00 Q .n. Cool: I ...... '. AND FREE TECHNICAL SUPPORT applies to this offer.

To order or for additional information VISA/MC/check Shipping/Handling $1.50 //C;~II(703) 356-7029 or (703) 847-1743 or write: card # Tax $ __ expires ---.1__ Total $ __ ~...". PEACOCK SYSTEMS, INC. ./~ ~ 2108 GALLOWS ROAD, SUrrE C Ali products are fully guaranteed. Disk format, / ~ VIENNA, VA 22180 8" 0 5" 0 type: ____ ~PEACOCK SYSTEms. inC C.C. Software, 1907 Alvarado Ave., Walnut Trademarks: Turbo C (Borland); Quick C (Microsoft); Ler£ C (Mark Williams); DeSmet Software); Creek, CA 94596, (415) 939·8153 DataJight (DataJight); Lattica C (Lattica); Microsoft C (Microsoft); Aztec C (Manx Software); Computer Innovations C (Computer Innovations); Eco-C (Ecosoft, Inc). CP/M and TURBO Pascal are trademarks of Digital Research & Borland Inl. Reader Service Number 20 Reader Service Number 31 Noah Boards The ARC "LIST." -TB] The registration fee for Arcmaster is When last we left the archiving • Quickly and easily select ARC or a modest $40, but you can save yourself scene, the deluge of ARCing and de­ DeARC switches and options. $10 if you include the user's question­ ARCing programs was well upon us. • Specify a target directory for file naire that Newlin provides at the end of (See "All Aboard the ARC" in the extraction, the manual. He's serious about getting Nov./Dec., 1987, Micro C issue, #38.) • Specify a target directory as host feedback, and Newlin is making it Now shareware author John J. Newlin for created .ARC files. worth your while to share your reac­ volunteers to take the helm. What could • Swiftly search entire system for tions with him. he have in mind? any file. Version 1.3 of Newlin's Arcmaster • View any file through Buerg's But Wait-There's More! answers the novice archivist's prayers LIST program. In addition, Newlin provides for a respite from the downpour. In brief, Newlin has taken PKARC registered users with a copy of Arcmaster embraces Phil Katz's and and PKXARC by Phil Katz, ARCA and Arcmaster Plus. (We really must find an Vernon Buerg's speedy archive utilities. ARCE by Vernon Buerg, and Buerg's alternative soon to the overworked As Newlin points out in his documenta­ LIST utility, and combined them so you "plus" suffix; don't you agree?) tion, Arcmaster provides the menu­ can view, combine, extract, and delete The Plus version includes extra fea­ driven ability to: archive files. User-friendliness has come tures like batch processing of file • View an .ARC file' directory list­ to the archiving business. moves, deletions, or copying; printing ing at the touch of a key. As shareware programs grow in size archive directories; renaming files; as­ • DeARC multiple files. and complexity, more software libraries signment of function keys to filename • Selectively extract (or delete) files and bulletin boards are using ARCing masks; date/time sorting; aliases for from an .ARC file. programs to combine and compress ARCA, ARCE, PKARC, and PKXARC; • Search any (or all) drives in your their files. New members of users and DOS wild cards for archive opera­ system for a file that resides in an groups raid the software library and tions. (Arcmaster Plus is restricted to .ARC file. come away with archives that may at registered users and cannot be other­ • Browse ARCed files using Vern first seem impenetrable. Arcmaster goes wise distributed.) Buerg's outstanding LIST a long way towards solving that For more information, pick up a program. [It's amusing to see that problem. Teach someone you love to copy of Arcmaster from your favorite Newlin i5....like me in thinking that use Arcmaster, and archiving worries local source or contact: "outstanding" always precedes are forever banished.

60 MICRO CORNUCOPIA, #41, May-June 1988 ZRP/M ™ creates Z280® CP/M©2.2 compatible IBM PC ZRP/M is an operating system combined with a Z280 emula­ tor. Either standalone or with DOS present, ZRP/M provides the solid base of a genuine operating system reliably distinct from the facade created by an MSDOS interface. All 2.2 system and CBIOS calls are supported, 56.5k TPA, file date and time stamping, fast virtual disk, iobyte redirection, ter­ minal emulation, color console display, auto relog, COM path, SAVE anywhere, single key phrase recall, built-in ac­ cess to DOS drives. SETDISK redefines a drive to any of over 80 CP/M formats. System disk with manual $129. Shipping $5 ($10 nonUS) ':!C II

!. 118 SW Firs1 St.· Box G Micro • Warrenton, OR 97146 Illef-hods, Inc. (503}861-1765

SHAREWARE DISK AVAILABLE FOR '10.00 ' -

Reader Service Number 87 John J. Newlin byte. Just cruise abollt with your cursor easier and cheaper than similar 4060-228 Rosenda Court to whatever you want to change. Press programs. San Diego, CA 92122 Enter to record your changes or Esc if The 39-page user's manual is written you'd rather not. There's also an Undo in a breezy style. My particular favorite From Our Foreign Correspondent command. is the section titled "What Annoys Me I don't often get mail from Hong Full-screen editing is a new idea in Most About EDDY Is:" Scofield then Kong, but Micro C has readers there. the directory utility field, particularly gives a laundry list of potential One of them is a shareware author when it extends to all of the vulnerable problems and recommended resolu­ named John Scofield. file characteristics-like name (includ­ tions. ''Trying to get a program distributed ing extension), date, time, and certain in the USA while living in Hong Kong attribute bits. The cursor leaps lightly The Path To Scofield's Door is nontrivial," he writes. over the file size because that's not one EDDY is up to version 2.31 and is I would imagine so. And what is it of the things subject to EDDY's editing. beginning to make its way into software that Scofield has for us? A DOS utility EDDY's screens are a bit busy, but libraries and onto bulletin boards. called EDDY, which stands for "EDit the information is useful and he in­ Scofield asks a modest registration fee DirectorY." (Perhaps coining acronyms cludes help screens. of US$1S. Write to: isn't John'S strong suit.) EDDY can sort You can sort your directory several a directory, fiddle with file attributes, ways and you can invert the order with John Scofield search and view files, patch bytes, and an Alt-I. You can customize EDDY, the Box 47136 copy, move, or delete files. program has a "patch" area. Since Morrison Hill P.O. That really doesn't sound too excit­ EDDY can edit any bytes in a disk file, Hong Kong ing or original, does it? But EDDY is a you can use EDDY on itself, to change slick tool just the same. the defaults. (Be careful, this qualifies as He notes that EDDY is also available user-driven self-modifying code. The on the Computer Language magazine Full-Screen Files most interesting stuff.) forum on CompuServe. True to its name, EDDY lets you wander about a full-screen display of The Better Mousetrap your current directory and edit. You can Clearly there's nothing in EDDY • • • edit the filename, date, time, or attribute that's really new. Scofield feels EDDY is

MICRO CORNUCOPIA, #41, May-June, 1988 61 Is There A Market For Your Product?

Gary L. Scott worth of BYTE, PC, and Micro C magazines. Decision Technology You're a technical person, right? So how are you Let's say your search turns up nothing P.O. Box 5040 researching th~ market for you new product .idea? similar to your idea. Aloha, OR 97007 Not very technically 1'd guess. In the following ar­ Perhaps you've stumbled on the one remain­ ticle Gary shows you how to apply a matrix to ing unexploited vertical market. But have you? marketing. Probably 75% of all software never makes it into your local software supermarket or any of the popular computer press. Why? Because the OW do you determine the market people who purchase that kind of software potential for your brainstorm? Is the don't read computer magazines. easiest and best method to simply What do these folks read? Sometimes noth­ Hspend the next six months developing ing. But most of these people subscribe to one your new product? Then call up all of the or more trade magazines, and you'll usually dealers on the West Coast that carry your type find ads for software that appeals to the same of product and offer to sell it to them? Then sit vertical markets that the magazines do. back and wait for the money to roll in? This article will aOddress commercial vertical market software. Although we will concentrate on marketing commercial software, most of what we discuss here should also work for the programmer who has written a fancy new utility. Be prepared to tell Before we get in too far, it's important to define the difference between horizontal and the inevitable "white vertical markets: Horizontal market: Programs like word lie" since no vendor processors that almost anyone in any job can use. wants to send literature Vertical market: Specialty programs directed toward a narrow market segment or specialized to a competitor. need. Programs fitting into this category in­ clude routines which calculate the optimum way to saw a log into lumber. Great, so now that we have a source for in­ Direction vestigating our potential market, how do we To sell a product you must understand the find these magazines? Normally the best source needs and wants of your target audience. Your for this type of magazine is someone in the in­ goal is to meet those needs more effectively dustry. They can not only tell you the names of than your competitors. This article will cover the magazines that cater to their industry, but marketing. We'll also discuss tools for deter­ more important, they can often tell you which mining what to offer your target audience. are highly regarded and which ones are ig­ Let's say you have an idea for a new nored. program and you want to assess its potential If you don't know anyone in the industry, market. The easiest way to do that is to find out your next best bet is a university library, how many other companies are already there. preferably one that offers a degree in your A quick trip to your local software supermarket chosen field. is a good start. Also check a couple of years University libraries usually subscribe to a

62 MICRO CORNUCOPIA, #41, May-June 1988 large number of trade magazines since you can get information from the com­ The columns in the matrix need to many trade magazines send copies to panies by filling out bingo cards in the address all of the four Ps of the market­ libraries for free. If the nearest college is magazines, but you should still expect a ing mix: Product, Price, Promotion, a two-day drive from your house, you follow-up call from the companies you Place. (See Figure 1.) can normally get a list of titles from the selected. The list isn't complete, it's just to get Readers Guide at your local library and you started. Note, however, that then get copies via inter-library loan. Meanwhile product, price, and promotion are the Once you have the magazines in While you're waiting for the litera­ most important. hand, check them for software ads. ture, start analyzing your competition. Xerox any ads offering products similar Go to your local office products store Phoning to yours. and purchase the largest pad of paper After you have completed a prelimi­ Also, it's not uncommon for trade you can find (desk pads work well, nary cut of the matrix analysis, it's time magazines to have annual comparisons especially if they have a pre-printed to get on the phone. Start with the of software. For example, every Decem­ grid). magazines. Talk to the authors of ar­ ber, Sales & Marketing Management Divide the pad into a matrix of boxes ticles covering your type of software. magazine runs a comparison of several hundred sales and marketing applica­ tions packages. Figure 1 - The Four Ps Often the comparison done in these magazines is superficial, but you can Product Price Promotion Place get some very important information quality list price advertisement how sold? from these articles. First is an indication options discounts how sold? coverage of the size of the market both in number packaging of programs sold by individual vendors warranty / and in the number of vendors that are currently in the market. You can also get a feel for the price the market will two to three inches square. Along the Y­ Check with columnists and editors who pay for your product. Most important, axis write the names of all of the com­ have mentioned your competitors' you'll probably get the names and ad­ peting programs. (Be sure to leave room products. Keep in mind that these dresses of your potential competitors. for your package.) Along the X-axis jot people are busy, don't expect them to Armed with the names of your com­ down all of the important features and spend hours discussing the pros and petitors, the work is ready to begin. All benefits. cons of every package. serious software vendors have literature For instance, if you're designing a Write down the questions ahead of describing their product and many have data base you should have a column for time and then pare them down to five demo disks (for a nominal fee). Call the maximum number of records-a minutes worth. Always ask the people them and request a copy of their litera­ column for variable or fixed length you call if they have the time to answer ture. You may talk to one of their sales records-a column for the maximum your questions, or if it would be more personnel who will probably ask you length of each record-etc. Be sure and convenient to call at another time. They some questions to try and weed out the leave a number of columns unlabeled. will appreciate your thoughtfulness and serious customer from the person col­ (You'll think of more after the literature may very well give you more informa­ lecting fuel for his wood stove. comes in.) Also include a column to tion than you would have gained other­ Be prepared to tell the inevitable track how long it takes the companies to wise. Above all, be Professional. "white lie" since no vendor wants to send you literature and how often they Record the conversations. If you find send literature to a competitor. Often call. the practice distasteful, take notes

MICRO CORNUCOPIA, #41, May-June, 1988 63 during and immediately after the con­ tance of the matrix analysis and inter­ Editor's note: Lots of beer companies versation. Don't assume that you will views. This work will provide a founda­ have tried the same procedure. Unsuccess­ remember the details two days later. tion for your project, so do a thorough fully. It's also a good idea to follow up job and keep it up-to-date. Remember that everything is a with a letter of thanks. You may well be tradeoff. Can you really lower the price contacting these people again as you First Decision Point and still offer good customer service? start marketing your product. You want Once· you have completed this Keep in mind that price differentia­ them to remember you as a profes­ matrix, you've reached your first tion is the worst reason to make a sional. decision point. You have enough infor­ "continue" decision. Price competition mation to make your first educated can be very destructive to yourself, your Context Questions "stop now" or "continue" decision. competitors, and eventually, your cus­ When you talk to these folk, you Look at the matrix and ask, "How tomer. want to ask context, not content, ques­ am I going to differentiate myself from tions. You will find context questions to everyone else?" Feasibility Study be harder to answer but more informa­ Remember we are discussing a What you have just done is a simple tive. An example of this line of ques­ market-driven business. You are not market feasibility study. This is not to tioning: "How important is local sup­ IBM, and even IBM has discovered that say that you are finished with your port for the product?" The content customers will not always line up to market research, but you should now equivalent: "How many companies buy a product just because it says IBM have enough information to make an in­ offer local support?" on it. formed decision on market potential. What you are trying to do with the When trying to determine how you The matrix is a tool. Like any other interviews is fill in the fuzzy areas. For are going to differentiate your product tool you can use it to create a work of instance, the annual comparison of sales from competition, keep in mind the four art or a pile of kindling. It depends on and marketing software mentioned ear­ P's of the marketing mix. Product, price, you. lier can give you all kinds of factual promotion, place all give you potential In a future article I'll discuss more data, but it probably wouldn't reveal a opportunities for differentiation. tools-tools that take you further into controversy among users over the value It's easy at this point to fall into the the realm of market research. of certain features (or the value of using trap of saying to yourself, "I'll add fea­ If you have questions, feel free to a computer at all). tures and lower the price so my product drop me a letter. I can't overemphasize the impor- will sell like canned beer." • • • Software Developers PROMPT DELIVERY!!! Ii SAME DAY SHIPPING (USUALLY) We need your program! Ie QUANTITY ONE PRICES SHOWN for FEB. 15, 1988 Do you have a program that's good enough to selL but don't want the problems or financial risk DYNAMIC RAM ".~..:s ~ of producing, typesetting, printing, packaging, 1Mbit 1048Kx1 1 00 ns $36.00 cP~~~ CO Q~ ~f6 warehousing, marketing, distributing and sup­ ~~ 51258 * 256Kx1 100 ns 9.25 ~ () ,cIa.

Reader Service Number 35 r 37

64 MICRO CORNUCOPIA, #41, May-June 1988 The UltimateLap-Top

com- ,..,-__-:::_._..--_ .•. __ The MCfek286B Lap-Top f color monitor or a digital bines the fastest, most reliable ··-·-'VU::.: ,;""; """:"'n ~ . or composite monochrome .. ' ---~!!!!!".·w*m'l:~:~!d&IR·!kJ~ -'-- \ A~ motherboar.d. available ".~~~r:.~,~t:} ~~"I v ----. monitor. Included also is 1 wIth the most vIsIble full- ,J ~ e J,:; 'I:/.- -Ii.. tl.z~ l"",0l; .~.~, '. "'" an external 5/4" floppy port . ~ ~ Q~?w •.jt v" ~-;j'" ~,ift .. -~t /" 1/~I·- 1 ~,,~ 1 1 I .. l SIze LCD lap-top sc~een I! t:

McTek Systems, Inc. e1411 San Pablo Avenue e Berkeley, CA 94702 e 414-843-0714

DISK DRIVES PRINTERS MONITOR$ PC/XT PC/AT MISe. Kingtech Portable Computer Fujitsu 360k ...... $75 CItizen CD 120 •••••••• $159 Samsung amber ••••••.•• $79 640k TurboMothrbrd ••••• $85 McTek286 6/8/10112MHV $289 Kits: XT/AT (power supply. Fujitsu 1.2MB ...... $99 CItizen CD 180 •••••••• $189 TVM EGA color ..•.••• $399 10MHz TurboMothrbrd ••• $89 Baby McTek 286B-AT case. keyboard. monitor) Teac ...... $79 HPLASAR SerlaI2 ..... $1799 TVM RGB color ...... $289 Multi I/O w/disk contrir .• $59 10/130-wait ...... $409 ...... $380/$410 Teac 1.2MB ...... $105 Epson LX-800 ...... $219 NEC Multisync •••••••. $559 640k RAM card ...... $39 McTek 286A O-wait 3MB Eprom burner 4-socket $139 Toshiba 3'h" 720k ..... $119 Toshiba 321 XL...... $559 Sony Mulliscan • • • • • • •• $650 2MB Expansion card ••• $115 4 ports on board •••• $449 Lap-Top Kits ...... $799 Floppy controller •••••••• $22 Call for prices of other brands HGC-compat.mono card .$55 RS232 2-port card .•.•••• $35 3 MB Multifunction card $125 AC power center .••••.•. $25 20MB Hard Disk Kit .... $289 Color graphic card •••••• $49 4-serlal port card ••••••.• $95 .2MB Expansion card ... $125 AC power strips ••.••.••. $15 30MB Hard Disk Klt. ... $319 EGA Paradise ...... $159 Game I/O card ...... $15 Multi 1/0 card •.••••••••• $59 MODEMS Diskette file box ...... $9 ST-225 ...... $219 384k Multifunction card •• $69 Locking slide case .••.••• $65 Printer or serial cable •.••• $8 ST-238 ...... $249 Easydata Int. 30011200 ••• $79 FCC-app. slide XT case •• $29 200W power supply •••••• $79 MOUSE 386 16MHz 2MB .. $1599 ST-4038...... • •• $529 Talheho external 3/12 •• $105 150W power supply ••..•• $.55 Enhanced keyboard ••••• $59 ST-251 40MB ...... $429 Everex 2400 external ••• $195 Loglmouse C7 ...... $75 XT keyboard ...... $49 WD HDllloppy controller $149 Reader Service Number 42 ·Prices subject to change without notice.

MICRO CORNUCOPIA, #41, May-June, 1988 65 A Pascal Debugger (For Programmers Who Are Less Than Perfect)

John P. Jones debugging is a symbolic source code debugger. There's a debugger for C? So what? There are Borland has announced that they are working 6245 Columbia Ave. on debuggers for their products. One for Turbo St. Louis, MO 63139 lots of debuggers for C. How about a debugger for (314) 645-1596 Pascal? It's a commercial debugger, but at $45 it C is due in the first quarter of 1988 with a ver­ sounds like a steal. sion for Turbo Pascal to follow. Until that time, there are alternatives-one of which is from Turbo Power Software of t's April 14 and you've just finished your Scotts Valley, California. Tdebug+ version 4.0 15,000 line Turbo Pascal program which in­ (available March 1) provides all the facilities sures that Uncle Sam doesn't get more than needed to effectively locate any insects (such as Ihis fair share. After putting in all the finan- giant-winged tax bills) lurking in your code. cial data (that you of course have fully or­ ganized and ready to input), the program What's Needed chews on the data for a few seconds, then What should a source level debugger do? At proudly informs you that you still owe the IRS the very least, it should provide a means to $7,324,857.82. step through the program and examine the Since you're not Chairman of General changing values of variables at each step. A Motors, you suspect something's amiss. You've "window" into the source with an indication of tested each of your subroutines and UNITs what statement is to be executed is helpful, but during development, so where do you go from at the very least it should display the current here? source line number. Debugging, like the original coding, should It should understand a variable's symbolic be done in a logical and structured manner. name rather than its memory address. First, isolate the problem area to minimize the Breakpoints and pass points are next in order number of routines that need to be examined. of importance-they let you execute at full tilt The next step, which is also the least effective, until execution reaches a certain point (or is to reexamine the source. Look for things like event). parameters mistakenly passed by value, unini­ How is all this possible? The files generated tialized variables, missing calculations, and the by assemblers and compilers include informa­ like. tion about both symbols and the source. The Next add output statements to indicate the linker, which then combines these files into an progress of the program. At critical or suspect executable program, can also produce a "map" points, put in a sequence of statements of this file that provides the information to a debug­ form: ger. In Turbo Pascal, the compiler puts the infor­ WriteLn ('In Procedure "CriticalProc", mation into the .TPU file (linkable object) and Taxes = " Taxes); the linker can generate a .TPM or special map RestartCh := ReadKey; file. Borland provides a utility to convert .TPM files into standard .MAP files. Only information This technique of course has it's disad­ about global variables and procedures is nor­ vantages; it involves repeatedly editing, compil­ mally included in these files. Local variables ing and running the program to check each sec­ and nested procedures are only visible within tion. The program will be larger. Also, the in­ their own block and therefore need only be formational writes will most likely interfere known to the compiler, not the linker. with other screen output. If your program uses For Pascal and Modula-2, local variables graphics, it may be very inconvenient to use only exist during the execution of the proce­ this method. dure that contains them. When the procedure is Perhaps the most effective tool to use in invoked, storage for the variables is allocated

66 MICRO CORNUCOPIA, #41, May-June, 1988 on the stack and then released on return search the text buffer forwards or back­ from the procedure. Obviously, a wards to rapidly find a procedure or debugger has a problem providing sym­ variable name. bolic access to local variables. The assembly The assembly mode is fun-you can learn a lot about how the compiler Tdebug+ mode is fun-it'll operates by using it. Since the original In order to allow symbolic access to source (if available) is interspersed with local variables and nested procedures, teach you a lot the symbolic disassembly, you can see Turbo Power includes a program that exactly what the compiler did for you. patches both of the Turbo Pascal com­ about your You can also disassemble to the printer pilers so that local symbol information or a disk file. This raises the possibility goes into their output. The resulting compiler. of hand optimization of time critical files are fully compatible with those routines. produced by the normal compilers but I haven't found any bugs in the beta can be double the normal size. test copy I've been evaluating, but I After installing the debugger and • N - executes to the next statement haven't really been able to push it to it's compiling your program with the (procedure calls in one step) limits either. At $45 ($90 with source), I proper switches to provide debug infor­ • J - like trace, but always forward think it's an exceptional buy. mation ($T+, $D+), you are ready for in the source the chase. Invoke the debugger with the • G - executes until break­ Add Ons command line: point set here reached The only computer language with all • GM - like G, but when the features for all situations is Ada. It's TDEBUG [OPTIONS] PROGNAME [PARAMETERS] set breakpoint is reached, it large, cumbersome, and difficult to checks the permanent and tem­ learn. Most languages try to provide a Tdebug will load, then load your porary breakpoints and stops if balance between features and size and program, read the source and .TPM any reached let the programmer create the routines files, and display the debugging screen. • GT - trace (T) with breakpoint he/ she needs for specific problems. This initial screen has two windows: monitor at every statement (slow!) Turbo Pascal is one of the languages one for the source, which has the next Tdebug knows about graphics-for that provides a good balance, fast and statement to be executed highlighted, all of the above tracing commands the efficient but with sufficient power built­ and the command window. debug screen is swapped with the in to make the coding easy. Within the text window, you can program's output screen unless the The lack of some special features has scroll back and forth through the "noswap" option in the command is created a market for useful, unique source, view other source files, and dis­ used. The possible problems you may and/ or difficult-to-program subroutine play a symbolic disassembly of the encounter with some graphics adapters libraries. If you are programming to machine code. When in assembly mode, are detailed in the manual (I had no learn, or just for recreation, you should another window opens. which shows problems in my testing). Each time you write all your own procedures and the current values of all the CPU return to the debug screen, the units. The best way to learn a language registers (this window can also be ac­ program's screen is saved and the is to use it. tivated in the source mode). debugging windows updated. If you are pressed for time, or are The watch window is opened when­ Variables can be examined/modified programming for pay, it makes more ever you "watch" a variable; it is ex­ by name or address with the E com­ sense to take advantage of the commer­ panded and contracted as watch vari­ mand. The W command sets up watch cial add-ons (why reinvent the wheel?). ables are added or deleted. The watch variables. The D command opens the Also, since source is usually included, window is updated periodically to in­ memory window and allows viewing of the routines can be modified or used as sure the values displayed are correct. variables in any of 14 different formats. models for your own routines. I'll intro­ The final window is the memory Again, these commands are fully sym­ duce you to two of the packages I've window. It allows you to monitor an bolic. The E command automatically been looking at recently, and in later area of memory (normally a data area) determines the type of the variable for columns will look at others. and is updated whenever you return to its display, but type casting can be used the debug screen. to force a different representation. Borland's Graphix Toolbox Permanent breakpoints and The TB command is used to show The whole series of toolboxes for passpoints are set with the P command. "how did we get here?" information. It Turbo Pascal has been upgraded for use These are monitored for all the tracing examines the stack and provides a with version 4. This time I'll look at the commands. Temporary breakpoints are traceback all the way to the main graphics package. set either with the tracing commands or program. I must admit I was a bit disap­ with the B command. The B command Tdebug+ has some additional fea­ pointed with this upgrade; I expected it is used to monitor a variable for change tures. It can use either extended or ex­ to be a total revision of the version for or reaching target value, or to monitor a panded memory for its source and sym­ Turbo 3. Instead, the package is basical­ range of memory for change. bol buffers; this reduces disk accesses ly the same, with the exception that it Program execution is initiated/fol­ and lets you debug larger programs. It uses linkable .OBJ modules for the dis­ lowed with the tracing commands. supports keyboard macros; you can as­ play adapters rather than $include files. • T - executes statements in sign frequent command sequences to a It seems to be a step backwards from either source or assembly mode function or control key. You can also the device independent graphics sup-

MICRO CORNUCOPIA, #41, May-June, 1988 67 port of the version 4 compiler package • Virtual screens sive window demos. to the device dependent nature of this • PopUp windows I've had the product for two weeks toolbox. Of course, to be fully display • Pulldown menus and haven't begun to explore all the independent, all of the drivers must be • Line editor (very small but very possibilities. The routines use both Pas­ present when your program initializes useful) cal and assembler; complete source is the graphics system, but that's better • Long (up to 65520 character) provided for everything. At $99 list, if than needing several versions of the strings you need even a few of the tools this program. • String manipulation package provides, you can't go wrong. Grumbles aside, if you need support • String formatting for multiple screen windows in a • DOS command line parser Next Time graphics environment, high-level plot­ • DOS and BIOS calls Next time I plan to talk about mixed ting routines, curve fitting, pie charts or • Interrupt and TSR management language programming. Some "foreign" histograms, this package may be for routines languages are more difficult to integrate you. • In memory sort routine (fast) than others. One especially good feature of the • Keyboard macro processor and window system is the world coordinate editor Sources concept. Each window can have its own • Routines to use both extended coordinate system, independent of its and expanded memory Turbo Graphix Toolbox physical screen coordinates. For in­ • Large (> 64K) arrays, in normal or Borland International stance, a window can be created whose EMS memory or in virtual 4585 Scotts Valley Dr. "world" includes only X and Y values memory Scotts Valley, CA 95066 between -1 and +1, even though it fills • BCD arithmetic (which Turbo lost (408) 438-8400 the screen. This can make plotting of in the upgrade to version 4) real life values easier. • Runtime error recovery (if not Tdebug+, Turbo Professional fatal, your program can continue) Turbo Power Software Turbo Professional V 4.0 3109 Scotts Valley Dr., Suite 122 This package, from the Tdebug+ They include a set of programs that Scotts Valley, CA 95066 people, rates an unqualified WOW! In it demonstrate the kinds of things you can (408) 438-8608 you'll find routines for: do with the package-several PopUps, a dandy little source generator for the • Fast windows and screen I/O menu unit, utilities and some impres- • • •

XEROX 820-1 AND 820-2 ITEMS Reconditioned, Assembled and Tested 820·1 8" COMPUTER SySTEM ...... $330.00 5 1/4" COMPUTER SySTEM ...... $350.00

820-2 8" COMPUTER SySTEM ...... $395.00 5 1/4" COMPUTER SySTEM ...... $415.00

820·1 (COMPLETE) ...... ~125.00 820·2 COMPUTER MONITOR (COMPLETE W/CONTROLLE ·95.00 820 COMPUTER MONITOR (NO MAIN BOARD)..... 85.00 ~,< HIGH PROFILE KEYBOARD (COMPLETE) ...... \.'\ ..... $ 45.00

820-1 MAIN COMPUTER BOARD...... •... $ 50.00 FULLY POPULATED BOARDS, EED REPAIR)$ 20.00 READI WRITE / 820-2 MAIN COMPUTER BOARD ...... $ 70.00 FULLY POPULATED BOA~pS, IS (NEED REPAIR)$ 30.00 820 - 2 FLOPPY CONTROLL R\~.()ARD ...... $ 95.00 I FORMAT IDUPLICATE

DUAL 8" SSDD DI 0 ES/ENCLOSURE (COMPLETE).$175.00 DUAL 8" DISK Of) CABINET (NO DRIVES) ...... $ 75.00 Disks from over 300 other micros (\1 'Ib, 5 1/4" D,gb~I~ISK DRIVE CABLE ...... •.. $ 20.00 8" DUAtlB)SK DRIVE CABLE ...... $ 35.00 RS-232 ~BLES ...... •...... $ 10.(10 s versions I 'Iabe from prevloU. grades aval . . LINE COROS .••..•.••..•.• ea.$3.00 Up 00 Call for Authonzatlon Z80-B 6MHz ..••.•..•....• ea.S3.00 E2I COMPUTER PRODUCTS for only $25, Z80·H 8MHz ••...... •..... ea.$9.50 2273 AMERICAN AVE. D8 5 1/4" 0500 OI5KETTE5 ..• ea.$ .60 HAYWARD, CA 94545 8" 5550 OI5KETTE5 •..•.•• ea.$1.25 To Order Contact: OC300A DATA CART .• U5EO •.. 2/S5.00 (415) 786-9203

TERMS: Pre-payment. COD. Visa/Mastercard. California residents add sales tax. Orders are FOB Hayward. CA •• Shipments by UPS Ground unless otherwise requested. Prices and availability are subject to change without notice. All products are assembled and tested and have a 30 day 2210 SIXTH ST. BERKELEY, CA. 94710 warranty unless otherwise stated. Call or write for current product and price listing. Xerox is a trademark of Xerox Corporation. CP/M is a trademark of DiQital Research. (415) 644-9386

Reader Service Number 33 Reader Service Number 39

68 MICRO CORNUCOPIA, #41, May-June, 1988 8280 Clairemont Mesa Blvd., Suite 117 San Diego, California 92111 ERAC co. (619) 569-1864 AT BABY AT XT/TURBO Motherboard 6 & 10 Meg Motherboard 6 & 10 Meg Motherboard Zero Wait State Zero Wait State 5 & 8 MHz Switchable 8 Expansion Slots 8 Expansion Slots 8088 - V20 Optional 1 Meg RAM On-Board 80286 Processor Optional Co-processor Math Co-processor Option Math Co-Processor Option 8 Expansion Slots Phoenix Bios 1 Meg RAM On-Board ERSO or Bison Bios 200 Watt Power Supply Phoenix Bios 640K RAM Hercules Compat. Video Board 200 Watt Power Supply 150 Watt Power Supply Parallel Port Hercules Compat. Video Board Hercules Compat. Video Board 2 Serial Ports Active Parallel Board Parallel Board Game Port 2 Serial Ports Active 2 Serial Ports Active Clock/Calendar Game Port Game Port Hard Disk & Floppy Controller Clock/Calendar Clock/Calendar 20M Hard Drive Hard Disk & Floppy Controller Hard Disk and 1.2M 5 %" Floppy Drive 20M Hard Drive Floppy Controller 360K 5 %" Floppy Drive 1.2M 5 %" Floppy Drive 20M 5% "Hard Drive 5061 Keyboard 360K 5 %" Floppy Drive 2 ea. 360K 5 %" Floppy Drive Case with Turbo & Reset, 5061 Keyboard AT Style Keyboard Hard Drive Light and Mini AT Case with Turbo & Standard Slide Case Keyboard Disable Switch Reset, Hard Drive Light and Amber Graphics Monitor Amber Graphics Monitor Keyboard Disable Switch Amber Graphics Monitor * * $1581 $999 EGA ADD $449 $1531 EGA ADD $429 40M HD ADD $150 EGA ADD $449 40M HD ADD $150 6 & 12 MHz ADD $73 40M HD ADD $150 5 & 10 MHz ADD $21 UNINTERRUPTIBLE POWER SUPPLY $129 ELGAR MODEL SPR401 - THESE SUPPLIES MAY HAVE SOME MINOR COSMETIC DAMAGE, BUT ARE ELECTRICALLY SOUND. 350VA WAVEFORM RECTANGULAR. RUN ON INTERNAL OR EXTERNAL 24VDC BATTERY WHEN LINE GOES DOWN. TYPICAL TRANSFER TIME = 12MS. NEW 24V INTERNAL BATTERY $75

KAYPRO EQUIPMENT CPU & SUPPORT CHIPS SWITCHERS 9" Green Monitor ...... $35.00 MC68000-8 CPU ...... $8.00 5V/9.5A, 12V/3.8A, -12V/.8A ...... $39.00 Keyboard ...... 75.00 Z80CPU ...... 75 5V/3A, 12V/2A, -12V/.4A. " ... '" .19.50 Hard Disk Cable Set (4) ...... 15.00 Z80A CPU ...... 1.50 5V/6A, 12V/2A, -12V/1A ...... 29.00 PRO-8 Mod. to your board ...... 149.00 Z80 CTC ...... 1.50 5V/6A, 24V/1 %A, 12V/.6A, Host Interface Board ...... 15.00 Z80A PIO ...... 2.00 -12V/.6A ...... 29.00 KAYPRO IC'S Z80A SIO ...... 5.00 5V/10A ...... 19.00 81-189 Video Pal...... $15.00 8088 ...... 6.50 5V/20A ...... 24.00 81-194 RAM Pal ...... 15.00 8089-3 ...... 6.50 5V/30A ...... 39.00 81-Series Character Gen. ROMs .. 10.00 D8284A ...... 2.50 5V/75A, 12V/8A, 24V/5A ...... 55.00 81-Series Monitor ROMs ...... 10.00 4164-15 ...... 1.90 MISCELLANEOUS 4164-12 ...... 2.10 Z80 Controller w/8-bit AID Conv .. $15.95 1793 ...... 6.00 POWER SUPPLIES Nicd Pack 12V/.5AH ...... 6.50 1797 ...... 7.00 Joystick 4 Switches 1" Knob ...... 5.50 0-8VDC 100A Metered ...... $249.00 ICL7107 LCD Driver ...... 7.00 Volt & Current Regulated 6845 ...... 5.00 TEST EQUIPMENT 5V/1A. -5V/.2A, 12V/1A, VC3524 Switching Regulators ..... 5.00 OSCILLOSCOPES -12V/.2A, -24VI.05A ...... 9.90 1458 Dual Op·AMP ...... 70 Phillips3260E 120MHzDuai ..... $975 LM2877P 4W Stereo Amp Dual ..... 2.50 TEK 7403N/7A18N/7B50A 60 MHz .. 695 MB81464-15 ...... 2.75 TEK 455 50 MHz Dual Trace ..... 595.00 HOURS: Mon .• Fri. 9·6 - Sat. 10 ·4 2716 ...... 3.00 ANALYZERS MINIMUM ORDER - $15.00 2732 .. '" ... " ...... " .. '" .3.25 TEK 491 10MHz· 40 GHz ..... $4500.00 TERMS: . VISA, MasterCard, Certified 2764 ...... , ...... '" .3.50 Nicolet 500A 1 Hz 0-100 KHz ..... 1800 Checks, Money Order, NO COD. Visa 27C128-1 ...... 9.00 Biomation 805 Waveform Anlyzr .259.00 and MasterCard add 3%. Personal 74HCOO ...... 38 checks must clear BEFORE we ship. 74LS125 ...... 30 DBASE BOOK OF BUSINESS include shipping charges. California 74LS373 ...... 50 residents add 6% Sales Tax. For more APPLICATIONS by Michael J. Clifford 74LS174 ...... 30 information please write (or call). Reg. $19.95 NOWONLY $3.95

Reader Service Number 93 MICRO CORNUCOPIA, #41, May-June, 1988 69 Letters (Continued from page 6)

So when you linked routines from C ing for columns ranging from zero to ductor patents with their 256K DRAM. and assembler, you had the eight-' maxcol, you divide the range by max­ Samsung agrees (not happily) to pay TI character limit-due to the assembler, col, not (maxcol - 1). Oh, what a familiar fifty cents per part as a royalty; 256K not the C compiler. error. He did it for rows and columns in DRAM prices are now about $2.60, and The author states that "this limita­ both programs and is not the first. rising. tion [name length] of one C compiler End of December, 1987: As usual, extends to all C compilers (if you want Hal Lewis Japanese manufacturing and shipping portability)." I've tried to port 8086 as­ Dept. of Physics shut down for two weeks at the end of sembly code from MASM to Aztec and University of California the year. This exacerbates an already other 8086 assemblers. They don't all Santa Barbara, CA 93106 bad shortage of parts. By the first work work the same, so we have a similar week of January, prices of typical 256K problem with assembly language. Editor's note: Thanks for the correction, DRAMs have shot up $1. The code generated from his ex­ Hal. A number of readers have sent in their January, 1988: DRAMs simply aren't ample obviously comes from an older fractal code, also. They used 8087 assembly, available in large quantities. A broker compiler without any optimization. The fixed point math, and more efficient algo­ suggests to me that Sam sung doesn't jmp to a label on the next line always rithms. Look for an article in the near future want to pay the patent royalty on gets removed by even simple peephole explaining these techniques. DRAMs to TI, so is simply not import­ optimizers. ing them into the U.S. By mid-January, The chkstk code in MSC may be dis­ The RAM Price Debacle prices have shot past $4.50 per chip-l abled during compile. This makes the If you've been following RAM prices Megs aren't so bad, "only" about $28. code to call a function smaller. But I've over the last few months, you know In a weird violation of the ironclad found chkstk to be a wonderful aid what's been happening. RAMs have rule of RAM sales (slower is cheaper), a during debugging. Stack problems can been skyrocketing in price at a rate to­ broker offers to sell 120 nsec DRAMs be notoriously difficult to find, especial­ tally unanticipated. Here's a brief for $4.50, 150 nsec for $4.65. Why? He's ly in code dealing with many interrupts. chronology, with some whys and out of stock on 150 nsec, but has plenty I use assembly for speed and C for wherefores. Keep in mind that I'm quot­ of 120 nsec. portability and readability. Code is ing volume pricing. End of January: A broker calls me often maintained by another person Early 1987-April: The price of 256K up and offers 256K DRAMs for $6.50. I than the author and my experience has DRAMs in large quantities is about don't faint. By this time, I'm numb to been that C is far easier to maintain. So $1.60; 1 Meg DRAMs go for about $18. the news. use whatever language is appropriate A reliable supplier of mine tells me that Now (February 3, 1988): No relief in for the task at hand. Assembly language 1 Meg DRAMs will be less than $10 by sight, yet I can't imagine this price run­ certainly has its place; so does C. And the end of the year. up lasting much longer. There are too perhaps there's even a good use for American DRAM manufacturers, many companies which depend on COBOL! chiefly TI and Micron Technology, have reasonably-priced RAMs. been complaining to their congressmen_ Open up a current PC-type Martin Nohr about alleged DRAM "dumping" by magazine. Notice the ad prices on 2 4152 Rosenbaum Ave. Japanese manufacturers. (Dumping is meg populated RAM boards (prices San Jose, CA 95136 either described as selling below the which are now probably below their cost of production of a product, or sell­ current RAM cost!). Call these guys up, Editor's note: If nothing else, Isaacson's ing at a price below the price in the and you'll probably hear either that article generated a flood of great letters. I home market.) they're "out of stock," have raised their haven't seen so much good-natured dis­ Congressmen yelled at the Japanese prices, or both! How can you blame agreement since a state department official government, which yelled at Japanese them? suggested statehood for South Africa. DRAM manufacturers to "stop it." I conclude that only about 20% of the Japanese manufacturers "voluntarily" RAM price increase we've seen has Fractal Error limited their production, which been caused by the Yen-dollar exchange Thanks for the free sample issue #39, gradually raised the price of 256K ratio, 50% is due to politically-inspired which did indeed have a bunch of DRAMs to over $2. Korean manufac­ production cuts in Japan, and 30% is worthwhile stuff-I might even sub­ turers, primarily Samsung, although not caused by opportunism by non­ scribe. bound by any agreement, raised their Japanese suppliers. Larry Fogg's article on the Man­ price to follow the market. delbrot and Julia sets was useful, not Mid 1987: The rise in the value of the James Bell because of still another bubbly descrip­ yen against the dollar continued to put SemiDisk Systems, Inc. tion of the unquestioned beauty of the pressure on the semiconductor market. P.O. BoxGG sets, but because of the simple core Still, 256K DRAM prices were holding Beaverton, OR 97075 programs which tempt one to play. fairly steady at about $2.25. The programs probably would have 4th Quarter 1987: Samsung, the main been slightly more useful if they had Korean manufacturer, reaches an out-of­ not had a trivial mathematical error. If court settlement with TI, which accused you want to find the intercolumn spac- Samsung of violating various semicon- • • •

70 MICRO CORNUCOPIA, #41, May-June 1988 Illustration by Greg Cross

"You know, a simple binary model would work beautifully for this species. There's no doubt that applying bearcognition would be overkill."

THE Z88 UNDER 2 LBS. A Computer Without Compromise

• Where laptops compromIse on dIsplay and RAM capacity to achlelfe portability, and desktops seem to equate price with power, the ZBBls a personal computer whIch makes no compromIses • A CMOS-technology computer with the power to address 4 Mbytes of memory • A computer wIth a wOrlc-free dIsplay of Bllnes of BO characters, an LCD screen whIch outdates all others, and a unIque dynamIc page map on screen • A computer with solid-state permanent storage • A computer with advanced word-processIng, spreadsheet and IngenIous tlme- and data-management software built-In • A computer whIch Is completely self-contaIned, whIch gllfes you up to 20 hours actllfe computing from Just 4 AA batteries, yet WhIch talks and listens to your IBM. A computer with a full-sIze keyboard,ln a package less than the sIze of an BMlJC", with a total weIght of less than 2lbs. • The ZBB. A computer without compromIse.

Z-88 Computer...... $479.00 SERIAL to PARALLEL ifF ...... $ 45.95 PC to Z-88 Linkup ...... 45.00 1/2 MEG. RAM ...... 359.95 32K RAM ...... 39.95 DATABASE S/W ...... 119.95 32K EPROM ...... 39.95 CARRYING CASE ...... 19.95 128K RAM ...... 89.95 Z-88 MAGAZINE.. 5.00 128KEPROM ...... 83.95 X·MODEM SlW ...... 89.95 RS 232 LEAD ...... 19.95

$5 SHIPPING ON Z-88. VISNMC Accepted with 3% surcharge. C.O.D. charge is $2.25.11 there are any questions, feel free to call or write. SHARP'S, INC. Route 10, Box 459 Mechanicsville, VA 23111 Add $5 tor shlppmg and handling. SHAREWARE DISK AVAILABLE FOR '10.00 (804) 746-1664 3% surcharge on credit cards. Reader Service Number 87

MICRO CORNUCOPIA, #41, May-June, 1988 71 CP/M Notes

$19.95 Real Time Clock ing them with a soldering iron and im­ laughing stock. My Kaypro 2-84 is equipped with mediately plunging in a wooden tooth­ I would be very keen to hear from Micro C's Pro 884 Max ROM. Recently I pick (if there's an easier way, I don't anyone who has overcome problems had the lid off, performing the drive know it). with the clock in the 84 series Kaypro step rate mod and noticed several MCONFIG (from the Pro 884 Max 10. I bought the machine partly because empty sockets and missing components. utilities disk) allows setting and display it had the clock. Since new, it has Checking the schematic, it appeared of the clock. Other Micro C disks (K46, jumped hours between power down that all I needed to have a clock were K49) have such routines for those and power up. Kaypro in Australia these parts: without the ROM. looked at it under warranty. But, as it Finally, if anyone tries this mod and was one if the first they had seen, they • Z80A-PIO (put in position U35) fries their board, I will disavow all couldn't help (although they were most • MM58167A clock chip (U36) knowledge of their actions. obliging). • 32.768 KHz crystal (Y 4) I bought the Advent "clock fix" • IN4148 diodes (two at CR6 and JDR Microdevices board, but it didn't make any dif­ CR7) 110 Knowles Dr. ference. Advent very promptly • 0.1 uF disk capacitor (C54) Los Gatos, CA 95030 refunded my money. I have the Advent • 22 pF disk capacitors (two at C64 Turbo ROM but the benefit of on-screen and C65) Billy Guthrie time display is lost. Has anyone any • 3 volt battery and holder (BTl) PO Box 8184 comments? Gadsden, AL 35902 Has anyone ever seen a public However, there were a couple of domain multiformat program (like problems with the schematic. Diode Editor's note: The universal board in the MFDISK) for Kaypros which has source CR6 is shown as a 1/1001". The only 2-84 Kaypros not only has room for the included? I'm surprised that there thing the local radio shop had with that clock (thanks Billy), but for the internal doesn't seem to be anything available. I number was a transistor. The board is modem as well. We made an attempt to would be most interested in hearing drilled and printed identically for CR6 chase down the parts a while back with from anyone, especially as I am rather andCR7, with CR7 shown as a IN4148 somewhat discouraging results. If anyone isolated here in Indonesia. diode. Since the diodes appeared to has done the modem mod and has a good have similar functions, I assumed a source of parts, let us know. Dr D. Yates, IPB-Aust. Project IN4148 for both. A IN4148 works fine in place of the Jakarta Bag The schematic also calls for 20 pF 1001. They're both just low power diodes. A Locked Bag 40 capacitors. Thar ain't no sich of a thang! solder sucker will also clean out the circuit Queen Victoria Tce I used 22s. board holes but a toothpick is cheaper. Parkes, ACT, 2600 All of the above parts are available Australia from JDR Microdevices for $19.95 in­ A Plea From Indonesia cluding shipping. A little overkill I am an Australian who this year Editor's guess: You've moved the here-the IN4148s come 25 for a dollar. commenced a two year stint on an Kaypro through so many time zones that Also, the 3 volt lithium battery Australian Foreign Aid program in In­ it's jumpy. Or your board might be having holder doesn't match the board holes donesia. Sources of useful information an AI problem. exactly. I managed to jimmy it in place and public domain software are very using one of the snipped capacitor leads difficult to find here. Mind you, software as an extension to the plus terminal. is available for about 30 cents plus the • • • Anyone finding a better fit can leave cost of the disk. Sickening, although $3.45 off the order to JDR. here there's nothing illegal about it. I had no difficulty soldering in Having been president of a Kaypro (gingerly!) all these parts from the top user group in Australia, I am always of the board. But use the solder sparing­ very careful about piracy issues. Here, ly. You can unplug the holes by touch- anyone concerned about piracy is a

72 MICRO CORNUCOPIA, #41, May-June 1988 Small C Utilities, Continued

Stephen S. Mitchell redirection operators. If it is an everyday utility, 320 King St., Suite 506 Small C has been a part of the computer com­ however, I would recode with VIEW.C to check Alexandria, VA 22314 munity longer than most computers. In this final for file name arguments as part of the com­ (703) 360-4659 look at Small C utilities, Steve brings us details on mand line. And failing that, to prompt for special things to watch for in printfO and the ASM them. assembler. Since the output of the program is going to "stdout," which is more likely to be redirected to a file than sent to the screen, we must send n Micro C Issue #21 (Dec-Jan 1985), Eric Sos­ operator messages to "stderr" (which is always man presented a BASIC program to strip the console). This avoids their burial within the the comments from an assembly language output file. Ifile. The program works fine. However, if Because fgetsO in IOLIB.ASM was still you are serious about learning to program in C, buggy, I used getlineO from Kernighan and why not write your comment stripper in C. Ritchie to fetch the input lines. Besides, getlineO Hence, NOCMNT.C (see Figure 1), which does returns the length of the text line it fetches, precisely that. eliminating the need for strlenO. As in VIEW.C, The algorithm is essentially a straightfor­ none of the functions in LIBASM.C are needed, ward translation of Sosman's BASIC into C, nor is LIBASM.C appended. coupled with part of Kernighan and Ritchie's code for removing trailing white space. Tabbing In order to reproduce Sosman's logic, both ENTAB.C (see Figure 2), which replaces C's "continue" and "break" statements were spaces with equivalent tabs, takes the same ap­ used. However, rather than opening and clos­ proach as NOCMNT.C with respect to input ing files, I relied on input/output redirection and output. (which the compiler on K7 supports, but Fred Note that this version of the compiler does Scacchitti's version does not). not support redirection to or from a device, Actually, I agree with Fred's viewpoint in only to or from a file. For example, if you at­ that CP/M is not UNIX, and I would prefer a tempt to send the output to a printer with command line syntax such as: >LST:, you will get a disk file named "LST:," but you will not be able to TYPE, REName, A>nocmnt fatfile.asm slimfile.asm ERAse, or PIP. Most aggravating. Instead of: You can, however, use a disk editor like DU A>nocmnt slimfile.asm to go into the directory and change the name, byte by byte, to something CP/M recognizes as However, redirection . is very convenient a file name. when you are developing a program. Test The algorithm comes from Software Tools, input can come from the keyboard and you can tweaked a bit by James Hendrix to allow for immediately see the result on the screen. This the possibility of tabs and backspaces in the makes debugging much easier. input. A fixed tab size of 8 (the standard CP/M Also, sometimes the code to fetch and tab interval) is used to simplify the program. If validate file name arguments can be as complex you really need to "entab" a file with other tab as the rest of the program. (If there is no such sizes, just retrieve the value from the command file, do you simply abort or do you give the line or prompt for it. user a second chance? Should you show the In either event, the obtained value could be user a directory? Of which disk. .. ) converted to an integer value with the function For this reason, if the program is only used dtoiO in LIBASM.C and assigned to the vari­ occasionally, I don't mind typing in the < and> able "tabsize." Currently, however, LIBASM.C

MICRO CORNUCOPIA, #41, May-June, 1988 73 is not needed and is not appended.

Avoiding The Singles Scene The best things in life often come in pairs-braces and brackets in C programs, for instance; quotation marks and parentheses in ordinary English text; and I\S and I\B underline and boldface controls in WordStar files. PAIR.C is designed to keep your files honest. It makes sure that items which should be paired, are. To do this, it reads the file character by character, counting braces, brackets, and so on. When it's finished, it determines whether the number of left-hand characters equal those on the right. (Or, in the case of quotation marks or print controls, which don't have a right and left, whether the total is evenly divisible by two.) Editor's note: PAIR and COUNT (which follows> are available in the Issue #41 file on the Micro C RBBS, 503-382- 7643, and on the Micro C Issue #41 disk. The disk is $6.00 for u.s. subscribers, $8.00 for everyone else, ppd. To order, use the prepaid order form in this magazine or call 1-800-888-8087. It either reports any discrepancies or pronounces the file healthy. As with VIEW, you can specify the file to be checked on the command line. If you forget or fail to do so, the program asks. Note the use of #define and #ifdef to control conditional compilation. If WordStar isn't used, there's obviously no point in looking for I\S's and 1\ B' s. Simply omit (or comment out) the line #define WORDST AR. This will ensure that the code between each #ifdef WORDSTAR and its terminating #endif won't be compiled. You can easily compile two different versions of P AIR-one with WORDSTAR defined for checking your word processing files, and one with WORDSTAR not defined for checking your C program source files. Either way, each character fetched from the input file is tested using a "switch" statement. A series of "if ... else if ... else if ." else if" tests could have been used instead, but the switch statement produces more efficient code. Note that the counting variables rparen, lparen, etc., are declared global­ ly (outside the mainO function), while ch is declared locally. The Small-C com­ piler generally produces more efficient code fetching and retrieving global vari­ ables than it does with locals. (Except for the last two local variables declared. They can be pushed and popped on and

74 MICRO CORNUCOPIA, #41, May-June 1988 off the stack.} Since ch is so heavily used, I declared it locally.

Names I got bitten by two of my variable names. In my first attempt at the PAIR program, I named the counters for I\S and I\B as ctrl_s and ctrCb, respectively. The compiler had absolutely no problem with these names, which are after all perfectly legal C names. But global variables create assembly .lan­ guage labels of the same name. And ASM doesn't like the underline charac­ ter. Had ctrl_s and ctrl_b been local, however, this would not have been a problem. Local variables are stored on the stack and there is no assembly lan­ guage label created. In this case, I left them global for the sake of efficiency and simply changed the name to a form ASM could live with. Incidentally, Hendrix's book has an extensive chap­ ter on Small-C efficiency considerations. I recommend it highly. Editor's note: A limited supply of "The Small-C Handbook" by James E. Hendrix is available from Micro C for $17.95, postage paid in the U.S.

Screen Output The messages to the screen could have been output more simply by using putsO rather than fputsO. However, the putsO function supplied in IOLIB.ASM has a bug which prevents it from responding properly to the newline es­ cape sequence \n. Additionally, it does not automatically append a newline to the string being output. You can fix the bug (see Figure 3), but remember, putsO still remains non­ standard (no automatic newline). However, since you can force a newline with the \n escape sequence, that should not present a problem. PAIR compiles to a 5K .COM file. Given an 18K text file to examine, it ran through it in 19 seconds on an un­ modified Kaypro II with 2.5 MH clock. By comparison, I have a low-priced commercial C compiler I play around with (particularly when floats or struc­ tures are needed, neither of which Small-C offers). Using it, the same program compiled to a 16K (!) .COM file and took 50 seconds. Even though this particular package is not the most highly-touted C com­ piler ever to come down the pike, the mean it generates second-rate code. surprisingly, the commercial package figures do serve to show that just be­ I've deliberately omitted a com­ (which includes a linking loader) is sig­ cause Small-C is public domain doesn't parison of compilation times where, not nificantly faster. For an application like

MICRO CORNUCOPIA, #41. May-June, 1988 75 PAIR, which I might call on several do you really need all the flexibility of used the function itouO from the Small­ times a day, however, I'm more than printf()? Most of the time you can out­ C library along with a separate function willing to trade an extra couple minutes put a line by repeated calls to fputsO, putnumO. The interface buries some of of compilation for the additional speed fputcO, and the Small-C conversion the complexity and makes it easier to and the smaller code size. functions itod(), itoxO, and itouO. understand. Obviously, it's a lot handier to write: The Virtues Of Compactness Epilogue The question of size brings me to printf ("Words = %6d\n" , words) ; Well, that's it-enough examples for that tantalizing suggestion by the a month of Sundays. They won't neces­ author of SAMPLE. DOC, who says, /lAs than it is to muddle your way through: sarily make you an expert Small-C you grow with C you will learn how to programmer, but a least you should be reduce the size of your final programs." fputs ("Words = ", stdout) ; pointed in the right direction. Now you I know I'm not the only one who fputs(itod(words,numstr,6),stdout); can start working your way through the regrets that no clues were offered as to fputc('\n',stdout); exercises in the many excellent books on what the technique was. (Presumably it C programming. was left as an exercise for the reader.) But the latter eliminates the con­ Proficiency in programming, as in Of course, you can reduce the size of siderable overhead associated with any other worthwhile human endeavor, the compiler's .ASM output by slim­ printfO, and will go a long way toward comes with practice. So don't just read ming down the runtime library files. keeping your programs compact. about C programming-fire up your After that, probably the best way to editor and start writing. keep your object files small is to avoid printfO Replacement No matter how many mistakes you appending LIBASM.C and use printfO You can have formatted output make along the way-and I've made as little as possible. without printfO, however. COUNT.C just about every one, often more than Without a linker, it's a real pain to (also on the Micro C RBBS and Issue once-there's still no thrill like seeing have to #include needed routines from #41 disk) is an adaptation of the the source code you've labored and the C library. Especially since you have familiar word counting program from puzzled over come alive, ready to do to be careful about functions that in The C Programming Language. your bidding at the press of a few turn call other functions (as both printfO Since Small-C has short integers, and keystrokes. and dtoiO do). But simply appending since the number of characters in even a Of course, the thrill is there in any LIBASM.C to your source file will add moderately large text file could well ex­ language, but Small-C is special. It 3K to your final program. ceed the maximum (signed) integer belongs to the hacker community and The biggest offender is printf(). value of 32,767, I declared the counting not to the commercial interests. By Avoiding it altogether (or at least variables to be character pointers (even using it, you're helping to keep a reserving it for those programs where though they are used like integers). remarkable tradition alive. the alternative would be truly cumber­ Small-C, while it does not have an ex­ some or inconvenient) will pay hand­ plicit unsigned integer type, treats some dividends in terms of reduced pointers as unsigned integers, which • • • program size. can have a maximum value of 65,535. When you think about it, how often To print out these unsigned values, I

Figure 3-Small-C Verso 2.03 (ASM) Bug Fixes JMP PUTS1 PUTSRET: RET (1) The puts() function supplied as part of IOLIB.ASM does not respond properly to the newline escape sequence \n, (2) When reading a disk file, fgets() fails to terminate as sending only a bare carriage return rather than the car­ it is supposed to when a carriage return is encountered, riage return/line feed pair that CP/M expects. (The func­ and continues reading characters until the maximum number tions fputs (), put char (), and fputc (), by contrast, all of characters is read. (This plays havoc with programs respond properly to \n). To correct this problem, edit the doing line-oriented input.) To cure the problem, change the file IOLIB.ASM to add the instructions shown here: one instruction in the file IOLIB.ASM as shown:

added instructions are marked with * changed instruction marked with * PUTS1: POP H FGETS3: MOV A,M MOV A,L ORA A pop H JZ PUTSRET MOV M,A MOV E,M INX H INX H PUSH H ANI 7FH PUSH 0 * save char on stack CPI EOL MVI C,PUTCH ;*was CPI LF CALL BOOS JNZ FGETS2 POP 0 * retrieve char MOV A,E ; * ANI 7FH * mask parity bit (The problem arises because FGETS fetches characters with CPI EOL * is it a CR? calls to GETC, which in turn "swallows" the character-as­ JNZ PUTSl * no, loop for next char sumed to be a line feed-following a carriage return. Thus MVI E,LF * else send line feed CPI LF is never true.) MVI C,PUTCH ; * CALL BOOS ; * END OF LISTING

76 MICRO CORNUCOPIA, #41, May-June 1988 Around the Bend (continued from page 4)

Later Just the other day, I was showing a fellow through the of­ fice. He was thinning a bit at the top and his quiet demeanor reminded me of the old man at the coast. I proudly pointed out our new clones, the ones with the high-power processors, copious RAM, winchesters, everything that technology could offer. Then he noticed my Big Board. "That's an early CP/M machine," I told him. He brightened a bit and ran his fingers over the dusty cir­ CS64.1 Aztec ROM SYstems New PC/M5-00S 6502165C02 • 8080IZSO cuitboard. S08S/80xa6 • 680xO "A friend had one of these. Once." CP/M·86 - ROM Superior I'9rfonnance. a powerful An IBM or Macintosh is not only a less SaG Fly-In nfIN array of features and utilities. expensive way to develop ROM code, it's and pricing that is unmatched make better. Targets include the Speaking of flying, Bill Davidson (PC Tech) will be bringing the new Aztec C86 the first choice 6502l65C02, 80801Z80. 8086/S0x86, his Bonanza to SOG. Cecil Stump will no doubt be showing up of serious software developers. and 68OxO. Aztec C has an excellent reputation for in his 172. So, they're organizing a fly-in. producing compact high performance On July 14-16 Bend International Airstrip will host the SOG Aztec C86·p ...... $199 code. Our systems for under $1.000 • optimized C with near. far. huge. outperform systems priced at over VII fly-in. There'll be a couple of pilot rental cars at the airport small, and large memory - Inllne $10.000. (large, old, station wagons), space to park your plane, room to assembler - In line 8087/80287 - sleep under the wing, and a chemical john (a nice one) avail­ ANSI support - Fast Float (32 bit) - InlUal Host Plus Targel .. $ 750 optimization options • Manx Aztec able when the FBO is closed. 8086/80x86 macro assembler Additional Targets ...... $ 500 If the weather's nasty (extremely unlikely) we'll throw my 'Aztec overlay linker (large/small ROM Support Package .... $ 500 model) • source level debugger • Stinson out of the hangar so you'll have a dry space for sleep­ object librarian • 3.x file sharing & ing. locking • comprehensive libraries of Vax, Sun, PDp·11 ROM Bend has a published VOR approach; Redmond (10 miles UNIX. DOS. Screen. Graphics, and special run time routines. HOSTS north) has ILS and FAA flight service (makes it a good alter­ Call for information on Vax. PDP-11. Sun and other host environments. nate). Bend has 100 low lead and Jet A (for the Stinson, of Aztec C86·d ...... $299 course). Redmond has 100LL, Jet A and unleaded auto fuel (at • includes all of Aztec C86-p • Unix Butler Aviation). utilities make, diff,grep • vi editor • Cross Development 6+ memory models • Profiler. Bend's runway is paved, north-south (16-34), 5,000 ft. long, Most Aztec C systems are available as cross development systems. Hosts 3200 ft. elevation. Bend unicom is 123.0 and is monitored by Aztec C86·c ...... $499 include: PCIMS-DOS, Macintosh. CP/M. the FBO during daylight hours. Amateur radio operators who • includes all of Aztec C86-d • Vax. PDP-11. Sun, and others. Call for are flying in might also monitor 146.52, simplex. Ground Source for library routines • ROM information and pricing. Support • CP/M-86 support • One bound hams should monitor the Bend repeater, 146.94-34. year of updates. If you'd like to join the fly-in, call Bill Davidson at PC-Tech CP/M· S080lZS0 ROM (612) 345-4555. He'll be coordinating transportation to and C compiler, 80801Z80 assembler. Third Party Software linker. librarian. UNIX libraries. and from the college and he's organizing some social to-do's. A large array of support software specialized utilities. is available for Aztec C86. Essential Other Ways To Bend Graphics • C Essentials • C Utility Aztec C lI·c CP/M & ROM .... $349 You can drive to Bend if you live on the West Coast, or you Library • Greenleaf Com. • Greenleaf CP/M ...... General • Halo • Panel • PC-lint • Aztec C lI·d $199 can fly into a commercial airport and drive. We're 11 hours by PforCe • Pre-C • Windows for C • car from San Francisco, 6 hours from Seattle, 5 hours from Windows for Data • C terp • db Vista • Phact • Plink86Plus • C­ Boise, Idaho, 3 hours from Portland, Oregon, 2 1/2 hours from tree. How To Become A User Eugene, Oregon, or 15 minutes from Redmond, Oregon. To become an Aztec C user call 800- Redmond has the only commercial airport in the area and 221-0440. From NJ or intemational C' Prime locations call 201-542-2121. Telex: it's served by three regional airlines. However, you'll often pay PC/M5-00S - Macintosh 4995812 or FAX: 201-542-8386. more to get from Portland to Redmond than from New York to Apple II_ TRS-80 _ CP/M C.O.D.. VISA. Master Card. American Express. wire (domestic and Portland. These C development systems are international). and terms are available. A lot of people fly to Portland, rent a car, and drive to Bend. unbeatable for the price. They are One and two day delivery available for all There are two major routes from Portland to Bend and both are earlier versions of Aztec C that domestic and most international originally sold for as much as $500. destinations. beautiful drives across the Cascade Range. The prettiest follows Each system includes C compiler, Azt S t bo ht d' ctl f assembler. linker. librarian, UNIX ec ys ems ug Ire y rom Interstate 5 from Portland to. Salem and then Highway 20 from Manx have a 30 day satisfaction routines. and more.. Special Salem to Bend. Reserve a couple of extra· hours for exploring discounts are available for use as guarantee. Most systems are upgradable by paying the difference in pnce plus and picnicking along the North Santiam River. course material. $10. Site licenses. OEM. educational. C' Prime ...... $75 and discounts are available. Graphics Snafus ~------~-- Desktop publishing is going along quite well. At least the text part is. The graphics end still has problems. I purchased a Microtek MSF-300C scanner after our bor­ rowed HP scanner was repossessed. I chose the Microtek be­ cause it was Editor's choice in PC Magazine.

Reader Service Number 17 MTCRO CORNUCOPIA. #41. Mav-Tune, 1988 77 A Reliable PC/XT Compatible The scanner works fine but the software which comes with For The it stinks. I've called Microtek over a dozen times. Each time Corner Stone of Your Products they've told me they'd send something that would help; only once did I receive anything and it was for the Mac. Bugs: The Genius display driver doesn't work. The software can't generate a usable paintbrush (PCX) file. Saving the whole scanned image in Eyestar format (its native mode) occasionally destroys the hard drive's FAT. Changing the scan resolution or size often causes an "illegal size" error message. It doesn't matter what you do after that, the program won't work. And, the manual is so opaque that it took me almost two weeks to generate my first image. The Microtek may be the PC editors' choice, but it isn't the Micro C editor's choice. The HP's software was so easy to use that I was generating Announcing The SLY40-XT images within ten minutes. And, it never ate a FAT or gar­ baged an image. The SLY40-XT is a small (4-1/4" by I've tried to find a paint program or other package which 9-1/4"), four layer card featuring supported the MSF 300-C. No luck. (They all support the HP.) Today I received some welcome news. Microtek will be all of the PC/XT mother board releasing a bug fix in March. Unfortunately, I'll have to pay functions. The board simply plugs $49 for the fixed version or sign up for one year of support for into a passive back plane or $150. (Meanwhile, HP is sending out new software with new features, free to registered owners. And the HP scanner would SLICER'S 10 slot bus board. have been cheaper.) Microtek also sent a package called Gemmate. (No • High Integration - Composed of just documentation, no read-me file, just a disk.) Very little help 17 Low Power CMOS ICS from tech support. It turns out that Gemmate lets you run the scanner while inside Ventura. Great. However, Gemmate • NEC's 8 MHZ V40 won't give you even a rough look at the image so you're scan­ • One Megabyte of Zero Wait State RAM ning blind. Thanks, but no thanks. • 8087 Co-Processor Socket Reflection • Standard Keyboard Connector Out of the blue (where else?) came a care package from • Slicer's Own Bios, Source Code Included IMSI. In that package was a small translation program called • Ideal For Tough Industrial, OEM and Reflection and Reflection cured my tif with Microtek. Portable Applications Microtek's Eyestar package generates reasonable .TIF files. Reflection can turn .TIF files (despite a few erroneous charac­ • American Made and Fully Supported ters left by Eyestar) into .PCX files. Once I have .PCX files, I by Slicer can edit the images with Publisher's Paintbrush and dump them into Ventura. Hooray. If all this sounds more complicated than it should be, • Complete SLY 40-XT System you're right. But it's workable because Reflection runs very with 20 MEG Hard Disk easily. - Just 1299.95, Retail By the way, Reflection translates any of the following to • Without Hard Disk any of the following: Amiga ILBM, Compuserve GIF, Halo - Just 995.95, Retail CUT, H.P. PCL, Inset PIX, Lotus PIC, MACPAINT, PC Paintbrush PCX, text, TIF.

Reflection ($89.00) Ask About Our Complete Line of Computer IMSI Products and Accessories! 1299 Fourth St. San Rafael, CA 94901

MasterCard, Visa, Check, Money Order, or C.O.D. Allow four weeks for delivery. Theoretical Issue Prices subject 10 change without notice. If this issue doesn't give your brain a charley horse then NOTE NEW ADDRESS & PHONE NO. you're either just out of school (which means your brain al­ Slicer Computers Inc. ready has a charley horse) or you're a lot like that perverse as­ 3450 Snelling Ave. So. sociate editor Gary Entsminger. Minneapolis, MN 55406 612/724-2710 It's not that this isn't an interesting issue. It's quite interest­ Telex 501357 ing. But then Micro C has become famous for mucking around SLICER UD in the fun, cheap, practical crannies of computing. We're project oriented, not theoretical. PC and XT Are Trademarks of International Business Machines But once in awhile, a little theoretical is good for you. (Like

Reader Service Number 19 78 MICRO CORNUCOPIA, #41, May-June 1988 Complete 8MHz Monochrome System $995 salad.) It stretches your brain, exercises your imagination, helps you grow hair in all the right places. • Fully compatible with IBM AT1M This was supposed to be an AI issue. It is, sort of. But it's • Intel 80286 CPU; 80287 socket much broader than that and I'm glad. I think that classic AI is • 512K Memory on 1MB motherboard in the doldrums right now. I think people are afraid of it. • HD/FD controller; Battery Backed Clock/Calendar Meanwhile our C issue (Issue #40) generated more excite­ • 1.2 MB Teac Floppy Drive; MaxiSwitch AT Keyboard ment, more feedback, more activity on the RBBS, more mail, • FCC Class B approved more newsstand sales, more new subscribers from word of • 48 hour factory burn-in and testing mouth, more everything than anything we've ever done. And • 12" Amber Monitor (720x350) with TilVSwivel the hottest thing in the issue was Gary Mellor's Turbo C • Hercules Compatible Monographics video card debugger. Thanks Gary. • 200-page Documentation and User Manual • DeSigned and Made in U.S.A. with 1 year warranty More Of Last Issue "What's the page number for the culture corner?" Call for our AT-SS6 machine (4075 Dhrystones) "Culture Corner?/1 Last issue was a killer: missing columns (two), a shortage of Options: graphics, confusing page layouts, incorrect page numbers ... 10MHz Upgrade $150 14- EGA Monitor/Card Add $399 20MB XT Kit, ST225 "Can we skip to issue 41?/1 $279 Taxan no Multisync $499 30MB XT Kit, ST238 $309 2MB EMS Crud $1~ "Nope. Somebody'd notice./1 Seagate ST225, 20MB $249 EVGA 1280x600 $295 If you've been following the continuing saga of Micro C and Seagate ST251 , 40MB $449 Everex 1200B modem $89 Desktop Publishing, you might expect me to take a poke at Miniscribe 6053, 43MB $595 Everex 2400B modem $179 Ventura. I can't. It worked better than ever. Micropolis 70MB 28ms $895 Software Call Our output was almost untouched from laser typesetter to All hardwarelboards include manuals and software for easy installation. printer. Our turnaround was faster than ever. In two weeks Call for further infomation and other products. Ask for our catalog. we'd Ventura'd the articles, laid out the magazine, typeset the pages, pasted everything together and shipped it off to AmTech Computers Michigan for printing. (Michigan? Hey Marge, Micro C's being 3701 Guadalupe St•• Suite 103. Austin. Texas 78705 printed in Michigan.) (512) 451-0921 The problem was human. Very human. Two weeks aren't Terms: Cashier'S Check, Money Order, VISA/MC (3%), personal checks enough when you're as imprecise, scatterbrained, and pushed (allow 10 days to clear). Shipping will be added. Prices and availability as I am at deadline time. I'm an idea person. You want an subject to change without notice. Texas residents add 7% Tax. idea? Here. You want something edited? Great. Reader Service Number 44 You want the table of contents to point to the right page? (We're talking infinite precision.) Find someone else. New/rom MBC $99.99 Fortunately I'm surrounded by people who cope pretty well with deadlines. They flagged most of the errors before those errors saw the dark of ink-but Culture Corner and NanoLISP CP1M Notes were misplaced. Oh, we've found them, but they A Common LISP Interpreter for MS-DOS didn't make issue #40. NanoLISP contains a large useful subset of the Common Next Issue LISP standard, including most Common LISP operations, National Advancement Corp. (they teach seminars on ser­ and adheres preC£se/y to the specifications of the standard. vicing XTs, ATs, etc.) says they've discovered a fix for flaky Seagates. You and I should see a major repair article from • Helpful Features: extremely thorough error-checking, them (including the Seagate fix) in issue #42. explicit error messages, excellent debugging facilities • Advanced Features: lexical and dynamic scoping, FastCopy closures, lambda-list keywords, structures, bit-arrays, Every once in awhile a treasure shows up in the mail. generic sequence functions, transcendental functions, Sometimes it's a large, four-color box with manual, disks, and output formatting a cover letter from a corporate officer. Other times it's a disk or two in a plain brown mailer. • UnCommon Features: graphics, low-level DOS access, FastCopy came in plain brown. customization It came from Jim Nech, its author, and it's super. • Sample AI application programs It's easy to use, very fast, powerful, everything. It's every­ • Fully-indexed 150-page reference manual thing that MS-DOS's diskcopy should have been. For instance, you can load a disk into memory, set the • Unlimited free technical support number of copies you want and start feeding blanks. It for­ Free sMpping on prepaid orders. mats the destination disk if necessary (automatically), will verify the data, can alternate between two floppy drives (so Microcomputer you can put a disk in one while it's copying data to the other), Systems and it'll do it all very quickly. MSC Consultants If I were a user group librarian or distributor of user disks P.O. Box 747, Santa Barbara, CA 93102 (oh yeah, I forgot) and couldn't afford one of those fancy (805) 963-3412 Reader Service Number 36

MICRO CORNUCOPIA, #41, May-June, 1988 79 SCIENTIFIC GRAPHICS automatic copy units, this would definitely do the trick. Presentation Quality Graphics How Fast? For Printers and Plotters On my system, for instance, diskcopy takes about 60 seconds to copy to an unformatted disk (that's without Screen Graphs for verification). Fast Previews FastCopy, on the other hand, did the following: With verify off, it copied the data onto a formatted disk in 12 seconds, and onto an unformatted disk in 38 seconds. With verify on, it took 24 seconds to a formatted disk and 50 seconds to an unfor­ matted disk. And,remember, your system doesn't have to reread the master each time it makes a copy. And I still haven't mentioned the online help, the fancy Curve-Smoothing menus, all the information the program tells you about the Interpolations source and destination disks and so forth. Fantastic package. Jim, you did a great job with FastCopy and I wish you all the best. .~~,~~--~~~~~~~~~~ . . . . Legends Placed Anywhere .... Ilt ...... FastCopy 3.0 $69.95 Built-In Editor AutolManual Scaling Log/Lin/SemiLog Systems, Software, Support P.O. Box 751022 An Indespensible Tool For Technical Professionals Houston, TX 77275-1022 Special (713) 941-3100 In~roductory $79 Pnce Larry's 8088 Piece System Requiremcnb: IBM-PC. XT. AT or Compatiblc running DOS 2.0 or highcr. Sm:cn graphs rcquire graphics card. Printcr Graphs rcquire Epson EX. FX. JX. RX. HS: Star This last PC LSI piece from Larry has been one of the most Gcmini. Rlldix. SO. SG. SR: IBM Gmphics: or compatibility with onc of the above. Plotter difficult. The 8088 is a complex chip, no doubt about it, but we graphs require HP-GL l·ol11patibility. both expected it to be well documented. It is, and it isn't. cientific The way it's used in the PC/XT threw us both a curve. Software P.O. Box 956, Dept. M, Valley Forge, PA 19482 For Technical Information: (215) 269-0198 Especially when it came to the LOCK pin. The LOCK pin sup­ Solutions ~ Reader Service Number 60 posedly goes low (true) when you run a LOCK instruction. A LOCK instruction tells the processor' that on the next instruc­ tion it gets RAM all to itself (no one else gets access to RAM during that instruction). We couldn't figure how the 8088 could access RAM after it had locked out everyone else. HAN We tried figuring signals logically, then illogically. Neither worked. Maybe the processor doesn't access RAM during a LOCK. REPAI Maybe it makes up its own data during a LOCK. Maybe LOCK doesn't work and no one realizes it. Maybe the XT doesn't work. Maybe I should go back to writing captions for the culture corner. P.S. Dean Klein straightened us out. I guess that's what deans are for.

Fixing Our Credibility I received a note from Darrell Bethune of West Vancouver, British Columbia. It was the first time someone had managed book-length prose on a single renewal form. One of Darrell's points: "Keep editorial integrity. Zortech and Trilogy plugs in the same issue as their first ads?" You're right Darrell, that's suspicious. However, both companies earned their plugs from the editors. And, they earned them long before they decided to ad­ vertise. See last issue's "On Your Own" column for my thoughts on advertising when you're getting editorial mention. I think they were smart. And, I reserve the right to say what I think about a product whether or not the company advertises. For instance, I've received three products which print out information on Ventura style sheets (or chapters). Two are standard commercial products, one is shareware. All have bugs. Many of the bugs are significant. The best, and only really workable package, is called

Reader Service Number 59 80 MICRO CORNUCOPIA, #41, May-June 1988 CALL FOR FREE CATALOG ~~------, ~ TEXT TO SPEECH BOARD! Withstyle. It's distributed by Pecan Software Systems and it lets :l PC/XT COMPATIBLE. MAKE YOUR COMPUTER TALK! you print out tag information as well as transfer tags from one ~ ~N~i:J:e~;~~~~~~5~~~2~fe~Wc~~~~~~ .fH~gTs~~::-I:i;~:f.r8~~::t~ z CONVERTER. style sheet to another (hooray). You can even use Ventura to N lr ~tg~H:~:~2RDUS:~D O~~Q~~~Js °A cTli~ print out (beautifully) the style sheet info. :l SERIAL PORT. BOARD MAY ALSO BE USED IN A > STAND ALONE ENVIRONMENT WITH ALMOST I had problems using this package to modify a style sheet­ a. ANY COMPUTER THAT HAS A RS232 SERIAL o PORT. FEATURES ON BOARD AUDIO AMP OR the numeric displays for leading, spacing, etc., were weird, but if U MAY BE USED WITH EXTERNAL AMPS. W DEMONSTRATION SOFTWARE AND A LIBRARY I entered a number several times it finally took. (I just talked to ~ ~NUd~D~c~:l~?:l::~E~EF~aL~'b~u~~:ll~ the author and the problem's fixed in version 1R0.1.) u.. TION AND SCHEMATICS ARE ALSO INCLUDED. ~ Ci\)~\ $6995 This is by far the most complete style sheet printer/editor. ASSEMBLED Definitely worth considering now that they've polished up the ~ N EW! ~~\Ci~ 8. TESTED rough spots. A limited version of Withstyle should be available ~~--...... ---- ...... ~ < NEW! IC TESTER! $149.00 soon on the Micro C RBBS. It only handles five tags. (Meanwhile, c== SIMILAR TO BELOW EPROM PROGRAMMER. PLUGS IN TO YOUR PC OR XT. TESTS W the shareware style sheet displayer is rough, but then it hasn't l- ~Cs~~~~i6Lis~~~;t:J>s~~Pd~:~~oXSSEER~~~Scl~g~~J>J~~ ::J>I~~~~g~~~:.;~·~~~~ I DETERMINE PART NUMBERS OF MOST UNMARKED AND HOUSENUMBERED DEVICES been released. I'll keep you posted.) i WITH SIMPLE MOD. THIS UNIT CAN ALSO TEST 6.4K AND 256K DRAMSI WITH MANUAL ~ AND SOFTWARE: $149. PERFECT FOR SCHOOLS. Withstyle $79.95 (version 1RO.1) c ~~------~o Pecan Software Systems, Inc. Q) PC/XT EPROM ASK ABOUT a: OUR NEW 1410 39th St. :l PROGRAMMER o PAL Brooklyn, NY 11218 u.. $169 PROGRAMMERI o ~ * LATEST DESIGN * PROGRAMS UPTO 4 DEVICES AT ONE TIME * FEATURES EASY Two Good Books a: TO USE MENU DRIVEN SOFTWARE THAT RUNS UNDER PC OR MS-DOS. * USES AN W INTELLIGENT PROGRAMMING ALGORITHM FOR SUPER FAST (8X) EPROM If you're planning to get into desktop publishing on a PC, I- BURNING. * THIS PLUG-IN BOARD ATTACHES TO AN EXTERNAL MINI CHASSIS W CONTAINING 4 TEXTOOL Z.I.F. SOCKETS. * NO PERSONALITY MODULES you should pick up Desktop Publishing With Style by Daniel Will­ :I: REQUIRED * AUTOMATIC VPP SELECTION: 12.5V, 21V, OR 25V. * EPROM DATA CAN I- ALSO BE LOADED FROM OR SAVED TO A DISKETTE. * PROGRAMMING SOFTWARE Harris. This is a huge look at the whole PC publishing arena o SUPPORTS: 2716,2732, 2732A, 2764, 2764A, 27128, 27128A, 27256, 27256A, 27512, AND I- 27512A. * ASSEMBLED AND TESTED, BURNED. IN WITH MANUAL. $169 WITH from Ventura to hard disk utilities. I- SOFTWARE. U JUST RECEIVED. SAME AS ABOVE PROGRAMMER, BUT PROGRAMS 8 UNITS AT ONE Daniel compares some of the graphics packages, Desktop ~ TIME - $299. packages, typesetters, laser printers, dot matrix printers. Cheap :lenm~------~ options with reasonable results, etc. en Digital Research Computers w It's a book that'll get you up to speed on the whole desktop ..J P.O. BOX 381450 • DUNCANVILLE, TX 75138 • (214) 225-2309 publishing arena and you'll enjoy his style. The writing is ~ I-=TE""R"""'M~S-:A.,....d:-:d...."S-:::-3.-::-:()()~p-os....,.ta-g-e .....,.W:-:-e-p-ay-:-ba-:-la-nc-e-. O=-r""":"de-r-s -un-:d-er-=$,..".,15=-a-:d:"7d -=75=-=.;:-:"h-an-d=Un--g-.:7 No-i :::l C.O.D. We accept Visa and MasterCard. Texas Res. add 6-1/4% Tax. Foreign orders friendly and easy to read. < (except Canada) add 20% P 8. H. Orders over $50 add 85'; for Insurance. If you already have Ventura Publisher and are looking for Reader Service Number 32 hints and kinks, I'd recommend Ventura Tips and Tricks. It's the book Carol keeps right next to her full-page monitor and it's the one the rest of us borrow carefully (after hours).

Desktop Publishing With Style Ventura Tips And Tricks $19.95, 448 pages $15.95, 286 pages ISBN 0-89708-162-5 ISBN 0-938151-01-0 And Books Peach pit Press 702 South Michigan 2127 Woolsey St. South Bend, IN 46618 Berkeley, CA 94705 (415) 843-6614

Help! I'm looking for information on database programs. If you've had experience with one program or a bunch, I want you. Write, log onto the RBBS, call me, whatever. Send an outline, short synopsis, a disk, a desk, your mother (return postage with mothers, please), anything that tells us what you're into. I'd like to do a complete look at databases. We're talking database design. Database utilities. dBASE 111+ compilers, inter­ preters, look alikes ... Menu-driven database creators and report generators. SQL. Everything.

Finally See you at SOG, get those database cards and letters in the mail today, keep your chin up, and your nose to the grindstone-because that's it from greater Bend.

David Thom~r

Reader Service Number 87 ommmUD Chaos, Butterflies, And The Borland Graphics Interface (BGI)

doesn't describe most interesting phenomena in By Gary Entsminger The whole AI field probably appears chaotic. nature-waves, clouds, turbulence, biological 1912 Haussler Dr. Well, chaos describes lots of things, more· things systems, population dynamics, ther­ Davis, CA 95616 than you might believe. modynamics, the weather, oscillation, and so on. Typically, nature requires more complex (often non-linear) equations. OSt of us believe, perhaps intuitively, So, let's consider one of, if not the simplest, that if we know the initial value of a non-linear equation- variable (say, X) and the function that Mdescribes how it changes (in time), XNext = (R .. X) .. (I-X) we can predict the future value of the variable at any time. which describes a familiar shape, the parabola. Consider the equation- It reaches a peak (determined by R) and then folds down. We can say that R expresses the XNext=R "X linearity in the system. If we start with some initial value of X (or where X is the variable and R describes its rate Seed value) and iterate the function, each time of change. putting XNext in for X, we'll discover that If we assume that each NextX is the X of the XNext reaches some equilibrium, some ex­ next equation (in other words, if we feed each pected value. That is-we'll find that it reaches XNext back into the equation as its new seed or an expected value some of the time, but not al­ X), then- ways. If R > 1, XNext will always increase, until at In fact, not only will it not reach an expected some infinite time, XNext will grow to be in­ value some of the time, but it will explode into finitely large. bizarre patterns and shapes, eventually leading And if R < 1, XNext will decrease until at to and through Chaos, or totally unexpected some infinite time, it will approach O. Either values. way, the function is dependable. The key to how the function behaves is R. A new science, called Chaos, which is loose­ At low R values (up to 3), the function is pre­ ly the study of feedback or iterative equations, dictably predictable. But at R values between 3 has recently challenged this simple notion of and 4, anything can happen; and perhaps most predictability, demonstrating convincingly that significant, anything can happen after very sub­ initial values and a function (or rate equation) tle or minute changes in R. aren't always sufficient for prediction. For example, I'll try to explain, and then I'll show you some code which will let you generate Chaos at 3.8284, a basic cycle of 3 first appears; on your PCs. at 3.8415, it becomes unstable; Non-Linearity & The Butterfly Effect Let's go back to the equation, at 3.99026 a basic cycle of 5 appears; "XNext = R * X." A little thought gives us one reason why it's so predictable-it's linear. at 3.99030, it becomes unstable; A moment's reflection should convince you that a linear description of behavior (or change) and so on. The subtlety in variation is virtually is the simplest of many possible descriptions infinite. (just as a straight line is the simplest connection This effect-of small changes in behavior between two points). But unfortunately, it (often generations before) leading to significant

82 MICRO CORNUCOPIA, #41, May-June 1988 changes-is known as the butterfly ef­ Set foreground and background colors; or Turbo C 1.5 BGls, but I expect they're fect, and has subtle implications in na­ very similar. ture. Set a ViewPort (or window) for graphic The code on the bulletin board uses a If you're interested in pursuing this display; linemenu (from the Prolog Toolbox), but fascinating subject, I enthusiastically you can use the vertical menu supplied recommend James Gleick's new book, And draw. with Turbo Prolog instead. Just sub­ Chaos, the first full-length feature study stitute menu for linemenu and omit the of this new science which promises to You can set a device driver (to "tpreds," "tdoms," and "linemenu" in­ affect many different areas of science. enable EGA or Hercules compatibility, clude files. Meanwhile, I'll briefly show you for example) or use a BGI predicate (or For more information about BGI- how to simulate Chaos on your PC function) to determine which graphics using the Borland Graphics Interface. display is online. For a demonstration Borland International I'm using it with Turbo Prolog, but you of the latter, check out the Micro C 4585 Scotts Valley Dr. C and Pascal programmers should have RBBS or get the Issue #41 disk ($6 for Scotts Valley, CA 95066 little trouble extrapolating to your subscribers, $8 for non-subscribers and favorite language. If you just want to foreign). Borland supplies drivers for For more info about Chaos-Cleick, see Chaos without programming it, EGA, CGA, MCGA, VGA, Hercules, James. Chaos, Making A New Science. grab CHAOS.EXE from the Micro C AT&T 400-line, 3270 PC, and IBM 8514 1987. Viking. Bulletin Board. graphics. Hofstadter, Douglas. Metamagical In all, the BGI includes 70 or more Themas: "Questing For The Essence Of BGI predicates for drawing dots, lines, rec­ Mind And Pattern". 1985. Basic Books. I've only had a few days to work tangles, arcs, circles, 3-d bars, text, and May, Robert M., Simple mathematical with BGI, but I've already found it to be so on in various line widths and fonts. models with very complicated dynamics. easy to use and powerful. It's by far the most complete graphics Nature. Vol 261. June 10, 1976. In order to generate Chaos (and to toolbox I've used and is a big improve­ And that's Tidbits. get BGI up and running in genera!), you ment over the Turbo Prolog and early need to- Turbo Pascal graphics routines. I haven't had a chance yet to compare the Initialize the graphics system; Turbo Prolog BGI with Turbo Pascal 4.0 • • •

Figure 1 - Turbo Prolog Chaos /* If you want to set a driver w/o detecting it, include "tdoms.pro" use the following 2 lines instead of include "tpreds.pro" the previous 5: include "linemenu.pro" assert(driver(7,7,"HercMono"», InitGraph(7,O, _, _, bgi_Path),!. */ Database - graphics ToText:- closegraph(). Determ driver (Integer, Integer, String) Determ maxcolors(Integer) KeepColor(l,_,O). KeepColor(_,Mode,Mode). Determ maXX(Integer) Determ maxY(Integer) GetDriverName(O,"Detect"). GetDriverName(l,"CGA"). Determ aspectCorr(Real) GetDriverName(3,"EGA") . Determ graphCoord(Integer,Integer) GetDriverName(7,"HercMono").

params(Real,Real,Real,Real,Real,Real,Real, /* Main */ Real, Real) PREDICATES

PREDICATES . Function (Real, Real, Real, Real, Real, Real, Real, Real, Real) GetDriverName(Integer,String) Iterate (Real, Real, Real, Real, Real, Real, Real, Initialize Real, Real, Real) KeepColor(Integer, Integer, Integer) Iterate Trace (Real, Real, Real, Real, Real, Real, ToGrapHic Real, Reil, Real, Real) ToText Main Main menu CLAUSES Nextprocess(Integer) Process (Integer) Initialize:- Testwindow(Integer) ToGraphic, GetMaxColor(MaxColors), assert(maxcolors(MaxColors», CLAUSES GetMaXX (MaXX), assert (maXX (MaXX) ) , GetMaxY(MaxY), assert(maxY(MaxY», Iterate (X,L,Count, I,XScale, YScale, Height, Width, GetAspectRatio(Xasp,Yasp), YStart,XStart) :- AspectRatio = Xasp/Yasp, Y = X * (l-X), /* Y = XNext */ assert(aspectCorr(AspectRatio» . Yl = Y * L, /* Row & Col are scaled */ Row = Height-«(Yl - YStart)/YScale) * Height), ToGrapHic:- /* Detect graphic equipment */ Col = «(Count - XStart)/ XScale» * Width, DetectGraph(G Driver, G Model), putpixel(Col,Row,7), KeepColor(G Driver,G Model,G Mode), Newcount = Count + I, XEnd = XScale + XStart, GetDriverName(G Driver,G Name), Newcount <= XEnd, /* Have we reached assert(driver(G-Driver,~Mode,G Name», user-defined end? No, then iterate. */ InitGraph(G_Driver,G_MOde, _, _~ bgi_Path),!. !, Iterate (Yl, L,Newcount, I, XScale, YScale, Height, Width,YStart,XStart) . Iterate (_,_,_,_,_,_,_,_,_,_) .

MICRO CORNUCOPIA, #41, May-June, 1988 83 GetViewSettings(Left,Top,Right,Bottom, ), Iterate Trace(X,L,Count,I,XScale,YScale,Height, Rectangle (Left, Top, Right, Bottom) , % Draw Border Width,YStart,XStart):- Height = Bottom-Top, Width = Right - Left, Y = X * (l-X) , Yl = Y * L, params(XStart,XEnd,XScale,YStart, ,YScale, Row = Height-«(Yl - YStart)/ YScale) * Height), Seed, Lambda, I), - Col = «(Count - XStart)/ XScale» * Width, Iterate Trace(Seed,Lambda,Seed,I,XScale,YScale, shiftwindow (3) , write ("YStart: ", YStart), Height,width,YStart,XStart), readchar(). write("X : ",Count," "), write("Y : ",Yl," "), Process (4) . - write ("Col : ", Col, II "), Process (5) :- testwindow(81) , exit(l).

write ("Row : II ,Row," ") ,nl, putpixel(Col,Row,7) , Newcount = Count + I, XEnd = XScale + XStart, NextProcess(l):­ Newcount <= XEnd, ! , shiftwindow(2) , params(A,B,C,D,E,F,G,H,I),nl, Iterate Trace(Y1,L,Newcount,I,XScale,YScale, write ("XStart ",A) ,n1, Height,Width,YStart,XStart) . write ("XEnd ",B) ,nl, Iterate_Trace(_,_,_,_,_,_,_,_,_,_). write ("XScale ",C),nl, write ("YStart ",D),nl, /* Draw parabola to scale. */ write ("YEnd ",E),nl, Function(I,X,Height,Width,XScale,YScale,L, write ("YScale ",F) ,nl, XStart,YStart):- write ("Seed ",G),nl, Y = L * X * (1 - X), write ("Lambda ",H) ,n1, Row = Height-«(Y - YStart)/ YScale) * Height), write ("Step ",I) ,nl. Col = «(X - XStart)/ XScale» * Width, NextProcess(l). NextXRe1 = X + I, XEnd = XScale + XStart, NextProcess(2):- NextXRel <= XEnd, shiftwindow(2) , write("Lambda "), putpixel(Col,Row,7) , readreal(Lam) , Lam <> 0, !,function(I,NextXRel,Height,Width,XScale, params(A,B,C,D,E,F,G,H,I), YScale,L,XStart,YStart) . retract(params(A,B,C,D,E,F,G,H,I», function(_,_,_,_,_,_,_,_,_). asserta(params(A,B,C,D,E,F,G,Lam,I». NextProcess(2) :- shiftwindow(2) , write("Invalid Lambda 0") . Main:- NextProcess(3) :­ makewindow(l, 7,0, '''',0,0,25,80), shiftwindow(2) , write("Step: "), makewindow(2,7,0,"",2,0,12,80), readreal(Inc) , Inc <> 0, makewindow(3,7,0, 1111,22,0,3,80), params(A,B,C,D,E,F,G,H,I), Main menu. retract (params(A,B,C,D,E,F,G,H,I», Main_menu:- asserta(params(A,B,C,D,E,F,G,H,Inc». linemenu (0,18,0, ["Parameters", "Function", NextProcess(3):- "Iterate","Trace","Quit"],C), shiftwindow(2) , write("Invalid Step 0") . Process (C) , ToText, Testwindow(81) , Main_menu. NextProcess(4):- shiftwindow(2) , write("XStart : "), Testwindow(N):- readreal(XS), params(A,B,C,D,E,F,G,H,I), existwindow(N), shiftwindow(N), removewindow. XScale = B - XS, XScale <> 0, Testwindow(N) . retract(params(A,B,C,D,E,F,G,H,I», asserta(params(XS,B,XScale,D,E,F,G,H,I». Process (1) :- NextProcess(4) :- linemenu (1,103,0, ["Show", II Lambda " , "Step", shiftwindow(2) , write("Invalid X Scale = 0"). "XStart", "XEnd", "YStart", "YEnd"], C), NextProcess(5) :­ NextProcess(C) , testwindow(81). shiftwindow(2) , Process(l). write("XEnd: "), readrea1(XE), Process (2) :- params(A,B,C,D,E,F,G,H,I), Initialize, ClearDevice, XScale = XE - A, XScale <> 0, SetColor(l) , % Set current color to white retract(params(A,B,C,D,E,F,G,H,I», SetBkColor(O) , % Set background to black asserta(params(A,XE,XScale,D,E,F,G,H,I» . maXX (MaXX) , maxY (MaxY) , R = MaxY - 50, NextProcess(5) :- SetViewPort(O,O,MaXX,R,l), shiftwindow(2) , write("Invalid X Scale = 0"). % Open port to upper screen NextProcess(6) :- GetviewSettings(Left,Top,Right,Bottom, ), shiftwindow(2) , write ("YStart: "), readreal(YS), Rectangle (Left, Top, Right, Bottom) , % Draw Border params(A,B,C,D,E,F,G,H,I), Height = Bottom-Top, Width = Right - Left, YScale = E - YS, YScale <> 0, params(XStart, ,XScale,YStart, ,YScale,Seed, retract(params(A,B,C,D,E,F,G,H,I», Lambda, Inc) , - - asserta(params(A,B,C,YS,E,YScale,G,H,I». function (Inc, Seed,Height,Width,XScale, YScale, NextProcess(6) :- Lambda,XStart,YStart), readchar(). shiftwindow(2) , write("Inva1id Y Scale = 0"). Process (2) . - NextProcess(7):­ Process (3) :- shiftwindow(2) , Initialize, write("YEnd : "), readreal(YE), SetColor(l) , % Set current color to white params(A,B,C,D,E,F,G,H,I), SetBkColor(O) , % Set background to black YScale = YE - D, YScale <> 0, maXX (MaXX) , maxY (MaxY) , R = MaxY - 50, retract(params(A,B,C,D,E,F,G,H,I», SetViewPort(O,O,MaXX,R,l), asserta(params(A,B,C,D,YE,YScale,G,H,I». % Open port to upper screen NextProcess(7) :- GetViewSettings(Left,Top,Right,Bottom,_), shiftwindow(2) , write("Invalid Y Scale = 0"). Rectangle (Left, Top, Right, Bottom) , % Draw Border Height = Bottom-Top, Width = Right - Left, GOAL assert(params(0,1,1,0,1,1,0.04,3.0,0.003», params(XStart,XEnd,XScale,YStart, ,YScale, Main. Seed, Lambda, I) , - iterate (Seed,Lambda,Seed,I,XScale,YScale,Height, END OF LISTING Width,YStart,XStart), readchar(). Process(3). - Process (4) :- Initialize, SetColor(l) , % Set current color to white SetBkColor(O) , % Set background to black maXX(MaXX), maxY(MaxY), R = MaxY - 50, SetViewPort(O,O,MaXX,R,l), % Open port to upper screen

84 MICRO CORNUCOPIA, #41, May-June 1988 Technical Tips

LogitechlZenith Compatibility the first two and 512 iterations works well for Laine Stump complained recently (Micro C the third. issue #40, p.58) about incompatibility between Logitech's C7 Serial Mouse and the Zenith Z181 Gregory K. Landheim laptop. I also own both units. 349 Almond St. Calls to Zenith and Logitech identified the Salt Lake City, UT 84103 problem as the source of power to the Logitech mouse. The mouse receives power from the RS232 port. Zenith has confirmed that their serial driver chip does not provide as much voltage as the chips used by other manufac­ Figure 1-Formal Mandelbrot Buddha turers. This conserves battery power. I suggest that anyone who wishes to use a Logitech mouse with the Zenith laptop add a serial to serial interface which would supply the necessary power to the mouse. I've thought about connecting the required 1488 and 1489 drivers back to back but haven't had the time.

Rod Morimoto 1107 Oregon Ave. Palo Alto, CA 94303

Fractal Parameters I received my first issue of Micro Cornucopia and fed the "Mandelbrot Set Generator" routine into my Turbo C compiler. After a few trials and errors, it generated a fair sample of the set-produced as a screen dump of CGA graphics using DOS's GRAPHICS.COM. A colleague of mine, Rick Daley, requested a copy and produced the enclosed sketch of a "Mandelbrot Buddha" (See Figure 1). I found it Editor's note: Gregory's right. Infinitely many amusing enough to pass it along. choices for Mandelbrot parameters means we also Since I'm aware of how difficult it is to do have infinitely many bad choices. Apologies to those technical writing, and to decide what to put in of you still (slowly) cranking out blank screens. and what to leave out, I'm reluctant to be criti­ Figure 2 shows the parameters Gregory sent, cal of such a nice and useful article as "Draw­ plus a few from The Beauty of Fractals. Remem­ ing The Mandelbrot And Julia Sets." It would, ber, any region near the boundary of the Mandelbrot however, have been extremely helpful if the set will produce interesting results. Also, a full plot had been accompanied by its range. 1000 iterations doesn't add much resolution, so stick And had some interesting "zoom" ranges to 500 or less. been included, naive experimenters could have saved themselves a lot of time. A friend sug­ Seagate Step Rates gested several ranges that I haven't tried yet. The Seagate ST4000 series full-height, linear (See first three lines of Figure 2.) I've been told voice coil drives have an unusually narrow step that a cutoff of 256 iterations works nicely for

MICRO CORNUCOPIA, #41, May-June, 1988 85 rate range. This may require setting the errors immediately, on every sector. step rate on the controller to a non­ We discovered that the controller's default value. Otherwise, the drive may default step rate (70.5 usec) was outside operate unreliably or not at all. of the 25 - 50 usec range specified for Our experience has been limited to the ST4026. We changed it to a smaller problems with the (recently discon­ value (28.5 usec) and reformatted the tinued) ST4026, together with the ubiq­ drive. It has since worked perfectly, for uitous Western Digital WDI002A WXl many hours. controller. The ST4026 has the nar­ Different controllers have different rowest step rate range of all of this default step rates, though 70.5 seems to family of drives: 25 - 50 usec. The WXl be an oft-used value. The OMTI 5510 defaults to a step rate of 70.5 usec, defaults to 15 usec, according to its which is too slow for this drive, and manual. The Centan 5027 controller has possibly too slow for its siblings as well a default step rate of 18 usec, thinks (See Figure 3). Mark Miyakawa of NCL America (Cen­ "I'm very impressed with the com­ Sea gate says that voice coil drives tan). There should be a way to change piler, editor, and debugger. I've tried typically have a narrow step rate win­ the default step rate for any controller, quite a few different compilers for the dow. Seagate's stepper motor drives do either through software or via jumpers PC and have given up on all of the in fact have much larger windows, typi­ on the board. others in favor of yours . .. I've gotten cally 5 - 200 usec (ST225). The step rate for the Western Digital to the point where I download C code The ST4026 OEM Manual says that WD 1002A WXl controller is change­ from a DEC ~/VMS system just to be able to compile it with the picky step rates between 25 and 50 usec and able only through the formatting flag set at 9. It finds lots of things above 3 msec are supported, but that routine in its BIOS ROM. Furthermore, VMS totally ignores . .. " lS, Oak Ridge, TN Figure 2 - Fractal Parameters The Eco~C88 c()mpilefjncludes: Mandelbrot Sets eAfuIl-featuredC c()mpil~rwithJ .mem­ Prnin Pmax Qmin Qmax ory m()dels( uP. to 1 m~gofcode ~nd data) plus most ANSlen~ancelJlents. -0.74877 -0.74162 0.1091 0.11625 • With()uta dotlbt, the ~sterror check .. -0.7454716 -0.7453868 0.1129605 0.1130453 ing you .. can get. We catch bugs the -0.74554433 -0.7454151 0.1129958 0.1130241 ot~ersmiss,makimtyoullluChlJl?t"e -2.25 0.75 -1.5 1.5 (shows whole set) p~oductive. ....•...... •...... •..•...... •..•...... -0.1992 -0.12954 1.0148 1. 06707 -0.95 -0.88333 0.23333 0.3 .. Cmoreisa full-featuredsourcec()de -0.75104 -0.7408 0.10511 0.11536 debugger, nofsollle stripped-down .....• -0.74591 -0.74448 0.11196 0.11339 versi?n ..• ·....•.••.• · .. · .•· ...... : -Robuststandard library with over 230 Julia Sets useful (no"fIuff') functions, many of

·· ..• ·.•..· •. at1d ... linkfrom wit~inC~~.< ..•• ··.... d ••.••..•••• ••••.. ii ·.~candmini~maKeutilitieslnc~tl~edJhat ... Figure 3 - Step Rate Ranges for Seagate ST4000 Series Drives simpli?~.s t~e.lJlo~t5omplex .~olllpiI~~. ·UsersmanualwithoverI50progralll· ST4026 ST4038 ST4051 ST4053 ST4096 examples· (notfragme~ts).toillustrate h()w. t()use t~eljbJ(lrYf~n~tions; Formatted Capacity (MS) 21.4 31.9 42.5 44.5 80.2 ; Fast compiles producing.faSt code ... Step Rate Range (usec) 25-50 10-70 10-70 3-70 3-70

"Step pulses issued between 50 usec one must choose to "dynamically" for­ and 3 msec may be lost." (Who needs mat the drive (specify parameters at the 'em?!) keyboard). This is not an option with Using the WXl controller, we low­ the early BIOS ROMs for this controller level and DOS-formatted three ST4026s. (or with the BIOS on the WXls shipped In each case the drive appeared to with Kaypro PCs). Either the Auto-Con­ operate normally until we attempted to fig BIOS (62-000043-xxx) or the Super copy over files. With each drive, 20 or BIOS (62-000094-xxx) mu~tbe present in fewer files went over fine, followed by socket U12 for this to be possible. "Seek Error Writing Drive C:". For dynamic formatting, leave all We were able to read endlessly from jumpers at jumper block SI OFF. Run the drives without errors but the formatter from DEBUG by entering: Reader Service Number 9 read/write operations produced read G=C800:5

86 MICRO CORNUCOPIA, #41, May-June 1988 . at DEBUG's"-" prompt. good value for the other members of the The formatter will ask for the drive ST4000 series, too, although one source ID (C:/D:), desired interleave (7 recom- (Konan controller manual) indicates that these drives should be dealt a step rate of a mere 10.5 usec (option 7). This makes sense, given the range for those drives. The numbers are entered all on one ",'.,'.. line, separated by spaces. For the ST4026, you should key in: in

U. 615 4 616 300 11 6

Which is to say: 615 cylinders, 4 heads, 1\ i II i)i /,iJ.+.,,T~~~'··!' :>., .'....> it),}) no reduced write current (think about i .... ·.'... .. ',' '.. ','.' ,\ · "',' ·,.,.,.i\ .

MICRO CORNUCOPIA, #41, May-June, 1988 87 It's SOG time again I The seventh annual SEMI-OFFICIAL GET TOGETHER (SOG) is com­ SOG ing to ~d, Oregon, July 14 through July 16, 1988. The amference will be held on Friday and Saturday at Central Oregon Community College, but we'll get thin~ started Thursday with river rafting and a barbeque. Let us know your plans so we can throw another burger on the barbie.

REGISTRATION Fill out and return the attached registration form indiating which VII activities you wish to attend. Enclose your full payment with the form. All teclmiatl sessions on Friday and Saturday are free, but to help defer the cost of the conference, we are asking for dona­ JuEg 14 -Jufg 16 tions in any amount

Check in at the Pind

People with display tables can set up their equipment in the Pinckney Center Thursday.

The dorms at Central Oregon Community College will be dosed for remodeling this year. We'll send out lodging pamphlets with the SOG information packets. Travel arrangements can be made through Cascades Travel, 5

THURSDAY RAFTING

• We start SOG VII off by offering two trips down the Deschutes River. You can choose between... • A 2 1/2 hour raft trip with 3 miles of class I-III rapids. Your price of $32 per person includes the Old Fashioned Barbe­ que. Check in at the Pinckney Center registration table before 11 a.m. Thursday for raft scheduling. OR. •• o An all day expedition down the lower Deschutes River Canyon approximately 1 1/2 hours from Bend. This trip includes class I-IV whitewater with 7 major rapids. A deli lunch and the Old Fashioned Bar­ beque are included in the $70 per person price. Busses leave Thursday morning at 7:30 a.m. sharp. Check in at the Pinckney Center registration table by 7:00 a.m. for a head count and bus loading. up the food. Prices for the barbeque are community colleges in their hometowns. INTRO TO DESKTOP SEMINAR." $10 for adults and $6 for children under • They will be offering 8088 based XT, • White water rafting not your thing? Then 12. Thursday Night Barbeque is included 80286 based AT, and 80386 kits at special try the day-long introduction to desktop in the price of all raft trips. SOG prices. As with last year, shipping publishing featuring those desktop ne'er­ the system home can be arranged. Con­ do-wells from Micro C, Carol Steffy, FRIDAY &SATURDAY tact Don Thompson or Cindy Johnson of Sandy Thompson, and David Thompson. • These two days will be filled with lectures, MicroSphere at 503-388-1194 for more in­ • You'll be introduced to scanning, discussions, workshops, and forums. formation and a registration form. Ventura'ing, PageMaking, computer We'll be discussing new C Compilers, graphics generation... the works. You'll C++, a new AI language, and more. For The SATURDAY NIGIIT BANQUET is an all­ break into groups for design competitions you hardware people PC Tech will be you-can-eat affair at the college. Price is $12 for and problem solving. Plus you'll get fed! there in force to talk about graphics and adults or Sl for children under 12 Included in the $65 price are lunch and extended memory boards. We'll continue the barbeque cookout. This seminar must with parallel processing and the amD CARE There will be a supervised be prepaid and will run from 9 a.m. to 5 transputer and delve into desktop publish­ playroom for the kids Friday and Saturday from p.m., Thursday, July 14. Check in at the ing, fractals and packet radio. 9-4. Pinckney Center registration desk SECOND ANNUAL BUILD YOUR OWN Thursday morning. For more informa­ SYSTEM DEADLINES All activites must be paid for by tion, contact Carol Steffy at ?03-382-8048. • Friday night, MicroSphere will be hosting July I, 1988. THE OLD FASlnONED BARBE QUE another ''Build Your Own Computer" • Will be held at Shevlin Park Thursday night at SOG. This event will be held at evening. Since Saga Foods did such a MicroSphere starting at 7 p.m. fine job of making sure we had plenty to • Several participants in last year's class are eat last year, they will again be cooking now teaching XT construction classes at

88 MICRO CORNUCOPIA, #41, May-June 1988 SOG REGISTRATION,1988

NUMBER EVENTS PRICE TOTAL

Thursday all day Raft trip & Old Fashioned Barbeque $70.00

Thursday 2 1/2 hour Raft trip & Old Fashioned Barbeque $32.00

Adult Thursday night Old Fashioned Barbeque only Adult $10.00 Child (Included in Raft trips) Child $6.00

Thursday Desktop Seminar $65.00 (Includes lunch and Barbeque) Adult $1200 Adult Saturday night SOG Banquet Child Child $7.00 Semi -Official SOG T-shirt $7.00 Adult sizes Small Medium Large Ex-large

Semi-Officia1 SOG T shirt $5.50 Youth sizes Small Medium Large

Donations o Check enclosed Register by July 1st TOTAL Number attending in your group __ ENCLOSED

Exp ______Signature ______Card No ______

Name ______

Company ______

Address ______

City ______State _____ Zip ______

MICRO CORNUCOPIA. P.O. BOX 223 • BEND, OR 97709 • 503-382-5060 Come join us and learn more about. .. C compilers and C tools Trilogy: A new AI language Advanced graphic processors Super fast ray tracing on the 34010 graphics processor Fractals Diagnostic software available for the XT and AT and how to use it Disk diagnostics Pseudo concurrancy using probablistic technique Numerical applications Desktop publishing All about SCSI Generic microprocessors Packet radio and much, much more ..... New Users Disks Fro ro Cornucopia

#MS49 PC-CALC and Extended DOS This 64 column X 256 row spreadsheet can import its data from any number of PC-File databases. Or you can treat it as a normal spreadsheet and enter data by #MS45 PC-Flle+ hand. Dive right into this database manager. The program is complete but this Context sensitive help screens will guide "evaluation copy-s" documentation you through the entire process. These new Micro C contains only portions of the manual. PC-File+ includes macro capability. Extended DOS (X D) extends the standard password access to foreign databases. Users Disks contain the DOS commands. At any time you can view and over 64.0000 records per database. famous Buttonware a menu of XD commands which Note: PC-File+ has on-screen help. You include-killing entire subdirectories. string collection. This is can get more complete documentation by search through multiple files. file attribute shareware and we registering with Buttonware. and time/date editing. and more. encourage you to #MS46 PC-Type+ #MS50 PC-Tickle and Button Games Another great Buttonware product. Organize your lifel Schedule events. keep register if you find the Macros. mail merge. and multiple file track of tasks. balance your checkbook. software useful. We editing capabilities make this text editor even follow your caloric input and output. compete favorably with commercial Includes its own mini-editor. editors. also encourage you to And. lest things should get too serious. we share copies of this Documentation exists in the form of finish the Buttonware Collection with two extensive help files along with more brief. adventure games. Become the main software with other PC context sensitive help screens. character in a South American Trek or a Castaway adventure. owners. #MS47 PC-Style and Dictionary Buttonware·s PC-Style analyzes your writing for readability. personal tone. and action. Find out if your sentences and words are too short or too long. PC-Style also reports the "grade-Ievel" of your writing. $6.00 PC-Type+ uses the dictionary on this disk To Order: (Each For U.S. Subscribers) for its spell-check function. Call (503) 382-5060 or #MS48 PC-Dial and PC-Graph 1-800-888-8087 Next in the line-up of Buttonware Mailing Address: products comes PC-Dial. This Micro Cornucopia J communications program supports P.O. Box 223 scripts and macros. has a built-in Bend. Oregon 9n09 ego mini-editor. and talks up to 9600 baud. Any database or report file created with PC-File can be graphed using PC-Graph. Prices: (each. postpaid) This program requires the Color Graphics $6.00 for U.S. Subscribers to Micro C o Adapter. $8.00 for non-subscribers & foreign

90 MICRO CORNUCOPIA, #41, May-June 1988 ORDERFORM

POSTAGE-PAID SELF-MAILER Tear out, fold, and staple both ends if check is enclosed.

THE MICRO TECHNICAL JOURNAL o YES, I WANT TO SUBSCRIBE! MICRO CORNUCOPIA The Great o NEW 0 RENEWAL C Issue 11 C Compilers ..... 6coItLaddeomp,'•• benehm.~ •• w , ••lur",II'IdDenelltecleode lor t,CcompUar. a: (IncludlngMlcrollOttCVISO w Ind8orla"""Vll.5., I u.s. CAN.lMEX. FOREIGN a: ~~i:~~'nA~imple ~8f 20 <{ Jack P\I,dum anowl you how 10 UM w ' •• tlil•••• prog'.md.'. I- 1 yr. D $18 D $26 D $36 C++. An Object OrientedC p.tIgr32 6 issues ::I:;:~ =::~.getll'nk'II"c.

Source Level Debugger 2 yrs. For Turbo C p.tIgr ~ EveryCneed•• cs.bugg«.H.,.·•• ',.. D $34 D $50 D $68 one lor Turbo wrlUln by 12 issues a.ryM,Uor PLUS: In-depth k)okl II: A I,,, new AII.ngUollgol,.g.... tnewdl...... mbl ... , 3 yrs. D $48 D $72 D $99 :uc:KII~=~~~ PCptI"IIeI)C,and 18 issues

DIS KS 0 MS DOS 5114" 0 MS DOS 3 Y:! " DISK o Other Specify Disk # and size TOTAL Save 24% Off D the newstand OTHER PRODUCTS OTHER price Back Issues, T-shirts ... specify size TOTALS D GRAND w TOTAL a: w I a: <{ w To Place Your Order Immediately I- o CHECK ENCLOSED U.s. funds drawn on a U.S. bank, please CALL: 1-800-888-8087 9-5, M-F, Pacific Time o VISA 0 MASTERCARD I I I I I-I I I I I-I I I 1-1...... 11...... 1 I / Expires Are you a current Micro C subscriber? 0 Yes LI No NAME ...... COMPANy ......

41 ADDRESS ...... , ...... , ...... t CiTy ...... , ...... STATE ...... ZiP ...... I •II D• •III : THE MICRO TECHNICAL JOURNAL

I MICRO CORNUCOPIA

liJ:tr11]3iI33i[f4[IJUr1iJ,] MAY/JUNE 1988 ISSUE NO. 41

Write in the reader service numbers NAME ______of any advertisers from whom you would like to receive free informa- COMPANY tion. ADDRESS ______

CITY ______

STATE ____~ZIP _____

FOLD HERE

NO POSTAGE NECESSARY I II II I IF MAILED INTHE UNITED STATES

BUSINESS REPLY MAIL FIRST CLASS PERMIT NO. 19 BEND, OR

POSTAGE WILL BE PAID BY ADDRESSEE

THE MICRO TECHNICAL JOURNAL MICRO CORNUCOPIA P.o. Box 223 Bend, OR 97709-0223

FOLD HERE

Diagnostic Issue • Symptoms and Solutions, Curing Your XT or AT • Theory of Operation for the XT • Drive Faults and Fixes Plus • 3-D Graphics Part II • More on Marketing Your Own Software • Laine Takes on OS-2

STAPLE TO CLOSE Fill in your back issues of Micro C today

ISSUE 114 (10/83) ISSUE #21 (12/84) ISSUE #26 (10/85) ISSUE #31 (8/86) ISSUE #36 (6/87) BBlI Installation Analos To Digital Interface Inside ZCPR3 RAM Resident PC Speedup Build A Midi Interface For Your PC The Perfect Terminal Installing Turbo Pascal §OG ~~gabytes On DSI-32 Practical Programming In Modula-2 Designing A Database, Part 2 Interface to Electronic Typewriter Low Intensity BBI Video Unblinking The PC's Blinkin' Cursor BBI Video Size Turbo Pascal, The Early Days Game Theory In PROLOG and C ~!~ke~P:sV?e:'v ~f ~~-DOS Vs 3.X Video Jitter Fix 80 pages ~s_6c;sr~ ~~~~bl~:i~~main 104 pages Digital To Analog Conversion, A Slicer Column Begins Graphics In Turbo Pascal Designer's View Kaypro Color Graphics Review 104 pages 96 pages ISSUE *22 (2/85) 48 pages ISSUE #32 (10/86) ~~~ond8~0~~le;~0~ ~:lth~-~TD Bus ISSUE #27 (12/85) Public Domain 32000: ISSUE #37 (9/87) ISSUE 115 (12/83) Reviews Of 256K RAM Expansion SOLD OUT Hardware and Software Desktop Publishing On A PC Screen Dump Listing In The Public Domain BeginS Writing A Printer Driver For MS-DOS Build Your Own Hi-Res GraphiCS Fixing Serial Ports 88 pages Recover A Directory By Scanner For $6.00, Part 1 ISSUE #28 (2/86) Reading & Writing Disk Sectors Designing A Database, Part 3 ~~Xm't1:~l~~~r~e ins Pascal Runoff Winners 96 pages Controlling AC Power From Your PC Upgrading Kaypro I~ to 4 ISSUE #23 (4/85) Rescuing Lost Text From Memory Expanded Memory On The PC/XTI AT Upgrading Kaypro 4 to 8 Automatic Disk Relogging Introduction To Modula-2 Un interruptible Power Supply For ISSUE #33 (12/86) 48 pages Interrupt Drive Serial Printer First Look At Amiga RAMdisks Low Cost EPROM Eraser Inside The PC C?r~~~i~~r ~~per Motors 96 pages Smart Video Controller 104 pages ISSUE 116 (2/84) Review: MlcroSphere RAM Disk Introduction To Fractals Xerox 820 Column Restarts Future Tense Begins The Secrets Of MS-DOS, From ISSUE #38 (11/87) BBI Double Density 86 pages ISSUE #29 (4/86) Boots To Devide Drivers Parallel Processing BBII 5"/8" Interface Fix Speeding Up Your XT Poking About In The System Laser Printers, Typesetters Kaypro ZCPR Patch Importing Systems From Taiwan With Turbo Pascal And Page Definition Languages Adding Joystick To Color Graphic! ISSUE *24 (6/85) Prototyping In C 96 pages Magic in the Real World Recovering Text From Memory C'ing Into Turbo Pascal C Interpreters Reviewed Build a Graphics Scanner 52 pages 8" Drives On the Kaypro Benchmarking The PCs for $6.00, Part 2 48 Lines On a BBI 104 pages ISSUE #34 (2/87) Writing a resident program 68000 Versus 80x86 Designing With The 80386 extractor in C. ISSUE 117 (4/84) Soldering: The First Steps Build A Simple Oscilloscope 96 pages 88 pages ISSUE #30 (6/86) A Cheap 68000 Operating System ~~JcUlf~~kizer PROLOG On The PC A concurrent Operating System Kaypro Morse Code Interface Expert Systems Recovering Directories And FATs ISSUE #39 (1/88) 68000-Based System Review ISSUE *25 (SiS5) Logic Programming 96 pages PC Graphics Why I Wrote A Debugger Building Your Own Logic Analyzer Inside CPIM 86 SOLD OUT Drawing the Mandelgrot and 56 pages The 32-Bit Super Chigs 256 K RAM For Your 83 Kaypro Julia Sets ~~~cl::'lling The 32 32 PC-DOS For Non-Clones Desktop Graphics 104 pages ISSUE #35 (4/87) Designing a PC Workstation Board ISSUE 118 (6/84) RS-232C: The Interface SOLD OUT Around The TMS 3410 Kaypro EPROM Programmer 104 pages 96 pages 110 Byte: A Primer ~:~~I~rOP!:~lfellnterface ISSUE #40 (3/88) Business COBOL The Great C Issue 60 pages 11 C Compilers BACK ISSUES OF MICRO C Writing a Simple Parser in C ISSUE 119 (8/84) C++, An Object Oriented C Adding Winchester To BBlI Source Level Debugger for Turbo C 6 MHz On the BBI 96 pages Bulletin Boards Track Buffering On Slicer 4 MHz For The 820-1 u.s., Canada & Mexico • 64 pages Issues #1-34 ...... $3.00 each ppd. ISSUE #20 (10/84) HSC 68000 Co-processor Issues #35 through current issue ...... $3.95 each ppd. DynaDisk For The BBlI Serial Printer On BBl Sans S10 Cheap & Dirty Talker For Kaypro Foreign (air mail) Extended 8" Single Density 72 pages Issues #1 through current issue ...... $7.00 each ppd. Advertisers Index Issue 41

Reader Page 07 CompuView ...... 47 12 LogitechInc ...... · 29 68 Programmer's Paradise 07 Service Number Lori and Nick's Enterprises .52 Project Data Systems 28 90 Dair Computer Systems .20 60 Scientific Software 80 72 AcquiredIntelligence .12 08 Datadesk Int'l ...... 01 17 Manx Software Systems .77 27 Serengeti Software . . 46 44 Amtech Computers .79 32 Digital Research Computers .81 42 McTek Systems .. · 65 Sharp's Inc ...... 71 38 Analogic Company .50 35 Merlin Publishers .64 19 Slicer Control!Computer 78 48 ASCII...... 35 33 E21 Computer. . . . 68 Micro Cornucopia 87,88,89 40 Star-K Software Systems 14 04 Austin Codeworks .53 09 Ecosoft Inc ...... 86 Micro Methods . . · 61 10 Emerald Microware .27 36 Microcomputer Systems .79 62 V Communications " . 18 05 Blaise Computing ...... 05 93 Erac Company .69 37 Microprocessors Unlmtd .64 01 Borland Int'l . . . . Back Cover 24 microSOLUTIONS .45 14 WindowOOS Associates 39 87 Brown Bag Software 61,71,81 •• Gimpel Software .15 02 Microsphere . " ... .02 39 Xenos oft ...... 68 53 C Store ...... 52 11 Halted Specialties .21 59 National Advancement . 80 15 Cascade Electronics .34 26 Harger I.N.T .44 70 Zortech, Inc. Inside Back Cover 31 CC Software .... .60 03 PC Tech . . Inside Front Cover 71 Complete Logic Systems ... 25 22 Integrand .87 20 Peacock Systems . . .. 25,60 ** Contact Advertiser Directly.

MICROCORNUCOPIA, #40, Mar-April, 1988 93 A Micro Ad is an inexpensive way to reach over 22,000 technical folks like yourself. To place a Micro Ad, just print out your message (make it short and sweet) and mail it to MICRO Micro C. We'll typeset your ad (no charge) and run it in the next available issus. You can also send camera-ready copy. Rates: $99 for 1 time, $267 for three times, $474 for 6 times (a best buy at only $79 per insertion). Full payment must accompany ad. Each ad space is 2 1/4 inches by ADS 1 3/4 inches.

WINDOWS • SPRITES • MULTIPLE SCREENS QUALITY SPEECH I/O PRODUCTS Digitized speech, synthetic text to speech, voice Periscope ARE EASY WITH recognition, music composing with voice, and more are available in hardware/software systems Debugging Systems for IBM OMNIVID - PC T.. from COVOX. IBM PC/XT/AT and compatibles, for the IBM - PC/Xl and comp atibles. Apple, Commodore, and Atari machines support­ Personal Computers ed. Easy programming for fun and education. Or BLAZING. FAST use to design your own products for this rapidly expanding technology. Prices starting at only FREE INFORMATION Compatible with any language. $39.95. Call or write the manufacturer direct for Offers support for multitasking. FREE product information package. 800/722-7006 CGA· Monochrome· Hercules Compatible. _Available March 1988 CD".. The ~ 1197 PEACHTREE ST. -=-. 69.95 I?\ ~e!~t PLAZA LEVEL Eugene, OR 97402 PERIS E ATLANTA, GA 30361 W Company, Inc. 404/875-8080 fii .. FLEX,SOFT (~~8~ta~e~~:~~~~ Ashland. KY 41101 (503) 342·1271 Reader Service Number 25 Reader Service Number 67 Reader Service Number 94

FUTURE86, THE LANGUAGE Cross Assemblers Variable level, extensible, rommable lan­ Universal Linker Librarian - Document revision history - Audit trails guage gives complete control. Including 80186/88. Simple syntax. Easy program- hosted 00: PCIMS DOS, micro VAX, - Branching and key word insertion - Utilities ming. Compact code. Easily optimized for VAX VMS, VAX UNiXIULTRIX speed or size. Interactive debugging facili­ ties. Library source available. Investigative Available for VAX, PDP-11 & MS-DOS. FUTURE86 ... world c1asss! Used in thou­ Targeting over 30 microprocessors To order or for more information, call 1-800-874-8501. sands of applications. Prices start at $349. OREGON SOFlWARE Development Associates Kinc 1520 S. Lyon, Santa Ana, CA 92705 6915 SW , Portland, OR 97219. . (215) 362-0968. 19 Jenkins Ave (714) 835-9512 e Lansdale. PA. 19446 I Reader Service Number 85 Reader Service Number 82

PAUL MACE SOFTWARE, INC. TurboGeometry Library PC C SHELL A faithful implementation of the MACE UTILITIES (Source &- Manual) Data recovery and dfsk optimization tools. Turbo Pascal 4.0/C/Mac, & Microsoft C. Berkeley Unix C Shell for MS-DOS. Eliminates hard disk risks .and optimizes hard Over ISO 2 & 3 dimensional routines • Full History Syntax disk performance! including: Intersections, Transforma­ • Looping Statements (while, foreach) $99.00 tions, Equations, Hidden Lines, Per- • Shell Variables and Arravs HTEST/HFORMAT spective. Curves, Areas, Volumes. Clip­ • Cursor Key Command Line Editor Advanced hard disk diagnostics. Delivers what ping, Planes, Matrices, Vectors, Distance. • Runs as default command processor the manufacturer promised! Poly Decomp. IBM PC & Comp., Mac • WORKS ON ANY MS-DOS $89.95 $99.95 + S&H. VisalMCI AE COMPUTER!! $50.00 400 Williamson Way, Ashland, OR 97520. DISK SOFTWARE, INC. Omega MicroConsulting (800) 523-0258 2116 E. Arapaho, No. 487 722 Rundell Street. Iowa City. IA 52240 ffi ~ Richardson, TX 75081 214/423-7288 (319) 338-6053 Reader Service Number 65 . Reader Service Number 80 Reader Service Number 77

DEVELOPERS, NOW AV AILABLE Instruction Manuals Sof-Tel Inc., in their goal to provide ATRON HARDWARE innovative Software Solutions, now has for your product ready for you two new IBM PC software DEBUGGER packages. Do you need Modem dialing and • Hardware breakpoints, source level Written in an informal style by interrupt C..omm port support? Get AUTO­ debugging. techies for real users. DIAL! User-definable script files allow use • Includes performance analysis software, Free quote. with many modems. Send $49.95 plus $3 4K hardware trace buffer. external break P&H. Also available. STAGE2-PC. the PC version of the mainframe macro processor switch. Rare Earth Services, Inc. STAGE2. Disk plus printed manual only • "AT Source Probe" has 1mb on board 3115 Willow Road NW $49.95 plus $3 P&H. (Florida residents add memory invisible to DOS. Roanoke, VA 24017 6% sales tax.) Currently retails for $2795. will sell for Soft-Tel Inc. $1,450.00 OBO 703-343-4565 P.O. Box 5116, Lighthouse Pt. FL 33074 Call Michael Crandell 805/969-6851 (305) 942-6671 Reader Service Number 73 Reader Service Number 92

94 MICRO CORNUCOPIA, #41, May-June 1988 CROSS ASSEMBLERS 68000 SOFTWARE P•• udoCode rei ••••• version 2 of its cross • K-OS ONE operating system assemblers. Assemblers for the 8048, 8051, uses MS-DOS disks· 8096,8085,Z80,6502,1802,6800,6805,6809, 68000, and 32000 microprocessor families are with source code ...... $50 available. Macros, Conditional Assembly, • K-OS ONE manual ...... $10 Include Files plus extensive expression hand­ • HT68K SBC w/K-OS ONE. $395 ling. Virtually no limit to program size. For IBM PC's and true compatibles with MS-DOS 2.0 or • Screen Editor Toolkit ...... $50 greater, and 256K memory. Complete with • HT-FORTH ...... $100 printed manual for $35.00. Each additional is • BASIC ...... $149 $20.00. (Michigan residents add 4% tax). Free newsletter & spec sheets Visa/MC. Order from distributor: Micro Kit HAWTHORNE TECHNOLOGY 6910 Patterson, Caledonia, MI 49316 1411 S.E. 31st Ave., Portland, OR 97214 616n91-9333 (503) 232-7332 Reader Service Number 75 Reader Service Number 34 8051 SIMULATOR , 'SCREEN MANAGER Before you code: Superb full function debugger MENU, WINDOW and DATA ENTRY Support The Idea Generato~ simulator supports all 8051 modes for the Professional Programmer1lnterfaces of interrupt, just like the real thing! to most languages, BASIC, C, FORTRAN, "Quickens and improves Full disassembler and many unique COBOL, PASCAL, ASSEMBLER. 100 Page problem solving."- InfoWorld features, ONLY $150.00 Manual. 30 day money back guarantee. CROSS ASSEMBLERS No Royalties. Usually $19~. For you, $145. from9 The West Chester Group Experience in Software, Inc. For Z80, 8080/8085,8048,8051 and P.O. Box 1304 8096 still $75.00 each! s7 West Chester. PA 19380 2039 Shattuck Ave. LEAR COM COMPANY VISA/Me (215)644-4206 Berkeley, CA 94704 415-644-0694 2440 KIPLING ST., SUITE 201 CALL FOR FREE DEMO LAKEWOOD, CO 80215 303/232-2226 CIRCLE 279 ON READER SERVICE CARD Reader Service Number 63 Reader Service Number 84 Reader Service Number 78 GRRPHICS TOOLKIT Want to Throw Out your U.P.S. COMPRTIBLE WITH PC/XT IRT RND NEW PS/2 LIMITED INTRODUCTORY Log Book? Now You Can! $59.95 OFFER (ROD 13 S/H) Here's what EASY·SHIP can do for you: • SUPPORTS NEW VGR GRRPHICS MODES Automatic U.P.S. Shipping to all of U.S & Canada. • 50+ FUNCTIONS ..! Fast, Easy Multiple-Shipments with All Options. • DRTR COMPRESSION RLGORITHM ..! U.P.S. Approved Shipping Labels & C.O.D. tags. • RLL SOURCE CODE INCLUDED (NO ROYRl TIES) ..! Access to your ASCII Customer Data File. • ROUTINES WRITTEN IN MICROSOFT RND RSSEMBLER ..! U.P.S. Approved Reports and Manifest Summary. • BUFFER & DISK SRVE/RESTORE ..! Approved Nationally by United Parcel SeTVic~. • PROGRRMMER SUPPORT PROVIDED ..! NO MORE MANUAL LOGGING! And more! II~II DEVTRONICS. INC • ~For all IBM PC, AT, OS/2 Systems. Only $365 + $3 S/II. 1571 HAIN STREET Stat Supply Company ATLANTIC BEACH. FLA. 52255 20214 Brondesbury, Katy, TX 77450 ORDERS ONLY. 1-800-332-4230 RMEX/COD (800) 666.4567 or (713) 492.1931 TECHNICrlL INQUIRIES. (904) 241-3281 Reader Service Number 86

CBASIC, CB80, CB86 USERS 16 Megabytes EMS and/or Conven your O>asic and O>asic compiler programs into C with MB861 MB86 suppons Access Manager, Display RAM DISK Extended Memory Manager, and allows your new C programs to use existing -Works on 8 or 16 bit bus CB86 data files. MB86 breaks CB86 file size and record S-100 -16 bit transfer on AT bus XT and AT number limits and enables network suppon. MB86 enhan­ -Single board design ces the O>asic language with new features as weD as fixing 2 Meg, Port I/O many old CB86 problems. Versions of MB86 are available -Includes RAM disk and Compatible for Microsoft C. Turbo C. Aztec C. and Micropon Unix. Call New, Warranteed extensive diagnostics or write for more information. We also carry a complete line -Quantity/OEM discounts of enhancements for CB86 and Pascal MT +. $725 Minnow Bear Computers S. Lugert P.O. Box 2233 Station A ~:s~~~::;ured. m~ ~I~ Champaign, IL 61820·8233 439 Peck Slip or call: Sold and Serviced by ~LJ~Gl(lJ (217) 344·1113 NY, NY 10272 718-622-0654 904 North 6th St. Lake City, MN 55041 (612) 345-4555 Reader Service Number 83 Reader Service Number 52 Reader Service Number 54

A Ventilation OPT-TECH SORT/MERGE System designed Extremely fast Sort/Merge/Select utility. to prolong the IIfeoflBM~ Run as an MS-DOS command or CALL PCPC/XT. as a subroutine. Supports most lan­ Coldblue fits guages and filetypes including Btrieve inlhe IBM and dBase. Unlimited filesizes, multiple enclosure reducing keys and much more! MS-DOS $149. operating XENIX $249. temperatures as much as 27°F increaSing airflow (702) 588-3737 across the card area. Opt-Tech Data Processing The one that really works! PO Box 33848, . TX 78265 $185. P.o. Box 678 - Zephyr Cove, NV 89448 800-531-5314 Dealers inquiries welcome. Reader Service Number 64 Reader Service Number 91

MICROCORNUCOPIA, #40, Mar-April, 1988 95 Machinery Of The Mind

neither necessary to model neurons, nor pos­ By Gary Entsminger In purest form, "Artificial Intelligence" re­ sible to capture the top level of the mind, sug­ 1912 Haussler Dr. searchers attempt to recreate human intelligence in gests a middle level where rules emerge. Davis, CA 95616 machines (or computers). This form seems to have On this level, where we solve anagrams and gotten lost in the commercialization of AI. At our the like, we aren't intentionally systematic. level (user, hobbyist), AI seems to mean "fancy According to Hofstadter, ''When you first programming," which sells better. read a Jumble in a newspaper, you play around, rearranging, regrouping, reshuffling, in complex ways that you have no control over. In ancy programming has little more to do fact, it feels as if you throw the letters up into with "better programming" than it has the air separately, and when they come down, to do with "Artificial Intelligence." Bet­ they have somehow magically 'glommed' Fter programming obviously comes from together in some English-like word! It's a mar­ better ideas and better ways of implementing velous feeling-and it's anything but cognitive, them. anything but conscious." According to George Johnson, in his well-re­ As a test of Micro C's intelligence, I sent searched history of AI, "Machinery Of The Larry Fogg Raphael Robinson's puzzle. He Mind" (available from Microsoft Press)- likes puzzles, and I had high hopes. Just fill in the blanks, I said- Artificial Intelligence is based on the assumption that the mind can be described as some kind of for­ In this sentence, the number of occurrences of 0 mal system manipulating symbols that stand for is -' of 1 is -' of 2 is -' of 3 is -' of 4 is _, of 5 things in the world. Thus it doesn't matter what the is -' of 6 is -' of 7 is -' of 8 is -' of 9 is _. brain is made of, or what it uses for tokens in the great game of thinking. Using an equivalent set of Feeling intelligent? If so, send us your tokens and rules, we can do thinking with a digital method and solution (in English or, even better, computer, just as we can play chess using cups, salt as machine intelligence, in a program). and pepper shakers, knives, forks, and spoons. Using Meanwhile, I forget the question. the right software, one system (the mind) can be For more information- mapped onto the other (the computer). • Johnson, George. Machinery Of The Mind. In this form, AI leads to interesting ideas A Tempus Book from Microsoft Press. about us, our minds, how we think. 1986. Again, from Johnson- • • • Ultimately, when all the details and rhetoric are stripped away, most debates on whether or not AI is possible come down to a standoff between the reduc­ tionists and the holists-those who believe that mind can be explained as the sum of its parts, and those who believe that in any such explanation something will always elude analysis.

Intuition eludes analysis. It can't be ex­ plained at low levels, in the firing of neurons and the like, or at high levels, in rules and facts. Douglas Hofstadter, believing that it's

96 MICRO CORNUCOPIA, #41, May-June 1988 Reader Service Number 70 Now solving scientific and engineering equations goes from agonizing to easy!

Eureka: The Solver Eureka'": The Solver and i Ie dit 01 ve onnands eport raph pt ions indou your PC can handle any J:rl j I. I'JIJ! problem you can hand Ii 1, :;.-'11 them-jnstantly. Just ( IJi, UI,f I ,I t) J'I I!! type in any linear or I I}: I 1)':' lj,) non-linear equation, r.):.q!.Jr"j. JI-h,!! I. I ,d:"f'U'J{ I' )"1 1)1 'h! nll]1 Y;1.;'i1'Wf1 select "Solve," and look 1) ( IJ I /1 IJ /'J'jl "M., 1M ~I./r J11111r1 at your answer. But 1~I:JJIJ d_ '\111 1""111 ;';~; ~\I-1HI1Hi1 that's not all, because J )",.IT"!"!jl 1 Ii, ',~ ~~~ "]',·j'JI11

Eureka can do a lot J I, I! T,,!);- ~~~~~

more. Like evaluate r 1/ r If ,J ~ . IJ I i ll "HI:::' "d , -" your solution and plot Thll,l'J[ J <:t1'Ii11 J, a graph. Or generate a complete report, sending the output to your -Hel? -Save -Load -ZOOM -Next -Beg Blk -End Blk -Size/noue screen, disk file or Eureka instantly solved this Physics equation by immediately calculating how much work is required W compress isobarically 2 grams of oxygen initially at STP W \12 it.s printer. original volum e, In Science. Engineerin g, Finance and any application in volving equa­ tions. Eureka gives you the right answer, right now You can check the ' equation itself or ask Easy a$ a Calculator . .. Eureka to continue Powerful as a Mainframe! searching iteratively for • Pull-down menus • Powerful built-in and a satisfactory solution. • Full-screen text editor user-defined math and Or, change the active • Context sensitive help financial functions variables or constants • On-screen calculator • Report generation com­ and search for an • Automatic 8087 math plete with plots and lists entirely different solu­ coprocessor support • Polynomial root finder tion. Using Eureka's • Inequality constraints windows, you can solve up to 20 equations at " Merely difficult problems Eureka solved virtually once. It's all done with instantaneously; the almost impossible took a few seconds . pull-down menus, full Stephen Randy Davis. PC Magazine " help screens and abso­ lutely no agony. And all for just $167. ~- - For the dealer nearest you ~:;O or to order call System Requirements: For the IBM PS/2" and the (800) 543-7543 IBMe and Compaq8 families of personal computers and all 100% compatibles. PC-DOS (MS-DOS) 2.0 BORLAND and laler. 384K INTERNATIONAL 60-Day Money-back Guarantee· Reader Service Number 1

' Cuslomer sa\l5lactlon IS 001 main concern. II within 60 days of purchase thIS prodUCI does nOl perform In accofdance with OUf ClauTlS. call OIJf customer SElIVICe department, arid we Will arranoe a refund.

All Borland products are t/ademalks or registered trademarks 01 Borland InIQmallOl'\8l, Ir.c: Other bfand and product names ale trademarks or regl Sierea Ir8Cle\'Mrks of thell' rsspect!W! holders. Copynghl ~' 987 Borland Inlern&hor'WIl. lnc:. 811119