#include <stdio.h>

#define GLOBAL
#include "tuner.h"

char *getenv();

main(argc, argv)
    int argc;
    char **argv;
{
    /*
    ** First check that this isn't a command-line based call.
    */
    if (try_cmd_call(argc, argv))
      exit(0);

    if ( getenv("XENVIRONMENT") == 0 )
#ifdef __STDC__
      putenv("XENVIRONMENT=" RESOURCE_PATH);
#else
      putenv(strcat("XENVIRONMENT=", RESOURCE_PATH));
#endif
    
    init_ui(&argc, argv);

    init_io();

    if ( argc != 1 ) {
	fprintf(stderr, "%s: Warning: extraneous args ignored\n", argv[0]);
	exit(1);
    }
    
    XtRealizeWidget(toplevel);

    XtMainLoop();
}

try_cmd_call(argc, argv)
    int argc;
    char **argv;
{
    int cur=0, list=0, pause=0, cont=0, tune=0;
    
    if ( argc != 2 ) return 0;
    if ( strcmp(argv[1], "-c") == 0 )
      cur = 1;
    else if ( strcmp(argv[1], "-l") == 0 )
      list = 1;
    else if ( strcmp(argv[1], "-P") == 0 )
      pause = 1;
    else if ( strcmp(argv[1], "-C") == 0 )
      cont = 1;
    else if ( strcmp(argv[1], "-?") == 0 ) {
	fprintf(stderr, "Interactive usage: %s [Xt options]\n", argv[0]);
	fprintf(stderr, "Current station:   %s -c\n", argv[0]);
	fprintf(stderr, "List stations:     %s -l\n", argv[0]);
	fprintf(stderr, "Mute radio:        %s -P\n", argv[0]);
	fprintf(stderr, "Unmute radio:      %s -C\n", argv[0]);
	fprintf(stderr, "Change station:    %s name\n", argv[0]);
	exit(1);
    } else if ( argv[1][0] != '-' )
      tune = 1;
    else
      return 0;

    /* Ok, so it is a non-interactive command */
    init_io();
    if ( pause ) {
	do_mute(1);
	return 1;
    }

    if ( cont ) {
	do_mute(0);
	return 1;
    }

    if ( list ) {
	print_stations();
	return 1;
    }

    if ( cur ) {
	print_curstation();
	return 1;
    }

    if ( !do_tune_by_name(argv[1]) ) {
	fprintf(stderr, "%s: %s: no such station\n", argv[0], argv[1]);
	exit(1);
    }
    return 1;
}
