Author Archives: Allen Huffman

About Allen Huffman

Co-founder of Sub-Etha Software.

Greetings from the Sub-Etha!

Don’t Panic!

You have been diverted.

Welcome to the new home of…

---------|---------|---------|---------|---------|---------|---------|---------|
       _______              __             _______             __
      / _____/\            / /\           / _____/\           / /\
     / /\____\/           / / /          / /\____\/  __      / / /     ______
    / /_/__    __  __    / /_/_   ___   / /_/     __/ /_    / /_/_    /___  /\
   /____  /\  / /\/ /\  / ___ /\ /__/\ / ___/\   /_  __/\  / __  /\  _\__/ / /
   \___/ / / / / / / / / /\/ / / \__\// /\__\/   \/ /\_\/ / /\/ / / / __  / /
 _____/ / / / /_/ / / / /_/ / /      / /_/__     / /_/   / / / / / / /_/ / /
/______/ / /_____/ / /_____/ /      /______/\   /___/\  /_/ /_/ / /_____/ /
\______\/  \_____\/  \_____\/       \______\/   \___\/  \_\/\_\/  \_____\/
 =======    ======    ======   ===   =======   ======    ======    ======
                                S O F T W A R E
                               Established 1990.

      "In Support of the CoCo and OS-9" ... and Perl, and Arduino, and...

---------|---------|---------|---------|---------|---------|---------|---------|

In 1990, Sub-Etha Software was formed in Lufkin, Texas. You can read all about it, if you are curious. Since then, much has changed. It’s hard to believe that was almost 25 years ago!

Although Sub-Etha hasn’t done much for years, for the past few months, I have been posting on my Apple site, www.appleause.com, about my exploits with the Arduino platform. I haven’t done this much recreational programming since my days using the Radio Shack Color Computer. This has made me decide to dust off my old software company, Sub-Etha Software, and set up this website. Although I have had the domain for many years, it was just a subsection of one of my personal sites… until tonight.

I have now migrated all my programming-related posts from the Appleause site over to this one. I think they will fit in better here, and it finally gave me an excuse to do something with this domain.

So here it is – the all-new Sub-Etha Software website. Here you will find historical information about the original Sub-Etha, which started back in 1990 to offer products for the Radio Shack Color Computer and Microware OS-9 operating system. There is even a page which will eventually document the items we made for the Interactive Media Systems MM/1 computer, which ran OS-9/68000 (“OSK”). I may even make a page covering some of the items we sold after I took a job with Microware and had to shut down Sub-Etha. (Hint: Sub-Etha SoftWEAR didn’t sell software…)

Around 2001, I learned a bit of Perl programing and created a few simple scripts which I made available free under the Sub-Etha Software name, so Perl gets a page here, too. And lastly, some of my recent development efforts on the Arduino and related devices like the Teensy 2.0. I may even through in some BASIC Stamp talk at some point if I ever dig out my old hardware.

But since Sub-Etha started with the CoCo, it remains with the CoCo. There will be discussions about new CoCo related projects, and a listing of some of CoCo websites I think all CoCoists should check out.

Stay tuned…

Part 3: Debouncing digital inputs.

See also: Part 1, Part 1b, Part 2, and Part 3.

It seems I completely forgot the story I started telling awhile ago. If you did, too, you can go back and read about how I got started with Arduino, along with a few more notes, and finally, the one where I started dissecting my first sketch which read inputs from a haunted house pressure mat and turned them in to serial signals some software could read.

Back in February, I was discussing a problem I noticed with my first Arduino project. When switches would connect, and generate the serial strings for on/off like I wanted, I would often see the data stutter, toggling back and forth quickly before resting at on or off. I recognized this problem from learning about how the TRS-80 Color Computer’s keyboard matrix worked, and I knew the solution would be to add some debounce code to my sketch.

There actually is a Debounce library available to the Arduino, but I chose to write my own since it was a good opportunity to learn. Plus, the Bounce library seemed to provide much more capability than I needed. You can find this library here:

http://playground.arduino.cc//Code/Bounce

It seems very easy to use, but instead, I chose to apply some of the information I read on another section of the Arduino site. My debounce code would look like this:

/* For I/O pin status and debounce. */
unsigned int pinStatus[DI_PIN_COUNT];    // Last set PIN mode.
unsigned long pinDebounce[DI_PIN_COUNT]; // Debounce time.
unsigned int debounceRate = DEBOUNCE_MS; // Debounce rate.

I would create arrays to hold the last known pin status, and a time value for that pin. The time value would be used to mark debounce time. The debounce rate variable would be used for how long the debounce should be.

First, notice I was using “unsigned int” for the pin status. On the Arduino, and int is a 16-bit value, and takes up 2-bytes of RAM. The pin count could easily be represented with byte variable instead, saving a byte for each instance. It’s not a big deal wasting a few bytes for a small sketch, but for big projects, every last byte can matter. SO, don’t code like that. Use a byte. Or if you are really in a crunch, remember that a byte is made up of eight bits, so one byte could actually be used to track the status of eight different pins. So, my original version would take 16 bytes of RAM to track eight pins, but I could have done that using only one byte. That’s quite a savings. I can discuss using bits in a future article.

Okay, so those were my variables. The actual code that did all the work looks like this. First, I defined the pins I would be using for the project:

/* TX/RX pins are needed to USB/serial. */
#define DI_PIN_START  2
#define DI_PIN_END    12
#define DI_PIN_COUNT  (DI_PIN_END-DI_PIN_START+1)

The different Arduinos and Teensys and such have different I/O pin numbers. I decided I would just use a range of pins, so I specify the starting pin and ending pin. In this example, I skipped pin 0 and 1 since those are used by the serail port. Pin 13 is connected to an LED I wanted to blink (letting me know the board was alive and processing), so I could use pins 2-12 and get eleven pins to wire up to the pressure mats in the haunted house.

Inside setup(), I did a loop through these pins to put them in INPUT mode (using the pull-up resistor so I didn’t need extra wiring), and to initialize my arrays. You will notice I have something commented out. Originally, I read the current state of all the pins so I could mark them as changing later. So, if a pressure mat was “on” when it started, it would do nothing until the mat was released. This sounded like a good idea, but it meant there would be no way for the software to know things needed to go “now” on power up, so instead I set the status to HIGH (meaning off), thus if a mat were depressed when the program started, it would immediately see that as a change to LOW and send out the serial data.

  // Initialize the pins and pinStatus array.
  for (int thisPin=0; thisPin < DI_PIN_COUNT; thisPin++ )
  {
    // Set pin to be digital input using pullup resistor.
    pinMode(thisPin+DI_PIN_START, INPUT_PULLUP);
    // Read and save the current pin status.
    pinStatus[thisPin] = HIGH; //digitalRead(thisPin+DI_PIN_START);
    // Clear debounce time.
    pinDebounce[thisPin] = 0;
  }

Inside the main loop(), I would once again loop through all the pins and check their status:

  // Loop through each Digital Input pin.
  for (int thisPin=0; thisPin < DI_PIN_COUNT; thisPin++ )
  {
    // Read the pin's current status.
    int status = digitalRead(thisPin+DI_PIN_START);

Next, I would compare the current status to the one stored in the array and see if it had changed. No need to do anything for a pin that reads HIGH if it previously read HIGH. We only care about changes in status, so someone standing on a pressure mat wouldn’t trigger it dozens of times before they stepped off.

    // In pin status has changed from our last toggle...
    if (status != pinStatus[thisPin])
    {

And now it gets fun. The pinDebounce[] array is used to hold a time value, or 0 if there is nothing going on with that pin. If it has a number in it, that means we are in the process of counting down a debounce value. If it is 0, we need to start a debounce counter. The way we do that is by looking at the current time using millis(), and adding the debounce time to it, and storing that. So if millis() is 1200 when a pressure mat is triggered, and we are using a debounce rate of 1 second (1000 millis), we would store 1200+1000=2200 in that variable:

      // Remember when it changed, starting debounce mode.
      // If not currently in debounce mode,
      if (pinDebounce[thisPin]==0)
      {
        // Set when we can accept this as valid (debounce is considered
        // done if the time gets to this point with the status still the same).
        pinDebounce[thisPin] = millis()+debounceRate;
      }

Next, we check the pin to see if it’s non-zero. If it is, it indicates this pin is in debounce mode, and we need to see if the current time in millis() is greater than the pin’s pinDebounce[] time that was set earlier. If it is, we have seen the status hold long enough to believe it is a real trigger, and emit either “on” or “off” messages depending on which way the pin just toggled:

      // Check to see if we are in debounce detect mode.
      if (pinDebounce[thisPin]>0)
      {
        // Yes we are. Have we delayed long enough yet?
        if ( (long)(millis()-pinDebounce[thisPin]) >= 0 )
        {
            // Yes, so consider it switched.
            // If pin is Active LOW,
            if (status==LOW)
            {
              // Emit UPPERCASE "On" character.
              Serial.println(char(65+thisPin));
            } else {
              // Emit lowercase "Off" character.
              Serial.println(char(97+thisPin));
              if (pinsOn>0) pinsOn--;
              if (pinsOn==0) digitalWrite(LED_PIN, LOW);
            }

Then we remember this new status, and reset the debounce counter for that pin back to zero.

            // Remember current (last set) status for this pin.
            pinStatus[thisPin] = status;
            // Reset debounce time (disable, not looking any more).
            pinDebounce[thisPin] = 0;
        } // End of if ( (long)(millis()-pinDebounce[thisPin]) >= 0 )

      } // End of if (pinDebounce[thisPin]>0)
    }
    else // No change? Flag no change.
    {
      // If we were debouncing, we are no longer debouncing.
      pinDebounce[thisPin] = 0;
    }
  } // End of for()

At the very end, we have a condition that is met only if the pin’s status has not changed since the last time.

Does this look correct to you? If the pin hasn’t changed, I am resetting the debounce back to 0. But what if the pin were in a debounce mode? Wouldn’t we want to keep counting? It looked weird to me as I put the code here, but it is correct. If the pin has not changed, we are not interested in debouncing. If the pin is HIGH, it just resets to zero over and over (useless), but if it changes from HIGH to LOW, we enter the code and start the debounce. Note that the pinStatus[] variable has not been updated yet, so it remains HIGH.

The next loop through, the status of the pin is read again. If it is still LOW, we enter the code again because it is still different than the last pinStatus[], which is still HIGH. We do more debounce checks. And this continues.

The reason the reset to 0 is correct is because of this. We are not comparing the status to the last time we read, but to the last time we considered it switched after a debounce. As we continue the example, at some point, the pin has held its status long enough to be considered debounced, and we toggle it and update pinStatus[] to now be LOW, and the debounce counter is reset.

Clear as mud? Because we have not really change the status, we keep setting it to 0. But as long as the current pin status is different than the previously saved pinStatus[], we will keep entering that loop and checking, never getting to the reset 0. In fact, the only time we get to the reset 0 if current pinStatus is the same as the last pinStatus[]. So, a switch not switching will just reset 0 all the time, but once the switch has changed, it will fall in to the code to check debounce and never touch the reset 0 code. This is what resets the debounce timer if the switch goes from ON to OFF (which should trigger, but not yet), then pops back to ON quickly… resetting the counter… Then if it pops to OFF again, it starts the counter fresh.

I hope that makes sense.

Here’s the full script. Remember, it was the first thing I ever wrote for the Arduino, and I have done more to it since then. You will also see I have a part that checks the serial input for “?” to be typed, then prints out the current pin status. A nice thing for debugging.

Hope this helps… The next version will add Analog inputs (for reading laser tag light sensors), and then this code morphs in to an Atari joystick converter.

Until then…

/*-----------------------------------------------------------------------------

Arduino Digital Input

Monitor digital inputs, then emit a serial character depending on the pin
status. The character will be uppercase for pin connected (N.O. button push)
and lowercase for pin disconnected (N.O. button released). It will begin with
"A" for the first I/O pin, "B" for the next, and so on. Currently, with pins
0 and 1 used for serial TX/RF, this leaves pins 2-12 available (10), with pin
13 reserved for blinking the onboard LED as a heartbeat "we are alive"
indicator.

This software was written to allow an Arduino act as a cheap input/trigger
interface to software such as VenueMagic. As I do not own a copy of this
software, I could only test it under the 15 day trial. There may be other
issues...

2012-10-09 0.0 allenh - Initial version.
2012-10-11 0.1 allenh - Updated debounce to work with timing rollover, via:
                        http://www.arduino.cc/playground/Code/TimingRollover
                        Fixed bug where last DI pin was not being used.

-----------------------------------------------------------------------------*/
//#include
#include

/* TX/RX pins are needed to USB/serial. */
#define DI_PIN_START  2
#define DI_PIN_END    12
#define DI_PIN_COUNT  (DI_PIN_END-DI_PIN_START+1)

#define LED_PIN 13
#define LEDBLINK_MS 1000
#define DEBOUNCE_MS 100 // 100ms (1/10th second)

/*---------------------------------------------------------------------------*/
/*
 * Some sanity checks to make sure the #defines are reasonable.
 */
#if (DI_PIN_END >= LED_PIN)
#error PIN CONFLICT: PIN END goes past LED pin.
#endif

#if (DI_PIN_START < 2)
#error PIN CONFLICT: PIN START covers 0-TX and 1-RX pins.
#endif

#if (DI_PIN_START > DI_PIN_END)
#error PIN CONFLICT: PIN START and END should be a range.
#endif
/*---------------------------------------------------------------------------*/

/* For I/O pin status and debounce. */
unsigned int  pinStatus[DI_PIN_COUNT];      // Last set PIN mode.
unsigned long pinDebounce[DI_PIN_COUNT];    // Debounce time.
unsigned int  debounceRate = DEBOUNCE_MS;   // Debounce rate.
unsigned long pinCounter[DI_PIN_COUNT];

/* For the blinking LED (heartbeat). */
unsigned int  ledStatus = LOW;             // Last set LED mode.
unsigned long ledBlinkTime = 0;            // LED blink time.
unsigned int  ledBlinkRate = LEDBLINK_MS;  // LED blink rate.

unsigned int pinsOn = 0;

/*---------------------------------------------------------------------------*/

void setup()
{
  // Just in case it was left on...
  wdt_disable();
  // Initialize watchdog timer for 2 seconds.
  wdt_enable(WDTO_4S);

  // Initialize the pins and pinStatus array.
  for (int thisPin=0; thisPin < DI_PIN_COUNT; thisPin++ )
  {
    // Set pin to be digital input using pullup resistor.
    pinMode(thisPin+DI_PIN_START, INPUT_PULLUP);
    // Read and save the current pin status.
    pinStatus[thisPin] = HIGH; //digitalRead(thisPin+DI_PIN_START);
    // Clear debounce time.
    pinDebounce[thisPin] = 0;

    pinCounter[thisPin] = 0;
  }

  // Set pin 13 to output, since it has an LED we can use.
  pinMode(LED_PIN, OUTPUT);

  // Initialize the serial port.
  Serial.begin(9600);

  // Docs say this isn't necessary for Uno.
  while(!Serial) {
    ;
  }

  // Emit some startup stuff to the serial port.
  Serial.println("ArduinoDI by Allen C. Huffman (alsplace@pobox.com)");
  Serial.print("Configured for: ");
  Serial.print(debounceRate);
  Serial.print("ms Debounce, ");
  Serial.print(DI_PIN_COUNT);
  Serial.print(" DI Pins (");
  Serial.print(DI_PIN_START);
  Serial.print("-");
  Serial.print(DI_PIN_END);
  Serial.println(").");
  Serial.println("(Nathaniel is a jerk.)");
}

/*---------------------------------------------------------------------------*/

void loop()
{
  // Tell the watchdog timer we are still alive.
  wdt_reset();

  // LED blinking heartbeat. Yes, we are alive.
  if ( (long)(millis()-ledBlinkTime) >= 0 )
  {
    // Toggle LED.
    if (ledStatus==LOW)  // If LED is LOW...
    {
      ledStatus = HIGH;  // ...make it HIGH.
    } else {
      ledStatus = LOW;   // ...else, make it LOW.
    }
    // Set LED pin status.
    if (pinsOn==0) digitalWrite(LED_PIN, ledStatus);
    // Reset "next time to toggle" time.
    ledBlinkTime = millis()+ledBlinkRate;
  }

  // Check for serial data.
  if (Serial.available() > 0) {
    // If data ready, read a byte.
    int incomingByte = Serial.read();
    // Parse the byte we read.
    switch(incomingByte)
    {
      case '?':
        showStatus();
        break;
      default:
        break;
    }
  }

  // Loop through each Digital Input pin.
  for (int thisPin=0; thisPin < DI_PIN_COUNT; thisPin++ )
  {
    // Read the pin's current status.
    int status = digitalRead(thisPin+DI_PIN_START);

    // In pin status has changed from our last toggle...
    if (status != pinStatus[thisPin])
    {
      // Remember when it changed, starting debounce mode.
      // If not currently in debounce mode,
      if (pinDebounce[thisPin]==0)
      {
        // Set when we can accept this as valid (debounce is considered
        // done if the time gets to this point with the status still the same).
        pinDebounce[thisPin] = millis()+debounceRate;
      }

      // Check to see if we are in debounce detect mode.
      if (pinDebounce[thisPin]>0)
      {
        // Yes we are. Have we delayed long enough yet?
        if ( (long)(millis()-pinDebounce[thisPin]) >= 0 )
        {
            // Yes, so consider it switched.
            // If pin is Active LOW,
            if (status==LOW)
            {
              // Emit UPPERCASE "On" character.
              Serial.println(char(65+thisPin));
              pinCounter[thisPin]++;
              pinsOn++;
              digitalWrite(LED_PIN, HIGH);
            } else {
              // Emit lowercase "Off" character.
              Serial.println(char(97+thisPin));
              if (pinsOn>0) pinsOn--;
              if (pinsOn==0) digitalWrite(LED_PIN, LOW);
            }
            // Remember current (last set) status for this pin.
            pinStatus[thisPin] = status;
            // Reset debounce time (disable, not looking any more).
            pinDebounce[thisPin] = 0;
        } // End of if ( (long)(millis()-pinDebounce[thisPin]) >= 0 )

      } // End of if (pinDebounce[thisPin]>0)
    }
    else // No change? Flag no change. if (status != pinStatus[thisPin])
    {
      // If we were debouncing, we are no longer debouncing.
      pinDebounce[thisPin] = 0;
    }
  } // End of for()
}

void showStatus()
{
  int status = 0;

  Serial.print("DI: ");

  for (int thisPin=0; thisPin < DI_PIN_COUNT; thisPin++ )
  {
    // Read the pin's current status.
    int status = digitalRead(thisPin+DI_PIN_START);
    Serial.print(thisPin+DI_PIN_START);
    Serial.print("=");
    Serial.print(digitalRead(thisPin+DI_PIN_START));
    Serial.print(" ");
  }
  Serial.println("");

  for (int thisPin=0; thisPin < DI_PIN_COUNT; thisPin++ )
  {
    Serial.print(thisPin+DI_PIN_START);
    Serial.print(":");
    Serial.print(pinCounter[thisPin]);
    Serial.print(" ");
  }
  Serial.println("");

  //Serial.print("millis() = ");
  //Serial.println(millis());
}
/*---------------------------------------------------------------------------*/
// End of file.

P.S. – Don’t mind my rude comment to Nathaniel in the status display. He’s the effects designer out at the Sleepy Hollow Haunted Scream Park I was doing this project for, and I only kid him because he’s such a great guy. He’s really not a jerk. Honest.

CoCo appears on TWiT

Curtis Boyle, a long time TRS-80 Color Computer developer, donated some Radio Shack CoCo stuff to Leo Laporte’s TWiT TV studio museum. (If you don’t know what that is, don’t worry. I would have no idea myself if it weren’t for working at a place that sold satellite TV systems back around 2002, where I watched him on a show at the defunct cable channel Tech TV.) Anyway, Curtis wrote a demo program that drew the TWiT logo and flashed colors, and it was shown on the live stream between recording some of their shows.

Screen shots follow. Good job, Curtis!

TRS-80 Color Computer items on Leo's desk.
TRS-80 Color Computer items on Leo’s desk.
Curtis Boyle's demo program, shown on TWiT between shows
Curtis Boyle’s demo program, shown on TWiT between shows

4/19/2013 Update: Curtis shared his source code on the CoCo mailing list today.


10 PALETTE 8,63:PALETTE 0,0:WIDTH40:CLS1
20 ON BRK GOTO 410
30 'TWIT logo CC3 program by L. Curtis Boyle
40 POKE65497,0:INPUT "<R>GB OR <C>OMPOSITE MONITOR (TV):";MN$
50 PALETTE 0,0:PALETTE 3,63
60 IF MN$<>"R" AND MN$<>"r" THEN 80
70 PALETTE 1,36:PALETTE 2,25:BC=0:GOTO 90
75 'Depending on your TV/Composite monitor settings, you may need to adjust these
80 PALETTE 1,8:PALETTE 2,31:BC=0
90 PALETTE 4,BC:HSCREEN2:HCLS4:POKE 65434,BC
100 HCIRCLE(70,96),70,2
110 HPAINT(70,96),2,2
130 HCIRCLE(70,96),56,0,1,.5,1
140 HCIRCLE(70,96),44,0,1,.51,.99
150 HCOLOR0:HLINE(15,92)-(125,104),PSET,BF
160 HPAINT(18,87),0,0
170 HLINE(50,70)-(62,134),PSET,BF
180 HLINE(78,96)-(90,134),PSET,BF
190 HCIRCLE(84,76),7,1:HPAINT(84,76),1,1
200 HCOLOR3:HPRINT(18,19),"Netcasts you love from"
210 HPRINT(21,20),"people you trust"
215 'Start of "TWiT"
220 HCOLOR3:HLINE(149,65)-(191,75),PSET,BF
230 HLINE(165,75)-(175,117),PSET,BF
240 HLINE(191,75)-(200,117),PSET:HLINE-(210,117),PSET
250 HLINE-(217,91),PSET:HLINE-(224,117),PSET:HLINE-(234,117),PSET
260 HLINE-(246,65),PSET:HLINE-(236,65),PSET:HLINE-(229,91),PSET:HLINE-(222,65),PSET
270 HLINE-(212,65),PSET:HLINE-(205,91),PSET:HLINE-(198,65),PSET:HLINE-(191,65),PSET
280 HPAINT(194,66),3,3
290 HLINE(254,75)-(264,117),PSET,BF:HCIRCLE(259,65),7,1:HPAINT(259,65),1,1
300 HLINE(272,65)-(314,75),PSET,BF:HLINE(288,75)-(298,117),PSET,BF
310 FORT=1 TO 4000:NEXT T
320 ST=1:EN=15
330 FOR TC=ST TO EN
340 IF INKEY$="" THEN 380
350 IF ST<>1 THEN 370
360 ST=BC:EN=BC:GOTO 330
370 ST=1:EN=15:GOTO330
380 PALETTE4,TC:POKE65434,TC:FORT=1TO100:NEXTT
390 NEXTTC:GOTO330
400 GOTO 400
410 POKE65496,0:END

A cheap way to get an Arduino on WiFi

Update 3/8/2014: There is an Arduino WiFi shield for around $40 now sold by Adafruit Industries (but you have to solder on the connectors). That shield costs about as much as the TP-Link router I mention in this article, and a $20 Ethernet shield. However, with clone Ethernet shields now around $9 from China, it’s still cheaper to hack something together. (Another advantage of the TP-Link device is you can have it set up to connect and publish the connection via Ethernet, and plug it in to anything that needs it — an Arduino, an OUYA, TiVo, etc.)

To test my Arduino Ethernet code, I needed a way to get my Arduino on my home network. Unfortunately, my router is somewhere else, and I was not able to run a long ethernet cable to it. I initially experimented with making my old MacBook act as a gateway using Apple’s Internet Sharing. I was going to have it share my home WiFi internet out the ethernet port, and hook that port up to the Arduino. Unfortunately, again, it seems there is some problem with the current version of Mac OS X and Internet Sharing and I was unable to get it to work. So, I turned to a free bit of software called Ice Floor which is a GUI front end for the Unix firewall running on Mac OS X. With a bit of Googling I was able to configure Ice Floor to let my Arduino hook to the MacBook, then reach out to the Internet.

I won’t be writing about that. It was easy, once I figured it out, but I spent all night trying.

What I really wanted was a way to get my Arduino on my home WiFi.

With Arduino ethernet interfaces being real cheap if your order from China, or slightly less cheap if your order from the USA, it puzzled me that WiFi shields were so much more. Well, if you don’t need everything to fit inside a small Arduino case, you can just get one of the cheap Ethernet shields and then use one of these things:

This $23 TP-LINK WR702N WiFi router is really teeny tiny (about 2″x2″ and .5″ tall), and comes with a short ethernet cable, USB cable, and USB power supply. It has several modes of operation, including the one you would expect — plugging up to an Ethernet jack and broadcasting it as a WiFi signal. But, it also has a Client mode, so you can plug it up via Ethernet to the Arduino and then use it as a WiFi card.

Configuration was a bit tricky because I didn’t know what I was doing, but basically, you plug it up to power (USB or power adapter), and configure it via your computer and an Ethernet cable. If your computer is already on a network that is 192.186.0.x (like mine was, from my home DSL router), you will need to disable that from your computer (turn off WiFi, or unplug the Ethernet cable). The instructions (on the website) tell you to change your computer’s IP address to 192.168.0.10, and then in your web browser you go to 192.168.0.254 (which is the router’s default IP address). Up loads an admin web page.

Type in the password (admin/admin), then click the easy setup button and select Client. It will then give you a screen where you can browse to the WiFi network you wish to join, and enter the password (if it’s a protected network) and encryption method used (again, if it’s a protected network).

Once you do that, the little box will reboot and then try to connect to that WiFi hotspot, and then get an IP address from it and link the Ethernet port to the WiFi… So, configure it, then unplug it from the computer and plug it to the Arduino and… your Arduino’s Ethernet code now talks out WiFi.

So, if you ever try to telnet in to my home Arduino, that is how the connection will be getting there.

Just passing information along. Hope it helps someone.

Telnet is pretty cool.

Now processing most of the Telnet protocol!
Now processing most of the Telnet protocol!

A few evenings ago, I noticed a bunch of garbage coming on from an Ethernet connection on the Arduino when a new connection was made to the example server code. This garbage turns out to be part of the Telnet protocol. There are various escape sequences (some of which are quite large) that flow across the connection, and must be handled else they pollute the data stream.

I began writing some code to do this, and like many tangents I get on, it has led me down quite the rabbit hole of discovery. My first stop was this very helpful web page that explained a bit about how Telnet works:

http://www.softpanorama.net/Net/Application_layer/telnet.shtml

I then proceeded to read the RFC documents about Telnet, and learn more details:

http://www.faqs.org/rfcs/rfc854.html

RFC 854 covers the Telnet protocol. This document is from 1983, which is the year I was writing my *ALL RAM* BBS system which I recently ported to the Arduino. There are other RFCs that cover specific aspects of Telnet, such as all the various Options that can be set.

Initially, I created something very simple that just “ate” all the Telnet escape codes. This is small code, and should be used on any Arduino sketch that expects someone to be able to Telnet in to the device. I will finish it and post it here, or as a sample on the Arduino webpage in the Playground area.

I soon learned there were even more codes than what I first learned, so I went and found more complete references:

http://www.tcpipguide.com/free/t_TelnetOptionsandOptionNegotiation-2.htm

Even after that, I still have a few others I can generate (from the PuTTY terminal program) and see but I haven’t found good documentation on them yet. (I just know it has an option in PuTTY to send special sequences, and I went through all of them to make sure I was handling them correctly.) I have learned quite a bit about Telnet in the past few days. It’s pretty neat.

So, I am now working on two things. One is a simple EthernetServer filter that will take care of the most simple bits of Telnet. I will make it so that can be compiled out, so it’s just a “eat all the Telnet escape sequences” thing, for sketches that are very tight on space.

The bigger project is the seTelnetServer. It’s a klunky name, but it follows that naming conventions I used back when I was coding 6809 assembly language utilities for the OS-9 operating system. seTelnetServer is going to be a more complete Telnet implementation, with (conditionally compiled out) the ability to emit all the protocol debug information on the console (for those curious). I am planning on supporting some of the basic features I see various Telnet clients try to set — line versus character mode, echo and things like that. It will have hooks in the code where you can modify it and handle more if you need to. For instance, do you want to do something with the BRK sequence? Or Suspend?

I am packaging this together in to a very simple-to-use server sketch that might be as easy to use as this:

void setup()
{
telnetInit(23); // Initialize, listening on port 23
}

void loop()
{
Serial.print("Waiting for connection:");
while(!done)
{
telnetInput(buffer, 80); // Read up to 80 characters.
// do stuff...
telnetPrint("Hello, user!");
}
}

The “telnetInput()” routine would take care of listening for a new connection, if there wasn’t one, and then read input from the user (handling Telnet protocol). If they disconnect, it would return a code that could be used to detect that and reset.

I have a rough version of this working. I even added the ability (with my Ethernet library fixes) for it to receive other connections while it is handling the first one and inform them that “The system is in use. Please try back later.” And, there is even an “offline” mode, so if the operator decides to log in via serial console, it will disable the Ethernet (again, giving those who connect a “System is offline” message) while the operator is using it.

Sounds like fun. And when I am done, I plan to end up writing some Telnet software for the CoCo as well (though that has already been done for the DriveWire project).

More to come…

Multiple source files in an Arduino project

The Arduino IDE does an amazing job of hiding all the technical details of what it’s doing. This allows the some of the easiest creation of programs I have seen since the days of BASIC. From the looks of many of the forum questions over at the main Arduino website, it seems there are certainly a bunch of new programmers doing just this.

As an experience embedded programmer, much of what the Arduino IDE does seems to be magic to me. How can I just type a function without a prototype? How does it know what libraries to include when I don’t specify them? How is this able to work at all?

Over the past week, I have learned a bit more about what is going on behind the scenes. Apparently, the IDE has a preprocessor that converts the Arduino “Sketch” in to C++ code, generating prototypes and such automatically. I have already ran in to one problem with this.

Many other things remain a mystery, but at least one more has been explained today. I was very curious how one could split up a larger project in to multiple files. As it turns out, the Arduino IDE makes this super simple… Just make a new tab in the existing project.

In the Arduino 1.0.4 (current released version) editor, I noticed a square icon with a down arrow in it on the right side of the window, under the magnifying glass “search” button. I had seen this before, with “New Tab” and other options in it. I had assumed this was so you could switch between multiple projects in the same window, but now I understand this is how you have multiple files in the same project. Just create a tab, and put your code in it.

So, if I have my setup() and loop() in the main tab, and create a second tab with doSomething(), I can then call doSomething() from setup() or loop(). More magic.

I will be splitting up my various code snippets in to separate files for easy including in future projects.

I post this because I expect maybe I am not the only “experienced embedded programmer” who doesn’t read the manual.

A real Arduino Telnet server?

  • 2014/03/16 Update: The source code to this is now on GitHub. Check the Arduino link at the top of each page of this site.
This sketch tries to process Telnet protocol mesages.
This sketch tries to process Telnet protocol mesages.

The example code for the Ethernet library has some things that try to act like Telnet servers, but really all they do is open up a port and listen for data. When someone connects with a Telnet client, that client will send Telnet protocol messages trying to negotiate the connection. The Arduino examples I have found posted around do not deal with this, which means whatever “garbage” comes in could have unexpected results if the program isn’t properly ignoring invalid data.

Tonight, I began working on a more complete Telnet server for the Arduino. I am sure many of them exist, but what better way to learn than to reinvent the wheel?

I am doing a “fuller” version that would support many of the Telnet protocol options, then a dumber one that would just get rid of the protocol from the stream and ignore pretty much everything.

And, I will wrap that with a simple to use bit of code for making connections without all the tedious setup.

Comment if this project is of interest, as I have several others I may work on first.

Arduino compiler problem with #ifdefs solved.

In C, “#ifdef” or “#if defined()” are used to hide or include portions of code only if certain conditions are met. For example, my recent *ALL RAM* BBS experiment contains code for using the SD card library as well as the Ethernet library. I used #ifdef around specific blocks of code so I could compile versions with or without either of those libraries. But all is not well in Arduino land. Consider this following, simple example:

#if defined(FOO)
byte mac[] = { 0x2A, 0xA0, 0xD8, 0xFC, 0x8B, 0xEE };
#endif

void setup()
{
Serial.begin(9600);
while(!Serial);
Serial.println("Test...");
}

void loop()
{
}

This is supposed to only include the “byte mac[] =” line if “FOO” is defined, such as with:

#define FOO

However, on the current Arduino IDE (1.0.4), this simple code will fail with:

ifdef.ino: In function ‘void setup()’:
ifdef:18: error: ‘Serial’ was not declared in this scope

What? Suddenly “Serial.println()” won’t work? Moving the byte declaration outside of the #if def make it work. Very weird.

I also found a similar example, where I tried to comment out a function that used SD library variable types:

void setup()
{
Serial.begin(9600);
while(!Serial);
Serial.println("Test...");
}

void loop()
{
}

#ifdef FOO
byte fileReadln(File myFile, char *buffer, byte count)
{
}
#endif

In this example, I did not want the fileReadln() function to be included unless I had defined FOO. But, compiling this produces:

ifdef:15: error: ‘File’ was not declared in this scope
ifdef:15: error: expected primary-expression before ‘char’
ifdef:15: error: expected primary-expression before ‘count’
ifdef:15: error: initializer expression list treated as compound expression

Unhelpful. And after wasting some time on this, I started a topic in the Arduino.cc forums to ask if others were experiencing the same thing. And they were. A helpful post from parajew pointed me to this site which helped explain the problem, and offered a workaround:

http://www.a-control.de/arduino-fehler/?lang=en

The pre-processor does some stuff behind the scenes, creating prototypes and including header files where needed, and it just does it wrong. The A-Control site figured out a simple workaround, which I trimmed a bit to just adding this at the top of my scripts:

// BOF preprocessor bug prevent - insert me on top of your arduino-code
// From: http://www.a-control.de/arduino-fehler/?lang=en
#if 1
__asm volatile ("nop");
#endif

…and now either of my examples will compile as intended. Thank you, parajew and A-Control! I can now move on to my next problem…

Hope it helps you, too.

Arduino Ethernet and multiple socket server connections

Greetings! If you are finding this writeup useful, please leave a comment. I originally shared these modifications in April 8, 2013. In February 2015, I went through them again using the current Arduino 1.6.0. They still work, but I did tweak the source code notes a bit to be clearer. – Allen

  • 2014/04/03: I just started using GitHub and found all the Arduino sources there, including this bug report which seems to discuss and address this issue. I will be reviewing it when I have time to see if those fixes take care of this bug.
  • 2014/04/08: This is, by far, the most viewed article on this site. I suppose I should do more posts about Arduino Ethernet.
  • 2013/04/09: I have done some more tweaks to the code listed in this article, and will try to update them when I have a chance. I will probably spin it off in to a whole new article on an easy “drop in” telnet server I am working on.
  • 2014/04/14: Fixed some HTML escape codes in the source code. (Thanks, Matt!)
  • 2014/04/16: You can now get an Ethernet shield shipped from the US for $11.49.
  • 2014/04/19: In the comments, Petr Stehlík pointed out that it doesn’t look like a check against incoming IP address is done, meaning that if any packet was received with the same port, it would just be accepted. I will need to investigate the rest of the code and see if it does that check. If not, you could blast a packet to an Arduino and as long as you match the port, it would accept it. That seems real bad, but should be very easy to fix, if needed.
  • 2015/02/15: I just checked these updates against the Arduino 1.6.0 release, and they still work. I am updating the notes on this page to note where the libraries folder is found on Mac OS X, and to clarify where one of the changes goes. I have zipped up my changed and places them here: EthernetMultiServer.zip This may allow a clean 1.6.0 install to “Import Library” and work, but I have not tested that yet. Also, Arduino forum user SurferTim has contributed another way to accomplish this without fixing the library. He has posted a Telnet example in the Playground that talks directly to the Wiznet 5100 chip to keep the incoming connections straight. Very clever (and similar to what I had to do in the library to track the remote ports and keep them separated). Cool
  • 2015/05/22: Similar to the SurferTim approach, a comment by Gene provides another standalone way to do this in code without having to modify the library. He includes a full example in his comment.

NOTE: The links and prices given below may be out of date. Since then. I discovered this seller (kbellenterprises) on e-Bay. They offer some low-cost Arduino clone items. They have always been responsive, and ship very fast. They currently have an UNO clone for $8.49, and a Wiznet 5100 Ethernet shield for $11.49.

The Arduino Ethernet shield (or the $17.99 workalike made by SainSmart) adds internet support to the Arduino. The limited memory of the Arduino does not have to run a full TCP/IP stack. Instead, the Ethernet shield uses a Wizpro chip that handles Ethernet, TCP, UDP and IP protocols. This particular chip, Wizpro W5100, supports four simultaneous connections. This means you could have an Arduino sketch that opens four different websites at the same time, or you could run a server that allows up to four simultaneous users to connect.

At least, you could if the Ethernet library worked right. The way it was designed (I call it a bug or at least an oversight), the existing library would only allow four incoming connections if each one was listening on a different port. For example, if you have port 23 set up to monitor incoming TELNET connections, and one user was connected, any other attempts to connect would be refused until the first connection was closed. I wanted to use the “up to four connections” part to still allow other users to connect, and then tell them “The system is busy. Go away.”

My first attempt to do this was to just create two server instances:

EthernetServer server1(23);
EthernetServer server2(23);

I then modified the WebServer example and trimmed everything out except what I wanted. My main addition was this second server instance, and a check for connections to it while processing the primary connection. It looks like this (see notes afterwards):


// MultiServer Demo

#include &lt;SPI.h&gt;
#include &lt;Ethernet.h&gt;

byte      mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 100);

EthernetServer server1(23);
EthernetServer server2(23);

void setup()
{
Serial.begin(9600);
while (!Serial);

// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server1.begin();
server2.begin();
Serial.print("nServer is listening at ");
Serial.println(Ethernet.localIP());
}

void loop()
{
EthernetClient client2;

// listen for incoming clients
EthernetClient client1 = server1.available();
if (client1) {
Serial.println("Client A connected.");
client1.println("Greetings, program!");

while(client1.available()&gt;0) client1.read(); // Gobble

// Loop while client is connected.
while (client1.connected())
{
client2 = server2.available();
if (client2.connected()) {
Serial.println("Client B connected. Getting rid of them...");
client2.println("nThe system is busy. Try back later.n");
delay(1);
client2.stop();
Serial.println("Client B disconnected.");
}
// Then handle the actual client.

// If data is available, just read it and write it back to the user.
if (client1.available())
{
char c = client1.read();
if (c&gt;0) Serial.write(c);
}
} // end of while... go back and do it again.

// If here, we must no longer be connected.
delay(1);
// close the connection:
client1.stop();
Serial.println("Client A disconnected.");
}
}

My plans was to wait for a connection. Once I had one, I would sit in a loop (as long as they remained connected) and check a second server instance to see if an additional connection attempt was made. If a second attempt was made, I’d send them a quick status message, then shut them down and go back to monitoring the main connection.

This should work, but doesn’t. It produced unexpected results:

Server Output:

Serving at 10.0.0.42
Server is listening at 10.0.0.42
Client 1 connected.
Client 2 connected. Getting rid of them…
Client 2 disconnected.
Client 1 disconnected.

Client (telent) Output:

alsmb:~ allenh$ telnet 10.0.0.42
Trying 10.0.0.42…
Connected to 10.0.0.42.
Escape character is ‘^]’.
Greetings, program!
The system is busy. Try back later.
Connection closed by foreign host.
alsmb:~ allenh$

It seemed the Ethernet could not distinguish between the two connections. I altered the server config to use different ports:

EthernetServer server1(23);
EthernetServer server2(2323);

Perhaps I could let 23 (telnet) be the main port, and 2323 be the status port. This provided much better results.

Server Output:

Server is listening at 10.0.0.42
Client 1 connected.
hello (I typed this from telnet)
(then, I made a second connection from another terminal, to port 2323)
Client 2 connected. Getting rid of them…
Client 2 disconnected.

On the first terminal, I was able to type “hello” and continue my connection, while the second terminal connected, then received the “Go away” message (after pressing some keys to generate some data to wake up the Ethernet code).

So it could work, but not with the same port.

Thanks to a forum post I found earlier explaining how to obtain the remote connection’s IP address, I was aware that the source code to the Ethernet libraries was part of the Arduino IDE, and that it was easy to make changes.

I decided to take a look and see if I could figure out how this Wiznet chip works.

Wiznet W5100

The Wiznet chip is an independent device. The Arduino sends it commands via the SPI bus (like sending byte commands to it) and then data can be read and written back, similarly to talking to a serial port. The Wiznet chip can be programmed to listen to up to four different socket connections, and then it takes care of the rest. The Ardunio basically says “Hey, Wiznet… Listen for connections on Port 23 of Socket 0” and then the Arduino code will query the Wiznet chip saying “Is anyone there?” and if so, handle accordingly.

Inside the Ethernet library code, I saw that it had an array to hold the ports the user was configuring. When you do EthernetServer begin(23), it puts a 23 in the first available slot then programs the Wiznet chip accordingly. These slots are how the Arduino knows which socket of the Wiznet to query. And that is where the problem is.

If you do “EthernetServer server1(23)” followed by “server1.being()”, slot 0 is set up with 23 and Wiznet socket 0 is programmed to listen for port 23 connections. If you then do “EthernetServer server2(23)” followed by “server2.begin()”, then slot 1 is set up with 23 and Wiznet socket 1 is programed to listen to port 23 connections. The Wiznet hardware is fine even with all four of it’s sockets listening to the same port. It tracks the actual connection internally.

But the Arduino code ONLY tracks the port number. So, if someone connects to the first socket 0 port, and is using it, then someone tries to connect to port 23 again, the Wiznet will hook them up to socket 1. The Arduino code makes a mistake, and when it checks for data, it grabs the first slot that matches the desired port. So, it keeps reading and writing data to slot 0 (socket 0) and never sees the second port 23 connection.

To resolve this, I made a few minor changes to the Arduino ethernet library code. First, I added secondary storage to track four remote ports (the ports used on the connecting client), and then added a bit of code that walked through all the available sockets trying to match up local server port number AND remote client port…

And it worked the first time, much to my amazement!

Here are my notes and modifications. There are a few things I did which I am not certain are correct, but they worked so I am sharing them. I will make a note of the parts I am unclear on.

Ethernet Library Modifications:


/--------------------------------------------------------------------------/
// 2015-02-15: Verified against Arduino 1.6.0.
//
// To fix the Ethernet library so it correctly allows multiple connections
// to the same port, the following files will need to be modified:
//
// libraries/Ethernet/src/Ethernet.h
// libraries/Ethernet/src/Ethernet.cpp
//
// libraries/Ethernet/src/EthernetClient.cpp
// libraries/Ethernet/src/EthernetClient.h
//
// libraries/Ethernet/src/EthernetServer.cpp
//
// On Mac OS X, these are embedded inside the Arduino.app package. Browse
// to that in the Finder, then right-click and select "Show Package
// Contents" and then you can go to:
//
// Contents/Resources/Java/libraries
//
// Is there a better way?
/*

Modify the following files:

1) Ethernet.h: The Ethernet object currently only tracks which Port the
socket is listening to. Add the following array to hold the remote Port.

Add this after static "uint16_t _server_port[MAX_SOCK_NUM];"

// ACH - added
static uint16_t _client_port[MAX_SOCK_NUM]; // ACH

2) Ethernet.cpp: Add the declaraction of the new array.

Add this after "uint16_t EthernetClass::_server_port[MAX_SOCK_NUM]"

// ACH - added
uint16_t EthernetClass::_client_port[MAX_SOCK_NUM] = { 0, 0, 0, 0 }; // ACH

3) EthernetClient.h: Add prototypes for the new functions, and declare a
new local variable that will track the destination port of this client.

Add this in the private: section

// ACH - added
uint16_t _dstport; // ACH

// ACH - added
uint8_t *getRemoteIP(uint8_t remoteIP[]); // ACH
uint16_t getRemotePort(); // ACH

4)  EthernetClient.cpp: When the Client object is stopped, it resets the
_server_port to zero. We should probably do this for the new _client_port.
In void EthernetClient::stop():

Add after this: EthernetClass::_server_port[_sock] = 0;

// ACH - added
EthernetClass::_client_port[_sock] = 0; // ACH

Add these two functions at the bottom of the file:

// ACH - added
uint8_t *EthernetClient::getRemoteIP(uint8_t remoteIP[]) // ACH
{
W5100.readSnDIPR(_sock, remoteIP);
return remoteIP;
}

uint16_t EthernetClient::getRemotePort() // ACH
{
return W5100.readSnDPORT(_sock);
}

5) EthernetServer.cpp: This code has to be modified so when it checks for
a connection, it checks both the Port (existing code) AND the remote
client's port (new code). If the connection has never been made, it will
initialize the remote port varaible correctly.

Add the following code to available()

EthernetClient EthernetServer::available()
{
accept();

for (int sock = 0; sock &lt; MAX_SOCK_NUM; sock++) {
EthernetClient client(sock);
if (EthernetClass::_server_port[sock] == _port &amp;&amp;
(client.status() == SnSR::ESTABLISHED ||
client.status() == SnSR::CLOSE_WAIT)) {

// ACH - added
// See if we have identified this one before
if (EthernetClass::_client_port[sock] == 0 ) {
client._dstport = client.getRemotePort();
EthernetClass::_client_port[sock] = client._dstport;
return client;
}
if (EthernetClass::_client_port[sock] != client._dstport) {
// Not us!
continue;
}
// ACH - end of additions
//if (client.available()) { // ACH - comment out
// XXX: don't always pick the lowest numbered socket.
return client;
//} // ACH - comment out
}
}

return EthernetClient(MAX_SOCK_NUM);
}

...and code to write():

size_t EthernetServer::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;

accept();

for (int sock = 0; sock &lt; MAX_SOCK_NUM; sock++) {
EthernetClient client(sock);

if (EthernetClass::_server_port[sock] == _port &amp;&amp;
// ACH - added
EthernetClass::_client_port[sock] == client._srcport &amp;&amp; // ACH
client.status() == SnSR::ESTABLISHED) {
n += client.write(buffer, size);
}
}

return n;
}

/
/--------------------------------------------------------------------------*/

During this research, I also found this part to be bothersome:


if (client.available()) {
// XXX: don't always pick the lowest numbered socket.
return client;
}

Unlike the EthernetClient.available(), the one for EthernetServer really shouldn’t be checking for data. It’s checking to see if a brand new connection has been made, then the code will be checking for data available elsewhere. For this to not just always return client would mean you would get a connection, but never see it until there is data. You couldn’t use this code to write a server that someone telnets to and it just spits out something (like a status or a time). It looks like it would force the remote user to send data first before the Arduino code even knows the connection is there.

I commented out the if so it always returns client, since it will bypass that if it finds no matching socket. It seems to work.

Bug?

Coming soon… Multi user BBS for Arduino!

1983 *ALL RAM* BBS ported to Arduino from BASIC

See also: Part 1Part 2, Part 3, and Part 4.

Updates:

  • 2/17/2017 – Removed link to my BBS since it hasn’t operated for years.
  • 6/24/2013 – Thanks to some comments, I fixed an issue around line 1010 where it was changing.
    aStr[ c]

    to aStr1. I am not sure why, but bracket-c-bracket must mean something to the code formatter I am using, which is unfortunate. Or maybe it’s just a bug. Which is also unfortunate. There was one other place in the code that had a bracket-c so I fixed it by adding a space after the bracket. Hopefully it works. Anyone know how to attach downloads to a WordPress posting?

  • 4/19/2013 – Sometimes, in the evening (or on weekends), I have my Arduino online. You can telnet to it: (no longer running)
  • 4/16/2013 – The WordPress editor just loves to mangle source code. I think I have finally gotten it all cleaned up. The version posted below is the latest version, with some bug fixes and other stuff cleaned up. Unlike the original posting, this one does not have Ethernet support. I have been working on a Telnet Server, and have been using the BBS to test it. You will see stuff #ifdef’d out below that makes use of the new Telnet functions. As soon as I have it polished, I will post it, too (or send it to you if you want to see the work-in-progress).
  • 7/1/2022 – Cleanup on aisle three…

Following up with part 1, part 2, part 3 and part 4, here is the source code. Remember, this is awful C. It is a line-by-line translation of BASIC to Arduino.

As I finish this experiment, I will continue to report the source code here to keep it in sync.

Source code last updated: 2/14/2015

See latest on my GitHub: GitHub – allenhuffman/ALLRAMBBS: 1983 cassette BBS ported from BASIC ;-)

// BOF preprocessor bug prevent - insert me on top of your arduino-code
#if 1
__asm volatile ("nop");
#endif
/*-----------------------------------------------------------------------------
 
 *ALL RAM* BBS for Arduino
 by Allen C. Huffman (alsplace@pobox.com / www.appleause.com)
 
 This is an experiment to see how easy it is to translate Microsoft BASIC to
 Arduino C. The translated C code is incredibly ugly and will be disturbing
 to most modern programmers. It was done just to see if it could be done, and
 what better thing to translate than a program that was also originally done
 just to see if it could be done -- a cassette based BBS package from 1983!
 
 About the *ALL RAM* BBS:
 
 The *ALL RAM* BBS System was writtin in 1983 for the Radio Shack TRS-80
 Color Computer ("CoCo"). At this time, existing BBS packages for the CoCo
 required "2-4 disk drives" to operate, so *ALL RAM* was created to prove
 a BBS could run from a cassette-based computer. Instead of using floppy
 disks to store the userlog and message base, they were contained entirely
 in RAM. The in-memory databases could be saved to cassette tape and
 reloaded later.
 
 The original BASIC source code is included in comments, followed by a very
 literal line-by-line translation to Arduino C. Remember, it's not a rewrite
 in C -- it's BASIC code done in C.
 
 Be warned. There be "gotos" ahead!
 
 References about memory saving:
 
 http://www.controllerprojects.com/2011/05/23/saving-ram-space-on-arduino-when-you-do-a-serial-printstring-in-quotes/
 http://www.adafruit.com/blog/2008/04/17/free-up-some-arduino-sram/
 
 2013-04-02 0.0 allenh - Initial version with working userlog.
 2013-04-03 1.0 allenh - Message base working. Core system fully functional.
 Preliminary support for Arduino Ethernet added.
 2013-04-04 1.1 allenh - SD card support for loading/saving.
 2013-04-05 1.2 allenh - Ethernet (telnet) support.
 2013-04-06 1.3 allenh - Cleanup for posting to www.appleause.com
 2013-04-09 1.4 allenh - Fixed a bug with INPUT_SIZE and input.
 2013-04-12 1.5 allenh - Integration with new Telnet server code, misc fixes.
 2015-02-14 1.6 allenh - Adding some "const" to make it build with 1.6.0.
 -----------------------------------------------------------------------------*/
#include <avr/pgmspace.h>

#define VERSION "1.6"

// To enable SD card support, define the PIN used by SD.begin(x)
//#define SD_PIN        4

// To enable Ethernet support, defined the PORT used by EthernetServer(PORT)
//#define ENET_PORT     23

// NOTE: On smaller Arduinos (UNO), there is not enough Flash or RAM to have
// both SD and Ethernet support at the same time.

#if defined(SD_PIN)
#include <SD.h>
#endif

#if defined(ENET_PORT)
#include <SPI.h>
#include <Ethernet.h>

extern EthernetClient client;

// Prototypes...
byte telnetRead(EthernetClient client);
byte telnetInput(EthernetClient client, char *cmdLine, byte len);
#endif

// And so it begins.
void setup()
{
  Serial.begin(9600);

  while(!Serial);

  showHeader();

#if defined(ENET_PORT)
  telnetInit();
#endif

  showConfig();

  // Scroll off any leftover console output.
  //for(int i=0; i<24; i++) print();
}

// We don't really have anything loop worthy for this program, so we'll
// just have some fun and pretend like we are starting up the CoCo each
// time through.
void loop()
{
  showCoCoHeader(); // Just for fun...

  allram();

  print();
  print(F("BREAK IN 520"));
  print(F("OK"));

  delay(5000);
}

// Show program header.
void showHeader()
{
  // Emit some startup stuff to the serial port.
  print(F("\n"
    "*ALL RAM* BBS for Arduino "VERSION" - 30 year anniversary edition!\n"
    "Copyright (C) 1983 by Allen C. Huffman\n"
    "Ported from TRS-80 Color Computer Extended Color BASIC.\n"
    "Build Date: "__DATE__" "__TIME__"\n"));
}

/*---------------------------------------------------------------------------*/
// In BASIC, strings are dynamic. For C, we have to pre-allocate buffers for
// the strings.
#define INPUT_SIZE  32  // 64. For aStr, etc.

#define MAX_USERS   3   // NM$(200) Userlog size. (0-200, 0 is Sysop)
#define NAME_SIZE   12   // 20. Username size (nmStr)
#define PSWD_SIZE   8   // 8. Password size (psStr & pwStr) 
#define ULOG_SIZE   (NAME_SIZE+1+PSWD_SIZE+1+1)

// To avoid hard coding some values, we define these here, too. Each message
// is made up of lines, and the first line will contain the From, To, and
// Subject separated by a character. So, while the original BASIC version
// hard coded this, we will calculate it, letting the subject be as large
// as whatever is left over (plus room for separaters and NULL at the end).
#define FR_SIZE     NAME_SIZE                      // From
#define TO_SIZE     NAME_SIZE                      // To
#define SB_SIZE     (INPUT_SIZE-FR_SIZE-1-TO_SIZE) // "From\To\Subj"

// The original BASIC version was hard-coded to hold 20 messages of 11 lines
// each (the first line was used for From/To/Subject). The Arduino has far
// less RAM, so these have been made #defines so they can be changed.
#define MAX_MSGS    3   // 19  (0-19, 20 messages)
#define MAX_LINE    2   // 10  (0-10, 11 lines)

// Rough estimate of how many bytes these items will take up.
#define ULOG_MEM    ((MAX_USERS+1)*(ULOG_SIZE))
#define MBASE_MEM   ((MAX_MSGS+1)*MAX_LINE*INPUT_SIZE)

// Validate the settings before compiling.
#if (FR_SIZE+1+TO_SIZE+SB_SIZE > INPUT_SIZE)
#error INPUT_SIZE too small to hold "From\To\Sub".
#endif

/*---------------------------------------------------------------------------*/

//0 REM *ALL RAM* BBS System 1.0
//1 REM   Shareware / (C) 1983
//2 REM     By Allen Huffman
//3 REM  110 Champions Dr, #811
//4 REM     Lufkin, TX 75901
//5 CLS:FORA=0TO8:READA$:POKE1024+A,VAL("&H"+A$):NEXTA:EXEC1024:DATAC6,1,96,BC,1F,2,7E,96,A3
//10 CLEAR21000:DIMNM$(200),MS$(19,10),A$,F$,S$,T$,BR$,CL$,NM$,PS$,PW$,A,B,C,CL,LN,LV,MS,NM,KY,UC

// All variables in BASIC are global, so we are declaring them outside the
// functions to make them global in C as well. Arrays in BASIC are "0 to X",
// and in C they are "0 to X-1", so we add one to them in C to get the same
// number of elements.
char nmArray[MAX_USERS+1][ULOG_SIZE];             // NM$(200)
char msArray[MAX_MSGS+1][MAX_LINE+1][INPUT_SIZE+1];// MS$(19,10) 1.4
char aStr[INPUT_SIZE+1];                          // A$ 1.4
char fStr[FR_SIZE];                               // F$ - From
char sStr[SB_SIZE];                               // S$ - Subj
char tStr[TO_SIZE];                               // T$ - To
char nmStr[NAME_SIZE];                            // NM$ - Name
char psStr[PSWD_SIZE];                            // PS$ - Pswd
char pwStr[PSWD_SIZE];                            // PW$ - Pswd

// To save RAM, these two strings will exist in Flash memory. It will
// require a bit of work later to use them (__FlashStringHelper*).
const char PROGMEM brStr[] PROGMEM = "*==============*==============*"; // BR$ - border
const char PROGMEM clStr[] PROGMEM = "\x0c\x0e";                        // CL$ - clear

int a, b, c, cl, ln, lv, ms, nm, ky, uc;
// A, B, C - misc.
// CL - Calls
// LN - Line Number
// LV - Level
// MS - Messages
// NM - Names (users)
// KY - Keys (commands entered)
// UC - Uppercase input (1=Yes, 0=No)

void allram()
{
  // HACK - create adefault Sysop account.
  nm = 0;
  strncpy_P(nmArray[0], PSTR("SYSOP\\TEST9"), ULOG_SIZE);

  cls(); // From line 5  

  //15 CL$=CHR$(12)+CHR$(14):BR$="*==============*==============*":GOSUB555
  //char cl[] = "\0xC\0xE";
  //char br[] = "*==============*==============*";
  gosub555();

//20 CLS:PRINTTAB(6)"*ALL RAM* BBS SYSTEM":PRINT"USERS:"NM,"CALLS:"CL:PRINTTAB(5)"SYSTEM AWAITING CALLER";:go:SOUND200,10
line20:
nmStr[0] = 0; // reset user.
  cls();
  printTab(6);
  print(F("*ALL RAM* BBS SYSTEM"));
  printSemi(F("USERS:"));
  printSemi(nm);
  printComma();
  printSemi(F("CALLS:"));
  print(cl);
  printTab(5);
  printSemi(F("SYSTEM AWAITING CALLER"));
  //gosub1005();
  if (gosub1005()==255) goto line20;
  sound(200,10);

  //25 A$="Welcome To *ALL RAM* BBS!":GOSUB1055:KY=0:CL=CL+1
  strncpy_P(aStr, PSTR("Welcome To *ALL RAM* BBS!"), INPUT_SIZE);
  gosub1055();
  ky = 0;
  cl = cl + 1;

  showLoginMessage();

  //30 PRINT:PRINT"Password or 'NEW' :";:UC=1:GOSUB1005:PS$=A$:IFA$=""ORA$="NEW"THEN55ELSEPRINT"Checking: ";:A=0
line30:
  print();
  printSemi(F("Password or 'NEW' :"));
  uc = 1;
  //gosub1005();
  if (gosub1005()==255) goto line20;
  strncpy(psStr, aStr, PSWD_SIZE);
  if (aStr[0]=='\0' || strcmp(aStr, "NEW")==0)
  {
    goto line55;
  }
  else
  {
    printSemi(F("Checking: "));
    a = 0;
  }

line35:
  //35 A$=NM$(A):B=INSTR(A$,"\"):NM$=LEFT$(A$,B-1):PW$=MID$(A$,B+1,LEN(A$)-B-1):LV=VAL(RIGHT$(A$,1)):IFPW$=PS$THEN45ELSEA=A+1:IFA<=NM THEN35
  strncpy(aStr, nmArray[a], ULOG_SIZE);
  b = instr(aStr, "\\");
  strncpy(nmStr, aStr, b-1);
  nmStr[b-1] = '\0';  
  strncpy(pwStr, &aStr[b], strlen(aStr)-b-1);
  pwStr[strlen(aStr)-b-1] = '\0';
  lv = atoi(&aStr[strlen(aStr)-1]);
  if (strncmp(pwStr, psStr, PSWD_SIZE)==0)
  {
    goto line45;
  }
  else
  {
    a = a + 1;
    if (a<=nm) goto line35;
  }

line40: // for empty userlog bug
  //40 PRINT"*INVALID*":KY=KY+1:IFKY<3THEN30ELSE215
  print(F("*INVALID*"));
  ky = ky + 1;
  if (ky<3) goto line30;
  goto line215;

line45:
  //45 PRINT"*ACCEPTED*":PRINTBR$:PRINT"On-Line: "NM$:PRINT"Access :"LV:PRINT"Caller :"CL:KY=0:GOTO115
  print(F("*ACCEPTED*"));
  print((__FlashStringHelper*)brStr);
  printSemi(F("On-Line: "));
  print(nmStr);
  printSemi(F("Access :"));
  print(lv);
  printSemi(F("Caller :"));
  print(cl);
  ky = 0;
  goto line115;

  //50 'New User
line55:
  //55 A$="Password Application Form":GOSUB1055
  strncpy_P(aStr, PSTR("Password Application Form"), INPUT_SIZE);
  gosub1055();

  //60 IFNM=200THENPRINT"Sorry, the userlog is full now.":GOTO215ELSEPRINT"Name=20 chars, Password=8 chars"
  if (nm==MAX_USERS)
  {
    print(F("Sorry, the userlog is full now."));
    goto line215;
  }
  else
  {
    printSemi(F("Name="));
    printNumSemi(NAME_SIZE);
    printSemi(F(" chars, Password="));
    printNumSemi(PSWD_SIZE); 
    printSemi(F(" chars"));
  }

line65:
  //65 PRINT:PRINT"Full Name :";:UC=1:GOSUB1005:NM$=A$:IFA$=""ORLEN(A$)>20THEN30
  print();
  printSemi(F("Full Name :"));
  uc = 1;
  //gosub1005();
  if (gosub1005()==255) goto line20;
  strncpy(nmStr, aStr, NAME_SIZE);
  if (aStr[0]=='\0' || strlen(aStr)>20) goto line30;

  //70 PRINT"Password  :";:UC=1:GOSUB1005:PW$=A$:IFA$=""ORLEN(A$)>8THEN30
  printSemi(F("Password  :"));
  uc = 1;
  //gosub1005();
  if (gosub1005()==255) goto line20;
  strncpy(pwStr, aStr, PSWD_SIZE);
  if (aStr[0]=='\0' || strlen(aStr)>8) goto line30;

  //75 PRINT:PRINT"Name :"NM$:PRINT"Pswd :"PW$:PRINT"Is this correct? ";:UC=1:GOSUB1005:IFLEFT$(A$,1)="Y"THEN80ELSE65
  print();
  printSemi(F("Name :"));
  print(nmStr);
  printSemi(F("Pswd :"));
  print(pwStr);
  printSemi(F("Is this correct? "));
  uc = 1;
  //gosub1005();
  if (gosub1005()==255) goto line20;
  if (aStr[0]=='Y')
  {
    goto line80;
  }
  else
  {
    goto line65;
  }

line80:
  //80 NM=NM+1:NM$(NM)=NM$+"\"+PW$+"0":LV=0:KY=0
  nm = nm + 1;
  strncpy(nmArray[nm], nmStr, NAME_SIZE);
  strcat_P(nmArray[nm], PSTR("\\"));
  strncat(nmArray[nm], pwStr, PSWD_SIZE);
  //strcat_P(nmArray[nm], PSTR("0"));
  strcat_P(nmArray[nm], PSTR("1")); // AUTO VALIDATED
  //lv = 0;
  lv = 1;
  ky = 0;
  //85 PRINT"Your password will be validated as soon as time permits.  Press":PRINT"[ENTER] to continue :";:GOSUB1005
  print(F("Your password will be validated as soon as time permits.  Press"));
  printSemi(F("[ENTER] to continue :"));
  //gosub1005();
  if (gosub1005()==255) goto line20;

  //100 'Main Menu
line105:
  //105 A$="*ALL RAM* BBS Master Menu":GOSUB1055
  strncpy_P(aStr, PSTR("*ALL RAM* BBS Master Menu"), INPUT_SIZE);
  gosub1055();

  //110 PRINT"C-all Sysop","P-ost Msg":PRINT"G-oodbye","R-ead Msg":PRINT"U-serlog","S-can Titles"
  printSemi(F("C-all Sysop"));
  printComma();
  print(F("P-ost Msg"));
  printSemi(F("G-oodbye"));
  printComma();
  print(F("R-ead Msg"));
  printSemi(F("U-serlog"));
  printComma();
  print(F("S-can Titles"));

line115:
  //115 PRINTBR$
  print((__FlashStringHelper*)brStr);

line120:
  //120 KY=KY+1:IFKY>200THENPRINT"Sorry, your time on-line is up.":GOTO210ELSEIFKY>180THENPRINT"Please complete your call soon."
  ky = ky + 1;
  if (ky>200)
  {
    print(F("Sorry, your time on-line is up."));
    goto line210;
  }
  else if (ky>180)
  {
    print(F("Please complete your call soon."));
  }

line125:
  showFreeRam();
  //125 PRINTTAB(7)"?=Menu/Command :";:UC=1:GOSUB1005:A$=LEFT$(A$,1)
  printTab(7);
  printSemi(F("?=Menu/Command :"));
  uc = 1;
  //gosub1005();
  if (gosub1005()==255) goto line20;
  aStr[1] = '\0';

line130:
  //130 LN=INSTR("?CGRSPU%",A$):IFLN=0THENPRINT"*Invalid Command*":GOTO120
  ln = instr("?CGRSPU%", aStr);
  if (ln==0)
  {
    print(F("*Invalid Command*"));
    goto line120;
  }

  //135 IFLV<1ANDLN>5THENPRINT" Sorry, you are not validated.":GOTO125
  if (lv<1 && ln>5)
  {
    print(F(" Sorry, you are not validated."));
    goto line125;
  }

  //140 ONLN GOTO105,155,205,405,455,305,255,505
  if (ln==1) goto line105;
  if (ln==2) goto line155;
  if (ln==3) goto line205;
  if (ln==4) goto line405;
  if (ln==5) goto line455;
  if (ln==6) goto line305;
  if (ln==7) goto line255;
  if (ln==8) goto line505;

  //150 'Call Sysop
line155:
  //155 A$="Calling the Sysop":GOSUB1055:A=0
  strncpy_P(aStr, PSTR("Calling the Sysop"), INPUT_SIZE);
  gosub1055();
  a = 0;

  //165 PRINT" BEEP!";:SOUND150,5:IFINKEY$=CHR$(12)THEN175ELSEprintING$(5,8);:A=A+1:IFA<25THEN165
line165:
  printSemi(F(" BEEP!"));
  sound(150, 5);
  if (inkey()==12)
  {
    goto line175;
  }
  else
  {
    string(5, 8);
    a = a + 1;
    if (a<25) goto line165;
  }

  //170 PRINT:PRINT" The Sysop is unavaliable now.":GOTO115
  print(F(""));
  print(F(" The Sysop is unavaliable now."));
  goto line115;

line175:
  //175 PRINT:PRINTTAB(6)"*Chat mode engaged*"
  print();
  printTab(6);
  print(F("*Chat mode engaged*"));

line180:
  //180 GOSUB1005:IFLEFT$(A$,3)="BYE"THEN185ELSE180
  //gosub1005();
  if (gosub1005()==255) goto line20;
  if (strncmp(aStr, "BYE", 3)==0)
  {
    goto line185;
  }
  else
  {
    goto line180;
  }

line185:
  //185 PRINTTAB(5)"*Chat mode terminated*":GOTO115
  goto line115;

  //200 'Goodbye
line205:
  //205 A$="Thank you for calling":GOSUB1055
  strncpy_P(aStr, PSTR("Thank you for calling"), INPUT_SIZE);
  gosub1055();

line210:
  //210 PRINT:PRINT"Goodbye, "NM$"!":PRINT:PRINT"Please call again."
  print(F(""));
  printSemi(F("Goodbye, "));
  printSemi(nmStr);
  print(F("!"));
  print();
  print(F("Please call again."));

line215:
  //215 PRINT:PRINT:PRINT"*ALL RAM* BBS disconnecting..."
  print();
  print();
  print(F("*ALL RAM* BBS disconnecting..."));

  //220 FORA=1TO1000:NEXTA
  delay(1000);

#if defined(ENET_PORT)
  telnetDisconnect();
#endif

  //225 GOTO20
  goto line20;

  //250 'Userlog
line255:
  //255 A$="List of Users":GOSUB1055:PRINT"Users on system:"NM:IFNM=0THEN115ELSEA=1
  strncpy_P(aStr, PSTR("List of Users"), INPUT_SIZE);
  gosub1055();
  printSemi(F("Users on system:"));
  print(nm);
  if (nm==0)
  {
    goto line115;
  }
  else
  {
    a = 1;
  }
line260:
  //260 A$=NM$(A):PRINTLEFT$(A$,INSTR(A$,"\")-1)TAB(29)RIGHT$(A$,1)
  strncpy(aStr, nmArray[a], INPUT_SIZE);
  {
    char tempStr[NAME_SIZE+1];         // Add room for NULL.
    strncpy(tempStr, aStr, NAME_SIZE+1);
    tempStr[instr(tempStr, "\\")-1] = '\0';
    printSemi(tempStr);
  }
  printTab(29);
  print(right(aStr,1));

  //265 IF(A/10)=INT(A/10)THENPRINT"C-ontinue or S-top :";:UC=1:GOSUB1005:IFLEFT$(A$,1)="S"THEN275
  if (a % 10 == 9)
  {
    printSemi(F("C-ontinue or S-top :"));
    uc = 1;
    //gosub1005();
    if (gosub1005()==255) goto line20;
    if (aStr[0]=='S') goto line275;
  }

  //270 A=A+1:IFA<=NM THEN260
  a = a + 1;
  if (a<=nm) goto line260;

line275:
  //275 PRINT"*End of Userlog*":GOTO115
  print(F("*End of Userlog*"));
  goto line115;

  //300 'Post Msg
line305:
  //305 IFMS=20THENPRINT"One moment, making room...":FORA=0TO18:FORB=0TO10:MS$(A,B)=MS$(A+1,B):NEXTB:NEXTA:MS=19
  if (ms==MAX_MSGS+1)
  {
    print(F("One moment, making room..."));
    for(a=0; a<=MAX_MSGS-1; a++)
    {
      for(b=0; b<=MAX_LINE; b++)
      {
        strncpy(msArray[a][b], msArray[a+1][b], INPUT_SIZE);
      }
    }
    ms = MAX_MSGS;
  }
  //310 CLS:PRINTCL$"This will be message #"MS+1:FORA=0TO10:MS$(MS,A)="":NEXTA:F$=NM$
  cls();
  print((__FlashStringHelper*)clStr);
  printSemi(F("This will be message #"));
  print(ms+1);
  for (a=0; a<=MAX_LINE; a++)
  {
    msArray[ms][a][0] = '\0';
  }
  strncpy(fStr, nmStr, NAME_SIZE);

  //315 PRINT"From :"F$:PRINT"To   :";:UC=1:GOSUB1005:A$=LEFT$(A$,20):T$=A$:IFA$=""THEN115
  printSemi(F("From :"));
  print(fStr);
  printSemi(F("To   :"));
  uc = 1;
  //gosub1005();
  if (gosub1005()==255) goto line20;
  aStr[NAME_SIZE] = '\0';
  strncpy(tStr, aStr, TO_SIZE);
  if (aStr[0]=='\0') goto line115;

  //320 PRINT"Is this message private? ";:UC=1:GOSUB1005:IFLEFT$(A$,1)="Y"THENS$="*E-Mail*":GOTO330
  printSemi(F("Is this message private? "));
  uc = 1;
  //gosub1005();
  if (gosub1005()==255) goto line20;
  if (aStr[0]=='Y')
  {
    strncpy_P(sStr, PSTR("*E-Mail*"), SB_SIZE);
    goto line330;
  }

  //325 PRINT"Subj :";:UC=1:GOSUB1005:A$=LEFT$(A$,18):S$=A$:IFA$=""THEN115
  printSemi(F("Subj :"));
  uc = 1;
  //gosub1005();
  if (gosub1005()==255) goto line20;
  aStr[SB_SIZE-1] = '\0';
  strncpy(sStr, aStr, SB_SIZE);
  if (aStr[0]=='\0') goto line115;

line330:
  //330 PRINT"Enter up to 10 lines, 64 chars. [ENTER] on a blank line to end.":A=0
  printSemi(F("Enter up to"));
  printSemi(MAX_LINE);
  printSemi(F("lines,"));
  printSemi(INPUT_SIZE);
  print(F("chars. [ENTER] on a blank line to end."));
  a = 0;

line335:
  //335 A=A+1:PRINTUSING"##>";A;:GOSUB1005:MS$(MS,A)=A$:IFA$=""THENA=A-1:GOTO345ELSEIFA<10THEN335
  a = a + 1;
  printUsingSemi("##>", a);
  //gosub1005();
  if (gosub1005()==255) goto line20;
  strncpy(msArray[ms][a], aStr, INPUT_SIZE);
  if (aStr[0]=='\0')
  {
    a = a - 1;
    goto line345;
  }
  else if (a<MAX_LINE) goto line335;

line340:
  //340 PRINT"*Message Buffer Full*"
  print(F("*Message Buffer Full*"));

line345:
  //345 PRINT"A-bort, C-ont, E-dit, L-ist, or S-ave Message? ";:UC=1:GOSUB1005:A$=LEFT$(A$,1):IFA$=""THEN345
  printSemi(F("A-bort, C-ont, E-dit, L-ist, or S-ave Message? "));
  uc = 1;
  //gosub1005();
  if (gosub1005()==255) goto line20;
  aStr[1] = '\0';
  if (aStr[0]=='\0') goto line345;

  //350 LN=INSTR("ACELS",A$):IFLN=0THEN345ELSEONLN GOTO385,355,360,375,380
  ln = instr("ACELS", aStr);
  if (ln==0) goto line345;
  if (ln==1) goto line385;
  if (ln==2) goto line355;
  if (ln==3) goto line360;
  if (ln==4) goto line375;
  if (ln==5) goto line380;

line355:
  //355 IFA<10THENPRINT"Continue your message:":GOTO335ELSE340
  if (a<MAX_LINE)
  {
    printSemi(F("Continue your message:"));
    goto line335;
  } 
  else goto line340;

line360:  
  //360 PRINT"Edit line 1 -"A":";:GOSUB1005:LN=VAL(LEFT$(A$,2)):IFLN<1ORLN>A THEN345
  printSemi(F("Edit line 1 -"));
  printSemi(a);
  printSemi(F(":"));
  //gosub1005();
  if (gosub1005()==255) goto line20;
  aStr[2] = '\0';
  ln = atoi(aStr);
  if (ln<1 || ln>a) goto line345;

  //365 PRINT"Line currently reads:":PRINTMS$(MS,LN):PRINT"Enter new line:":GOSUB1005:A$=LEFT$(A$,64):IFA$=""THENPRINT"*Unchanged*"ELSEMS$(MS,LN)=A$:PRINT"*Corrected*"
  print(F("Line currently reads:"));
  print(msArray[ms][ln]);
  print(F("Enter new line:"));
  //gosub1005();
  if (gosub1005()==255) goto line20;
  aStr[INPUT_SIZE] = '\0'; // 1.4
  if (aStr[0]=='\0')
  {
    print(F("*Unchanged*"));
  }
  else
  {
    strncpy(msArray[ms][ln], aStr, INPUT_SIZE);
    print(F("*Corrected*"));
  }

  //370 GOTO360
  goto line360;

line375:
  //375 CLS:PRINTCL$"Message Reads:":FORB=1TOA:PRINTUSING"##>";B;:PRINTMS$(MS,B):NEXTB:GOTO345
  cls();
  print((__FlashStringHelper*)clStr);
  print(F("Message Reads:"));
  for (b=1; b<=a; b++)
  {
    printUsingSemi("##>", b);
    print(msArray[ms][b]);
  }
  goto line345;

line380:
  //380 MS$(MS,0)=T$+"\"+F$+"\"+S$:MS=MS+1:PRINT"*Message"MS"stored*":GOTO115
  strcpy(msArray[ms][0], tStr);
  strcat_P(msArray[ms][0], PSTR("\\"));
  strcat(msArray[ms][0], fStr);
  strcat_P(msArray[ms][0], PSTR("\\"));
  strcat(msArray[ms][0], sStr);
  ms = ms + 1;
  printSemi(F("*Message"));
  printSemi(ms);
  print(F("stored*"));
  goto line115;

line385:
  //385 PRINT"*Message Aborted*":GOTO115
  print(F("*Message Aborted*"));
  goto line115;

  //400 'Read Msg
line405:
  //405 IFMS=0THENPRINT"The message base is empty.":GOTO115
  if (ms==0)
  {
    print(F("The message base is empty."));
    goto line115;
  }

  //410 CLS:PRINTCL$
  cls();
  print((__FlashStringHelper*)clStr);

line415:
  //415 PRINT"Read Message 1 -"MS":";:GOSUB1005:A=VAL(LEFT$(A$,2)):IFA<1ORA>MS THEN115
  printSemi(F("Read Message 1 -"));
  printSemi(ms);
  printSemi(F(":"));
  //gosub1005();
  if (gosub1005()==255) goto line20;
  aStr[2] = '\0';
  a = atoi(aStr);
  if (a<1 || a>ms) goto line115;

  //420 A$=MS$(A-1,0):B=INSTR(A$,"\"):C=INSTR(B+1,A$,"\"):T$=LEFT$(A$,B-1):F$=MID$(A$,B+1,C-B-1):S$=RIGHT$(A$,LEN(A$)-C)
  strncpy(aStr, msArray[a-1][0], INPUT_SIZE);
  b = instr(aStr, "\\");
  c = instr(b+1, aStr, "\\");
  strncpy(tStr, aStr, b-1);
  tStr[b-1] = '\0';
  strncpy(fStr, (aStr-1)+b+1, c-b-1);
  fStr[c-b-1] = '\0'; // FIXTHIS - max copy sizes here?
  strncpy(sStr, right(aStr, strlen(aStr)-c), SB_SIZE);

  //425 IFS$="*E-Mail*"ANDLV<8THENIFNM$<>T$ANDNM$<>F$THENPRINT"That message is private.":GOTO415
  if (strcmp(sStr, "*E-Mail*")==0 && lv<8)
  {
    if (strcmp(nmStr, tStr)!=0 && strcmp(nmStr, fStr)!=0)
    {
      print(F("That message is private."));
      goto line415;
    }
  }

  //430 CLS:PRINTCL$"Message #"A:PRINT"From :"F$:PRINT"To   :"T$:PRINT"Subj :"S$:PRINT:B=0
  cls();
  print((__FlashStringHelper*)clStr);
  printSemi(F("Message #"));
  print(a);
  printSemi(F("From :"));
  print(fStr);
  printSemi(F("To   :"));
  print(tStr);
  printSemi(F("Subj :"));
  print(sStr);
  print();
  b = 0;

line435:
  //435 B=B+1:PRINTMS$(A-1,B):IFMS$(A-1,B)=""THEN440ELSEIFB<10THEN435
  b = b + 1;
  print(msArray[a-1][b]);
  if (msArray[a-1][b][0]=='\0')
  {
    goto line440;
  }
  else if (b<MAX_LINE) goto line435;

line440:
  //440 PRINT"*End of Message*":GOTO415
  print(F("*End of Message*"));
  goto line415;

  //450 'Scan Titles
line455:
  //455 IFMS=0THENPRINT"The message base is empty.":GOTO115
  if (ms==0)
  {
    print(F("The message base is empty."));
    goto line115;
  }

  //460 CLS:PRINTCL$"Message Titles:":A=0
  cls();
  print((__FlashStringHelper*)clStr);
  print(F("Message Titles:"));
  a = 0;

line465:
  //465 A$=MS$(A,0):PRINTUSING"[##] SB: ";A+1;:B=INSTR(A$,"\"):C=INSTR(B+1,A$,"\"):PRINTRIGHT$(A$,LEN(A$)-C):PRINTTAB(5)"TO: "LEFT$(A$,B-1):A=A+1:IFA<MS THEN465
  strncpy(aStr, msArray[a][0], INPUT_SIZE);
  printUsingSemi("[##] SB: ", a+1);
  b = instr(aStr, "\\");
  c = instr(b+1, aStr, "\\");
  print(right(aStr, strlen(aStr)-c));
  printTab(5);
  printSemi(F("TO: "));
  {
    char tempStr[TO_SIZE];
    strncpy(tempStr, aStr, b-1);
    tempStr[b-1] = '\0';
    print(tempStr);
  }
  a = a + 1;
  if (a<ms) goto line465;

  //470 PRINT"*End of Messages*":GOTO115
  print(F("*End of Messages*"));
  goto line115;

  //500 '%SYSOP MENU%
line505:
  //505 IFLV<9THENA$="Z":GOTO130
  if (lv<9)
  {
    strncpy_P(aStr, PSTR("Z"), INPUT_SIZE);
    goto line130;
  }

  //510 PRINT"PASSWORD?";:GOSUB1005:IFA$<>"?DROWSSAP"THENPRINT"Thank You!":GOTO115
  printSemi(F("PASSWORD?"));
  //gosub1005();
  if (gosub1005()==255) goto line20;
  if (strcmp(aStr, "?DROWSSAP")!=0)
  {
    print(F("Thank You!"));
    goto line115;
  }

  //515 PRINT"Abort BBS? YES or NO? ";:UC=1:GOSUB1005:IFA$<>"YES"THEN115
  printSemi(F("Abort BBS? YES or NO? "));
  uc = 1;
  //gosub1005();
  if (gosub1005()==255) goto line20;
  if (strcmp(aStr, "YES")!=0) goto line115;

  //520 GOSUB605:STOP
  gosub605();
  return;
} // end of allram()

/*---------------------------------------------------------------------------*/
// Subroutines (formerly GOSUBs)
//
//550 '%LOAD%
void gosub555()
{
  //555 PRINT"%LOAD% [ENTER] WHEN READY";:GOSUB1005
  printSemi(F("%LOAD% [ENTER] WHEN READY"));
  //gosub1005();
  print();
  if (aStr[0]=='!') return;

  //560 OPEN"I",#-1,"USERLOG":INPUT#-1,CL,NM:FORA=0TONM:INPUT#-1,NM$(A):NEXTA:CLOSE
  loadUserlog();

  //565 OPEN"I",#-1,"MSG BASE":INPUT#-1,MS:FORA=0TOMS-1:FORB=0TO10:INPUT#-1,MS$(A,B):NEXTB:NEXTA:CLOSE:RETURN
  loadMsgBase();
}

//600 '%SAVE%
void gosub605()
{
  //605 PRINT"%SAVE% [ENTER] WHEN READY";:GOSUB1005:MOTORON:FORA=0TO999:NEXTA
  printSemi(F("%SAVE% [ENTER] WHEN READY"));
  gosub1005();
  
  //610 OPEN"O",#-1,"USERLOG":PRINT#-1,CL,NM:FORA=0TONM:PRINT#-1,NM$(A):NEXTA:CLOSE
  saveUserlog();

  //615 OPEN"O",#-1,"MSG BASE":PRINT#-1,MS:FORA=0TOMS-1:FORB=0TO10:PRINT#-1,MS$(A,B):NEXTB:NEXTA:CLOSE:RETURN
  saveMsgBase();
}

//1000 'User Input
#define CR         13
#define INBUF_SIZE 64
byte gosub1005()
{
  byte ch; // Used only here, so we can make it local.
  byte count;

  //1005 LINEINPUTA$:A$=LEFT$(A$,64):IFUC=0ORA$=""THENRETURN
  count = lineinput(aStr, INPUT_SIZE);
  aStr[INPUT_SIZE] = '\0';
  if ((uc==0) || (aStr[0]=='\0')) return count;

  //1010 FORC=1TOLEN(A$):CH=ASC(MID$(A$,C,1)):IFCH>96THENMID$(A$,C,1)=CHR$(CH-32)
  for (c=0; c<strlen(aStr); c++)
  {
    ch = aStr[c];
    if (ch>96) aStr[c] = ch-32;    
    //1015 IFCH=92THENMID$(A$,C,1)="/"
    if (ch==92) aStr[c] = '/';
    //1020 NEXTC:UC=0:RETURN
  }
  uc = 0;
  
  return count;
}

//1050 'Function Border
void gosub1055()
{
  //1055 CLS:PRINTCL$BR$:PRINTTAB((32-LEN(A$))/2)A$:PRINTBR$:RETURN
  cls();
  print((__FlashStringHelper*)clStr);
  print((__FlashStringHelper*)brStr);
  printTab((32-strlen(aStr))/2);
  print(aStr);
  print((__FlashStringHelper*)brStr);
}

/*---------------------------------------------------------------------------*/
// The following functions mimic some of the Extended Color BASIC commands.

// CLS
// Clear the screen.
void cls()
{
  print();
  print(F("--------------CLS--------------"));
}

// SOUND tone, duration
// On the CoCo, tone (1-255), duration (1-255; 15=1 second).
void sound(byte tone, byte duration)
{
  Serial.write(0x07);   // BEL
  delay(duration*66.6); // Estimated delay.
}

/*---------------------------------------------------------------------------*/
// String functions.

// STRING$(length, charcode)
// Generate a string of length charcode chracters.
void string(byte length, byte charcode)
{
  int i;

  for (i=0; i<length; i++) printCharSemi(charcode);
}

// RIGHT$(str, length)
// Note: Modifies the passed in string, which is okay for our purpose but
// would not be suitable as a generic replacement for RIGHT$.
char *right(char *str, byte length)
{
  return &str[strlen(str)-length];
}

// INSTR(first, str, substr)
// Starting at pos, return position of substr in str, or 0 if not found.
int instr(byte pos, char *str, char *substr)
{
  if (pos<1) return 0;
  return instr(aStr+pos, substr) + pos;
}
int instr(char *str, char *substr)
{
  char *ptr;

  ptr = strstr(str, substr);
  if (ptr==NULL) return 0; // No match?
  if (ptr==&str[strlen(str)]) return 0; // Matched the \0 at end of line?
  return ptr-str+1;
}

/*---------------------------------------------------------------------------*/
// Input functions.

#ifdef ENET_PORT
byte lineinput(char *cmdLine, byte len)
{
  return telnetInput(client, cmdLine, len);
}
#else
// LINE INPUT str
// Read string up to len bytes. This code comes from my Hayes AT Command
// parser, so the variables are named differently.
#define CR           13
#define BEL          7
#define BS           8
#define CAN          24
byte lineinput(char *cmdLine, byte len)
{
  int     ch;
  byte    cmdLen = 0;
  boolean done;

  done = false;
  while(!done)
  {
    //ledBlink();

    ch = -1; // -1 is no data available

    if (Serial.available()>0)
    {
      ch = Serial.read();
    }
    else
    {
      continue; // No data. Go back to the while()...
    }
    switch(ch)
    {
    case -1: // No data available.
      break;

    case CR:
      print();
      cmdLine[cmdLen] = '\0';
      done = true;
      break;

      /*case CAN:
       print(F("[CAN]"));
       cmdLen = 0;
       break;*/

    case BS:
      if (cmdLen>0)
      {
        printCharSemi(BS);
        printSemi(F(" "));
        printCharSemi(BS);
        cmdLen--;
      }
      break;

    default:
      // If there is room, store any printable characters in the cmdline.
      if (cmdLen<len)
      {
        if ((ch>31) && (ch<127)) // isprint(ch) does not work.
        {
          printCharSemi(ch);
          cmdLine[cmdLen] = ch; //toupper(ch);
          cmdLen++;
        }
      }
      else
      {
        printCharSemi(BEL); // Overflow. Ring 'dat bell.
      }
      break;
    } // end of switch(ch)
  } // end of while(!done)

  return cmdLen;
}
#endif

// INKEY$
// Return character waiting (if any) from standard input (not ethernet).
char inkey()
{
  if (Serial.available()==0) return 0;
  return Serial.read();
}

/*---------------------------------------------------------------------------*/

// File I/O
// Ideally, I would have created wrappers for the OPEN, READ, CLOSE commands,
// but I was in a hurry, so...

//SD Card routines
#if defined(SD_PIN)
#define TEMP_SIZE 4
#define FNAME_MAX (8+1+3+1)
boolean initSD()
{
  static bool sdInit = false;

  if (sdInit==true) return true;

  printSemi(F("Initializing SD card..."));
  pinMode(SD_PIN, OUTPUT);
  if (!SD.begin(SD_PIN))
  {
    print(F("initialization failed."));
    return false;
  }
  print(F("initialization done."));
  sdInit = true;

  return true;
}
#endif

//560 OPEN"I",#-1,"USERLOG":INPUT#-1,CL,NM:FORA=0TONM:INPUT#-1,NM$(A):NEXTA:CLOSE
void loadUserlog()
{
#if defined(SD_PIN)
  File myFile;
  char tempStr[TEMP_SIZE];
  char filename[FNAME_MAX];

  if (!initSD()) return;

  strncpy_P(filename, PSTR("USERLOG"), FNAME_MAX);

  myFile = SD.open(filename, FILE_READ);

  if (myFile)
  {
    printSemi(filename);
    print(F(" opened."));
    fileReadln(myFile, tempStr, TEMP_SIZE);
    cl = atoi(tempStr);
    Serial.print(F("cl = "));
    Serial.println(cl);
    fileReadln(myFile, tempStr, TEMP_SIZE);
    nm = atoi(tempStr);
    Serial.print(F("nm = "));
    Serial.println(nm);
    for (a=0; a<=nm; a++)
    {
      fileReadln(myFile, nmArray[a], ULOG_SIZE);
      Serial.print(a);
      Serial.print(F(". "));
      Serial.println(nmArray[a]);
    }  
    myFile.close();
  }
  else
  {
    printSemi(F("Error opening "));
    print(filename);
  }
#else  
  print(F("(USERLOG would be loaded from tape here.)"));
#endif
}

//565 OPEN"I",#-1,"MSG BASE":INPUT#-1,MS:FORA=0TOMS-1:FORB=0TO10:INPUT#-1,MS$(A,B):NEXTB:NEXTA:CLOSE:RETURN
void loadMsgBase()
{
#if defined(SD_PIN)
  File myFile;
  char tempStr[TEMP_SIZE];
  char filename[FNAME_MAX];

  if (!initSD()) return;

  strncpy_P(filename, PSTR("MSGBASE"), FNAME_MAX);

  myFile = SD.open(filename, FILE_READ);
  if (myFile)
  {
    printSemi(filename);
    print(F(" opened."));
    fileReadln(myFile, tempStr, TEMP_SIZE);
    ms = atoi(tempStr);
    Serial.print("ms = ");
    Serial.println(ms);
    for (a=0; a<=ms-1; a++)
    {
      for (b=0; b<=MAX_LINE; b++)
      {
        fileReadln(myFile, msArray[a][b], INPUT_SIZE);
        Serial.print(F("msArray["));
        Serial.print(a);
        Serial.print(F("]["));
        Serial.print(b);
        Serial.print(F("] = "));
        Serial.println(msArray[a][b]);
      }
    }  
    myFile.close();
  }
  else
  {
    printSemi(F("Error opening "));
    print(filename);
  }
#else
  print(F("(MSGBASE would be loaded from tape here.)"));
#endif
}

#if defined(SD_PIN)
//byte fileReadln(File myFile, char *buffer, byte count)
{
  char ch;
  int  pos;

  pos = 0;
  while(myFile.available() && pos<count)
  {
    ch = myFile.read();
    if (ch==CR)
    {
      buffer[pos] = '\0';
      break;
    }
    if (ch>=32)
    {
      //Serial.print(ch);
      buffer[pos] = ch;
      pos++;
    }
  }
  if (pos>=count) buffer[pos] = '\0';
  //Serial.println();
  return pos;
}
#endif

//610 OPEN"O",#-1,"USERLOG":PRINT#-1,CL,NM:FORA=0TONM:PRINT#-1,NM$(A):NEXTA:CLOSE
void saveUserlog()
{
#if defined(SD_PIN)
  File myFile;
  char filename[FNAME_MAX];

  if (!initSD()) return;

  strncpy_P(filename, PSTR("USERLOG"), FNAME_MAX);

  if (SD.exists(filename)==true) SD.remove(filename);

  myFile = SD.open(filename, FILE_WRITE);
  if (myFile)
  {
    printSemi(filename);
    print(F(" created."));
    myFile.println(cl);
    Serial.print(F("cl = "));
    Serial.println(cl);
    myFile.println(nm);
    Serial.print(F("nm = "));
    Serial.println(nm);
    for (a=0; a<=nm; a++)
    {
      myFile.println(nmArray[a]);
      Serial.print(a);
      Serial.print(F(". "));
      Serial.println(nmArray[a]);
    }
    myFile.close();
  }
  else
  {
    print(F("Error creating file."));
  }
#else
  print(F("save USERLOG"));
#endif
}

//615 OPEN"O",#-1,"MSG BASE":PRINT#-1,MS:FORA=0TOMS-1:FORB=0TO10:PRINT#-1,MS$(A,B):NEXTB:NEXTA:CLOSE:RETURN
void saveMsgBase()
{
#if defined(SD_PIN)
  File myFile;
  char filename[FNAME_MAX];

  if (!initSD()) return;

  strncpy_P(filename, PSTR("MSGBASE"), FNAME_MAX);

  if (SD.exists(filename)==true) SD.remove(filename);

  myFile = SD.open(filename, FILE_WRITE);
  if (myFile)
  {
    printSemi(filename);
    print(F(" created."));
    myFile.println(ms);
    for (a=0; a<=ms-1; a++)
    {
      for (b=0; b<=MAX_LINE; b++)
      {
        myFile.println(msArray[a][b]);
        Serial.print(F("msArray["));
        Serial.print(a);
        Serial.print(F("]["));
        Serial.print(b);
        Serial.print(F("] = "));
        Serial.println(msArray[a][b]);
      }
    }
    myFile.close();
  }
  else
  {
    print(F("Error creating file."));
  }
#else
  print(F("save MSGBASE"));
#endif
}

/*---------------------------------------------------------------------------*/
// Print (output) routines.

// For TAB to work, we need to track where we think we are on the line.
byte tabPos = 0;

// We want to simulate the following:
// PRINT "HELLO"  -- string, with carraige return at end of line
// PRINT A        -- number (space before and after), with carraige return
// PRINT "HELLO"; -- no carraige return
// PRINT TAB(5);  -- tab to position 5
// PRINT "A","B"  -- tab to column 16 (on 32-column screen)

// Due to various types of strings on Arduino (in memory or Flash), we will
// have to duplicate some functions to have versions that take the other
// types of strings.

// printTypeSemi() routines will not put a carraige return at the end.

// PRINT TAB(column);
void printTab(byte column)
{
  while(tabPos<column)
  {
    printSemi(F(" ")); // Print, and increment tab position.
  }
}

// PRINT,
// NOTE: DECB doesn't add a carraige return after a comma.
void printComma()
{
  printTab(tabPos + (16-(tabPos % 16)));
}

// PRINT "STRING";
// For normal strings in RAM.
void printSemi(const char *string)
{
  tabPos = tabPos + Serial.print(string);
#if defined(ENET_PORT)
  client.print(string);
#endif
}
// For strings in Flash.
void printSemi(const __FlashStringHelper *string)
{
  tabPos = tabPos + Serial.print(string);
#if defined(ENET_PORT)
  client.print(string);
#endif
}
// For printing a byte as a number (0-255).
void printSemi(byte num)
{
  Serial.print(F(" "));
  tabPos = tabPos + Serial.print(num);
  Serial.print(F(" "));
  tabPos = tabPos + 2;
#if defined(ENET_PORT)
  client.print(F(" "));
  client.print(num);
  client.print(F(" "));
#endif
}
// For printing a single character.
void printCharSemi(char ch)
{
  tabPos = tabPos + Serial.print(ch);
#if defined(ENET_PORT)
  client.print(ch);
#endif
}
// For printing a byte as a number with no spaces.
void printNumSemi(byte num)
{
  tabPos = tabPos + Serial.print(num);
#if defined(ENET_PORT)
  client.print(num);
#endif
}

// PRINT
void print(void)
{
  Serial.println();
#if defined(ENET_PORT)
  client.println();
#endif
}

// PRINT "STRING"
void print(const char *string)
{
  Serial.println(string);
  tabPos = 0;
#if defined(ENET_PORT)
  client.println(string);
#endif
}
void print(const __FlashStringHelper *string)
{
  Serial.println(string);
  tabPos = 0;
#if defined(ENET_PORT)
  client.println(string);
#endif
}

// PRINT I
void print(int num)
{
  Serial.print(F(" "));
  Serial.println(num);
  tabPos = 0;
#if defined(ENET_PORT)
  client.print(F(" "));
  client.println(num);
#endif
}

// PRINT USING(format, number);
// NOTE: This only emulates printing positive integers, which is the
// only way it is used by this program.
void printUsingSemi(char *format, byte num)
{
  byte i;
  byte fmtDigits;
  byte numDigits;
  byte tempNum;

  i = 0;
  while(format[i]!='\0')
  {
    if (format[i]!='#') {
      printCharSemi(format[i]);
      i++;
      continue;
    }
    else
    {
      // Start counting the run of #s.
      // Find end of #'s to know how many to use.
      fmtDigits = 0;
      while(format[i]=='#' && format[i]!='\0')
      {
        fmtDigits++;
        i++;
      }
      // Now we know how many # (digits).
      tempNum = num;
      numDigits = 1;
      while(tempNum>10)
      {
        tempNum = tempNum/10;
        numDigits++;
      }
      while(numDigits<fmtDigits)
      {
        printSemi(F(" "));
        fmtDigits--;
      }
      printNumSemi(num);
    }
  }
}

/*---------------------------------------------------------------------------*/
// Show some stuff functions.

// Emit some configuration information.
void showConfig()
{
  print((__FlashStringHelper*)brStr);
  print(F("*ALL RAM* Configuration:"));
  printSemi(F("Userlog size :"));
  print(MAX_USERS+1);
  printSemi(F("Input size   :"));
  print(INPUT_SIZE);
  printSemi(F("Username size:"));
  print(NAME_SIZE);
  printSemi(F("Password size:"));
  print(PSWD_SIZE);
  printSemi(F("Msg base size:"));
  print(MAX_MSGS+1);
  printSemi(F("Message lines:"));
  print(MAX_LINE+1);
#if defined(SD_PIN)
  print(F("SD card      : Enabled"));
#endif
#if defined(ENET_PORT)
  print(F("Ethernet     : Enabled"));
#endif
  printSemi(F("ESTIMATED MEM:"));
  printSemi(ULOG_MEM + MBASE_MEM);
  print(F("bytes."));
  printSemi(F("Free RAM     :"));
  print(freeRam());
  print((__FlashStringHelper*)brStr);
}

void showLoginMessage()
{
  print(F("\nYou are connected to an Arduino UNO R3, a small computer thing you can buy\n"
    "from Radio Shack for $29.99 (or around $22 online). It has 2K of RAM and\n"
    "32K of Flash for program storage. It has a SainSmart Ethernet Shield ($17.99)\n"
    "attached to it. The software running here is a line-by-line port of my\n"
    "*ALL RAM* BBS program written in 1983. The original Extended Color BASIC\n"
    "code was converted as literally as possible to Arduino C. It's a travesty.\n"
    "\n"
    "This BBS program was designed to run on a cassette based TRS-80 Color\n"
    "Computer with 32K of RAM. All messages and users were stored in memory.\n"
    "Obviously, with only 2K of RAM, this is not possible, so this version has\n"
    "been configured to allow only a few users and a teensy tiny message base\n"
    "(smaller than Twitter posts!). Enjoy the experiment!\n"
    "\n"
    "(If userlog is full, use the Sysop password 'TEST'.)"));
}

void showCoCoHeader()
{
  cls();
  print(F("EXTENDED COLOR BASIC 1.1\n"
    "COPYRIGHT (C) 1982 BY TANDY\n"
    "UNDER LICENSE FROM MICROSOFT\n"
    "\n"
    "OK\n"
    "CLOAD\"ALLRAM\"\n"
    "RUN"));
}

/*---------------------------------------------------------------------------*/

// Debug and utility functions.
//

unsigned int freeRam() {
  extern int __heap_start, *__brkval; 
  int v; 
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); 
}

void showFreeRam()
{
  printSemi(F("Free RAM:"));
  print(freeRam());
}

/*---------------------------------------------------------------------------*/

void showUserlog()
{
  int i;
  printSemi(F("Users: "));
  print(nm);
  for (i=0; i<=nm; i++) {
    printSemi(i);
    printSemi(F(". "));
    print(nmArray[i]);
  }
}

void showMessageBase()
{
  int i,j;

  for (int i=0; i<ms; i++)
  {
    for (int j=0; j<=MAX_LINE; j++)
    {
      printSemi(F("msArray["));
      printSemi(i);
      printSemi(F(","));
      printSemi(j);
      printSemi(F("] = "));
      print(msArray[i][j]);
    }
  }
}


/*---------------------------------------------------------------------------*/

//0 REM *ALL RAM* BBS Editor 1.0
//1 REM   Shareware / (C) 1983
//2 REM     By Allen Huffman
//3 REM  110 Champions Dr, #811
//4 REM     Lufkin, TX 75901
//5 FORA=0TO8:READA$:POKE1024+A,VAL("&H"+A$):NEXTA:EXEC1024:DATAC6,1,96,BC,1F,2,7E,96,A3
//10 CLEAR21000:DIMNM$(200),MS$(19,10),A$,F$,S$,T$,NM$,PW$,A,B,C,LN,LV,MS,NM,PR:PR=80
//15 CLS:PRINTTAB(3)"*ALL RAM* EDITOR COMMANDS:":printING$(32,45)
//20 PRINTTAB(4)"1. CREATE USERLOG",TAB(4)"2. LOAD USERLOG/MSG BASE",TAB(4)"3. SAVE USERLOG/MSG BASE",TAB(4)"4. PRINT USERLOG",TAB(4)"5. PRINT MESSAGES",TAB(4)"6. EDIT USERS",TAB(4)"7. KILL MESSAGES",TAB(4)"8. QUIT"
//25 PRINT@392,"ENTER FUNCTION :"
//30 A$=INKEY$:IFA$=""THEN30ELSEPRINT@408,A$:LN=VAL(A$):IFLN<1ORLN>8THENSOUND50,1:GOTO25
//35 SOUND200,1:ONLN GOTO55,105,155,205,255,305,405,40
//40 STOP
//50 'Create Userlog
//55 CLS:PRINTTAB(7)"SYSOP INFORMATION:":printING$(32,45)
//60 PRINT@128,"SYSOP'S NAME:    (20 CHARACTERS)>";:LINEINPUTA$:IFA$=""ORLEN(A$)>20THENSOUND50,1:GOTO15ELSENM$=A$
//65 PRINT@192,"PASSWORD    :     (8 CHARACTERS)>";:LINEINPUTA$:IFA$=""ORLEN(A$)>8THENSOUND50,1:GOTO15ELSEPW$=A$
//70 PRINT@297,"*VERIFY ENTRY*":PRINT:PRINT"NAME :"NM$:PRINT"PSWD :"PW$:PRINT@456,"IS THIS CORRECT?";
//75 LINEINPUTA$:IFLEFT$(A$,1)<>"Y"THENSOUND50,1:GOTO55
//80 NM$(0)=NM$+"\"+PW$+"9":GOTO15
//100 'Load Userlog/Msg Base
//105 CLS:PRINTTAB(5)"LOAD USERLOG/MSG BASE:":printING$(32,45)
//110 LINEINPUT" READY TAPE, THEN PRESS ENTER:";A$:PRINT@168,"...ONE MOMENT..."
//115 OPEN"I",#-1,"USERLOG":PRINT@232,"LOADING  USERLOG":INPUT#-1,CL,NM:FORA=0TONM:INPUT#-1,NM$(A):NEXTA:CLOSE
//120 OPEN"I",#-1,"MSG BASE":PRINT@240,"MSG BASE":INPUT#-1,MS:FORA=0TOMS-1:FORB=0TO10:INPUT#-1,MS$(A,B):NEXTB:NEXTA:CLOSE:GOTO15
//150 'Save Userlog/Msg Base
//155 CLS:PRINTTAB(5)"SAVE USERLOG/MSG BASE:":printING$(32,45)
//160 LINEINPUT" READY TAPE, THEN PRESS ENTER:";A$:PRINT@168,"...ONE MOMENT...":MOTORON:FORA=1TO1000:NEXTA
//165 PRINT@232,"SAVING   USERLOG":OPEN"O",#-1,"USERLOG":PRINT#-1,CL,NM:FORA=0TONM:PRINT#-1,NM$(A):NEXTA:CLOSE
//170 PRINT@240,"MSG BASE":OPEN"O",#-1,"MSG BASE":PRINT#-1,MS:FORA=0TOMS-1:FORB=0TO10:PRINT#-1,MS$(A,B):NEXTB:NEXTA:CLOSE:GOTO15
//200 'Print Userlog
//205 IFNM$(0)=""THENPRINT@454,"*USERLOG NOT LOADED*":SOUND50,1:GOTO25
//210 CLS:PRINTTAB(9)"PRINT USERLOG:":printING$(32,45)
//215 LINEINPUT"    PRESS ENTER WHEN READY:";A$:PRINT@169,"...PRINTING..."
//220 PRINT#-2,TAB((PR-30)/2)"[*ALL RAM* BBS System Userlog]":PRINT#-2,"":PRINT#-2,TAB((PR-46)/2)"[###]  [        NAME        ]  [PASSWORD]  [L]"
//225 FORA=0TONM:A$=NM$(A):B=INSTR(A$,"\"):NM$=LEFT$(A$,B-1):PW$=MID$(A$,B+1,LEN(A$)-B-1):LV=VAL(RIGHT$(A$,1))
//230 A$="000........................................0":B=LEN(STR$(A))-1:MID$(A$,4-B,B)=RIGHT$(STR$(A),B):MID$(A$,8,LEN(NM$))=NM$:MID$(A$,32,LEN(PW$))=PW$:MID$(A$,44,1)=RIGHT$(STR$(LV),1)
//235 PRINT@238,A:PRINT#-2,TAB((PR-44)/2)A$:NEXTA:GOTO15
//250 'Print Messages
//255 IFMS$(0,0)=""THENPRINT@454,"*MSG BASE NOT LOADED*":SOUND50,1:GOTO25
//260 CLS:PRINTTAB(8)"PRINT  MESSAGES:":printING$(32,45)
//265 LINEINPUT"    PRESS ENTER WHEN READY:";A$:PRINT@169,"...PRINTING..."
//270 PRINT#-2,TAB((PR-30)/2)"[*ALL RAM* BBS System Messages]":PRINT#-2,""
//275 FORA=0TOMS-1:A$=MS$(A,0):B=INSTR(A$,"\"):C=INSTR(B+1,A$,"\"):T$=LEFT$(A$,B-1):F$=MID$(A$,B+1,C-B-1):S$=RIGHT$(A$,LEN(A$)-C)
//280 PRINT@238,A+1:B=(PR-64)/2:PRINT#-2,TAB(B)"Message #"A:PRINT#-2,TAB(B)"TO :"T$:PRINT#-2,TAB(B)"FR :"F$:PRINT#-2,TAB(B)"SB :"S$:PRINT#-2,STRING$(64,45):C=0
//285 C=C+1:PRINT#-2,TAB(B)MS$(A,C):IFMS$(A,C)=""THEN290ELSEIFC<10THEN285
//290 PRINT#-2,"":NEXTA:GOTO15
//300 'Edit Users
//305 IFNM$(0)=""THENPRINT@454,"*USERLOG NOT LOADED*":SOUND50,1:GOTO25
//310 CLS:PRINTTAB(10)"EDIT  USERS:":printING$(32,45):A=0
//315 PRINT@70,"USERS ON SYSTEM:"NM
//320 A$=NM$(A):B=INSTR(A$,"\"):NM$=LEFT$(A$,B-1):PW$=MID$(A$,B+1,LEN(A$)-B-1):LV=VAL(RIGHT$(A$,1))
//325 PRINT@128,"USER #"A:PRINT:PRINT"NAME: "NM$:PRINT"PSWD: "PW$:PRINT"LVL :"LV
//330 PRINT@320,STRING$(32,45)TAB(4)"D-LET   UP-BACK   J-UMP",TAB(4)"E-DIT   DN-NEXT   M-ENU"
//335 PRINT@456,"ENTER FUNCTION :"
//340 A$=INKEY$:IFA$=""THEN340ELSEPRINT@472,A$;:LN=INSTR("DEJM"+CHR$(94)+CHR$(10),A$):IFLN=0THENSOUND50,1:GOTO335
//345 SOUND200,1:ONLN GOTO350,365,385,15,390,395
//350 IFA=0THENSOUND1,5:GOTO335
//355 IFA=NM THENNM=NM-1:A=A-1:GOTO315
//360 FORB=A TONM:NM$(B)=NM$(B+1):NEXTB:NM=NM-1:GOTO315
//365 PRINT@198,;:LINEINPUTA$:IFA$=""ORLEN(A$)>20THENPRINT@198,NM$ELSENM$=A$
//370 PRINT@230,;:LINEINPUTA$:IFA$=""ORLEN(A$)>8THENPRINT@230,PW$ELSEPW$=A$
//375 PRINT@262,;:LINEINPUTA$:B=VAL(A$):IFB<1ORB>9THENPRINT@261,LV ELSELV=B
//380 NM$(A)=NM$+"\"+PW$+RIGHT$(STR$(LV),1):GOTO335
//385 PRINT@456," JUMP TO USER # ";:LINEINPUTA$:B=VAL(A$):IFB<0ORB>NM THENSOUND1,5:GOTO335ELSEA=B:GOTO320
//390 A=A-1:IFA<0THENA=NM
//391 GOTO315
//395 A=A+1:IFA>NM THENA=0
//396 GOTO315
//400 'Kill Messages
//405 IFMS$(0,0)=""THENPRINT@454,"*MSG BASE NOT LOADED*":SOUND50,1:GOTO25
//410 CLS:PRINTTAB(9)"KILL MESSAGES:":ING$(32,45)
//415 PRINT@96,"DELETE MESSAGE # 1 -"MS":";:LINEINPUTA$:A=VAL(A$):IFA<1ORA>MS THEN15
//420 A$=MS$(A-1,0):B=INSTR(A$,"\"):C=INSTR(B+1,A$,"\"):T$=LEFT$(A$,B-1):F$=MID$(A$,B+1,C-B-1):S$=RIGHT$(A$,LEN(A$)-C)
//425 PRINT:PRINT"TO: "T$:PRINT"FR: "F$:PRINT"SB: "S$
//430 PRINT:LINEINPUT"DELETE THIS?";A$:IFLEFT$(A$,1)<>"Y"THEN410
//435 IFA=MS THENMS=MS-1:GOTO410
//440 FORB=A-1 TOMS-2:FORC=0TO10:MS$(B,C)=MS$(B+1,C):NEXTC:NEXTB:MS=MS-1:GOTO410

// End of file.