/*
** FILE:	main.c
** PROGRAM:	idev
** VERSION:	1.0
**
** DESCRIPTIPON:
**	This file contains main().  It checks the arguments, creates
**	the reply port and IORequest, and initializes the IORequest
**	through OpenDevice.  It then calls idev() (see idev.[ch])
**	to perform the user interaction.  When idev() returns, the
**	IORequest and reply port are cleaned up, and the device is
**	closed.
**
**	Quit() is the function which handles cleanup.  If fmt is not
**	NULL, an information line of the form:
**		progname: fmt_msg
**	is printed before cleanup.  The extra arguments are passed to
**	printf() for the format string (in case it includes %X's).
**	Finally, exit() is called with exitval.
**
**	Cmdname is set to argv[0] (the name of the program) upon
**	program entry.
**
** HISTORY:
**	26-Aug-87	Original Version   (Ed Puckett)
*/

#include <exec/types.h>
#include <exec/ports.h>
#include <exec/io.h>
#include <exec/devices.h>
#include <stdio.h>

#include "main.h"
#include "idev.h"



char  *cmdname;

static BOOL  devopen = FALSE;

static struct MsgPort	*devport = NULL;
static struct IOStdReq	*ioreq	 = NULL;



void  main (argc, argv)

int   argc;
char  *argv[];

{ char		   *devname;
  int		   unitnum;
  ULONG 	   flags;
  int		   error;
  ULONG 	   getnum();
  void		   usage();
  struct MsgPort   *CreatePort();
  struct IOStdReq  *CreateExtIO();


  if (argc == 0)
    exit (0);		/* don't run from WB */


  cmdname= argv[0];

  if (argc != 4)
    usage ();

  devopen= FALSE;
  devport= NULL;
  ioreq=   NULL;

  devname= argv[1];
  unitnum= getnum (argv[2], "unitnum");
  flags=   getnum (argv[3], "flags");


  if ((devport= CreatePort (NULL, 0)) == NULL)
    quit (Q_RSRCERR, "can't create message port", 0, 0, 0);

  if ((ioreq= CreateExtIO (devport, IOREQSIZE)) == NULL)
    quit (Q_RSRCERR, "can't create I/O request", 0, 0, 0);

  if ((error= OpenDevice (devname, unitnum, ioreq, flags)) != 0)
    quit (Q_RSRCERR, "can't open device \"%s\"; error = %d", (int) devname, error, 0);

  devopen= TRUE;


  idev (devname, unitnum, ioreq, flags);


  quit (Q_OK, NULL, 0, 0, 0);
}



void  quit (exitval, fmt, arg1, arg2, arg3)

int   exitval;
char  *fmt;
int   arg1, arg2, arg3;

{ if (fmt != NULL)
    { fprintf (stderr, "%s: ", cmdname);
      fprintf (stderr, fmt, arg1, arg2, arg3);
      fputs ("\n", stderr);
    }

  if (devopen)
    { CloseDevice (ioreq);
      devopen= FALSE;
    }

  if (ioreq != NULL)
    { DeleteExtIO (ioreq, IOREQSIZE);
      ioreq= NULL;
    }

  if (devport != NULL)
    { DeletePort (devport);
      devport= NULL;
    }

  exit (exitval);
}



static void  usage ()

{ fprintf (stderr, "Usage: %s devname unitnum flags\n", cmdname);
  quit (Q_USAGE, NULL, 0, 0, 0);
}



static ULONG  getnum (str, varname)

char   *str;
char   *varname;

{ ULONG  num;

  if (sscanf (str, "%ld", &num) != 1)
    quit (Q_ARGERR, "%s must be an integer", varname, 0, 0);

  return num;
}

