                   StateMaker User Manual 
         (Text Only - View Diagrams with StateMaker)

1.                        Introduction
StateMaker is a CASE (computer aided software engineering) tool
create state diagrams and to generate C or C++ code from the
state diagrams.   State diagrams are also referred to as state
transition diagrams.   StateMaker was developed by MicroGold
Software, 696 Birch Hill Drive, Bridgewater,  NJ, 08807 telephone
1 - 908 - 722 - 6438 CompuServe 71543,1172 or Internet
71543.1172@compuserve.com.   StateMaker operates under Windows
3.1 or later.   The generated C or C++ may be compiled with any C
or C++ compiler.   All examples in this manual were compiled
using Borland C++ Version 3.1.

1.1.Why State Diagrams?
State diagrams are useful for software developers who are
modeling complex state based behavior.   State diagrams are
useful in control systems, graphic user interfaces, network
systems, etc.   Most software development methodologies use state
diagrams in some form or another.  For example, Structured
Analysis and Design has state diagrams.    Virtually all object
oriented analysis and design methodologies use state diagrams
including Coad/Yourdon, Booch, and Rumbaugh. Numerous texts on
object oriented analysis and design are listed in the references
section. 

The  StateMaker state transition program is useful for developers
doing real-time or multitasking programming who want functions or
objects that act simultaneously in a system where modules of code
have independent tasks.  The state machine allows the programmer
functions to have a memory of what it was doing when it leaves
the task and later returns.  State diagrams are a useful tool for
dealing with this concurrency.

1.2.Why StateMaker?
StateMaker allows the developer the following advantages for
rapid state diagram development:
     1.  A quick way to diagram state diagrams,
     2.  A quick way to generate the C or C++ code from state
diagrams.
     3.  A good hard copy of documentation for the state diagram
     4.  A useful way to learn about state diagrams.

1.3.Install Procedure
To install StateMaker or the Demo,  run the install batch file on
the floppy disk.   If you are installing on hard drive C, you
should type Install C:   at the DOS prompt The program will
create directory SM for your program just below the c:\ root
directory.

When you have finished installing into DOS you must now install
into Windows.  Simply go to the New  menu command in the Program
Manager  and browse for  sm.exe under the SM directory of the
drive you installed the program on.  The program will be added to
your applications group.   As an alternative,  you can use the
Windows Setup program to bring sm.exe into Windows in the same
way.

2.                StateMaker Menus and Toolbars
StateMaker has five pull-down menus to create state diagrams,
generate C/C++, and generate state diagram documentation.   The
menu consists of five categories for operating StateMaker.  They
are File, Draw,  View,  Generate, and List.


                          State Maker +
File      Draw         View        Generate       List
  New       State        Zoom In     C/C++          Record Events
  Open      Transition   Zoom Out    Reverse        Record Actions
  Save      Delete On    Show Text   Add Event      About
  SaveAs    Select On    Show Grid            
  Save To
    Clipboard
  Print   
  Print Text
  Edit Text
  Quit

StateMaker has two toolbars (palettes).  The "Tools Toolbar" has
the following symbols to create state diagrams, view the state
diagram, generate C/C++, and reverse C/C++:

                              State               Transition
                              Zoom In             Zoom Out
                              Open                Save
                              Generate C/C++      Reverse
                              Select On           Delete On
                              Grid                Print

The "Transition Toolbar" has the following symbols to display
transitions between states.   CW refers to the clockwise
direction.  CCW refers to counter clockwise direction. 

                              Straight            
                              Arc-CW              Arc-CCW
                              Bracket-CW          Bracket-CCW
                              Top Loop            Bottom Loop



2.1.File Commands
File commands allow the user to create, open and save a file.  In
addition it will allow the user to print the diagram on the
screen.  Files must be saved with extension *.sm.  Save is
available in the toolbox as well.

                          State Maker +
File      Draw         View        Generate       List
  New          
  Open           
  Save          
  SaveAs      
  Save To
    Clipboard
  Print   
  Print Text
  Edit Text
  Quit

2.1.1.New
This menu command clears the current diagram.

2.1.2.Open
This menu option will open a .sm file.

2.1.3.Save
This option saves a .sm file.  The file contains all information
about the current diagram.  

2.1.4.Save As
This command allows you to save your file under a different  .sm
filename.

2.1.5.Save to Clipboard
This menu option will  save the selected area outlined by the
clipping tool to the clipboard.

2.1.6.Print
This prints out the entire state diagram.  

2.1.7.Print Text
This allows you to print any text file. This includes *.h, *.cpp,
and *.c files.

2.1.8.Edit Text
This command allows you to edit a text file.   The editor is a
Windows editor similar to Windows Notepad.

2.1.9.Quit
This menu option exits the program.  It will ask for a save
first. 

2.2.Draw Commands
Draw commands allow the user to create a state diagram showing
states and transitions.  This menu gives you the option of
creating states and transitions from the menu.   These functions
are also available on the toolbar.

                          State Maker +
File      Draw         View        Generate       List
            State            
            Transition         
            Delete On          
            Select On           
 

2.2.1.State
This menu item brings up the state dialog box to create a state
on the state diagram.  A state is shown as a rectangle or oval
symbol on the state diagram.  A state represents a mode of
behavior, e.g. an OnState, ReadyState, or OffState.  A state is
static, e.g. waiting for an event to arrive.

The user can pick the name, shape and length of the  state here. 
The allowable range for length of shape is 20 to over  100.  When
the user clicks OK, the state placement tool will appear in the
drawing window.  The user can then click with the left mouse on
the place where the user wishes the shape to appear. The user can
then click on the state with the left mouse button and drag the
state anywhere in the window. If the user double clicks with the
left      mouse button on the state, it will bring up the dialog
box for that state.  The user may enter the following:
- State Name, e.g. OffState or OnState,
- Shape of the State Symbol, e.g. Rectangle or Oval,
- Length of the State Symbol, e.g. 20 for a small symbol or 100
for a large symbol,
- Initial State, e.g. Yes or No.

2.2.2.Transition
This menu item brings up the transition dialog box to create a
transition between two states on the state diagram.  It allows
the user to create a transition arrow for connecting two states
together.   A transition is a unique combination of an event,
conditions, and actions.   An event represents a stimulus at a
point in time.  Sample events are TURNON, CHANGE, and TURNOFF.  
Frequently, an event is passed to the object or operation, e.g.
process (Event anEvent).   In C/C++ an event may be implemented
as an object of a C/C++ enumerated type, e.g. EventType.   A
condition is a logical value (true or false) that is valid over a
period of time that affects transition from one state to another
state.  Sample conditions are TEMPERATUREHIGH, TEMPERATUREOK,
TEMPERATURELOW.   A condition is a guard or boolean expression
signifying OK or NOTOK.   In C/C++ a condition is implemented as
follows:
- an object of an enumeration type, e.g. TemperatureStatus,
- an expression, e.g. (temperature == 100), or
- a function that can evaluated as TRUE or FALSE, e.g.
temperatureOK().
A condition is used in an if..then statements e.g. if
TEMPERATUREOK then ........  An action is an operation or
function that is invoked after the event and condition.  Sample
actions are start(), run(), stop().

Choosing the Transition feature in this menu (or on the toolbox)
brings up the Transition Dialog Box. The transition dialog box
provides editing for the following:
- C/C++ Code for Events/Conditions, e.g. (anEvent==CHANGE) &&
(aCondition==TRUE),
- Event Reference Number, e.g. E1
- C/C++ Code for Actions, e.g. cout << "Turn On Actions" or
start();
- Action Reference Number, e.g. A1
- Shape of the Transition Arrow, e.g. Straight, Arc-CW
(Clockwise), Arc-CCW (Counter Clockwise), Bracket-CW,
Bracket-CCW, Top Loop, or Bottom Loop.

To the right of these editing boxes is a reference to the event
and action, respectively.  The event is the "If" part of the
transition.  No if is necessary here, however, if you are going
to generate C code the condition must be supplied with the
various C symbols and variables inside the if  e.g.

     (  (time == 5 )    &&
     (lever == UP)  )  ||
     (temperature != 30)

If the user wishes to use pseudocode instead,  simply substitute
English statements in place of the conditions:
     either time reaches 5 seconds and
     the lever is pressed  or the temperature
     is not 30 degrees.

Actions are the then part of the if statement.  The same rules
for syntax that applied to the events dialog, also apply to the
actions dialog.  You also need to terminate actions with a
semicolon for single or multiple actions e.g:
     turnOnHeat();
     resetTimer();

The assignment for transitioning between states is an action
handled by the program.

After the user clicks OK, the transition drawing tool appears. 
Simply, click the left mouse button on the state you wish to
connect the source of the transition to and drag to the state you
wish to be the destination of the transition.

The Reference Numbers are used to reference the transitions in
the diagram.   They are generated automatically for you, but can
be changed if the user wishes.
     Events are in the form E # .
     Actions are in the form A# .

Transitions are dragged by clicking on the reference text with
the left mouse button and pulling the transition to the desired
location.  The transition can be stretched by clicking on either
the head or tail of the transition.  Double clicking with the
left mouse button on the transition's text will bring up the
dialog box for that transition.

2.2.3.Delete On
This option turns the delete tool on or off, allowing the user to
delete a state or transition from the diagram.  When the delete
"X" comes up, use the left mouse button to click on the undesired
shape.  Go to this menu option to toggle the delete mode off
again.

2.2.4.Select On
This turns the clipping tool on.  The user simply clicks the left
mouse button down in the corner in which the user wishes to clip
and drags to the far corner.  The dotted rectangle borders the
area of clipping.  The user then chooses the File Save to
Clipboard.

2.3.View Commands
View commands presents different ways to view a state diagram. 

                          State Maker +
File      Draw         View        Generate       List
                          Zoom In       
                          Zoom Out        
                          Show Text            
                          Show Grid            

2.3.1.Zoom In
This feature expands the diagram until it is full size.  The
maximum sized diagram shows all class details of attributes and
operations.

2.3.2.Zoom Out
This feature shrinks the diagram.  Zooming out can help you see
more of the diagram, especially if your diagram is very large.

2.3.3.Show Text
This Menu Option allows the user to view the actual text of the
transition in the diagram, instead of the references.   This
option is toggled on and off each time it is selected.   Note:
The diagram will appear on the print out the same way it appears
on the screen.

2.3.4.Show Grid
This Menu Option allows the user to view a grid on the screen.  
Moving shapes inside this grid will cause the states and
transitions to align with the grid points. This option is also
toggled on and off upon selection.

2.4.Generate Commands
Generate commands allows the user to generate C/C++ from the
diagram, create a class diagram from C/C++ code (REVERSE), and
add events.  The menu selections are shown below:

                          State Maker +
File      Draw         View        Generate       List
                                    C/C++         
                                     Reverse       
                                     Add Event    

2.4.1.C/C++
This option brings up the Compiler Options Dialog -  This dialog
is brought up after  the user chooses to generate C/C++ code.  
The dialog allows the user to choose whether or not they want C
or C++, and set the respective function name for C and  the class
and method name for C++.   When the user picks this option, the C
code is generated, and the user is prompted with an options
dialog.  The users is asked to fill in the following information:
- Code Options, e.g. Generate C file or Generate C++ file,
- C Function Name, e.g. process,
- C++ Class Name, e.g. Controller,
- C++ Method Name, e.g. process.

After the user chooses the options they wish, the program will
generate the code and prompt the user  to save the file in a *.c
or *.cpp  ASCII file.  The file can be edited by any ASCII editor
(e.g. notepad.exe).   Upon examining the file, one observes the C
code takes the form of a switch statement.  The cases have the
various state names chosen by the user.  Inside the case block is
the transitional information for events that trigger the
transition, actions that result from triggering a particular
transition, and a transitional assignment to the next state.

2.4.2.Reverse
This option allows the user to take the generated C or C++ code
and turn the code into an updated state diagram.  If the user
writes their own C code in the same switch-case fashion as
StateMaker does,  they can then reverse their own code and
display it as a diagram on the screen.  The user is asked to
enter the following information:
- Filename of the C/C++ file to be reversed, e.g. process.c,
- Directory of the C/C++ file to be reversed, e.g. C:\SM,
- State Symbol Orientation, e.g. Vertical or Circular.

2.4.3.Add Event
This option brings up an event dialog box in which the user can
add event constants.   These events will appear as an enumerated
member of the type Event.   For example, if there are two events
such as START and STOP, then you enter these events in the dialog
box.   Ensure that all events that have been entered on the state
diagram are also entered in the "Add Event Dialog Box".  It is
necessary to enter events in the "Add Event Dialog Box" for code
generation.

2.5.List Commands
List commands permit the creation of text files for events and
actions.  The menu items are shown below.   This allows the user
to generate a XRef list of the transitional information, e.g.
events and actions. 

                          State Maker +
File      Draw         View        Generate       List
                                                    Record Events
                                                    Record Actions
                                                    About

2.5.1.Record Events
This generates a list of all events and conditions in the state
diagram and their references.   The user is asked the following:
- Filename for the list of events and conditions, e.g.
EVENTS.ELS,
- Directory of the file, e.g. C:\SM,
The user may examine this text file with the commands EDIT TEXT
and PRINT TEXT in the FILE pull down menu.

2.5.2.Record Actions
This generates a list of all actions in the state diagram and
their references.   The user is asked the following:
- Filename for the list of actions, e.g. ACTIONS.ALS,
- Directory of the file, e.g. C:\SM,
The user may examine this text file with the commands EDIT TEXT
and PRINT TEXT in the FILE pull down menu.

2.5.3.About
This shows the "About StateMaker" dialog box which indicates the
developer's name and current version number.

3.          Creating a State Diagram with StateMaker

The following is an example that takes you step by step through
creating a state diagram with StateMaker:  The diagram we will
produce is a simple on/off switch state machine:

3.1.Create the States
First let's create the states.  Click on the state tool located
on the upper left hand side of the toolbox.  A state dialog will
come up. Enter ON into the text field and click the Rectangle
radio button.   Click OK and the ON state will appear in the
corner of the window.  Drag the state out to center of the window
by clicking on the state with the mouse and moving the mouse.  
Now repeat the creation process for the OFF state and drag the
OFF state underneath the ON state.

3.2.Create the Transitions
Next we will make the transitions going to and from the states. 
Bring up a transition dialog by clicking on the transition tool
on the upper right hand side of the toolbox.  Now fill in the
edit fields.

Click OK and an arrow should appear in the upper left hand corner
of the screen.  Drag the arrow in between the ON and OFF states
by clicking on the reference text in the center of the arrow,  
and moving the mouse in between the two states.  Stretch the
arrow to the ON and OFF states by first clicking on the endpoint
of the tail of the arrow,  and dragging it inside the ON state.  
Then click on the head of the arrow and drag it inside the OFF
state.  The arrow will automatically be sized by the program to
fit between the states.

Create another transition by filling in the edit fields in the
transition dialog.

Drag this transition in between the ON and OFF state, and drag
the tail to the OFF state and the head of the arrow to the ON
state.

3.3.Display the State Diagram
The final diagram will look something like switch.sm.  By playing 
with some of the display features you can have the same diagram 
show events and actions by selecting "View - Show Text".

3.4.Print and Save the State Diagram
You have now finished a simple state diagram. If you own a
printer,  print out the diagram by going to the file menu and
choosing the print option.  You will be prompted for a title
which will be printed at the top of your diagram.   Save the file
by going to the save option in the lower right hand corner of the
toolbox.  Save the file as mySwitch.sm.

3.5.Generate C Code from the State Diagram
Now that you have drawn your diagram,  you will want to generate
a C file.  Simply choose the  generate option in the lower left
hand corner of the toolbox.  After the C code is generated,   You
will be prompted to save the file with extension *.c.  Save the
file mySwitch.c.  If you examine with the editor you should see
the following listing:


enum Event { NULLEVENT};
enum State { Off, On};

int process(int anEvent)
{
static int aState = Off;

  switch(aState)
  {
  case On:
    if (isToggledDown())
      {
        turnOff();
        aState = Off;
        return aState;
      }

    break;
  case Off:
    if (isToggledUp())
      {
        turnOn();
        aState = On;
        return aState;
      }

    break;

  default:
     return aState;
   }

  return aState;
 }

3.6.Generate C++ from the State Diagram
By selecting the C++  option in the Options dialog you generate
the following C++ code:

class LightSwitch {

public:
     enum State { Off, On};
     enum Event { NULLEVENT};

private:
State aState;

public:

LightSwitch(State InitState = Off){aState = InitState;}
~LightSwitch(){}

int process(Event anEvent = NULLEVENT);
};


int LightSwitch::process(Event anEvent)
{
  switch(aState)
  {
  case On:
    if (isToggledDown())
      {
        turnOff();
        aState = Off;
        return aState;
      }

    break;
  case Off:
    if (isToggledUp())
      {
        turnOn();
        aState = On;
        return aState;
      }

    break;

  default:
     return aState;
   }

  return aState;
 }

This code can now be used by a C compiler to generate object
code.  Note the user needs to provide the C functions such as
turnOn(), and isToggledUp(), but once these are accessible by
switch.c, the code will compile.

3.7.List Events and Actions
To list the events and the actions in the state diagram select
the List menu item.  This is to produce Xreference lists for
the switch.   Choose the List option in the menu and select Record
Events.  Save the cross reference list as switch.els.   The
following xref list for events is produced:

Events

Conditions
E1        isToggledDown()
E2        isToggledUp()

Next choose the List option for Action.  Save the cross reference
as switch.als.  The following xref list is produced:

Actions
A1        turnOff();
A2        turnOn();

3.8.Reverse Code into a State Diagram

After the C/C++ code has been compiled, executed, and tested,
then the C/C++ source code may be updated.  For example, new
events may be added directly in the source code.  New actions may
be added.   Events, conditions, or actions may be revised.  To
ensure the C/C++ source code and the state diagram are
consistent, then the source code may be reversed to create a new
state diagram.

4.      Modeling State Machines with StateMaker Tutorial

The purpose of this tutorial to examine how to model complex
control logic with state diagrams using the StateMaker tool.     
In a soda machine example, the system has event response
behavior that can be modeled with states and transitions.   The
states of a soda vending machine might be "off state", "ready to
dispense soda state", and the "no soda state".   The "soda
selection made event" has a different response based upon the
state of the system.  The response for the "soda selection made
event" in the "no soda state" is a "user notified of no sodas
response".   The response to this event in the "ready to dispense
soda state" is the "soda dispensed response".

Many systems and objects of classes have very simple control in
which each event always results in the same response.   There are
no states or modes of control.  A motor with an "on button" and
an "off button" is an example of a single mode system without
states.  The "on button pressed event" always result in the
"motor turned on response".  The "off button pressed event"
always results in the "motor turned off response".   

However, systems and objects may have states which are modes of
control.  An event may result in different responses depending
upon the current state of the system or object.  An event may
result in a transition to a new state.  A system or class with
states and transitions is called a Finite State Machine.   A
simple example of a finite state machine is a motor with a toggle
switch.  The "toggle event" has different responses depending
whether theToggleSwitch is in the OnState or in the OffState.  In
the OnState the response to the "toggle event" is "motor turned
off".  In the OffState the response to the "toggle event" is
"motor turned on".   

Frequently objects of classes that can be modeled as finite state
machines are called controller objects.   A controller object has
the control logic to select the proper action for each event
depending upon its current state.   A controller object in the
motor with a toggle switch has the control logic to select the
proper action to turn on the motor or to turn off the motor.

In this tutorial we will construct the following documentation
products to describe the event response behavior of a system:
 State Diagram
 State Transition Table

In modeling event response behavior with states and transitions,
we will progress as shown below:

Step 1 -            Step 2 (Optional)             Step 3 -
Create State         Create State                  Generate & Update
Diagram        -->  Transition Table         -->  C++ Source Code

4.1.Creating the State Diagram  (State Transition Diagram)
The state diagram shows complex event response behavior for a
system or objects of a class.  It is a directed graph whose nodes
are states and whose directed arcs are transitions.   The
directed arc shows the event that triggers the transition with
the applicable condition and actions as described below.  

- An event is an occurrence at a point in time that is a stimulus
for a system or  an object.  The events for a car object are
"start event", "operate event", and "stop event".    An event may
 represented as an event object, such as "theStartEvent" or as a
message signifying that the event has occurred such as "start
()".   As an object identity an attributes of the event object.  
As a message identify  any parameters that are passed in the
event message.   An event may be a system event that is passed to
the system being modeled, such as "start".   Alternatively an
event may be an internal event that is sent from an object in the
system, such as "Abnormal Status".

- A condition is a logical value (true or false) that is valid
over a period of time that affects transitions from one state to
another.    A condition is a guard or boolean expression
signifying OK or NOTOK that are used in IF Condition = True THEN
DoSomeAction.  Examples of conditions in a Temperature Class
might be "temperature high" and "temperature OK".  The conditions
for a car object are "GasOK" and "NoGas".

- An action is an operation such as startMotor () in response to
an event.  Actions include updating an attribute, sending a
message, creating or destroying an object, or similar action.  
The actions for a car object are "theMotor.start ()",
"theMotor.operate ()", and "theMotor.stop()".  An action may be
instantaneous such as "theMotor.stop()" or may be continuous
activity, such as "monitor car status".  A continuous activity is
indicated on a state diagram with "do:", such as
"do:monitorCarStatus".   An action may lead to a system response
that is passed from the system, such as "car started".    
Alternatively an action may be an internal response to an
internal event, such as "Correct abnormal status" response to the
internal event "Status abnormal".

-  A state represents a mode of control that has a unique
combination of events, conditions, actions, and next state.  A
state is static, i.e. waiting for an event to occur.  While in a
state, a defined set of rules, laws, and policies apply.  A state
is like a manager or coordinator that knows how to respond to
each event according to his rules, laws, and procedures.  There
is an initial state that is entered when the object is created.  
There is a final state that is entered prior to the object being
destroyed.   The states for a car object are "OffState" and
"OperatingState".   States may be shown in a generalization
specialization hierarchy in which generalization states
(superclasses) define the most general, common behavior and
specialization states (subclasses) define specialized behavior
for an object in the specialization state.

- A transition is a unique pattern of a current state, event,
conditions, actions, and a destination state.  For each state
identify applicable events.  Then for each event  identify the
applicable conditions, actions, and the destination state.

The purpose of the state diagram (state transition diagram) is to
specify event response logic for a system or class of objects.  
It specifies the pattern of event messages, conditions, actions,
and states.    The state diagram for objects of the car class is
shown in car.sm.


     The basic steps to create the state diagram are:

1 - Identify a class, e.g., Car (finite state machine) that has
states, e.g., modes of control.

2 - Identify the states, e.g., OffState and OperatingState.   
Identify the initial state that is entered when an object of the
class is created, e.g. OffState.  Identify a final state that is
entered prior the destruction of an object of the class, e.g.
OffState.

3 - Identify the events.  Represent events as event objects, e.g.
"anEvent = START" or as messages signifying that the event has
occurred, e.g. "start ()".  Identify event object attributes or
event message parameters to hold specific information on an
event..  

4 - Identify the conditions that affect the transition from one
state to another, e.g. "gasStatus = GasOK".

5 - Identify the actions in response to each event, e.g.
"theMotor.start ()".

6 - Identify the transitions from each state to a destination
state.  The transition consists of the triggering event and
applicable conditions and actions.

7 - Walk through the state diagram by simulating each event
occurrence to ensure the correct  actions are invoked and the
correct transitions occur. 

8 - Prototype, test, and iterate.

StateMaker provides the capability to create state diagrams, to
generate C/C++ source code from a state diagram, and to generate
a state diagram from C/C++ source code.   The following are the
steps to create a state diagram with StateMaker:
>> Launch StateMaker.
>> Select "File New" to create a new state diagram.
>> Select "File SaveAs" to save the new state diagram.
>> Enter the events, e.g. TURNON, that will trigger transitions
under "Generate Add Event".
>> Select and place a state icon to represent each state
>> Select a transition icon and enter events, conditions, and
actions.
>> Enter an event, e.g. "(anEvent == TURNON)"
>> Enter a condition, e.g. "&&  (gasStatus == GasOK)"
>> Enter an action, e.g. theMotor.start();  Enter the semicolon.
>> Select "File Save" to save the state diagram.
>> Select "Generate C\C++" to generate source code.
>> After generation, select "File Edit Text" to view and edit the
source code.
>> If desired, enter a test function into the source code to test
the state machine.   In this tutorial the main functions are test
functions.
>> Launch the C/C++ environment to compile, link, and run the
source code.
>> If desired after you have made changes to the source code,
select "Generate Reverse" to recreate the state diagram from the
changed source code

4.2.Creating the State Transition Table

The state transition table shows the event response behavior for
a system or objects of a class in a table form.  It shows the
following:
- states,
- events and conditions,
- actions.

The state transition table complements the state diagram.  When
the state diagram has many states and transitions it becomes very
cluttered and difficult to read.  At this point, it is useful to
create the state transition table that can describe highly
complex systems with a large number of states and transitions.  

The following is a state transition table for objects of the car
class.


               State                    State
               OffState                 OperatingState
Event [Condition]
Start [GasOK]  Action:theMotor.start()  Action: None
               NewState: OperatingState New State: No Change

Start [NoGas]  Action: None             Action: None
               NewState: No Change      New State: No Change

Operate [GasOK]     Action: None        Action:theMotor.operate()
               NewState: No Change      New State: No Change

Operate [NoGas]     Action: None        Action: None
               NewState: No Change      New State: OffState

Stop           Action: None             Action: theMotor.stop()
               NewState: No Change      New State: OffState

     The steps to create the state transition table are as
follows:

1.  Create the state diagram first to identify events,
conditions, actions, and states.

2.  Fill in the state transition table by entering all valid
event [condition] pairs along the top or the side of the table. 

3.  Enter all valid states along the top or the side of the table
opposite the event [condition] pairs.

4.  In each cell of the table enter the action and the
destination state.

5.  Walk-through the table by checking that each event
[condition] pair has the proper action and destination state.  

4.3.Generating C++ Code for State Machines
There are three major ways to code state machines in C++: switch
case method, table lookup method, and the inheritance with
polymorphic operations method.  The following is a sample
generated code from StateMaker that uses the switch case method. 
This C++ code is based upon the state diagram in the previous
section.    The class diagram from WithClass may be created.  
The C++ code from StateMaker are shown below.  Only the 
attributes and operations for the states and transitions are shown.

Listing  C++ code for a state machine.

#include <iostream.h>

class Car
{

public:
     enum State { OperatingState, OffState};
     enum Event { NULLEVENT, START, OPERATE, STOP};

private:
     State aState;
     enum GasStatuses {GasOK, NoGas };
     GasStatuses gasStatus;
     //Motor theMotor;   //Commented out for initial compilation
public:

     Car(State InitState = OperatingState){aState = InitState;}
     ~Car(){}
     int process(Event anEvent = NULLEVENT);
};


int Car::process(Event anEvent)
{
  switch(aState)
  {
  case OffState:
    if ((anEvent == START) && (gasStatus ==GasOK))
      {
      //theMotor.start ();//Commented out for initial compilation
        aState = OperatingState;
        return aState;
      }

    break;
  case OperatingState:
    if ((anEvent == OPERATE) && gasStatus == GasOK)
      {
    //theMotor.operate ();//Commented out for initial compilation
        aState = OperatingState;
        return aState;
      }
    if ((anEvent == OPERATE) && (gasStatus == NoGas))
      {
      //theMotor.stop ();//Commented out for initial compilation
        aState = OffState;
        return aState;
      }
    if ((anEvent == STOP))
      {
      //theMotor.stop ();//Commented out for initial compilation
        aState = OffState;
        return aState;
      }

    break;

  default:
     return aState;
   }

  return aState;
 }


int main () 
{
     Car aCar;
     aCar.process (Car::START);
     aCar.process (Car::OPERATE);
     aCar.process (Car::STOP);
     return 0;
}

4.4.Toggle Switch Example with States and Transitions
The state diagram and C++ for a toggle switch is shown in togglesw.sm.  
C++ code was generated from this state diagram with StateMaker. 
The toggle switch processes the event CHANGE.  It invokes a "turn
on" action from the OffState or a "turn off" action from the
OnState.  The class diagram from WithClass may be created.
With Class is a CASE tool that is used to create class diagrams
and generate C++ code.  With Class is available from MicroGold
Software.

#include <iostream.h>

class ToggleSwitch {

public:
     enum State { OnState, OffState};
     enum Event { NULLEVENT, CHANGE};

private:
State aState;

public:

   ToggleSwitch(State InitState = OffState){aState = InitState;}
     ~ToggleSwitch(){}
     int process(Event anEvent = NULLEVENT);
};


int ToggleSwitch::process(Event anEvent)
{
  switch(aState)
  {
  case OffState:
    if (anEvent ==CHANGE)
      {
        cout << "Turn On Action\n";
        aState = OnState;
        return aState;
      }

    break;
  case OnState:
    if (anEvent ==CHANGE)
      {
        cout << "Turn Off Action\n";
        aState = OffState;
        return aState;
      }

    break;

  default:
     return aState;
   }

  return aState;
 }

 int main ()        //Test function - represents MainUser
{                   //in class diagram
     ToggleSwitch aToggleSwitch;
     cout << "Event is Change\n";
     aToggleSwitch.process (ToggleSwitch::CHANGE);
     cout << "Event is Change\n";
     aToggleSwitch.process (ToggleSwitch::CHANGE);
     return 0;
}

----------------------Sample Output---------------------------
Event is Change
Turn On Action
Event is Change
Turn Off Action

In this tutorial we presented how to model a system or an object
in the system with states and transitions.   Whenever we have a
system or object with complex stimulus response behavior it is
useful to identify states and transitions.   A state diagram
and/or a state table displays the sequence and logic of events
and conditions triggering actions and possibly triggering the
transition to a different state.

5.                 Frequently Asked Questions

1.  What do I do if I get a General Protection Fault?  On rare
occasions StateMaker has a memory conflict with another program
or video driver.  If the GPF occurs on start up, try different
screen resolutions (starting with standard VGA 640x480) and the
lowest number of screen colors (16).  Then increase the screen
resolutions.   Try to obtain the latest video driver from the
manufacturer.  Also, remove any memory resident software. 
Problems have been reported with PC Tools, QEMM, and Diamond
Video cards.  Notify MicroGold of any GPF's including the GPF
number.

2. How do you integrate With Class with StateMaker? Use
StateMaker in C++ mode to generate a method (e.g. process).  Make
a method called process in your state machine class, e.g.
Controller using With Class. Cut and paste the generated code
into With Class's process operation either using the class dialog
or the browser.

3.  How do you create nested states, e.g. states within a state,
in state diagram as discussed by Rumbaugh and Booch?   This
current version of StateMaker does not support nested states.  
To create the state diagram, identify all states, events,
conditions, and actions.   If you have a very large state
diagram, consider partitioning the large state diagram into two
or more smaller state diagrams.   A process function may call
another process function.

6.                         References

Coad, Peter, and Yourdon, Edward, "Object Oriented Analysis" and
"Object Oriented Design", Prentice Hall

Booch, Grady "Object Oriented Design with Applications" The
Benjamin/Cummings Publishing Co

Embley, David, Kurtz, Barry, and Woodfield, Scott "Object
Oriented Systems Analysis - A Model Driven Approach" Yourdon
Press, Englemwood Cliffs, NJ

Felsinger, Richard "Object Oriented Design and Prototyping"
Seminar Notes 
RCF Associates, 960 Scottland Dr, Mt Pleasant, SC 29464

MicroGold Software, "WithClass User Manual" MicroGold Software,
696 Birch Hill Drive, Bridgewater,  NJ, 08807 tele  908 - 722 -
6438

Rumbaugh, Blaha, Premerlani, Eddy, Lorensen "Object-Oriented
Modeling and Design" Prentice Hall

Ward, Paul and Mellor, Steve "Structured Development for
Real-Time Systems", Prentice Hall, Inc.


Ordering Information:
To Order StateMaker Call 1 - 908 - 722 - 6438
Visa/MC accepted.

Or send order to:
MicroGold Software
696 Birch Hill Drive
Bridgewater,  NJ, 08807
1 - 908 - 722 - 6438
CompuServe  71543,1172
Internet 71543.1172@compuserve.com

Acknowledgment: Tutorial provided by Richard Felsinger, RCF
Associates, 960 Scottland Dr, Mt Pleasant, SC 29464 phone
803-881-3648 CompuServe 71162,755 or Internet
71162.755@compuserve.com 

Comments and suggestions on this manual and StateMaker are
requested.   Mike Gold, MicroGold Software, 696 Birch Hill Drive,
Bridgewater, NJ 08807  phone 1-908-722-6438 CompuServe 71543.1172 or
Internet 71543.1172@compuserve.com 















CopyRight Notice
COPYRIGHT 1994 BY MICROGOLD SOFTWARE, ALL RIGHTS RESERVED.  This
manual and the accompanying disk which is described by this
manual are copyrighted and contain proprietary information
belonging to MicroGold Software.  No one may give or sell copies
of this manual or the accompanying disk or of listings of the
programs on the disks to any person or institution, except as
provided by the written consent with MicroGold Software.  No one
may copy or reproduce the diskette without prior permission of
MicroGold Software.  Any person/persons reproducing any portion
of this program shall be guilty of Copyright Violation, and shall
be subject to civil liability at the discretion of the copyright
holder.



Warranty and Liability
Neither MICROGOLD SOFTWARE, nor any distributer of the software
makes any warranty, express or implied, with respect to this
manual, the disk or any related item, their quality, performance,
merchantablility, or fitness for any purpose.  It is the sole
responsibility of the purchaser to determine the suitability of
the products for any purpose.  To the original purchaser only,
MICROGOLD SOFTWARE warrants the media to be free from defects in
material for 90 days.  If during the 90 day period a defect
should occur, the software may be returned to MICROGOLD software,
who will replace the media at no charge.  If after the 90 day
period you media becomes defective, the media may be returned to
MICROGOLD SOFTWARE for replacement at a $10 service charge.  In
no case will MICROGOLD SOFTWARE be held liable for direct,
indirect or incidental damages resulting from any defect in the
disk or omission in the manual, or other related items and
processes, including, but not limited to any interruption of
service, loss of business,  anticipated profit, or other
consequential damages.


1 
