/*

Copyright (C) 2001  Gopal Narayanan <gopal@astro.umass.edu>

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; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.

*/

/* main.c by Gopal Narayanan
 * This file contains the main program.
 */

#include "transcalc.h"
#include "setup_menu.h"
#include <config.h>
#include "help.h"

void usage (void);
char *get_home_directory (void);
char *get_config_directory (void);
char *get_config_filename (void);
char *get_save_filename (void);
void running_for_first_time (void);
extern gint trc_file_load (FILE *, short);

char version[] = "transcalc " VERSION;
GtkWidget *main_body_window;
GtkWidget *transtype_combo;

short current_transtype;
trans_win *twin;
short statusint;
trans_gui *tgui;
gboolean statusexists;
int main_window_width, main_window_height;


/*
 * simple error message
 */
void error_mes(gchar * text)
{
  perror(text);
  exit(-1);
}


void
usage (void)
{
  char *help_txt;
  /* allocate memory for the Help text */
  
  if ((help_txt = (char *) malloc(2000*sizeof(char)))  == NULL){
    perror("help text error: malloc");
    return;
  } else {
    sprintf(help_txt, "\n TRANSCALC %s\n",VERSION);
    strcat(help_txt, HELPTEXT);
  }
  printf("usage: transcalc [-h] [-v] \n");
  printf("%s\n",help_txt);
  exit (0);
}

char *
get_home_directory (void)
{
  char *home = getenv ("HOME");
  
  if (!home) {
#ifndef PLATFORM_WIN32
    /* If HOME is not defined, try getting it from the password
       file.  */
    struct passwd *pwd = getpwuid (getuid ());
    if (!pwd || !pwd->pw_dir)
      return NULL;
    home = pwd->pw_dir;
#else  /* WINDOWS */
    home = ".";
#endif /* WINDOWS */
  }
  return home;
}


char *
get_config_directory (void)
{
  char *config_directory;
  int length =
    strlen (get_home_directory ()) + strlen (TRC_CONFIG_DIRECTORY) + 2;

  config_directory = (char *) calloc (length, sizeof (char));
  sprintf (config_directory, "%s/" TRC_CONFIG_DIRECTORY,
           get_home_directory ());

  return config_directory;
}

char *
get_config_filename (void)
{
  char *config_filename;
  int length = strlen (get_home_directory ()) + strlen (TRC_CONFIG_FILE) + 2;

  config_filename = (char *) calloc (length, sizeof (char));
  sprintf (config_filename, "%s/" TRC_CONFIG_FILE, get_home_directory ());
  return config_filename;
}

char *
get_save_filename (void)
{
  char *save_filename;
  int length = strlen (get_home_directory ()) + strlen (TRC_SAVE_FILE) + 2;

  save_filename = (char *) calloc (length, sizeof (char));
  sprintf (save_filename, "%s/" TRC_SAVE_FILE, get_home_directory ());
  return save_filename;
}

void
running_for_first_time (void)
{
  struct stat *config_file_stat=NULL;
  int config_file_fd;
  char *config_directory = get_config_directory ();
  char *config_filename = get_config_filename ();

#ifndef PLATFORM_WIN32
  if (mkdir (config_directory, TRC_CONFIG_DIRECTORY_MODE) != 0) { 
#else
  if (mkdir (config_directory) != 0) { 
#endif
    /*config dir already there */
    return;
  } else {
      printf ("Config directory %s is absent\n",config_directory);
      printf ("%s created\n", config_directory);
  }
  /* see if config file exists */
  if (stat (config_filename, config_file_stat) != 0) {
    /* config file missing, so touch it */
    config_file_fd = open (config_filename, O_CREAT, 0644);
    if (config_file_fd == -1)
      {
	perror ("open[config_file]");
	exit (-1);
      }
#ifndef PLATFORM_WIN32
    if (fchmod (config_file_fd, TRC_CONFIG_DIRECTORY_MODE) != 0)
        {
          perror ("fchmod[" TRC_CONFIG_FILE "]");
          exit (-1);
        }
#endif
    close (config_file_fd);
    printf ("[%s] created\n\n", config_filename);
  }
  free (config_directory);
  free (config_filename);
}

void
read_config_file (void)
{
  FILE *fp;
  struct stat config_file_stat;
  char buf[256], *ip = NULL, *end = NULL;
  gchar tmp_str1[80];
  char *config_filename = get_config_filename ();

  if (stat(config_filename, &config_file_stat) == 0){
    if (config_file_stat.st_size > 0) { /*not empty file */
      fp = fopen(config_filename, "r");
      do { 
	fgets(buf, 256, fp);
	ip = &buf[0];
	/* skip spaces */
	while ((*ip == ' ') || (*ip == '\t'))
	  ip++;
      }
      while ((*ip == '#') || (*ip == '\n')); /* don't process empty lines */
      
      /* Get the ending position.  */
      for (end = ip; *end && *end != '\n'; end++);
      /* make sure it terminates with '\0' */
      *end = '\0';
      
      sscanf(ip,"%s %hd\n",tmp_str1,&freq_unit);
      fscanf(fp,"%s %hd\n",tmp_str1,&length_unit);
      fscanf(fp, "%s %hd\n",tmp_str1,&res_unit);
      fscanf(fp, "%s %hd\n",tmp_str1,&ang_unit);      
    }
  }
}


  
int 
main( int   argc,
               char *argv[] )
{

  FILE *fpinit;
  char *save_filename = get_save_filename ();


  /* GtkWidget is the storage type for widgets */
  /*         GtkWidget *mainwindow;*/
  /* GtkWidget *button; */
  /*         GtkWidget *vbox1;*/
  /*         GtkWidget *menu;*/
  /*         GtkWidget *body;*/
  
  
  /* This is called in all GTK applications. Arguments are parsed
   * from the command line and are returned to the application. */
  gtk_init(&argc, &argv);
  
   if (argc > 1)
    {
      if (strcmp (argv[1], "--help") == 0 || strcmp (argv[1], "-h") == 0)
        usage ();
      else if (strcmp (argv[1], "--version") == 0
               || strcmp (argv[1], "-v") == 0)
        {
          printf ("%s\n", version);
          exit (0);
        }
    }
 
   /* default values */  
  length_unit = LENGTH_MIL;
  freq_unit = FREQ_GHZ;
  res_unit = RES_OHM;
  ang_unit = ANG_DEG;
  statusint = CONSISTENT;
  statusexists = FALSE;


  running_for_first_time();

  read_config_file ();

  
  /*allocate memory for structure of main GUI */
  tgui = g_malloc(sizeof(*tgui));
  
  /*allocate memory for structure of transmission line window */
  twin = g_malloc(sizeof(*twin));
  
  /* Any command line options for program should follow here */
  
  /* create a new window */
  tgui->mainwindow = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  
  /* set title of main window */
  
  gtk_window_set_title (GTK_WINDOW (tgui->mainwindow), "transcalc");
  
  /* When the window is given the "delete_event" signal (this is given
   * by the window manager, usually by the "close" option, or on the
   * titlebar), we ask it to call the delete_event () function
   * as defined above. The data passed to the callback
   * function is NULL and is ignored in the callback function. */
  gtk_signal_connect (GTK_OBJECT (tgui->mainwindow), "delete_event",
		      GTK_SIGNAL_FUNC (delete_event), NULL);
  
  /* Here we connect the "destroy" event to a signal handler.  
   * This event occurs when we call gtk_widget_destroy() on the window,
   * or if we return FALSE in the "delete_event" callback. */
  gtk_signal_connect (GTK_OBJECT (tgui->mainwindow), "destroy",
		      GTK_SIGNAL_FUNC (destroy), NULL);
  
  /* Sets the border width of the window. */
  gtk_container_set_border_width (GTK_CONTAINER (tgui->mainwindow), 10);
  
  /* Create a virtual vertical box that will hold everything */
  /* First argument - homogeneous, 2nd vert. spacing */
  tgui->vertbox = gtk_vbox_new (FALSE, 0);
  
  
  /* Put this box in the main window */
  gtk_container_add (GTK_CONTAINER (tgui->mainwindow), tgui->vertbox);
  
  
  /* setup the menu */
  tgui->menu = GTK_WIDGET (setup_menu (tgui));
  
  /* setup the main area of calculations */
  tgui->body = setup_body (tgui);

  /* setup the status field at the botttom */
  /*  status = GTK_WIDGET (setup_status (tgui)); 
      statusexists = TRUE; */
  
  gtk_widget_show (tgui->vertbox);
  gtk_widget_show (tgui->mainwindow);


  fpinit = fopen(save_filename, "r");
  g_free (save_filename);
  if (fpinit != NULL) {
    trc_file_load (fpinit, LOAD_INIT);
    gtk_window_set_default_size (GTK_WINDOW (tgui->mainwindow), 
				 main_window_width, main_window_height);
  }
  
  /* All GTK applications must have a gtk_main(). Control ends here
   * and waits for an event to occur (like a key press or
   * mouse event). */
  gtk_main ();
  
  
  /*	 free(twin);*/
  
  return(0);
}
/* end of transcalc main */
