/* (C)1999-2000 Dr. Aleksander Malinowski, Bradley University
    olekmali at bradley dot edu, http://gdansk.bradley.edu/olekmali/

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, version 2 of the License.

    The full text of the license follows the source code
*/

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.applet.Applet;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.URL;

public class tbClient extends Applet implements WindowListener,
                    ActionListener, AdjustmentListener,
                    MouseListener, MouseMotionListener {

    private static boolean PrintLog=false;
            static String  VersionString = "WebBot Interface v. 1.33, April 29, 2000";
    private static String  TitleString   = "Bradley University Office Explorer";

    public static void log(String line) {
        if (PrintLog) System.out.println(line);
    }

    public static void main(String[] args) {
        Frame F=new Frame("WebBot Controller");
        tbClient C=new tbClient();
        F.setSize(750, 500);
        F.addWindowListener(C);
        F.add(C);
        C.init();
        C.PrintLog=true;
        C.start();
        F.setVisible(true);
    }

    // Client-server parameters
    private static final String  imgLocDefault   = "http://gdansk.bradley.edu/webcam/";
//  private static final String  imgLocDeafault  = "http://localhost/webcam/";
                         String  imgLoc          = null;
    private static final int     timSlMsDefault  = 1000;
                         int     timSlMs         = 1000;
    private static final String  srvLocDefault   = "gdansk.bradley.edu";
//  private static final String  srvLocDefault   = "localhost"; // enable only for testing
                         String  srvLoc          = null;
    private static final int     srvPortDefault  = 8051;
                         int     srvPort         = 8051;
    //  Robot control parameters
    private static final int     timToutDefault  = 10;
                         int     timTout         = 10;
    private static final int     senMoveDefault  = 25;
                         int     senMove         = 25;

    // GUI
    tbImage WC;
    tbTextArea LOG;
    Button bGoLeft, bGo, bGoRight, bLeft, bStop, bRight, bBackLeft, bBack, bBackRight;
    Button b1on, b2on, b3on, b4on, b1off, b2off, b3off, b4off;
    Button stat;
    Label     lSens;
    Scrollbar sSens;

    // Connection
    Socket          SOCK=null;
    PrintWriter     SEND=null;
    BufferedReader  RECV=null;
    boolean         conn=false;

    private void Connect() {
        tbClient.log("START: connecting to WebBot server...");
        try {
            SOCK=new Socket(srvLoc, srvPort);
            SEND=new PrintWriter(SOCK.getOutputStream());
            RECV=new BufferedReader(new InputStreamReader(SOCK.getInputStream()));
            conn=true;
            tbClient.log("START: connected to WebBot server");
            LOG.start();
        } catch (Exception e) {
            SOCK=null;
            SEND=null;
            RECV=null;
            conn=false;
            tbClient.log("ERROR: connecting to WebBot server failed - "+e);
            LOG.append("! cannot connect to the robot.");
            LOG.append("! reported: "+e);
            LOG.append("\tPossible causes:\n\t- server is down\n\tInternet connection lost\n\tYou are behind a fire wall");
        }
    }


    public void ReportConnectionLost() {
        tbClient.log("LOG: connection loss reproted");
        SOCK=null;
        SEND=null;
        RECV=null;
        conn=false;
        setEnabledControlPanel(false);
    }

    public void setEnabledControlPanel(boolean status) {
        bGoLeft.setEnabled(status);
        bGo.setEnabled(status);
        bGoRight.setEnabled(status);
        bLeft.setEnabled(status);
        bStop.setEnabled(status);
        bRight.setEnabled(status);
        bBackLeft.setEnabled(status);
        bBack.setEnabled(status);
        bBackRight.setEnabled(status);
        b1on.setEnabled(status);
        b2on.setEnabled(status);
        b3on.setEnabled(status);
        b4on.setEnabled(status);
        b1off.setEnabled(status);
        b2off.setEnabled(status);
        b3off.setEnabled(status);
        b4off.setEnabled(status);
        if (status) {
            tbClient.log("LOG: control panel activated");
            stat.setLabel("status report");
        } else {
            tbClient.log("LOG: control panel deactivated");
            stat.setLabel("regain control");
        }
}

    private Panel CreateControlPanel() {
        Panel CP=new Panel();
        CP.setLayout(new GridLayout(3,1, 10, 10));

        // assuming that LOG is already created by start();
        CP.add(LOG);

        // create the direction buttons
        // and direction button subpanel
        bGoLeft   =new Button("go left");
        bGo       =new Button("go");
        bGoRight  =new Button("go right");
        bLeft     =new Button("turn left");
        bStop     =new Button("STOP");
        bRight    =new Button("turn right");
        bBackLeft =new Button("back left");
        bBack     =new Button("back");
        bBackRight=new Button("back right");
        bGoLeft.addActionListener(this);
        bGo.addActionListener(this);
        bGoRight.addActionListener(this);
        bLeft.addActionListener(this);
        bStop.addActionListener(this);
        bRight.addActionListener(this);
        bBackLeft.addActionListener(this);
        bBack.addActionListener(this);
        bBackRight.addActionListener(this);

        lSens=new Label(senMove+"%", Label.RIGHT);
        sSens=new Scrollbar(Scrollbar.HORIZONTAL, senMove, 5, 0, 105);
        sSens.addAdjustmentListener(this);

        {
            Panel PSEN=new Panel();
            {
                PSEN.setLayout(new GridLayout(2,1, 0,0));
                PSEN.add(lSens);
                PSEN.add(sSens);
            }
            Panel PBUT=new Panel();
            PBUT.setLayout(new GridLayout(4,1, 5,5));
            Panel PBR1=new Panel();
            PBR1.setLayout(new GridLayout(1,3, 5,5));
            Panel PBR2=new Panel();
            PBR2.setLayout(new GridLayout(1,3, 5,5));
            Panel PBR3=new Panel();
            PBR3.setLayout(new GridLayout(1,3, 5,5));
            PBR1.add(bGoLeft);
            PBR1.add(bGo);
            PBR1.add(bGoRight);
            PBR2.add(bLeft);
            PBR2.add(bStop);
            PBR2.add(bRight);
            PBR3.add(bBackLeft);
            PBR3.add(bBack);
            PBR3.add(bBackRight);
            PBUT.add(PBR1);
            PBUT.add(PBR2);
            PBUT.add(PBR3);
            PBUT.add(PSEN);
            CP.add(PBUT);
        }

        // create the on-off buttons
        // and direction button subpanel
        b1on =new Button("A");
        b2on =new Button("B");
        b3on =new Button("C");
        b4on =new Button("D");
        b1on.addActionListener(this);
        b2on.addActionListener(this);
        b3on.addActionListener(this);
        b4on.addActionListener(this);
        b1off=new Button("A");
        b2off=new Button("B");
        b3off=new Button("C");
        b4off=new Button("D");
        b1off.addActionListener(this);
        b2off.addActionListener(this);
        b3off.addActionListener(this);
        b4off.addActionListener(this);

        {
            Panel SWPAN=new Panel();
            SWPAN.setLayout(new GridLayout(5,1, 5,5));
            SWPAN.add(new Label("", Label.CENTER));
            Panel SWON=new Panel();
            SWON.setLayout(new GridLayout(1,5, 5,5));
            SWON.add(b1on);
            SWON.add(b2on);
            SWON.add(new Label("on", Label.CENTER));
            SWON.add(b3on);
            SWON.add(b4on);
            SWPAN.add(SWON);
            Panel SWOF=new Panel();
            SWOF.setLayout(new GridLayout(1,5, 5,5));
            SWOF.add(b1off);
            SWOF.add(b2off);
            SWOF.add(new Label("off", Label.CENTER));
            SWOF.add(b3off);
            SWOF.add(b4off);
            SWPAN.add(SWOF);
            stat=new Button("report status");
            stat.addActionListener(this);
            SWPAN.add(stat);
            SWPAN.add(new Label(tbClient.VersionString, Label.CENTER));
            CP.add(SWPAN);
        }

        return(CP);
    }


    private String getParamOrDefault(String name, String def) {
        String p=def;
        try {
            p=getParameter(name);
        } catch (Exception e) {
            p=def;
        }
        tbClient.log("PARAM: "+name+"="+p);
        return(p);
    }

    private int getParamOrDefault(String name, int def) {
        int p=def;
        try {
            p=Integer.parseInt(getParameter(name), 10);
        } catch (Exception e) {
            p=def;
        }
        tbClient.log("PARAM: "+name+"="+p);
        return(p);
    }

    public void init() {
        tbClient.log("INIT: getting applet parameters...");
        PrintLog=(getParamOrDefault("client-debug","false").equals("true"));
        imgLoc =getParamOrDefault("image-location",  imgLocDefault);
        timSlMs=getParamOrDefault("image-refresh",   timSlMsDefault);
        srvLoc =getParamOrDefault("server-location", srvLocDefault);
        srvPort=getParamOrDefault("server-port",     srvPortDefault);
        timTout=getParamOrDefault("control-tout",    timToutDefault);
        senMove=getParamOrDefault("control-sens",    senMoveDefault);

        tbClient.log("INIT: starting all services...");

        // Client command log text area
        LOG=new tbTextArea(this);

        // Transmitted image canvas
        WC=new tbImage(imgLoc, timSlMs);
        WC.addMouseListener(this);
        // WC.addMouseMotionListener(this); not used for now

        setLayout(new BorderLayout(20,20));

        Label title=new Label(tbClient.TitleString, Label.CENTER);
        title.setFont(new Font("Helvetica", Font.BOLD, 24));
        title.setForeground(new Color(0,0,128));
        add("North",  title);
        add("East",  new Label(""));
        Panel CP=new Panel();
        CP.setLayout(new BorderLayout(20,20));
        CP.add("Center", WC);
        CP.add("East", CreateControlPanel());
        add("Center", CP);
        add("South", new Label(""));
        add("West",  new Label(""));
        setVisible(true);

        tbClient.log("INIT: new GUI created");
    }


    public void start() {
        tbClient.log("START: starting all services...");
        setEnabledControlPanel(true);
        WC.start();

        Connect(); // also starts LOG

        // enable controls only if connected!
        setEnabledControlPanel(conn);

        tbClient.log("START: all services started...");
        LOG.append("! services started");
    }

    public void stop() {
        tbClient.log("STOP: stopping all services...");
        setEnabledControlPanel(false);

        tbClient.log("STOP: stopping image acquisition...");
        WC.stop();

        tbClient.log("STOP: stopping command log...");
        LOG.stop();

        tbClient.log("STOP: disconnecting from WebBot server...");
        conn=false;
        try { SEND.close(); } catch (Exception e) { } 
        try { RECV.close(); } catch (Exception e) { } 
        try { SOCK.close(); } catch (Exception e) { } 
        SOCK=null; SEND=null; RECV=null;

        tbClient.log("STOP: applet PROBABLY stopped by now");
    }

    private void SendCommand(String command) {
        if (SOCK==null||SEND==null) return;
        try {
            SEND.println(command);
            SEND.flush();
            LOG.append("->"+command);
            tbClient.log("COMMAND: "+command+" sent");
        } catch (Exception e) {
            tbClient.log("ERROR: "+command+" "+e);
            LOG.append("! connection to server lost");
            ReportConnectionLost();
        }
    }


// INTERFACE ActionListener -------
    public void actionPerformed(ActionEvent e) {
        final int duration=senMove*timTout;
        if (e.getSource()==bGoLeft) {
            SendCommand("go left "+duration);
        }
        else if (e.getSource()==bGo) {
            SendCommand("go straight "+duration);
        }
        else if (e.getSource()==bGoRight) {
            SendCommand("go right "+duration);
        }
        else if (e.getSource()==bLeft) {
            SendCommand("turn left "+duration);
        }
        else if (e.getSource()==bStop) {
            SendCommand("stop 1");
        }
        else if (e.getSource()==bRight) {
            SendCommand("turn right "+duration);
        }
        else if (e.getSource()==bBackLeft) {
            SendCommand("back left "+duration);
        }
        else if (e.getSource()==bBack) {
            SendCommand("back straight "+duration);
        }
        else if (e.getSource()==bBackRight) {
            SendCommand("back right "+duration);
        }
        else if (e.getSource()==b1on) {
            SendCommand("switch 1 on");
        }
        else if (e.getSource()==b2on) {
            SendCommand("switch 2 on");
        }
        else if (e.getSource()==b3on) {
            SendCommand("switch 3 on");
        }
        else if (e.getSource()==b4on) {
            SendCommand("switch 4 on");
        }
        else if (e.getSource()==b1off) {
            SendCommand("switch 1 off");
        }
        else if (e.getSource()==b2off) {
            SendCommand("switch 2 off");
        }
        else if (e.getSource()==b3off) {
            SendCommand("switch 3 off");
        }
        else if (e.getSource()==b4off) {
            SendCommand("switch 4 off");
        }
        else if (e.getSource()==stat) {
            if (!conn) {
                Connect();
                // enable controls only if connected!
                if (conn) setEnabledControlPanel(true);
            }
            SendCommand("status");
        }
        else {
            tbClient.log("COMMAND: unknown!");
            LOG.append("! unrecognized event");
        }
    }

// INTERFACE MouseListener --------
    public void mouseClicked(MouseEvent e)        {
        final Rectangle r=WC.getBounds();
        final int cx=e.getX();
        final int cy=e.getY();

                              // senMove is within 0..100 range
        final int sensitivity=20*senMove;
        final int px= sensitivity*(cx-r.width/2 )/r.width;
        final int py=-sensitivity*(cy-r.height/2)/r.height;

        SendCommand("move "+py+" "+px);
    }
    public void mousePressed(MouseEvent e)        {}
    public void mouseReleased(MouseEvent e)       {}
    public void mouseEntered(MouseEvent e)        {}
    public void mouseExited(MouseEvent e)         {}
// INTERFACE MouseMotionListener --
    public void mouseMoved(MouseEvent e)          {}
    public void mouseDragged(MouseEvent e)        {}

// INTERFACE AdjustmentListener -------
    public void adjustmentValueChanged(AdjustmentEvent e) {
        if (e.getSource()!=sSens) return;
        senMove=e.getValue();
        lSens.setText(senMove+"%");
    }

// INTERFACE WindowListener -------
    public void windowClosing(WindowEvent e)      { stop(); System.exit(0); }
    public void windowClosed(WindowEvent e)       {  }
    public void windowOpened(WindowEvent e)       {  }
    public void windowIconified(WindowEvent e)    { WC.pause();  }
    public void windowDeiconified(WindowEvent e)  { WC.resume(); }
    public void windowActivated(WindowEvent e)    {  }
    public void windowDeactivated(WindowEvent e)  {  }
}









class tbImage extends Canvas implements Runnable {

    // parameters
    private String imgLoc;
    private int    tmSlMs;

    // variables
    private MediaTracker MT     = null;
    private Image    webcam     = null;
    private Thread   process    = null;
    private boolean  pause      = false;

    tbImage(String loc, int wait) {
        super();
        imgLoc=loc;
        tmSlMs=wait;
        MT=new MediaTracker(this);
    }

    public void start() {
        if (process!=null) return;
        process=new Thread(this,"Image Update");
        tbClient.log("IMAGE: thread starting...");
        process.start();
    }

    public void pause() {
        tbClient.log("IMAGE: update paused...");
        pause=true;
    }

    public void resume() {
        tbClient.log("IMAGE: update resumed...");
        pause=false;
    }

    public void stop() {
        tbClient.log("IMAGE: thread stop requested");
        if (process==null) return;
        Thread tokill=process;
        process=null;
        tokill.interrupt();
        try {
            tokill.join(100);
        } catch (Exception e) {
            tbClient.log("IMAGE: thread cannot stop in 100ms");
        }
    }

    public void run() {
        tbClient.log("IMAGE: thread started for sure");
        while(Thread.currentThread()==process) {
            if (pause) {
                try {
                    Thread.currentThread().sleep(100);
                } catch (Exception e) { }
            } else {
                try {
// tbClient.log("IMAGE: downloading...");
                    // remove the previous image from cache
                    if (webcam!=null) webcam.flush();
                    // get a new image by location
                    webcam = getToolkit().getImage(new URL(imgLoc));
                    // wait for downloading the image
                    // -- extra time added to thread.sleep()
                    MT.addImage(webcam,0);
                    MT.waitForAll();
                    MT.removeImage(webcam,0);
// tbClient.log("IMAGE: refreshing...");
                } catch(Exception e) {
                    webcam=null;
                    tbClient.log("IMAGE: "+e+"!");
                }
                repaint();
                try {
// tbClient.log("IMAGE: sleeping...");
                    Thread.currentThread().sleep(tmSlMs);
                } catch (Exception e) { }
            }
        }
        tbClient.log("IMAGE: thread commenced");
    }

    public void paint(Graphics g) {
        final Rectangle r=getBounds();
        g.drawRect(1,1,r.width-2,r.height-2);
        if (webcam!=null) {
            int wi=webcam.getWidth(this);
            int hi=webcam.getHeight(this);
            int w1=(r.width -wi)/2;
            int h1=(r.height-hi)/2;

            int w2=w1+wi;
            int h2=h1+hi;
            g.clearRect(2, 2, r.width-3,h1-3);
            g.clearRect(2, h1,w1-3,hi);
            g.clearRect(w2,h1,w1-3,hi);
            g.clearRect(2,h2+1,r.width-3,h1-3);

            g.drawImage(webcam, w1, h1, this);
        }
    }

    public void update(Graphics g) {
        paint(g);
    }
}









class tbTextArea extends TextArea implements Runnable {

    private tbClient PARENT  = null;
    private Thread   process = null; // not running yet

    tbTextArea(tbClient parent) {
        super("", 4, 10, TextArea.SCROLLBARS_VERTICAL_ONLY);
        setEditable(false);
        setFont(new Font("Times", Font.BOLD, 10));
        PARENT=parent;
    }


    public void append(String line) {
        super.append(line+"\n");
    }


    public void start() {
        if (process!=null) return; // do not start if already running
        process=new Thread(this,"Command Log");
        tbClient.log("LOG: thread starting");
        process.start();
    }

    public void stop() {
        tbClient.log("LOG: thread stop requested");
        Thread tokill=process;
        process=null;
        tokill.interrupt();
        try {
            tokill.join(100);
        } catch (Exception e) {
            tbClient.log("LOG: thread cannot stop in 100ms");
        }
    }

    public void run() {
        tbClient.log("LOG: thread started for sure");
        try {
            while (Thread.currentThread()==process) {
                if (PARENT.RECV.ready()) {
                    String line=(PARENT.RECV).readLine();
                    append(line);
//tbClient.log("LOG: "+line);
                } else {
                    try {
                        Thread.currentThread().sleep(20);
                    } catch (Exception e) { }
                }
            }
        } catch (Exception e) {
            append("* connection lost");
            tbClient.log("LOG: connection lost - disabling controls");
        }
        process=null;
        PARENT.ReportConnectionLost();
        tbClient.log("LOG: thread commenced");
    }

}



/*          GNU GENERAL PUBLIC LICENSE
               Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
                          675 Mass Ave, Cambridge, MA 02139, USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

            GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this Licens