/**************************************************************
 * Structured Markov Chains Solver       [  SMCSolver  ]      *
 * Dario Bini, Beatrice Meini, Sergio Steffe'                 *
 * bini@dm.unipi.it, meini@dm.unipi.it, steffe@dm.unipi.it    *
 * Dipartimento di Matematica "Leonida Tonelli"               *
 * Largo Pontecorvo 5                                         *
 * 56127 Pisa                                                 *
 * Italy                                                      *
 * Version 1.1 - Oct 2006                                     *
 **************************************************************
 *
 *  rw.c - reading and writing data files - both callbacks and interfaces
 *
 */

#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>   /* opendir */
#include <sys/stat.h> /* mkdir */
#include <unistd.h>
#include <pthread.h>
#include <libgen.h>
#include <gtk/gtk.h>
#include <errno.h>
#include <ctype.h> /* character functions */
#include <string.h>
#include <stdlib.h>
#include <math.h>

#include "structures.h"
#include "rw.h"
#include "icons.h"

/* Save NotePad: File Selection Dialog ***** Interface */
GtkWidget*
create_fileselection1 (void)
{
  GtkWidget *fileselection;
  GtkWidget *ok_button;
  GtkWidget *cancel_button;

  fileselection = gtk_file_selection_new ("Append the NotePad to a File");
  gtk_container_set_border_width (GTK_CONTAINER (fileselection), 10);

  ok_button = GTK_FILE_SELECTION (fileselection)->ok_button;
  gtk_widget_show (ok_button);
  GTK_WIDGET_SET_FLAGS (ok_button, GTK_CAN_DEFAULT);

  cancel_button = GTK_FILE_SELECTION (fileselection)->cancel_button;
  gtk_widget_show (cancel_button);
  GTK_WIDGET_SET_FLAGS (cancel_button, GTK_CAN_DEFAULT);
  gtk_button_box_set_layout (GTK_BUTTON_BOX (GTK_DIALOG (fileselection)->action_area), GTK_BUTTONBOX_SPREAD);

  g_signal_connect ((gpointer) ok_button, "clicked", G_CALLBACK (on_ok_button_fs1_clicked), NULL);
  g_signal_connect ((gpointer) fileselection, "destroy", G_CALLBACK (on_destroy_fs1),NULL); 
  g_signal_connect ((gpointer) cancel_button, "clicked", G_CALLBACK (on_cancel_button_fs1_clicked), NULL);

  return fileselection;
}
/*******************************/

/* SaveNotePad (fs1) File Selectio Dialog: ok  ***** Callback */
void
on_ok_button_fs1_clicked      (GtkButton   *button, gpointer  user_data)
{
/* GtkWidget *appendsave; global */
/* GtkWidget *statusb; global    */
/* GtkWidget *textview; global   */
gchar * filename;
FILE * appendfile;
GtkTextBuffer *buffer_pad;
GtkTextIter start,end;
gint nchar, nn;

/* Extract filename from the file selection dialog */
filename = (gchar *) gtk_file_selection_get_filename(GTK_FILE_SELECTION(appendsave));
if ((appendfile = fopen(filename,"a+")) == NULL) {
       /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(appendsave));
        }
else {
/* File is ok, close window and attempt to write */
        is_savepad_open=0;
        gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
        buffer_pad = (GtkTextBuffer *) gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview));
        nchar = gtk_text_buffer_get_char_count (buffer_pad);
        gtk_text_buffer_get_start_iter(buffer_pad,&start);
        gtk_text_buffer_get_end_iter(buffer_pad,&end);
        nn=fwrite(gtk_text_buffer_get_text (buffer_pad,&start,&end,0),1,nchar,appendfile);
        fclose(appendfile);
/* notify ok or error */
        if (nn==nchar) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Notepad Appended to file");
        else
        gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Notepad NOT Appended to file! ***");
        }
}
/**********************************/

/* SaveNotePad (fs1) File Selectio Dialog: cancel ***** Callback */
void
on_cancel_button_fs1_clicked  (GtkButton   *button, gpointer   user_data)
{
if(is_debug==1) printf("Save NotePad File Selection Dialog: quit\n");
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
}
/******************************/

/* SaveNotePad (fs1) File Selectio Dialog: destroy ***** Callback */
void
on_destroy_fs1  (GtkWidget *ww, gpointer   user_data)
{
if(is_debug==1) printf("on_destroy_fs1:\n");
is_savepad_open=0;
}
/******************************/


/* Save G: File Selection Dialog Interface  ***** Interface */
GtkWidget*
create_fileselection_g(void)
{
GtkWidget *fileselection;
GtkWidget *ok_button;
GtkWidget *cancel_button;
GtkWidget *button1,*button2,*button3;
GtkWidget *hbox1,*hbox2,*hbox3;
GtkWidget *label1,*label2,*label3;
/* all this mess to show the icon we want in the buttons OK */
GtkWidget *pixmapwid1,*pixmapwid2,*pixmapwid3;
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkStyle *style;
GdkColormap *mappacolor;
/* end  mess                                             */

fileselection = gtk_file_selection_new ("Save G in a File");
gtk_container_set_border_width (GTK_CONTAINER (fileselection), 10);
gtk_file_selection_set_filename (GTK_FILE_SELECTION(fileselection),pathgru_fs);

ok_button = GTK_FILE_SELECTION (fileselection)->ok_button;
gtk_widget_hide (ok_button);
/* GTK_WIDGET_SET_FLAGS (ok_button, GTK_CAN_DEFAULT);*/

cancel_button = GTK_FILE_SELECTION (fileselection)->cancel_button;
gtk_widget_show (cancel_button);
GTK_WIDGET_SET_FLAGS (cancel_button, GTK_CAN_DEFAULT);

/* build out icons */
style = gtk_widget_get_style(fileselection);
mappacolor = gdk_colormap_get_system ();
pixmap =gdk_pixmap_colormap_create_from_xpm_d(fileselection->window,mappacolor,&mask,&style->bg[GTK_STATE_NORMAL],stock_ok_20);
pixmapwid1 = gtk_pixmap_new(pixmap,mask);
pixmapwid2 = gtk_pixmap_new(pixmap,mask);
pixmapwid3 = gtk_pixmap_new(pixmap,mask);
gtk_widget_show(pixmapwid1);
gtk_widget_show(pixmapwid2);
gtk_widget_show(pixmapwid3);
/*  
button_new = gtk_dialog_add_button(GTK_DIALOG(fileselection),"Maple\nOK",GTK_RESPONSE_DELETE_EVENT);
*/
label1 = gtk_label_new("Matlab\nASCII");
label2 = gtk_label_new("Fortran\nASCII\n(2dim+data)");
label3 = gtk_label_new("Fortran\nASCII\n(1dim+data)");
gtk_widget_show(label1);
gtk_widget_show(label2);
gtk_widget_show(label3);

hbox1 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox1), pixmapwid1, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox1), label1, TRUE, TRUE, 0);
gtk_widget_show(hbox1);
button1= gtk_button_new();
gtk_container_add (GTK_CONTAINER(button1),hbox1);
gtk_widget_show(button1);
hbox2 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox2), pixmapwid2, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), label2, TRUE, TRUE, 0);
gtk_widget_show(hbox2);
button2= gtk_button_new();
gtk_container_add (GTK_CONTAINER(button2),hbox2);
gtk_widget_show(button2);
hbox3 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox3), pixmapwid3, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), label3, TRUE, TRUE, 0);
gtk_widget_show(hbox3);
button3= gtk_button_new();
gtk_container_add (GTK_CONTAINER(button3),hbox3);
gtk_widget_show(button3);

/* GTK_RESPONSE_DELETE_EVENT */
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button1,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button2,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button3,GTK_RESPONSE_DELETE_EVENT);

/* g_signal_connect ((gpointer) ok_button, "clicked", G_CALLBACK (on_ok_button_fsg_clicked), NULL); */
g_signal_connect ((gpointer) cancel_button, "clicked", G_CALLBACK (on_cancel_button_fsg_clicked), NULL);
g_signal_connect ((gpointer) fileselection, "destroy", G_CALLBACK (on_destroy_fsg),NULL);
g_signal_connect ((gpointer)button1,"clicked", G_CALLBACK (on_ok1_button_fsg_clicked), NULL);
g_signal_connect ((gpointer)button2,"clicked", G_CALLBACK (on_ok2_button_fsg_clicked), NULL);
g_signal_connect ((gpointer)button3,"clicked", G_CALLBACK (on_ok3_button_fsg_clicked), NULL);
return fileselection;
}
/***********************************/

/* Save G File Selection Dialog: ok1 ***** Callback  Matlab ASCII matrix*/
void
on_ok1_button_fsg_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveg_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_saveg_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result; 

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveg_fs));
if(is_debug) printf("on_ok1_button_fsg_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveg_fs); 
        gtk_widget_show(overwrite_dialog); 
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0; 
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok1_button_fsg_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup */
        gtk_widget_show(create_dialog_nowritable(saveg_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
for(i=1;i<=completed.dimension_m;i++) {
                    for(j=1;j<=completed.dimension_m;j++) { /* write the row in one line */
                           read_matg_(&i,&j,&r);   
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
		    if(fprintf(savefile,"\n") <0) err=1;
           }
fprintf(savefile,"\n");
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_saveg_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save G */
}    
/******************************/
 
/* Save G File Selection Dialog: ok2 ***** 2dims+data ASCII Callback */
void
on_ok2_button_fsg_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveg_fs; global    */
/* struct running_problem_str  completed;    */
/* int is_saveg_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveg_fs));
if(is_debug) printf("on_ok2_button_fsg_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveg_fs);
        gtk_widget_show(overwrite_dialog); 
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0; 
               }
        gtk_widget_destroy(overwrite_dialog); 
        if (is_debug==1) printf("on_ok2_button_fsg_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saveg_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
if(fprintf(savefile," %d %d\n",completed.dimension_m,completed.dimension_m) <0) err=1;
for(i=1;i<=completed.dimension_m;i++) for(j=1;j<=completed.dimension_m;j++) { /* column1, column2, ..... */
         read_matg_(&j,&i,&r);
           if(fprintf(savefile,digits_to_save,r) <0) err=1;
           }
fprintf(savefile,"\n");
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_saveg_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save G */
}
/******************************/

/* Save G File Selection Dialog: ok3 ***** 1dim+data ASCII Callback */
void
on_ok3_button_fsg_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveg_fs; global    */
/* struct running_problem_str  completed;    */
/* int is_saveg_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveg_fs));
if(is_debug) printf("on_ok3_button_fsg_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveg_fs);
        gtk_widget_show(overwrite_dialog); 
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0; 
               }
        gtk_widget_destroy(overwrite_dialog); 
        if (is_debug==1) printf("on_ok3_button_fsg_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saveg_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
if(fprintf(savefile," %d\n",completed.dimension_m) <0) err=1;
for(i=1;i<=completed.dimension_m;i++) for(j=1;j<=completed.dimension_m;j++) { /* column1, column2, ..... */
         read_matg_(&j,&i,&r);
           if(fprintf(savefile,digits_to_save,r) <0) err=1;
           }
fprintf(savefile,"\n");
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_saveg_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save G */
}
/******************************/

/* Save G File Selection Dialog: cancel ***** Callback */
void
on_cancel_button_fsg_clicked      (GtkButton   * button, gpointer user_data )
{
/* int is_saveg_open; global */
if(is_debug==1) printf("Save G File Selection Dialog: quit\n");
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
}
/*****************************/

/* Save G File Selection Dialog: destroy ***** Callback */
void
on_destroy_fsg   (GtkWidget   * ww, gpointer user_data )
{
/* int is_saveg_open; global */
if(is_debug==1) printf("Save G File Selection Dialog: destroy\n");
is_saveg_open=0;
}
/*****************************/

/* Save R: File Selection Dialog Interface  ***** Interface */
GtkWidget*
create_fileselection_r(void)
{
GtkWidget *fileselection;
GtkWidget *ok_button;
GtkWidget *cancel_button;
GtkWidget *button1,*button2,*button3;
GtkWidget *hbox1,*hbox2,*hbox3;
GtkWidget *label1,*label2,*label3;
/* all this mess to show the icon we want in the buttons OK */
GtkWidget *pixmapwid1,*pixmapwid2,*pixmapwid3;
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkStyle *style;
GdkColormap *mappacolor;
/* end  mess                                             */

fileselection = gtk_file_selection_new ("Save R in a File");
gtk_container_set_border_width (GTK_CONTAINER (fileselection), 10);
gtk_file_selection_set_filename (GTK_FILE_SELECTION(fileselection),pathgru_fs);

ok_button = GTK_FILE_SELECTION (fileselection)->ok_button;
gtk_widget_hide (ok_button);
/* GTK_WIDGET_SET_FLAGS (ok_button, GTK_CAN_DEFAULT);*/

cancel_button = GTK_FILE_SELECTION (fileselection)->cancel_button;
gtk_widget_show (cancel_button);
GTK_WIDGET_SET_FLAGS (cancel_button, GTK_CAN_DEFAULT);

/* build out icons */
style = gtk_widget_get_style(fileselection);
mappacolor = gdk_colormap_get_system ();
pixmap =gdk_pixmap_colormap_create_from_xpm_d(fileselection->window,mappacolor,&mask,&style->bg[GTK_STATE_NORMAL],stock_ok_20);
pixmapwid1 = gtk_pixmap_new(pixmap,mask);
pixmapwid2 = gtk_pixmap_new(pixmap,mask);
pixmapwid3 = gtk_pixmap_new(pixmap,mask);
gtk_widget_show(pixmapwid1);
gtk_widget_show(pixmapwid2);
gtk_widget_show(pixmapwid3);
/*  
button_new = gtk_dialog_add_button(GTK_DIALOG(fileselection),"Maple\nOK",GTK_RESPONSE_DELETE_EVENT);
*/
label1 = gtk_label_new("Matlab\nASCII");
label2 = gtk_label_new("Fortran\nASCII\n(2dim+data)");
label3 = gtk_label_new("Fortran\nASCII\n(1dim+data)");
gtk_widget_show(label1);
gtk_widget_show(label2);
gtk_widget_show(label3);
hbox1 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox1), pixmapwid1, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox1), label1, TRUE, TRUE, 0);
gtk_widget_show(hbox1);
button1= gtk_button_new();
gtk_container_add (GTK_CONTAINER(button1),hbox1);
gtk_widget_show(button1);
hbox2 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox2), pixmapwid2, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), label2, TRUE, TRUE, 0);
gtk_widget_show(hbox2);
button2= gtk_button_new();
gtk_container_add (GTK_CONTAINER(button2),hbox2);
gtk_widget_show(button2);
hbox3 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox3), pixmapwid3, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), label3, TRUE, TRUE, 0);
gtk_widget_show(hbox3);
button3= gtk_button_new();
gtk_container_add (GTK_CONTAINER(button3),hbox3);
gtk_widget_show(button3);
/* GTK_RESPONSE_DELETE_EVENT */
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button1,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button2,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button3,GTK_RESPONSE_DELETE_EVENT);

/* g_signal_connect ((gpointer) ok_button, "clicked", G_CALLBACK (on_ok_button_fsr_clicked), NULL); */
g_signal_connect ((gpointer) cancel_button, "clicked", G_CALLBACK (on_cancel_button_fsr_clicked), NULL);
g_signal_connect ((gpointer) fileselection, "destroy", G_CALLBACK (on_destroy_fsr),NULL);
g_signal_connect ((gpointer)button1,"clicked", G_CALLBACK (on_ok1_button_fsr_clicked), NULL);
g_signal_connect ((gpointer)button2,"clicked", G_CALLBACK (on_ok2_button_fsr_clicked), NULL);
g_signal_connect ((gpointer)button3,"clicked", G_CALLBACK (on_ok3_button_fsr_clicked), NULL);
return fileselection;
}   
/***********************************/

/* Save R File Selection Dialog: ok1 ***** Callback  Matlab ASCII matrix*/
void
on_ok1_button_fsr_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saver_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_saver_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saver_fs));
if(is_debug) printf("on_ok1_button_fsr_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saver_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok1_button_fsr_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saver_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
for(i=1;i<=completed.dimension_m;i++) {
                    for(j=1;j<=completed.dimension_m;j++) {
                           read_matr_(&i,&j,&r); /* write the row in one line */
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
                    if(fprintf(savefile,"\n") <0) err=1;
           }
fprintf(savefile,"\n");
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_saver_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save R */
}
/******************************/

/* Save R File Selection Dialog: ok2 ***** 2dims+data ASCII Callback */
void
on_ok2_button_fsr_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saver_fs; global    */
/* struct running_problem_str  completed;          */
/* int is_saver_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saver_fs));
if(is_debug) printf("on_ok2_button_fsr_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saver_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok2_button_fsr_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saver_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
if(fprintf(savefile," %d %d\n",completed.dimension_m,completed.dimension_m) <0) err=1;
for(i=1;i<=completed.dimension_m;i++) for(j=1;j<=completed.dimension_m;j++) { /* column1, column2, ..... */
         read_matr_(&j,&i,&r);
           if(fprintf(savefile,digits_to_save,r) <0) err=1;
           }
fprintf(savefile,"\n");
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_saver_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save R */
}
/******************************/

/* Save R File Selection Dialog: ok3 ***** 1dim+data ASCII Callback */
void
on_ok3_button_fsr_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saver_fs; global    */
/* struct running_problem_str  completed;          */
/* int is_saver_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saver_fs));
if(is_debug) printf("on_ok3_button_fsr_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saver_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok3_button_fsr_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saver_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
if(fprintf(savefile," %d\n",completed.dimension_m) <0) err=1;
for(i=1;i<=completed.dimension_m;i++) for(j=1;j<=completed.dimension_m;j++) { /* column1, column2, ..... */
         read_matr_(&j,&i,&r);
           if(fprintf(savefile,digits_to_save,r) <0) err=1;
           }
fprintf(savefile,"\n");
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_saver_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save R */
}
/******************************/

/* Save R File Selection Dialog: cancel ***** Callback */
void
on_cancel_button_fsr_clicked      (GtkButton   * button, gpointer user_data )
{
/* int is_saver_open; global */
if(is_debug==1) printf("Save R File Selection Dialog: quit\n");
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
}
/*****************************/

/* Save R File Selection Dialog: destroy ***** Callback */
void
on_destroy_fsr      (GtkWidget   * ww, gpointer user_data )
{
/* int is_saver_open; global */
if(is_debug==1) printf("Save R File Selection Dialog: destroy\n");
is_saver_open=0;
}
/*****************************/


/* Save U: File Selection Dialog Interface  ***** Interface */
GtkWidget*
create_fileselection_u(void)
{
GtkWidget *fileselection;
GtkWidget *ok_button;
GtkWidget *cancel_button;
GtkWidget *button1,*button2,*button3;
GtkWidget *hbox1,*hbox2,*hbox3;
GtkWidget *label1,*label2,*label3;
/* all this mess to show the icon we want in the buttons OK */
GtkWidget *pixmapwid1,*pixmapwid2,*pixmapwid3;
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkStyle *style;
GdkColormap *mappacolor;
/* end  mess                                             */

fileselection = gtk_file_selection_new ("Save U in a File");
gtk_container_set_border_width (GTK_CONTAINER (fileselection), 10);

gtk_file_selection_set_filename (GTK_FILE_SELECTION(fileselection),pathgru_fs);
ok_button = GTK_FILE_SELECTION (fileselection)->ok_button;
gtk_widget_hide (ok_button);
/* GTK_WIDGET_SET_FLAGS (ok_button, GTK_CAN_DEFAULT);*/

cancel_button = GTK_FILE_SELECTION (fileselection)->cancel_button;
gtk_widget_show (cancel_button);
GTK_WIDGET_SET_FLAGS (cancel_button, GTK_CAN_DEFAULT);

/* build out icons */
style = gtk_widget_get_style(fileselection);
mappacolor = gdk_colormap_get_system ();
pixmap =gdk_pixmap_colormap_create_from_xpm_d(fileselection->window,mappacolor,&mask,&style->bg[GTK_STATE_NORMAL],stock_ok_20);
pixmapwid1 = gtk_pixmap_new(pixmap,mask);
pixmapwid2 = gtk_pixmap_new(pixmap,mask);
pixmapwid3 = gtk_pixmap_new(pixmap,mask);
gtk_widget_show(pixmapwid1);
gtk_widget_show(pixmapwid2);
gtk_widget_show(pixmapwid3);
/*  
button_new = gtk_dialog_add_button(GTK_DIALOG(fileselection),"Maple\nOK",GTK_RESPONSE_DELETE_EVENT);
*/
label1 = gtk_label_new("Matlab\nASCII");
label2 = gtk_label_new("Fortran\nASCII\n(2dim+data)");
label3 = gtk_label_new("Fortran\nASCII\n(1dim+data)");
gtk_widget_show(label1);
gtk_widget_show(label2);
gtk_widget_show(label3);
hbox1 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox1), pixmapwid1, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox1), label1, TRUE, TRUE, 0);
gtk_widget_show(hbox1);
button1= gtk_button_new();
gtk_container_add (GTK_CONTAINER(button1),hbox1);
gtk_widget_show(button1);
hbox2 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox2), pixmapwid2, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), label2, TRUE, TRUE, 0);
gtk_widget_show(hbox2);
button2= gtk_button_new();
gtk_container_add (GTK_CONTAINER(button2),hbox2);
gtk_widget_show(button2);
hbox3 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox3), pixmapwid3, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), label3, TRUE, TRUE, 0);
gtk_widget_show(hbox3);
button3= gtk_button_new();
gtk_container_add (GTK_CONTAINER(button3),hbox3);
gtk_widget_show(button3);

/* GTK_RESPONSE_DELETE_EVENT */
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button1,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button2,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button3,GTK_RESPONSE_DELETE_EVENT);

/* g_signal_connect ((gpointer) ok_button, "clicked", G_CALLBACK (on_ok_button_fsu_clicked), NULL); */
g_signal_connect ((gpointer) cancel_button, "clicked", G_CALLBACK (on_cancel_button_fsu_clicked), NULL);
g_signal_connect ((gpointer) fileselection, "destroy", G_CALLBACK (on_destroy_fsu),NULL);
g_signal_connect ((gpointer)button1,"clicked", G_CALLBACK (on_ok1_button_fsu_clicked), NULL);
g_signal_connect ((gpointer)button2,"clicked", G_CALLBACK (on_ok2_button_fsu_clicked), NULL);
g_signal_connect ((gpointer)button3,"clicked", G_CALLBACK (on_ok3_button_fsu_clicked), NULL);

return fileselection;
}
/***********************************/

/* Save U File Selection Dialog: ok1 ***** Callback  Matlab ASCII matrix*/
void
on_ok1_button_fsu_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveu_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_saveu_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveu_fs));
if(is_debug) printf("on_ok1_button_fsu_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveu_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok1_button_fsu_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saveu_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
for(i=1;i<=completed.dimension_m;i++) {
                    for(j=1;j<=completed.dimension_m;j++) {
                           read_matu_(&i,&j,&r); /* write the row in one line */
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
                    if(fprintf(savefile,"\n") <0) err=1;
           }
fprintf(savefile,"\n");
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_saveu_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save R */
}
/******************************/

/* Save U File Selection Dialog: ok2 ***** 2dims+data ASCII Callback */
void
on_ok2_button_fsu_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveu_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_saveu_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveu_fs));
if(is_debug) printf("on_ok2_button_fsu_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveu_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok2_button_fsu_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saveu_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
if(fprintf(savefile," %d %d\n",completed.dimension_m,completed.dimension_m) <0) err=1;
for(i=1;i<=completed.dimension_m;i++) for(j=1;j<=completed.dimension_m;j++) { /* column1, column2, ..... */
         read_matu_(&j,&i,&r);
           if(fprintf(savefile,digits_to_save,r) <0) err=1;
           }
fprintf(savefile,"\n");
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_saveu_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save U */
}
/******************************/

/* Save U File Selection Dialog: ok3 ***** 1dims+data ASCII Callback */
void
on_ok3_button_fsu_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveu_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_saveu_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveu_fs));
if(is_debug) printf("on_ok3_button_fsu_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveu_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok1_button_fsr_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saveu_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
if(fprintf(savefile," %d\n",completed.dimension_m) <0) err=1;
for(i=1;i<=completed.dimension_m;i++) for(j=1;j<=completed.dimension_m;j++) { /* column1, column2, ..... */
         read_matu_(&j,&i,&r);
           if(fprintf(savefile,digits_to_save,r) <0) err=1;
           }
fprintf(savefile,"\n");
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_saveu_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save U */
}
/******************************/

/* Save U File Selection Dialog: cancel ***** Callback */
void
on_cancel_button_fsu_clicked      (GtkButton   * button, gpointer user_data )
{
/* int is_saveu_open; global */
if(is_debug==1) printf("Save U File Selection Dialog: quit\n");
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
}
/*****************************/

/* Save U File Selection Dialog: destroy ***** Callback */
void
on_destroy_fsu      (GtkWidget   * ww, gpointer user_data )
{
/* int is_saveu_open; global */
if(is_debug==1) printf("Save U File Selection Dialog: destroy\n");
is_saveu_open=0;
}
/*****************************/

/* Save G+R+U: File Selection Dialog Interface  ***** Interface */
GtkWidget*
create_fileselection_gru(void)
{
GtkWidget *fileselection;
GtkWidget *ok_button;
GtkWidget *cancel_button;
GtkWidget *button1,*button2,*button3;
GtkWidget *hbox1,*hbox2,*hbox3;
GtkWidget *label1,*label2,*label3;
/* all this mess to show the icon we want in the buttons OK */
GtkWidget *pixmapwid1,*pixmapwid2,*pixmapwid3;
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkStyle *style;
GdkColormap *mappacolor;
/* end  mess                                             */

fileselection = gtk_file_selection_new ("Save G+R+U in a File or in 3 files in a New Dir");
gtk_container_set_border_width (GTK_CONTAINER (fileselection), 10);

gtk_file_selection_set_filename (GTK_FILE_SELECTION(fileselection),pathgru_fs);
ok_button = GTK_FILE_SELECTION (fileselection)->ok_button;
gtk_widget_hide (ok_button);
/* GTK_WIDGET_SET_FLAGS (ok_button, GTK_CAN_DEFAULT);*/

cancel_button = GTK_FILE_SELECTION (fileselection)->cancel_button;
gtk_widget_show (cancel_button);
GTK_WIDGET_SET_FLAGS (cancel_button, GTK_CAN_DEFAULT);

/* build out icons */
style = gtk_widget_get_style(fileselection);
mappacolor = gdk_colormap_get_system ();
pixmap =gdk_pixmap_colormap_create_from_xpm_d(fileselection->window,mappacolor,&mask,&style->bg[GTK_STATE_NORMAL],stock_ok_20);
pixmapwid1 = gtk_pixmap_new(pixmap,mask);
pixmapwid2 = gtk_pixmap_new(pixmap,mask);
pixmapwid3 = gtk_pixmap_new(pixmap,mask);
gtk_widget_show(pixmapwid1);
gtk_widget_show(pixmapwid2);
gtk_widget_show(pixmapwid3);
label1 = gtk_label_new("Matlab\nASCII\nDIR with 3 files");
label2 = gtk_label_new("Fortran\nASCII\n3 x (2dim+data)");
label3 = gtk_label_new("Fortran\nASCII\n(1dim+ 3 x data)");
gtk_widget_show(label1);
gtk_widget_show(label2);
gtk_widget_show(label3);
hbox1 = gtk_hbox_new(TRUE,0);
hbox2 = gtk_hbox_new(TRUE,0);
hbox3 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox1), pixmapwid1, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), pixmapwid2, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), pixmapwid3, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox1), label1, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), label2, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), label3, TRUE, TRUE, 0);
gtk_widget_show(hbox1);
gtk_widget_show(hbox2);
gtk_widget_show(hbox3);
button1 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button1),hbox1);
gtk_widget_show(button1);
button2 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button2),hbox2);
gtk_widget_show(button2);
button3 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button3),hbox3);
gtk_widget_show(button3);

/* GTK_RESPONSE_DELETE_EVENT */
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button1,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button2,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button3,GTK_RESPONSE_DELETE_EVENT);
g_signal_connect ((gpointer) cancel_button, "clicked", G_CALLBACK (on_cancel_button_fsgru_clicked), NULL);
g_signal_connect ((gpointer) fileselection, "destroy", G_CALLBACK (on_destroy_fsgru),NULL);
g_signal_connect ((gpointer)button1,"clicked", G_CALLBACK (on_ok1_button_fsgru_clicked), NULL);
g_signal_connect ((gpointer)button2,"clicked", G_CALLBACK (on_ok2_button_fsgru_clicked), NULL);
g_signal_connect ((gpointer)button3,"clicked", G_CALLBACK (on_ok3_button_fsgru_clicked), NULL);
return fileselection;
}
/***********************************/

/* Save G+R+U File Selection Dialog: ok1 ***** Callback  Matlab 3 files in separate dir ASCII matrices */
/* cretes a new dir and 3 files G, R, U inside - dirname must not exist before */
void
on_ok1_button_fsgru_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savegru_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savegru_open; global */
gchar * filename;
char  buf[256];
FILE * savefile;
int i,j,err;
double  r;

/* Extract new dir name from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savegru_fs));
if(is_debug) printf("on_ok1_button_fsgru_clicked: filename = %s\n",filename);
/* now create new dir */
err = mkdir (filename,0777);
if (err == -1) {
        if(is_debug==1) printf("on_ok1_button_fsgru_clicked: %d\n",err);
        create_dialog_nonewdir(savegru_fs);
        return;	
	}
pathstripper(filename,pathgru_fs);   /* save the path  */
sprintf(buf,"%s/G",filename);
if ((savefile = fopen(buf,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savegru_fs));
        return;
        }
else {
    /* file is ok now write */
    err=0; /* error flag */
    for(i=1;i<=completed.dimension_m;i++) {
                    for(j=1;j<=completed.dimension_m;j++) {
                           read_matg_(&i,&j,&r); /* write the row in one line */
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
			if(fprintf(savefile,"\n") <0) err=1;
                    }
    fprintf(savefile,"\n");
    fclose(savefile);
    }
sprintf(buf,"%s/R",filename);
if ((savefile = fopen(buf,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savegru_fs));
        return;
        }
else {
    /* file is ok now write */
    err=0; /* error flag */
    for(i=1;i<=completed.dimension_m;i++) {
                    for(j=1;j<=completed.dimension_m;j++) {
                           read_matr_(&i,&j,&r); /* write the row in one line */
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
			if(fprintf(savefile,"\n") <0) err=1;
                 }
    fprintf(savefile,"\n");
    fclose(savefile);
    }
sprintf(buf,"%s/U",filename);
if ((savefile = fopen(buf,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savegru_fs));
        return;
        }
else {
    /* file is ok now write */
    err=0; /* error flag */
    for(i=1;i<=completed.dimension_m;i++) {
                    for(j=1;j<=completed.dimension_m;j++) {
                           read_matu_(&i,&j,&r); /* write the row in one line */
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
			if(fprintf(savefile,"\n") <0) err=1;
                   }
    fprintf(savefile,"\n");
    fclose(savefile);
       }
    /* if err not 0 something did not work else ok... write messages */
    if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on 3 files ( G, R, U ) in the chosen directory");
    else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on files ***");
    is_savegru_open=0;
    gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save G+R+U */
}

/******************************/

/* Save G+R+U File Selection Dialog: ok2 ***** Callback  Fortran (1) ASCII matrix*/
void
on_ok2_button_fsgru_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savegru_fs; global    */
/* struct running_problem_str  completed;    */
/* int is_savegru_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savegru_fs));
if(is_debug) printf("on_ok2_button_fsgru_clicked: filename = %s\n",filename);
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savegru_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok2_button_fsgru_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savegru_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
if(fprintf(savefile," %d %d\n",completed.dimension_m,completed.dimension_m) <0) err=1;
for(i=1;i<=completed.dimension_m;i++) { /* column1, column2, ..... */
                    for(j=1;j<=completed.dimension_m;j++) {
                           read_matg_(&j,&i,&r);
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
           }
if(fprintf(savefile,"\n %d %d\n",completed.dimension_m,completed.dimension_m) <0) err=1;
for(i=1;i<=completed.dimension_m;i++) { /* column1, column2, ..... */
                    for(j=1;j<=completed.dimension_m;j++) {
                           read_matr_(&j,&i,&r);
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
           }
if(fprintf(savefile,"\n %d %d\n",completed.dimension_m,completed.dimension_m) <0) err=1;
for(i=1;i<=completed.dimension_m;i++) { /* column1, column2, ..... */
                    for(j=1;j<=completed.dimension_m;j++) {
                           read_matu_(&j,&i,&r);
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
           }
fprintf(savefile,"\n");
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_savegru_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save G+R+U */
}
/******************************/

/* Save G+R+U File Selection Dialog: ok3 ***** Callback  Fortran (2) ASCII matrix*/
void
on_ok3_button_fsgru_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savegru_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savegru_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savegru_fs));
if(is_debug) printf("on_ok3_button_fsgru_clicked: filename = %s\n",filename);
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savegru_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok3_button_fsgru_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savegru_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
if(fprintf(savefile," %d\n",completed.dimension_m) <0) err=1;
for(i=1;i<=completed.dimension_m;i++) { /* column1, column2, ..... */
                    for(j=1;j<=completed.dimension_m;j++) {
                           read_matg_(&j,&i,&r);
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
           }
for(i=1;i<=completed.dimension_m;i++) { /* column1, column2, ..... */
                    for(j=1;j<=completed.dimension_m;j++) {
                           read_matr_(&j,&i,&r);
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
           }
for(i=1;i<=completed.dimension_m;i++) { /* column1, column2, ..... */
                    for(j=1;j<=completed.dimension_m;j++) {
                           read_matu_(&j,&i,&r);
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
           }
fprintf(savefile,"\n");
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_savegru_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save G+R+U */
}
/******************************/

/* Save G+R+U File Selection Dialog: cancel ***** Callback */
void
on_cancel_button_fsgru_clicked      (GtkButton   * button, gpointer user_data )
{
/* int is_savegru_open; global */
if(is_debug==1) printf("Save G+R+U File Selection Dialog: quit\n");
is_savegru_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
}
/*****************************/

/* Save G+R+U File Selection Dialog: destroy ***** Callback */
void
on_destroy_fsgru      (GtkWidget   * ww, gpointer user_data )
{
/* int is_savegru_open; global */
if(is_debug==1) printf("Save G+R+U File Selection Dialog: destroy\n");
is_savegru_open=0;
}
/*****************************/


/* Save Pi: File Selection Dialog Interface  ***** Interface */
GtkWidget*
create_fileselection_pi(void)
{
GtkWidget *fileselection;
GtkWidget *ok_button;
GtkWidget *cancel_button;
GtkWidget *button1,*button2,*button3,*button4,*button5,*button6;
GtkWidget *hbox1,*hbox2,*hbox3,*hbox4,*hbox5,*hbox6;
GtkWidget *label1,*label2,*label3,*label4,*label5,*label6;
/* all this mess to show the icon we want in the buttons OK */
GtkWidget *pixmapwid1,*pixmapwid2,*pixmapwid3,*pixmapwid4,*pixmapwid5,*pixmapwid6;
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkStyle *style;
GdkColormap *mappacolor;
/* end  mess                                             */

if (is_debug==1) fileselection = gtk_file_selection_new ("Save Pi and/or Pi0 in Files");
else fileselection = gtk_file_selection_new ("Save Pi");
gtk_container_set_border_width (GTK_CONTAINER (fileselection), 10);

gtk_file_selection_set_filename (GTK_FILE_SELECTION(fileselection),pathgru_fs);
ok_button = GTK_FILE_SELECTION (fileselection)->ok_button;
gtk_widget_hide (ok_button);
/* GTK_WIDGET_SET_FLAGS (ok_button, GTK_CAN_DEFAULT);*/

cancel_button = GTK_FILE_SELECTION (fileselection)->cancel_button;
gtk_widget_show (cancel_button);
GTK_WIDGET_SET_FLAGS (cancel_button, GTK_CAN_DEFAULT);

/* build out icons */
style = gtk_widget_get_style(fileselection);
mappacolor = gdk_colormap_get_system ();
pixmap =gdk_pixmap_colormap_create_from_xpm_d(fileselection->window,mappacolor,&mask,&style->bg[GTK_STATE_NORMAL],stock_ok_20);
if (is_debug==1) {
pixmapwid1 = gtk_pixmap_new(pixmap,mask);
pixmapwid2 = gtk_pixmap_new(pixmap,mask);
pixmapwid3 = gtk_pixmap_new(pixmap,mask);
pixmapwid4 = gtk_pixmap_new(pixmap,mask);
}
pixmapwid5 = gtk_pixmap_new(pixmap,mask);
pixmapwid6 = gtk_pixmap_new(pixmap,mask);
if (is_debug==1) {
gtk_widget_show(pixmapwid1);
gtk_widget_show(pixmapwid2);
gtk_widget_show(pixmapwid3);
gtk_widget_show(pixmapwid4);
}
gtk_widget_show(pixmapwid5);
gtk_widget_show(pixmapwid6);
if (is_debug==1) {
label1 = gtk_label_new(" Matlab ASCII\n pi0");
label2 = gtk_label_new(" Matlab ASCII\n pi (single file)");
label3 = gtk_label_new(" Fortran ASCII\n  pi0 (dim+data)");
label4 = gtk_label_new(" Fortran ASCII\n  pi (length+dim+data)");
}
label5 = gtk_label_new(" Matlab ASCII\n Pi");
label6 = gtk_label_new(" Fortran ASCII\n  Pi (dim+data)");
if (is_debug==1) {
gtk_widget_show(label1);
gtk_widget_show(label2);
gtk_widget_show(label3);
gtk_widget_show(label4);
}
gtk_widget_show(label5);
gtk_widget_show(label6);
if (is_debug==1) {
hbox1 = gtk_hbox_new(FALSE,0);
hbox2 = gtk_hbox_new(FALSE,0);
hbox3 = gtk_hbox_new(FALSE,0);
hbox4 = gtk_hbox_new(FALSE,0);
}
hbox5 = gtk_hbox_new(FALSE,0);
hbox6 = gtk_hbox_new(FALSE,0);
if (is_debug==1) {
gtk_box_pack_start (GTK_BOX (hbox1), pixmapwid1, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), pixmapwid2, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), pixmapwid3, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox4), pixmapwid4, FALSE, TRUE, 0);
}
gtk_box_pack_start (GTK_BOX (hbox5), pixmapwid5, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox6), pixmapwid6, FALSE, TRUE, 0);
if (is_debug==1) {
gtk_box_pack_start (GTK_BOX (hbox1), label1, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), label2, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), label3, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox4), label4, FALSE, TRUE, 0);
}
gtk_box_pack_start (GTK_BOX (hbox5), label5, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox6), label6, FALSE, TRUE, 0);
if (is_debug==1) {
gtk_widget_show(hbox1);
gtk_widget_show(hbox2);
gtk_widget_show(hbox3);
gtk_widget_show(hbox4);
}
gtk_widget_show(hbox5);
gtk_widget_show(hbox6);
if (is_debug==1) {
button1 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button1),hbox1);
gtk_widget_show(button1);
button2 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button2),hbox2);
gtk_widget_show(button2);
button3 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button3),hbox3);
gtk_widget_show(button3);
button4 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button4),hbox4);
gtk_widget_show(button4);
}
button5 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button5),hbox5);
gtk_widget_show(button5);
button6 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button6),hbox6);
gtk_widget_show(button6);
/* GTK_RESPONSE_DELETE_EVENT */
if (is_debug==1) {
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button1,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button2,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button3,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button4,GTK_RESPONSE_DELETE_EVENT);
}
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button5,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button6,GTK_RESPONSE_DELETE_EVENT);
g_signal_connect ((gpointer) cancel_button, "clicked", G_CALLBACK (on_cancel_button_fssavepi_clicked), NULL);
g_signal_connect ((gpointer) fileselection, "destroy", G_CALLBACK (on_destroy_fssavepi),NULL);
if (is_debug==1) {
g_signal_connect ((gpointer)button1,"clicked", G_CALLBACK (on_ok1_button_fssavepi_clicked), NULL);
g_signal_connect ((gpointer)button2,"clicked", G_CALLBACK (on_ok2_button_fssavepi_clicked), NULL);
g_signal_connect ((gpointer)button3,"clicked", G_CALLBACK (on_ok3_button_fssavepi_clicked), NULL);
g_signal_connect ((gpointer)button4,"clicked", G_CALLBACK (on_ok4_button_fssavepi_clicked), NULL);
}
g_signal_connect ((gpointer)button5,"clicked", G_CALLBACK (on_ok5_button_fssavepi_clicked), NULL);
g_signal_connect ((gpointer)button6,"clicked", G_CALLBACK (on_ok6_button_fssavepi_clicked), NULL);
return fileselection;
}
/*****************************/

/* Save Pi File Selection Dialog: cancel ***** Callback */
void
on_cancel_button_fssavepi_clicked      (GtkButton   * button, gpointer user_data )
{
/* int is_savepi_open; global */
if(is_debug==1) printf("Save Pi File Selection Dialog: quit\n");
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
}
/*****************************/

/* Save Pi File Selection Dialog: destroy ***** Callback */
void
on_destroy_fssavepi      (GtkWidget   * ww, gpointer user_data )
{
/* int is_savepi_open; global */
if(is_debug==1) printf("Save Pi File Selection Dialog: destroy\n");
is_savepi_open=0;
}
/*****************************/


/* Save Pi File Selection Dialog: ok1 ***** Matlab Pi0 ASCII Callback */
void
on_ok1_button_fssavepi_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savepi_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savepi_open; global */
gchar * filename;
FILE * savefile;
int i,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savepi_fs));
if(is_debug) printf("on_ok1_button_fsisavepi_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savepi_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok1_button_fssavepi_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savepi_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
/* Pi0 is a vector of  completed.dimension_n (as B0)  */
for(i=1;i<=completed.dimension_n;i++) {
         read_matpi0_(&i,&r);
           if(fprintf(savefile,digits_to_save,r) <0) err=1;
           }
fprintf(savefile,"\n");
fclose(savefile);

/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
if(is_debug==0) {is_savepi_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));}
}
/******************************/

/* Save Pi File Selection Dialog: ok2 ***** Matlab Pi ASCII Callback */
void
on_ok2_button_fssavepi_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savepi_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savepi_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savepi_fs));
if(is_debug) printf("on_ok2_button_fsisavepi_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savepi_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok2_button_fssavepi_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savepi_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
/* Pi  consists of completed.maxnc  vectors of  completed.dimension_m  */
for(i=1;i<=completed.dimension_m;i++) {
		for(j=1;j<=completed.maxnc;j++) {
         		read_matpi_(&i,&j,&r);
           		if(fprintf(savefile,digits_to_save,r) <0) err=1;
           		}
			if(fprintf(savefile,"\n")<0) err=1;
		}
if(fprintf(savefile,"\n")<0) err=1;
fclose(savefile);

/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
if(is_debug==0) {is_savepi_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));}
}
/******************************/

/* Save Pi File Selection Dialog: ok3 ***** Fortran Pi0 ASCII Callback */
void
on_ok3_button_fssavepi_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savepi_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savepi_open; global */
gchar * filename;
FILE * savefile;
int i,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savepi_fs));
if(is_debug) printf("on_ok3_button_fsisavepi_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savepi_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok3_button_fssavepi_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savepi_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
/* Pi0 is a vector of  completed.dimension_n  */

if(fprintf(savefile," %d\n",completed.dimension_n) <0) err=1;
for(i=1;i<=completed.dimension_n;i++) {
         read_matpi0_(&i,&r);
           if(fprintf(savefile,digits_to_save,r) <0) err=1;
           }
fprintf(savefile,"\n");
fclose(savefile);

/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
if(is_debug==0) {is_savepi_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));}
}
/******************************/

/* Save Pi File Selection Dialog: ok4 ***** Fortran Pi ASCII Callback */
void
on_ok4_button_fssavepi_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savepi_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savepi_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savepi_fs));
if(is_debug) printf("on_ok4_button_fsisavepi_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savepi_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok4_button_fssavepi_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savepi_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
/* Pi  consists of completed.maxnc  vectors of  completed.dimension_m  */

if(fprintf(savefile," %d %d\n",completed.dimension_m,completed.maxnc) <0) err=1;
for(i=1;i<=completed.dimension_m;i++) {
	for(j=1;j<=completed.maxnc;j++) {
            read_matpi_(&i,&j,&r);
            if(fprintf(savefile,digits_to_save,r) <0) err=1;
	    }
           }
if(fprintf(savefile,"\n")<0) err=1;
fclose(savefile);

/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
if(is_debug==0) {is_savepi_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));}
}
/******************************/

/* Save Pi File Selection Dialog: ok5 ***** Matlab Pi All ASCII Callback */
/* Pi All - Pi0 + the maxnc vectors of Pi saved in one file */
void
on_ok5_button_fssavepi_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savepi_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savepi_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savepi_fs));
if(is_debug) printf("on_ok5_button_fsisavepi_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savepi_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok5_button_fssavepi_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savepi_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
/* Pi0 is a vector of  completed.dimension_n  */
for(i=1;i<=completed.dimension_n;i++) {
         read_matpi0_(&i,&r);
           if(fprintf(savefile,digits_to_save,r) <0) err=1;
           }
/* Pi  consists of completed.maxnc  vectors of  completed.dimension_m  */
for(j=1;j<=completed.maxnc;j++){
	for(i=1;i<=completed.dimension_m;i++) {
                        read_matpi_(&i,&j,&r);
                        if(fprintf(savefile,digits_to_save,r) <0) err=1;
                        }
                }

if(fprintf(savefile,"\n")<0) err=1;
fclose(savefile);

/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
if(is_debug==0) {is_savepi_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));}
}
/******************************/

/* Save Pi File Selection Dialog: ok6 ***** Fortran Pi All ASCII Callback */
/* Pi All - Pi0 + the maxnc vectors of Pi saved in one file */
void
on_ok6_button_fssavepi_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savepi_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savepi_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savepi_fs));
if(is_debug) printf("on_ok6_button_fsisavepi_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savepi_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok6_button_fssavepi_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savepi_fs));
        return;
        }
/* file is ok now write */
pathstripper(filename,pathgru_fs);   /* save the path  */
err=0; /* error flag */
/* first write the dimension of the vector, completed.dimension_n + completed.maxnc * completed.dimension_m */
if(fprintf(savefile," %d \n",completed.dimension_n+completed.maxnc*completed.dimension_m) <0) err=1;
/* Pi0 is a vector of  completed.dimension_n  */
for(i=1;i<=completed.dimension_n;i++) {
         read_matpi0_(&i,&r);
           if(fprintf(savefile,digits_to_save,r) <0) err=1;
           }
/* Pi  consists of completed.maxnc  vectors of  completed.dimension_m  */
for(j=1;j<=completed.maxnc;j++) {
	for(i=1;i<=completed.dimension_m;i++) {
                        read_matpi_(&i,&j,&r);
                        if(fprintf(savefile,digits_to_save,r) <0) err=1;
                        }
                }
if(fprintf(savefile,"\n")<0) err=1;
fclose(savefile);

/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
if(is_debug==0) {is_savepi_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));}
}
/******************************/

/* Save A: File Selection Dialog Interface  ***** Interface */
GtkWidget*
create_fileselection_savea(void)
{
GtkWidget *fileselection;
GtkWidget *ok_button;
GtkWidget *cancel_button;
GtkWidget *button1,*button2,*button3,*button4,*button5;
GtkWidget *hbox1,*hbox2,*hbox3,*hbox4,*hbox5;
GtkWidget *label1,*label2,*label3,*label4,*label5;
/* all this mess to show the icon we want in the buttons OK */
GtkWidget *pixmapwid1,*pixmapwid2,*pixmapwid3,*pixmapwid4,*pixmapwid5;
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkStyle *style;
GdkColormap *mappacolor;
/* end  mess                                             */

fileselection = gtk_file_selection_new ("Save A Matrices in a File or in more Files in a Dir");
gtk_container_set_border_width (GTK_CONTAINER (fileselection), 10);

gtk_file_selection_set_filename (GTK_FILE_SELECTION(fileselection),pathgru_fs);
ok_button = GTK_FILE_SELECTION (fileselection)->ok_button;
gtk_widget_hide (ok_button);
/* GTK_WIDGET_SET_FLAGS (ok_button, GTK_CAN_DEFAULT);*/

cancel_button = GTK_FILE_SELECTION (fileselection)->cancel_button;
gtk_widget_show (cancel_button);
GTK_WIDGET_SET_FLAGS (cancel_button, GTK_CAN_DEFAULT);

/* build out icons */
style = gtk_widget_get_style(fileselection);
mappacolor = gdk_colormap_get_system ();
pixmap =gdk_pixmap_colormap_create_from_xpm_d(fileselection->window,mappacolor,&mask,&style->bg[GTK_STATE_NORMAL],stock_ok_20);
pixmapwid1 = gtk_pixmap_new(pixmap,mask);
pixmapwid2 = gtk_pixmap_new(pixmap,mask);
pixmapwid3 = gtk_pixmap_new(pixmap,mask);
pixmapwid4 = gtk_pixmap_new(pixmap,mask);
pixmapwid5 = gtk_pixmap_new(pixmap,mask);
gtk_widget_show(pixmapwid1);
gtk_widget_show(pixmapwid2);
gtk_widget_show(pixmapwid3);
gtk_widget_show(pixmapwid4);
gtk_widget_show(pixmapwid5);
/*  
button_new = gtk_dialog_add_button(GTK_DIALOG(fileselection),"Maple\nOK",GTK_RESPONSE_DELETE_EVENT);
*/
label1 = gtk_label_new(" Matlab\n ASCII\n (DIR with files)");
label2 = gtk_label_new(" Matlab\n ASCII\n (single file)");
label3 = gtk_label_new(" Fortran ASCII\n (#blocks+\ndim+(all data))");
label4 = gtk_label_new(" Fortran ASCII\n (#blocks+rptd\n(2dims+data))");
label5 = gtk_label_new(" ASCII\n Sparse Matrix\nblk,row,col,float");
gtk_widget_show(label1);
gtk_widget_show(label2);
gtk_widget_show(label3);
gtk_widget_show(label4);
gtk_widget_show(label5);
hbox1 = gtk_hbox_new(FALSE,0);
hbox2 = gtk_hbox_new(FALSE,0);
hbox3 = gtk_hbox_new(FALSE,0);
hbox4 = gtk_hbox_new(FALSE,0);
hbox5 = gtk_hbox_new(FALSE,0);
gtk_box_pack_start (GTK_BOX (hbox1), pixmapwid1, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), pixmapwid2, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), pixmapwid3, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox4), pixmapwid4, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox5), pixmapwid5, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox1), label1, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), label2, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), label3, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox4), label4, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox5), label5, FALSE, TRUE, 0);
gtk_widget_show(hbox1);
gtk_widget_show(hbox2);
gtk_widget_show(hbox3);
gtk_widget_show(hbox4);
gtk_widget_show(hbox5);
button1 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button1),hbox1);
gtk_widget_show(button1);
button2 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button2),hbox2);
gtk_widget_show(button2);
button3 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button3),hbox3);
gtk_widget_show(button3);
button4 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button4),hbox4);
gtk_widget_show(button4);
button5 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button5),hbox5);
gtk_widget_show(button5);

/* GTK_RESPONSE_DELETE_EVENT */
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button1,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button2,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button3,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button4,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button5,GTK_RESPONSE_DELETE_EVENT);
g_signal_connect ((gpointer) cancel_button, "clicked", G_CALLBACK (on_cancel_button_fssavea_clicked), NULL);
g_signal_connect ((gpointer) fileselection, "destroy", G_CALLBACK (on_destroy_fssavea),NULL);
g_signal_connect ((gpointer)button1,"clicked", G_CALLBACK (on_ok1_button_fssavea_clicked), NULL);
g_signal_connect ((gpointer)button2,"clicked", G_CALLBACK (on_ok2_button_fssavea_clicked), NULL);
g_signal_connect ((gpointer)button3,"clicked", G_CALLBACK (on_ok3_button_fssavea_clicked), NULL);
g_signal_connect ((gpointer)button4,"clicked", G_CALLBACK (on_ok4_button_fssavea_clicked), NULL);
g_signal_connect ((gpointer)button5,"clicked", G_CALLBACK (on_ok5_button_fssavea_clicked), NULL);

return fileselection;
}
/***********************************/

/* Save A File Selection Dialog: ok1 ***** Callback  Matlab qa files in separate dir ASCII matrices */
/* cretes a new dir and qa files A_i inside - dirname must not exist before */
void
on_ok1_button_fssavea_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savea_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savea_open; global */
gchar * filename;
char  buf[256];
FILE * savefile;
int i,j,k,err;
double  r;

if (is_debug==1) printf("on_ok1_button_fssavea_clicked: committed.matrix_a_num = %d committed.dimension_m=%d\n",committed.matrix_a_num,committed.dimension_m);
/* Extract new dir name from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savea_fs));
if(is_debug) printf("on_ok1_button_fssavea_clicked: filename = %s\n",filename);
/* now create new dir */
err = mkdir (filename,0777);
if (err == -1) {
        if(is_debug==1) printf("on_ok1_button_fssavea_clicked: %d\n",err);
        create_dialog_nonewdir(savea_fs);
        return;
        }
pathstripper(filename,pathgru_fs);   /* save the path  */
for (k=1;k<=committed.matrix_a_num;k++) {
        sprintf(buf,"%s/A%05d",filename,k); /* A00001, A00002,  ... */
        if ((savefile = fopen(buf,"w+")) == NULL) {
             /* File not writeble popup  */
             gtk_widget_show(create_dialog_nowritable(savea_fs));
             return;
             }
        else {
             /* file is ok now write */
             err=0; /* error flag */
             for(i=1;i<=committed.dimension_m;i++) {
                    for(j=1;j<=committed.dimension_m;j++) {
                           read_mata_(&i,&j,&k,&r); /* transposed matrix for Matlab */
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
                    if(fprintf(savefile,"\n") <0) err=1;
                    }
             if(fprintf(savefile,"\n") <0) err=1;
             fclose(savefile);
             }
       }
    /* if err not 0 something did not work else ok... write messages */
 if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on  A1...Aqa files in the chosen directory");
    else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on files ***");
    is_savea_open=0;
    gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save A */
}
/******************************/

/* Save A File Selection Dialog: ok2 ***** Callback  Matlab single ASCII file */
/* the blocks are written in a row, side by side */
void
on_ok2_button_fssavea_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savea_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savea_open; global */
gchar * filename;
FILE * savefile;
int i,j,k,err;
double  r;
int go_on, exists, result;

if (is_debug==1) printf("on_ok2_button_fssavea_clicked: committed.matrix_a_num = %d committed.dimension_m=%d\n",committed.matrix_a_num,committed.dimension_m);
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savea_fs));
if(is_debug) printf("on_ok3_button_fssavea_clicked: filename = %s\n",filename);
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savea_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok3_button_fssavea_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savea_fs));
        return;
        }
/* file is ok now write matrix A described in committed */
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, ... */
err=0; /* error flag */
for(i=1;i<=committed.dimension_m;i++) { /* for each column */
			for (k=1;k<=committed.matrix_a_num;k++) { /* for eack block */
						for(j=1;j<=committed.dimension_m;j++) { /* write the row */
                           			  read_mata_(&i,&j,&k,&r);
                           		          if(fprintf(savefile,digits_to_save,r) <0) err=1;
				                  }
			}
		        if(fprintf(savefile,"\n") <0) err=1;/* line feed after long row line */	
                     }
if(fprintf(savefile,"\n") <0) err=1; /* last line feed after all data */
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on a file in Matlab style)");
    else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on files ***");
    is_savea_open=0;
    gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save A */
}
/******************************/

/* Save A File Selection Dialog: ok3 ***** Callback  Fortran (1) ASCII matrix qa+ qa x ( 2 dims + data ) */
void
on_ok3_button_fssavea_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savea_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savea_open; global */
gchar * filename;
FILE * savefile;
int i,j,k,err;
double  r;
int go_on, exists, result;

if (is_debug==1) printf("on_ok3_button_fssavea_clicked: committed.matrix_a_num = %d\n",committed.matrix_a_num);
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savea_fs));
if(is_debug) printf("on_ok3_button_fssavea_clicked: filename = %s\n",filename);
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savea_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok3_button_fssavea_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savea_fs));
        return;
        }
/* file is ok now write matrix A described in committed */
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, ... */
err=0; /* error flag */
if(fprintf(savefile," %d\n",committed.matrix_a_num) <0) err=1; /* number of blocks */ 
for(k=1;k<=committed.matrix_a_num;k++) { /* for each block */
        if(fprintf(savefile," %d %d\n",committed.dimension_m,committed.dimension_m) <0) err=1; /* block dimensions */
        for(i=1;i<=committed.dimension_m;i++) {/* for each row */
                    for(j=1;j<=committed.dimension_m;j++) { /* write a column */
                           read_mata_(&j,&i,&k,&r);
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
                }
		if(fprintf(savefile,"\n") <0) err=1;
        }
if(fprintf(savefile,"\n") <0) err=1;
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file in Fortran style");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_savea_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save A */
}

/* Save A File Selection Dialog: ok4 ***** Callback  Fortran (2) ASCII matrix qa, dim, qa x data */
void
on_ok4_button_fssavea_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savea_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savea_open; global */
gchar * filename;
FILE * savefile;
int i,j,k,err;
double  r;
int go_on, exists, result;

if (is_debug==1) printf("on_ok4_button_fssavea_clicked: committed.matrix_a_num = %d committed.dimension_m=%d\n",committed.matrix_a_num,committed.dimension_m);
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savea_fs));
if(is_debug) printf("on_ok4_button_fssavea_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savea_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok4_button_fssavea_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savea_fs));
        return;
        }
/* file is ok now write matrix A described in committed */
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, ... */
err=0; /* error flag */
if(fprintf(savefile," %d %d\n",committed.matrix_a_num, committed.dimension_m) <0) err=1;
for(k=1;k<=committed.matrix_a_num;k++) {
        for(i=1;i<=committed.dimension_m;i++) {
                    for(j=1;j<=committed.dimension_m;j++) {
                           read_mata_(&j,&i,&k,&r);
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
                }
        }
if(fprintf(savefile,"\n") <0) err=1;
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file in Fortran style");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_savea_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save A */
}
/******************************/

/* Save A File Selection Dialog: ok5 ***** Callback   ASCII sparse matrix  */
void
on_ok5_button_fssavea_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *savea_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_savea_open; global */
gchar * filename;
FILE * savefile;
int i,j,k,err;
double  r;
int go_on, exists, result;
char digits_special[64];

if (is_debug==1) printf("on_ok5_button_fssavea_clicked: committed.matrix_a_num = %d committed.dimension_m=%d\n",committed.matrix_a_num,committed.dimension_m);
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(savea_fs));
if(is_debug) printf("on_ok5_button_fssavea_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(savea_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok5_button_fssavea_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }       
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(savea_fs));
        return;
        }
if (committed.is_a_sparse==0) { /* if A is not sparse, write in sparse format ? */
        confirm_sparse_dialog = create_dialog_sparse(savea_fs);
        gtk_widget_show(confirm_sparse_dialog);
        result = gtk_dialog_run (GTK_DIALOG(confirm_sparse_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(confirm_sparse_dialog);
        }
/* file is ok now write matrix A described in committed */
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, ... */
err=0; /* error flag */
if(fprintf(savefile," %d %d %d\n",committed.matrix_a_num, committed.dimension_m,committed.dimension_m) <0) err=1;
strcpy(digits_special," %d %d %d");
strcat(digits_special,digits_to_save);
strcat(digits_special,"\n");
if (is_debug==1) printf("on_ok5_button_fssavea_clicked: digits_special=%s\n",digits_special);
for(k=1;k<=committed.matrix_a_num;k++) {
	for(j=1;j<=committed.dimension_m;j++) {
                           for(i=1;i<=committed.dimension_m;i++) {
                           read_mata_(&j,&i,&k,&r);
                           if ( r != 0.0) if(fprintf(savefile,digits_special,k,j,i,r) <0) err=1;
                           }
                }
        }
if(fprintf(savefile," 0 0 0 0.0\n") <0) err=1;
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file in sparse matrix format");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
is_savea_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save A */
}
/******************************/

/* Save A File Selection Dialog: cancel ***** Callback */
void
on_cancel_button_fssavea_clicked      (GtkButton   * button, gpointer user_data )
{
/* int is_savea_open; global */
if(is_debug==1) printf("Save A File Selection Dialog: quit\n");
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
}
/*****************************/

/* Save A File Selection Dialog: destroy ***** Callback */
void
on_destroy_fssavea      (GtkWidget   * ww, gpointer user_data )
{
/* int is_savea_open; global */
if(is_debug==1) printf("Save A File Selection Dialog: destroy\n");
is_savea_open=0;
}
/*****************************/


/* Save B: File Selection Dialog Interface  ***** Interface */
GtkWidget*
create_fileselection_saveb(void)
{
/* int is_saveb_open; global */
GtkWidget *fileselection;
GtkWidget *ok_button;
GtkWidget *cancel_button;
GtkWidget *close_button;
GtkWidget *button1,*button2,*button3,*button4,*button5,*button6;
GtkWidget *hbox1,*hbox2,*hbox3,*hbox4,*hbox5,*hbox6;
GtkWidget *label1,*label2,*label3,*label4,*label5,*label6;
/* all this mess to show the icon we want in the buttons OK */
GtkWidget *pixmapwid1,*pixmapwid2,*pixmapwid3,*pixmapwid4,*pixmapwid5,*pixmapwid6;
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkStyle *style;
GdkColormap *mappacolor;
/* end  mess                                             */

fileselection = gtk_file_selection_new ("Save B Matrices in  Files ");
gtk_container_set_border_width (GTK_CONTAINER (fileselection), 10);

gtk_file_selection_set_filename (GTK_FILE_SELECTION(fileselection),pathgru_fs);
ok_button = GTK_FILE_SELECTION (fileselection)->ok_button;
gtk_widget_hide (ok_button);
/* GTK_WIDGET_SET_FLAGS (ok_button, GTK_CAN_DEFAULT);*/

cancel_button = GTK_FILE_SELECTION (fileselection)->cancel_button;
/*gtk_widget_show (cancel_button);
GTK_WIDGET_SET_FLAGS (cancel_button, GTK_CAN_DEFAULT);*/
gtk_widget_hide (cancel_button);

close_button =  gtk_button_new_from_stock (GTK_STOCK_CLOSE);
gtk_widget_show (close_button);


/* build out icons */
style = gtk_widget_get_style(fileselection);
mappacolor = gdk_colormap_get_system ();
pixmap =gdk_pixmap_colormap_create_from_xpm_d(fileselection->window,mappacolor,&mask,&style->bg[GTK_STATE_NORMAL],stock_ok_20);
pixmapwid1 = gtk_pixmap_new(pixmap,mask);
pixmapwid2 = gtk_pixmap_new(pixmap,mask);
pixmapwid3 = gtk_pixmap_new(pixmap,mask);
pixmapwid4 = gtk_pixmap_new(pixmap,mask);
pixmapwid5 = gtk_pixmap_new(pixmap,mask);
pixmapwid6 = gtk_pixmap_new(pixmap,mask);
gtk_widget_show(pixmapwid1); 
gtk_widget_show(pixmapwid2); 
gtk_widget_show(pixmapwid3);
gtk_widget_show(pixmapwid4);
gtk_widget_show(pixmapwid5);
gtk_widget_show(pixmapwid6);
/*  
button_new = gtk_dialog_add_button(GTK_DIALOG(fileselection),"Maple\nOK",GTK_RESPONSE_DELETE_EVENT);
*/
label1 = gtk_label_new(" Matlab ASCII\n BN1");
label2 = gtk_label_new(" Matlab ASCII\n B0");
label3 = gtk_label_new(" Matlab ASCII\n B");
label4 = gtk_label_new(" Fortran ASCII\n BN1");
label5 = gtk_label_new(" Fortran ASCII\n B0");
label6 = gtk_label_new(" Fortran ASCII\n B");
gtk_widget_show(label1);
gtk_widget_show(label2);
gtk_widget_show(label3);
gtk_widget_show(label4);
gtk_widget_show(label5);
gtk_widget_show(label6);
hbox1 = gtk_hbox_new(FALSE,0);
hbox2 = gtk_hbox_new(FALSE,0);
hbox3 = gtk_hbox_new(FALSE,0);
hbox4 = gtk_hbox_new(FALSE,0);
hbox5 = gtk_hbox_new(FALSE,0);
hbox6 = gtk_hbox_new(FALSE,0);
gtk_box_pack_start (GTK_BOX (hbox1), pixmapwid1, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), pixmapwid2, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), pixmapwid3, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox4), pixmapwid4, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox5), pixmapwid5, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox6), pixmapwid6, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox1), label1, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), label2, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), label3, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox4), label4, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox5), label5, FALSE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox6), label6, FALSE, TRUE, 0);
gtk_widget_show(hbox1);
gtk_widget_show(hbox2);
gtk_widget_show(hbox3);
gtk_widget_show(hbox4);
gtk_widget_show(hbox5);
gtk_widget_show(hbox6);

button1 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button1),hbox1);
gtk_widget_show(button1);

button2 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button2),hbox2);
gtk_widget_show(button2);

button3 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button3),hbox3);
gtk_widget_show(button3);

button4 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button4),hbox4);
gtk_widget_show(button4);

button5 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button5),hbox5);
gtk_widget_show(button5);

button6 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button6),hbox6);
gtk_widget_show(button6);



/* GTK_RESPONSE_DELETE_EVENT */
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),close_button,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button2,GTK_RESPONSE_DELETE_EVENT);
if (committed.is_b==1) gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button3,GTK_RESPONSE_DELETE_EVENT);
if (committed.is_bn1==1) gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button1,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button5,GTK_RESPONSE_DELETE_EVENT);
if (committed.is_b==1) gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button6,GTK_RESPONSE_DELETE_EVENT);
if (committed.is_bn1==1) gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button4,GTK_RESPONSE_DELETE_EVENT);
g_signal_connect ((gpointer) close_button, "clicked", G_CALLBACK (on_cancel_button_fssaveb_clicked), NULL);
g_signal_connect ((gpointer) cancel_button, "clicked", G_CALLBACK (on_cancel_button_fssaveb_clicked), NULL);
g_signal_connect ((gpointer) fileselection, "destroy", G_CALLBACK (on_destroy_fssaveb),NULL);
if (committed.is_bn1==1) g_signal_connect ((gpointer)button1,"clicked", G_CALLBACK (on_ok1_button_fssaveb_clicked), NULL);
g_signal_connect ((gpointer)button2,"clicked", G_CALLBACK (on_ok2_button_fssaveb_clicked), NULL);
if (committed.is_b==1) g_signal_connect ((gpointer)button3,"clicked", G_CALLBACK (on_ok3_button_fssaveb_clicked), NULL);
if (committed.is_bn1==1) g_signal_connect ((gpointer)button4,"clicked", G_CALLBACK (on_ok4_button_fssaveb_clicked), NULL);
g_signal_connect ((gpointer)button5,"clicked", G_CALLBACK (on_ok5_button_fssaveb_clicked), NULL);
if (committed.is_b==1) g_signal_connect ((gpointer)button6,"clicked", G_CALLBACK (on_ok6_button_fssaveb_clicked), NULL);

return fileselection;
}
/*****************************/

/* Save B File Selection Dialog: ok1 ***** Callback  Matlab ASCII BN1 matrix m x n except GIM1 problems n x m */
void
on_ok1_button_fssaveb_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveb_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_saveb_open; global */
gchar * filename;
FILE * savefile;
int i,j,err, n,m;
double  r;
int go_on, exists, result;

if (is_debug==1) printf("on_ok1_button_fssaveb_clicked: committed.dimension_n = %d  committed.dimension_m = %d\n",committed.dimension_n,committed.dimension_m);
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveb_fs));
if(is_debug) printf("on_ok1_button_fssavesba_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveb_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok1_button_fssaveb_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saveb_fs));
        return;
        }
/* file is ok now write matrix BN1 described in committed */
if (committed.type==3) { /* GIM1 have exchanged dimensions */
    n=committed.dimension_n;
    m=committed.dimension_m;
   } else {
    n=committed.dimension_m; 
    m=committed.dimension_n;
   }
if (is_debug==1) printf("on_ok1_button_fssaveb_clicked: problem type = %d, BN1 is %d x %d \n",committed.type,n,m);
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, ... */
err=0; /* error flag */
for(i=1;i<=n;i++) { /* for each column */
                      for(j=1;j<=m;j++) { /* write the row */
                      read_matbn1_(&i,&j,&r);
                      if(fprintf(savefile,digits_to_save,r) <0) err=1;
                      }
                      if(fprintf(savefile,"\n") <0) err=1;/* line feed after long row line */
                     }
if(fprintf(savefile,"\n") <0) err=1; /* last line feed after all data */
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
}
/******************************/

/* Save B File Selection Dialog: ok2 ***** Callback  Matlab ASCII matrix B0 n x n */
void
on_ok2_button_fssaveb_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveb_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_saveb_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

if (is_debug==1) printf("on_ok2_button_fssaveb_clicked: committed.dimension_n = %d\n",committed.dimension_n);
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveb_fs));
if(is_debug) printf("on_ok2_button_fssaveb_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveb_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok2_button_fssaveb_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saveb_fs));
        return;
        }
/* file is ok now write matrix B0 described in committed  n x n */
if (is_debug==1) printf("on_ok1_button_fssaveb_clicked: problem type = %d, B0 is %d x %d \n",committed.type,committed.dimension_n, committed.dimension_n);

pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, ... */
err=0; /* error flag */
for(i=1;i<=committed.dimension_n;i++) { /* for each column */
                      for(j=1;j<=committed.dimension_n;j++) { /* write the row */
                      read_matb0_(&i,&j,&r);
                      if(fprintf(savefile,digits_to_save,r) <0) err=1;
                      }
                      if(fprintf(savefile,"\n") <0) err=1;/* line feed after long row line */
                     }
if(fprintf(savefile,"\n") <0) err=1; /* last line feed after all data */
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
}
/******************************/

/* Save B File Selection Dialog: ok3 ***** Callback  Matlab ASCII matrix B  */
/* for M/G/1 problems blocks are written side by side like for the A blocks */
/* for GI/M/1 the blocks are written one after the other - this is different from the format used for the A !!! */
void
on_ok3_button_fssaveb_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveb_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_saveb_open; global */
gchar * filename;
FILE * savefile;
int i,j,k,err,m,n;
double  r;
int go_on, exists, result;

if (is_debug==1) printf("on_ok2_button_fssaveb_clicked: committed.matrix_b_num = %d committed.dimension_m=%d committed.dimension_n=%d\n",committed.matrix_b_num,committed.dimension_m,committed.dimension_n);
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveb_fs));
if(is_debug) printf("on_ok2_button_fssaveb_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveb_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok3_button_fssaveb_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saveb_fs));
        return;
        }
/* file is ok now write matrix B described in committed */

if (committed.type==3) { /* GIM1 have exchanged dimensions */
    m=committed.dimension_n;
    n=committed.dimension_m;
   } else {
    m=committed.dimension_m; 
    n=committed.dimension_n;
   }
if (is_debug==1) printf("on_ok1_button_fssaveb_clicked: problem type = %d, B is %d blocks %d x %d \n",committed.type,committed.matrix_b_num,n,m);

pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, ... */
err=0; /* error flag */

if (committed.type==3) { /* GIM1 write blocks one after the other */
  for (k=1;k<=committed.matrix_b_num;k++) { /* for eack block */
     for(i=1;i<=n;i++) { /* for each column */
                   for(j=1;j<=m;j++) { /* write the row */
                                     read_matb_(&i,&j,&k,&r);
                                     if(fprintf(savefile,digits_to_save,r) <0) err=1;
                                     }
                        if(fprintf(savefile,"\n") <0) err=1;/* line feed after  row line */ 
                       }
     }
} else { /* MG1 and QBD use same style as A blocks */
   for(i=1;i<=n;i++) { /* for each column */
                        for (k=1;k<=committed.matrix_b_num;k++) { /* for eack block */
                                                for(j=1;j<=m;j++) { /* write the row */
                                                  read_matb_(&i,&j,&k,&r);
                                                  if(fprintf(savefile,digits_to_save,r) <0) err=1;
                                                  }
                        }
                        if(fprintf(savefile,"\n") <0) err=1;/* line feed after long row line */
                     }
}
if(fprintf(savefile,"\n") <0) err=1; /* last line feed after all data */
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
}
/******************************/

/* Save B File Selection Dialog: ok4 ***** Callback  Fortran ASCII matrix BN1  */
void
on_ok4_button_fssaveb_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveb_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_saveb_open; global */
gchar * filename;
FILE * savefile;
int i,j,err,n,m;
double  r;
int go_on, exists, result;

if (is_debug==1) printf("on_ok4_button_fssaveb_clicked: committed.dimension_n=%d, committed.dimension_m = %d\n",committed.dimension_n, committed.dimension_m);
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveb_fs));
if(is_debug) printf("on_ok4_button_fssaveb_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveb_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok4_button_fssaveb_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saveb_fs));
        return;
        }
/* file is ok now write matrix BN1 described in committed */
if (committed.type==3) { /* GIM1 have exchanged dimensions */
    n=committed.dimension_n;
    m=committed.dimension_m;
   } else {
    n=committed.dimension_m;
    m=committed.dimension_n;
   }
if (is_debug==1) printf("on_ok1_button_fssaveb_clicked: problem type = %d, BN1 is  %d x %d \n",committed.type,n,m);

pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, ... */
err=0; /* error flag */
if(fprintf(savefile," %d %d\n",n,m) <0) err=1; /* rows, columns */
for(i=1;i<=m;i++) { /* write 1 column, then 2 column ... */
          for(j=1;j<=n;j++) {
                      read_matbn1_(&j,&i,&r);
                      if(fprintf(savefile,digits_to_save,r) <0) err=1;
                      }
          }
if(fprintf(savefile,"\n") <0) err=1;
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
}
/******************************/

/* Save B File Selection Dialog: ok5 ***** Callback  Fortran ASCII matrix B0 */
void
on_ok5_button_fssaveb_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveb_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_saveb_open; global */
gchar * filename;
FILE * savefile;
int i,j,err;
double  r;
int go_on, exists, result;

if (is_debug==1) printf("on_ok5_button_fssavea_clicked: committed.dimension_n = %d\n",committed.dimension_n);
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveb_fs));
if(is_debug) printf("on_ok5_button_fssavea_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveb_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok5_button_fssaveb_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saveb_fs));
        return;
        }
/* file is ok now write matrix B0 described in committed  n x n*/
if (is_debug==1) printf("on_ok1_button_fssaveb_clicked: problem type = %d, B0 is %d x %d \n",committed.type,committed.dimension_n, committed.dimension_n);
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, ... */
err=0; /* error flag */
if(fprintf(savefile," %d %d\n",committed.dimension_n, committed.dimension_n) <0) err=1; 
        for(i=1;i<=committed.dimension_n;i++) {
                    for(j=1;j<=committed.dimension_n;j++) {
                           read_matb0_(&j,&i,&r);
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
                }
if(fprintf(savefile,"\n") <0) err=1;
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
}
/******************************/

/* Save B File Selection Dialog: ok6 ***** Callback  Fortran  ASCII matrix B (3 dims + data )*/
void
on_ok6_button_fssaveb_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *saveb_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_saveb_open; global */
gchar * filename;
FILE * savefile;
int i,j,k,err,n,m;
double  r;
int go_on, exists, result;

if (is_debug==1) printf("on_ok6_button_fssaveb_clicked: committed.matrix_b_num = %d committed.dimension_m=%d committed.dimension_n=%d \n",committed.matrix_b_num,committed.dimension_m,committed.dimension_n);
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(saveb_fs));
if(is_debug) printf("on_ok6_button_fssaveb_clicked: filename = %s\n",filename);
exists=0; /* 0= file does not exists , 1 exists  */
if ((savefile = fopen(filename,"r")) != NULL) {
                    exists =1;   /* file exists and can be read */
                    fclose (savefile);
                    }
if (exists ==1) { /* warning: file exists, overwrite ? */
        overwrite_dialog = create_dialog_overwrite(saveb_fs);
        gtk_widget_show(overwrite_dialog);
        result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
           switch (result) {
               case GTK_RESPONSE_ACCEPT:  go_on=1; break;
               /*case GTK_RESPONSE_CANCEL: go_on=0; break;*/
               default:go_on =0;
               }
        gtk_widget_destroy(overwrite_dialog);
        if (is_debug==1) printf("on_ok6_button_fssaveb_clicked:  go_on=%d\n",go_on);
        if (go_on==0)  { return;}
        }
if ((savefile = fopen(filename,"w+")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_nowritable(saveb_fs));
        return;
        }
/* file is ok now write matrix B described in committed */
if (committed.type==3) { /* GIM1 have exchanged dimensions */
    m=committed.dimension_n;
    n=committed.dimension_m;
   } else {
    m=committed.dimension_m;
    n=committed.dimension_n;
   }
if (is_debug==1) printf("on_ok1_button_fssaveb_clicked: problem type = %d, B is %d blocks  %d x %d \n",committed.type,committed.matrix_b_num,n,m);

pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, ... */
err=0; /* error flag */
if(fprintf(savefile," %d %d %d\n",committed.matrix_b_num,n,m) <0) err=1; /* number of blocks rows, columns */ 
for(k=1;k<=committed.matrix_b_num;k++) { /* for each block */
        for(i=1;i<=m;i++) {/* for each row */
                    for(j=1;j<=n;j++) { /* write a column */
                           read_matb_(&j,&i,&k,&r);
                           if(fprintf(savefile,digits_to_save,r) <0) err=1;
                            }
                }
                if(fprintf(savefile,"\n") <0) err=1;
        }
if(fprintf(savefile,"\n") <0) err=1;
fclose(savefile);
/* if err not 0 something did not work else ok... write messages */
if (err == 0) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  Data written on file");
else gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  ***Failure ! Data were not correctly written on file ***");
}
/******************************/

/* Save B File Selection Dialog: cancel ***** Callback */
void
on_cancel_button_fssaveb_clicked      (GtkButton   * button, gpointer user_data )
{
/* int is_saveb_open; global */
if(is_debug==1) printf("Save B File Selection Dialog: quit\n");
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
}
/*****************************/

/* Save B File Selection Dialog: destroy ***** Callback */
void
on_destroy_fssaveb      (GtkWidget   * ww, gpointer user_data )
{
/* int is_saveb_open; global */
if(is_debug==1) printf("Save B File Selection Dialog: destroy\n");
is_saveb_open=0;
}
/*****************************/



/* Read A: File Selection Dialog Interface  ***** Interface */
GtkWidget*
create_fileselection_reada(void)
{
GtkWidget *fileselection;
GtkWidget *ok_button;
GtkWidget *cancel_button;
GtkWidget *button1,*button2,*button3;
GtkWidget *hbox1,*hbox2,*hbox3;
GtkWidget *label1,*label2,*label3;
/* all this mess to show the icon we want in the buttons OK */
GtkWidget *pixmapwid1,*pixmapwid2,*pixmapwid3;
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkStyle *style;
GdkColormap *mappacolor;
/* end  mess                                             */

if(selected_a_problem==1) fileselection = gtk_file_selection_new ("QBD Problem: Read 3 A Blocks from a File");
if(selected_a_problem==2) fileselection = gtk_file_selection_new ("M/G/1 Problem: Read qa A Blocks from a File");
if(selected_a_problem==3) fileselection = gtk_file_selection_new ("GI/M/1 Problem: Read qa A Blocks from a File");
gtk_container_set_border_width (GTK_CONTAINER (fileselection), 10);

gtk_file_selection_set_filename (GTK_FILE_SELECTION(fileselection),pathgru_fs);
ok_button = GTK_FILE_SELECTION (fileselection)->ok_button;
gtk_widget_hide (ok_button);
/* GTK_WIDGET_SET_FLAGS (ok_button, GTK_CAN_DEFAULT);*/

cancel_button = GTK_FILE_SELECTION (fileselection)->cancel_button;
gtk_widget_show (cancel_button);
GTK_WIDGET_SET_FLAGS (cancel_button, GTK_CAN_DEFAULT);

/* build out icons */
style = gtk_widget_get_style(fileselection);
mappacolor = gdk_colormap_get_system ();
pixmap =gdk_pixmap_colormap_create_from_xpm_d(fileselection->window,mappacolor,&mask,&style->bg[GTK_STATE_NORMAL],stock_ok_20);
pixmapwid1 = gtk_pixmap_new(pixmap,mask);
pixmapwid2 = gtk_pixmap_new(pixmap,mask);
pixmapwid3 = gtk_pixmap_new(pixmap,mask);
gtk_widget_show(pixmapwid1);
gtk_widget_show(pixmapwid2);
gtk_widget_show(pixmapwid3);
/*  
button_new = gtk_dialog_add_button(GTK_DIALOG(fileselection),"Maple\nOK",GTK_RESPONSE_DELETE_EVENT);
*/
label1 = gtk_label_new("Single\nASCII File");
label2 = gtk_label_new("DIR with\nASCII Files");
label3 = gtk_label_new("READ\nASCII FILE");
gtk_widget_show(label1);
gtk_widget_show(label2);
gtk_widget_show(label3);
hbox1 = gtk_hbox_new(TRUE,0);
hbox2 = gtk_hbox_new(TRUE,0);
hbox3 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox1), pixmapwid1, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), pixmapwid2, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), pixmapwid3, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox1), label1, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), label2, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), label3, TRUE, TRUE, 0);
/* gtk_widget_show(hbox1);
gtk_widget_show(hbox2);*/
gtk_widget_show(hbox3);
button1 = gtk_button_new();
/*gtk_container_add (GTK_CONTAINER(button1),hbox1);
gtk_widget_show(button1); */
button2 = gtk_button_new();
/*gtk_container_add (GTK_CONTAINER(button2),hbox2);
gtk_widget_show(button2);*/
button3 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button3),hbox3);
gtk_widget_show(button3);

/* GTK_RESPONSE_DELETE_EVENT */
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button1,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button2,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button3,GTK_RESPONSE_DELETE_EVENT);
g_signal_connect ((gpointer) cancel_button, "clicked", G_CALLBACK (on_cancel_button_fsreada_clicked), NULL);
g_signal_connect ((gpointer) fileselection, "destroy", G_CALLBACK (on_destroy_fsreada),NULL);
g_signal_connect ((gpointer)button1,"clicked", G_CALLBACK (on_ok1_button_fsreada_clicked), NULL);
g_signal_connect ((gpointer)button2,"clicked", G_CALLBACK (on_ok2_button_fsreada_clicked), NULL);
g_signal_connect ((gpointer)button3,"clicked", G_CALLBACK (on_ok3_button_fsreada_clicked), NULL);

return fileselection;
}
/*****************************/

/* Read A File Selection Dialog: ok1 ***** Callback   unused - pattern based - ONE ASCII FILE  */
void
on_ok1_button_fsreada_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *reada_fs; global    */
/* struct running_problem_str  completed;   */
/* int is_reada_open; global */
gchar * filename;
FILE * readfile;
int c;                  /* read from file one char by one */
char num_str[1024];     /* a number with more then 1024 digits will crash the program ... to fix later ...*/
int n_fblocks;
int fblocks[2048];      /* more than 2048 blocks of consecutive floats will not be analyzed during the euristic scan phase */
int which_n;            /* 0 integer 1 float */
long int fl, ln, nonasc;/* file length, number of lines, non ascii chars not in comment line */
int kl;                 /* comment lines */
int totint;             /* total integers number */
long int totfl;         /* total floating point numbers */
long int  blk_max;  /* length of float blocks */ 
int i,err; /* mi,ni,mk dimensions, i,j,k indexes, err error flag */
char *pattern1, *pattern2;
int  ipat1,ipat2,lenpat1,lenpat2,rpt,ok,kpat2;
char buf[64];
return;
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(reada_fs));
if(is_debug) printf("on_ok1_button_fsreada_clicked: algorithm=%d,  filename = %s\n",selected_a_problem,filename);
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, ... */
if ((readfile = fopen(filename,"r")) == NULL) {
        /* File not writeble popup  */
        gtk_widget_show(create_dialog_noreadable(reada_fs));
        return;
        }
/* file is open ok  */
/* first step: scan the file to get length, check if ascii or not, check line separators, count possible integers and float 
 * analyze file structure in terms of blocks of floats and show the result of the scan */
err = 0; /* no error till now */
fl=0; ln=0; nonasc=0;
kl=0;
totint=0; totfl=0;
n_fblocks=0; blk_max=0; for(i=0;i<2048;i++) fblocks[i]=0; which_n=0; /*integer by default */
if (is_debug==1) printf("on_ok1_button_fsreada_clicked:  file scan begins\n");
/* watch_for_number: initialize with watch_for_number(0, 0,num_str); and fill num_str with 0 before using; add watch_for_number('\n', 1,num_str) at last.
 * return value: 0=other ASCII <128   1=considering a number    2=comment line and new line    3=new line    4=new line following a new line
                 5=int   6=int and new line   7=floatFP   8=floatEX   9=floatFP and new line   10 floatEX and new line  11 ASCII > 127 not in comment line */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */
while((c = getc(readfile)) != EOF) {
	fl++;
	switch(watch_for_number(c, 1,num_str)) {
		case 2:  kl++; break;
		case 3:  ln++; break;
		case 5:  totint++; if(which_n==1) which_n=0;break;
                case 6:  ln++;totint++;if(which_n==1) which_n=0;break;
		case 7:  totfl++; if(which_n==0) {which_n=1; n_fblocks++;}; fblocks[n_fblocks]++;break;
		case 8:  totfl++; if(which_n==0) {which_n=1; n_fblocks++;};fblocks[n_fblocks]++;break;
		case 9:  ln++;totfl++;if(which_n==0) {which_n=1; n_fblocks++;};fblocks[n_fblocks]++;break;
		case 10: ln++;totfl++;if(which_n==0) {which_n=1; n_fblocks++;};fblocks[n_fblocks]++;break;
		case 11: nonasc++;break;
		default: break;
		}
	if(n_fblocks==1000) n_fblocks--;
	
	}
if (is_debug==1) printf("on_ok1_button_fsreada_clicked:  file scan ends\n");
if (is_debug==1) printf("filelength=%ld, lines=%ld, nonascii chars = %ld, comment lines=%d,\ni",fl,ln,nonasc,kl);
if (is_debug==1) printf("integers=%d, floats=%ld n. blocchi floats=%d\n",totint,totfl,n_fblocks);
if (is_debug==1) for (i=1; i<=n_fblocks;i++) printf("fblocks[%d]=%d\n",i,fblocks[i]);
/* first step; (alternative analysis); */
fseek(readfile,(long int)0,SEEK_SET);
pattern1=calloc(1024*1204,sizeof(c));
pattern2=calloc(1024*1204,sizeof(c));
if (pattern1==NULL) return; /* just for testing */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */
while((c = getc(readfile)) != EOF) {
        switch(watch_for_number(c, 1,num_str)) {
                case 2:  kl++; break;
                case 3:  ln++; sprintf(buf,"N");strcat(pattern1,buf);break;
                case 5:  totint++; sprintf(buf,"I");strcat(pattern1,buf);break;
                case 6:  ln++;totint++; sprintf(buf,"IN");strcat(pattern1,buf);break;
                case 7:  totfl++; sprintf(buf,"F");strcat(pattern1,buf);break;
                case 8:  totfl++; sprintf(buf,"F");strcat(pattern1,buf);break;
                case 9:  ln++;totfl++;sprintf(buf,"FN");strcat(pattern1,buf);break;
                case 10: ln++;totfl++;sprintf(buf,"FN");strcat(pattern1,buf);break;
                case 11: nonasc++;break;
                default: break;
                };
        }
if (is_debug) printf("%s\n",pattern1);
/* pattern recognition - step a) collect repetition of identical symbols */
lenpat1=strlen(pattern1);
ipat2=0;
pattern2[0]=pattern1[0];
rpt=0;
for(ipat1=0;ipat1<=lenpat1;ipat1++) {
if(pattern1[ipat1]==pattern2[ipat2]) rpt++;
else {
     if(rpt>1) {sprintf(buf,"%d",rpt);
              strcat(pattern2,buf);}
     ipat2=strlen(pattern2);
     rpt=1;
     pattern2[ipat2]=pattern1[ipat1];
     }
}
if (is_debug) printf("%s\n",pattern2);
/* pattern recognition - step b) collect repetition of identical groups of symbols */
for(i=0;i<=lenpat1;i++) pattern1[i]=0;
lenpat2=strlen(pattern2);
ipat1=0; ipat2=0; 
rpt=0;
for(ipat2=0;ipat2<lenpat2;ipat2++) {
  /* search kpat2 such that pattern2(ipat2)==pattern2(ipat2+kpat2) and check if pattern from ipat2 to ipat2+kpat2-1 is repeated */
  for(kpat2=1;2*kpat2<lenpat2-ipat2;kpat2++) {
			if(pattern2[ipat2]==pattern2[ipat2+kpat2]) ok=0;
			 
			     ok=1; /* test pattern2 from ipat2 to ipat2+kpat2-1 */
			     for (i=0;i<kpat2;i++) if (pattern2[ipat2+i]!=pattern2[ipat2+kpat2+i]) ok=0;
			     if (ok==1) /* pattern2 from ipat2 to ipat2+kpat2-1 is repeated */  {
				   /* copy it in a pattern1 with parentesis () */
				   pattern1[ipat1]='(';
				   for (i=0;i<kpat2;i++) pattern1[ipat1+i]=pattern2[ipat2+i];
				   pattern1[ipat1+kpat2] =')';
				   rpt=2;
				} else {
				       /* a replicated pattern is not found starting from pattern2[ipat2], copy it to pattern1[ipat1] and
						try next ipat2 value */
					pattern1[ipat1]=pattern2[ipat2];
					ipat1++;
					}
			}
	
}
if (is_debug) printf("%s\n",pattern1);
/* second step: if the file structure is compatible with the required problem, dimension the matrices and read the data */
/* fseek(readfile,pos_in,SEEK_SET);rewind */
fclose(readfile);
is_reada_open=0;
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save A */
}
/******************************/

/* Read A File Selection Dialog: ok2 ***** Callback   unused */
void
on_ok2_button_fsreada_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *reada_fs; global    */
/* struct running_problem_str  completed;    */
/* int is_reada_open; global */
}
/******************************/

/* Read A File Selection Dialog: ok3 ***** Callback  READ ASCII FILE  */
/* 1. scan file to get some structure data
 * 2. check 
 * 3. read
 */
void
on_ok3_button_fsreada_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *reada_fs; global    */
/* struct running_problem_str  committed, completed;  */
/* int is_reada_open; global */
gchar * filename;
FILE * readfile;
int c;                  /* read from file one char by one */
char num_str[1024];     /* a number with more then 1024 digits will crash the program ... to fix later ...*/
long int fl, ln, nonasc;/* file length, number of lines, non ascii chars not in comment line */
int kl;                 /* comment lines */
int totint;             /* total trings corresponding to integers number */
long int totfl,ckfl;    /* total strings corresponding to floating point numbers and number of floats really read from file */
int i,j,k,na,ma,qa,err; /* ma,na,qa dimensions of blocks and # of blocks, i,j,k indexes, err error flag */
double  r;              /* float value to read */
int int1,int2,int3,ii;  /* first 3 integers present in the file, if any, and how many (0,1,2,3) of them */
char buf[256] ;
int ksparse,is_sparse,valid;    /* count sparse matrix patterns */
struct sparse_four dims,actual; /* try to detect dimension of sparse matrix */
int matlab_valid,rows,columns, oldcolumns;   /* matlab_valid=1 if the file is NOT a matlab matrix */

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(reada_fs));
if(is_debug) printf("on_ok3_button_fsreada_clicked: algorithm=%d,  filename = %s\n",selected_a_problem,filename);
if ((readfile = fopen(filename,"r+")) == NULL) {  /* "r" should be enougth.. but with "r" dir can be opended too, and a check will be needed */
        /* File not readable popup  */
        gtk_widget_show(create_dialog_noreadable(reada_fs));
        return;
        }
/* file is open ok  */
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, */
/* first step: scan the file to get length, check if ascii or not, check line separators, count possible integers and float 
 * read, if present, the first 3 integers, count sparse matrix pattern (I I I F ), check for regular rows of floats for 
 * matlab ASCII matrix format - for valid matlab ascii we require no integers, floats only, same number in each line.
 */
err = 0; /* no error till now */
fl=0; /* file length */
ln=0; /* lines */
nonasc=0; /* ascii >128 */
kl=0; /* comment lines */
totint=0; /* strings corresponding to integers */
totfl=0;  /* strings corresponding to floats */
ii=0;     /* count if preset first 3 integers */
int1=0;
int2=0;
int3=0;
is_sparse=0; /* 0=not sparse 1=sparse matrix */
sparse_detect(0, &ksparse, NULL, &actual, &dims); /* initilize sparse detect status machine  */
matlab_valid=0; /* if this =1 we are shure that the file is not compatible with pure float ascii matrix matlab style */
rows=0;  /* number of rows of pure float ascii matrix matlab style */
columns=0;  /* number of columns of pure float ascii matrix matlab style (counting variable) */
oldcolumns=0; /* number of columns of pure float ascii matrix matlab style (first line - if any - ) */
if (is_debug==1) printf("on_ok3_button_fsreada_clicked:  file scan begins\n");
/* watch_for_number: initialize with watch_for_number(0, 0,num_str); and fill num_str with 0 before using; add watch_for_number('\n', 1,num_str) at last.
 * return value: 0=other ASCII <128   1=considering a number    2=comment line and new line    3=new line    4=new line following a new line
                 5=int   6=int and new line   7=floatFP   8=floatEX   9=floatFP and new line   10 floatEX and new line  11 ASCII > 127 not in comment line */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */
/* main loop for scanning file begins */
while((c = getc(readfile)) != EOF) {
        fl++; /* file length */
        switch(watch_for_number(c, 1,num_str)) {
                case 2:  kl++; matlab_valid=1; break; /* comments lines not allowed in matlab ascii matrix */
                case 3:  ln++; 
			rows++;
			if(oldcolumns==0) oldcolumns=columns; /* first row only */
			if (oldcolumns!=columns) matlab_valid=1;
			columns=0;
			break;
		case 6:  ln++;
                case 5:  totint++; matlab_valid=1; /* integers not allowed in matlab ascii matrix */
				switch(ii){
				case 0: sscanf(num_str,"%d",&int1);ii=1;break;
				case 1: sscanf(num_str,"%d",&int2);ii=2;break;
				case 2: sscanf(num_str,"%d",&int3);ii=3;break;
				}
				sparse_detect('I',&ksparse,num_str,&actual,&dims);
				break;
                case 7: totfl++;  
			columns++;
			sparse_detect('F',&ksparse,num_str,&actual,&dims);
			break;
                case 8: totfl++;
			columns++;
			sparse_detect('F',&ksparse,num_str,&actual,&dims);
			break;
                case 9: ln++;totfl++;
			columns++;
			rows++;
			if(oldcolumns==0) oldcolumns=columns; /* first row only */
			if (oldcolumns!=columns) matlab_valid=1;
			columns=0;
			sparse_detect('F',&ksparse,num_str,&actual,&dims);
			break;
                case 10: ln++;totfl++;
			columns++;
			rows++;
			if(oldcolumns==0) oldcolumns=columns; /* first row only */
			if (oldcolumns!=columns) matlab_valid=1;
                        columns=0;
			sparse_detect('F',&ksparse,num_str,&actual,&dims);
			break;
                case 11: nonasc++;matlab_valid=1;break; /* nonascii not allowed in matlab ascii matrix */
                default:break;
                };
        }
/* main loop for scanning file ends */
if (is_debug==1) printf("on_ok3_button_fsreada_clicked:  file scan ends\n");
if (is_debug==1) printf("on_ok3_button_fsreada_clicked: filelength=%ld, lines=%ld, nonascii chars = %ld, comment lines=%d,\n",fl,ln,nonasc,kl);
if (is_debug==1) printf("on_ok3_button_fsreada_clicked: integers=%d, floats=%ld sparse matrix patterns=%d\n",totint,totfl,ksparse);
if (is_debug==1) if (ii==0) printf("on_ok3_button_fsreada_clicked: no integers\n");
if (is_debug==1) if (ii==1) printf("on_ok3_button_fsreada_clicked: int1=%d \n",int1);
if (is_debug==1) if (ii==2) printf("on_ok3_button_fsreada_clicked: int1=%d int2=%d \n",int1,int2);
if (is_debug==1) if (ii==3) printf("on_ok3_button_fsreada_clicked: int1=%d int2=%d int3=%d\n",int1,int2,int3);
if (is_debug==1) printf("on_ok3_button_fsreada_clicked: matlab valid=%d, rows=%d columns=%d places =%d\n",matlab_valid,rows,oldcolumns,oldcolumns*rows);

/* second step: if the file structure is compatible with the required problem, dimension the matrices and read the data */
if(nonasc > 10) {
        /* non ascii chars in the file ! reject ! */
           gtk_widget_show(create_dialog_data_noreadable(reada_fs,"\nThe file contains NON ASCII chars !\n"));
           return;
        }
if(totfl < 12) {
	/* too little floats in the file ! reject ! */
           gtk_widget_show(create_dialog_data_noreadable(reada_fs,"\nThe file contains very few Floats !\n"));
	   return;
	}
/* sparse matrix will have totfl==ksparse, and ii-3*ksparse = 0,1,2,3,+4 at most 7 */
if ((totfl==ksparse)&&(totint-3*ksparse >=0)&&(totint-3*ksparse <8)) {
                is_sparse=1;
                if (is_debug==1) printf("on_ok3_button_fsreada_clicked: sparse matrix detected:");
                if (is_debug==1) printf(" max dimensions %d %d and blocks %d from status machine\n",dims.ii,dims.jj,dims.kk);
                }
/* from here on we reinforce the significance of matlab_valid, to be operative requires correct dimensioning */
if (matlab_valid==0) { 
                            qa=oldcolumns/rows;
                            ma=rows;
                            na=rows;
                            if (totfl- qa*ma*ma !=0 ) matlab_valid=1;
                            if(is_debug==1) printf("on_ok3_button_fsreada_clicked: Matlab ASCII matrix %d blocks size %d x %d detected\n",qa,ma,na);
                      }
/* from now on if matlab_valid==0 qa,ma,na are computed accordingly */
if(ii==0) {
	/* no integers in the file - cannot be sparse obviously ! it could be matlab ascii matrix */
	if((selected_a_problem==1)&&(matlab_valid==0)&&(qa!=3)) { /* QBD, there must be 3 block matrices */
 			sprintf(buf,"\n\n      QBD problem  must have 3 blocks      \n\n The file seems to hold  %d blocks  sized  %d x %d \n\n ",qa,ma,na);
                        gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
                        return;
			}
	if((selected_a_problem==1)&&(matlab_valid==1)) { /* QBD, assume 3 square matrices, ASCII Fortran file no integers in it */
			qa=3;
			na=totfl/qa; /* integer division */			
			ma=sqrt((double)na);
			na=ma;
			if (totfl - qa*ma*ma !=0) {
				/* unknown dimension */
				sprintf(buf,"\n  Unknown Dimension !\n(%ld Floats, no integers)\n",totfl);
				gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
				return;
				}
			/* now we suppose to have 3 ma x ma matrices to read */
			if(is_debug==1) printf("on_ok3_button_fsreada_clicked: QBD Problem and 3 x %d x %d = %ld Floats to read\n",ma,na,totfl);
			} else if(matlab_valid==1) {
	                    /* no integers an no QBD !  */
	                    sprintf(buf,"\n      Unknown Dimension !     \n (no integers in file) \n (no QBD) \n (no valid matlab ascii file) \n");
                            gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
                            return;
	                    }
	} /* if we come to this point, if there are no integers, qa, ma, na are ok */
if (is_sparse == 0) { /* not sparse matrix  */
  if(ii>=1) {
	/* al least first integer present , we presume it is qa */
	qa=int1;
	na=totfl/qa; /* integer division */
        ma=sqrt((double)na);
	na=ma;
        if (totfl - qa*ma*na !=0) {
                  /* unknown dimension */
                  sprintf(buf,"\n  Problem Dimensioning A :\n(%ld Floats, 1st int=%d)\n",totfl,int1);
                  gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
                  return;
                  }
	if((selected_a_problem==1)&&(qa !=3)) {/* not possible with QBD */
		  gtk_widget_show(create_dialog_data_noreadable(reada_fs,"\n More than 3 Matrices \n   with QBD Problem ? \n"));
		  return;
		}
	/* now we suppose to have qa ma x ma matrices to read */
	if(is_debug==1) printf("on_ok3_button_fsreada_clicked: Problem %d with %d x %d x %d = %ld Floats to read\n",selected_a_problem,qa,ma,ma,totfl);
	}
    }/* end of non sparse matrix analysis ..... */
   else 
      { /* start of sparse matrix analysis - ii>=1 obviously ... */
      if (ii==3*ksparse) {/* no choice, the dimensions will be dims.ii .jj .kk we assume first index is block index */
 	if (dims.jj != dims.kk ) {
		/* not sure */
		sprintf(buf,"\n  Problem Dimensioning A :\n It looks a sparse matrix %d x %d x %d \n with not square blocks\n",dims.ii,dims.jj,dims.kk);
		return;
		}
	qa=dims.ii;
	ma=dims.jj;
	na=dims.kk;
       } else {
         /* if present we prefer to setup qa, ma, na from  int1, int2, int3, but additional integers could be anyware, so no guarantee they are correct  */
         qa=int1; if (dims.ii > qa) qa=dims.ii;
         ma=int2; if (dims.jj > ma) ma=dims.jj;
	 na=int3; if (dims.kk > na) na=dims.kk;
	}
	if((selected_a_problem==1)&&(qa!=3)) { /* QBD, there must be 3 block matrices */
                        sprintf(buf,"\n\n      QBD problem  must have 3 blocks      \n\n The file seems to hold  %d blocks  sized  %d x %d \n\n ",qa,ma,na);
                        gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
                        return;
                        }
      if(is_debug==1) printf("on_ok3_button_fsreada_clicked:  sparse matrix %d x %d x %d ; %ld Floats to read\n",qa,ma,ma,totfl);	
     } /* end of sparse matrix analysis ..... */


/* we now have qa matrices of dimension ma x ma to read */

/* from now on the old A data are not valid any more  - take note of the selected problem */
selected.type = selected_a_problem;
if (selected_a_problem==1) gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  New Problem QBD ");
if (selected_a_problem==2) {
			   if (algorithms_choice.type == 2) {   /* LR not available, deselect it */
                                algorithms_choice.type=1;
                                algorithms_choice.cr_base=1;
                                algorithms_choice.cr_shift=0;
                                algorithms_choice.cr_diag=0;
                                }
	                   gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  New Problem M/G/1 *  (Warning: Logaritmic Reduction not available)");
			   }
if (selected_a_problem==3) {
			   if (algorithms_choice.type == 2) { /* LR not available, deselect it */
                                algorithms_choice.type=1;
                                algorithms_choice.cr_base=1;
                                algorithms_choice.cr_shift=0;
                                algorithms_choice.cr_diag=0;
                                }
                           gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  New Problem GI/M/1 *  (Warning: Logaritmic Reduction not available) ");
			   }
/* here we should add a check for qa >=3 anyway ! */
if (qa <3) {
    sprintf(buf,"\n  Too few Blocks in A (%d)   \n       ( minimum 3 required )    \n",qa);
        gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
        return;
  }
committed.type =0;
committed.allocated=0;
err=0;
 g_idle_add((GtkFunction) selection_uptodaten,NULL);
/* allocate A and initialize to 0.0E0 all terms */
alloc_mata_(&ma,&qa,&err);
if (err !=0) {
	sprintf(buf,"\n  Allocation of A did Fail !\n(%ld Floats needed)\n",totfl);
        gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
        return;
	}

/* rewind the file */
fseek(readfile,(long int) 0,SEEK_SET); 
/* read the data */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */
i=1;
j=1;
k=1;
ckfl=0; /* will count real really read */
if (is_sparse ==0) { /* not sparse matrix */
  while(((c = getc(readfile)) != EOF)&&(err==0)) {
        switch(watch_for_number(c, 1,num_str)) {
                case 7:  
                case 8: 
                case 9:  
                case 10:
			if(sscanf(num_str,"%lf",&r)==0) err=1; /* printf(" %s --> A(%d,%d,%d)=%g\n",num_str,i,j,k,r);*/
			ckfl++;
			write_mata_(&j,&i,&k,&r);
			if(matlab_valid==0) {
				i++; if (i>ma) {i=1;k++;} ; if(k>qa) {k=1;j++;};	
				} else {			
			        j++; if (j>ma) {j=1;i++;}; if(i>ma) {i=1;k++;}; 
			        } 
			break;
                default:break;
                };
        }
 if (err!=0) {
        sprintf(buf,"\n Some Error in reading floats !  " );
        gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
        return;
	}
 if (ckfl!=totfl) {
	sprintf(buf,"\n We did skip some float ! " );
        gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
        return;
	}
  }
else { /* sparse matrix   note that now A=0.0 */
          sparse_detect(0, &ksparse, NULL, &actual, &dims); /* initilize it */
          while((c = getc(readfile)) != EOF) {
               switch(watch_for_number(c, 1,num_str)) {
                    case 2:   break;
                    case 3:   break;
                    case 6:  
                    case 5:  
                                valid=sparse_detect('I',&ksparse,num_str,&actual,&dims);
                                break;
                    case 7: 
                        valid=sparse_detect('F',&ksparse,num_str,&actual,&dims);
                        break;
                    case 8: 
                        valid=sparse_detect('F',&ksparse,num_str,&actual,&dims);
                        break;
                    case 9: 
                        valid=sparse_detect('F',&ksparse,num_str,&actual,&dims);
                        break;
                    case 10: 
                        valid=sparse_detect('F',&ksparse,num_str,&actual,&dims);
                        break;
                    case 11: nonasc++;break;
                    default:break;
                };
		if (valid==1) {
				/* valid data may include out of bounds indexex like 0 0 0 */
				if ((actual.kk>0)&&(actual.jj>0)&&(actual.ii>0)&&(actual.kk<=ma)&&(actual.jj<=ma)&&(actual.ii<=qa))
				write_mata_(&(actual.jj),&(actual.kk),&(actual.ii),&(actual.ff));
				valid=0;
				}
           }
  }


/* chk stocasticity mv in a ad hoc window
smax=0;
for(j=1;j<=ma;j++) {
   ss=0.0;
   for(k=1;k<=qa;k++) for(i=1;i<=ma;i++) {read_mata_(&j,&i,&k,&r);ss=ss+r;}
   ss=ss-(double)1.0;
   smax=ss*ss;
   }
smax=sqrt(smax);
sprintf(buf,"\n Read A %d x %d x %d \n stoc.err=%g",ma,ma,qa,smax );
gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
*/

/* no errors, we did read the file ! take note that we did it */
invalidate_completed(); /* data is not ready any more for writing results */

committed.type = selected_a_problem;
committed.allocated = 1;
committed.example = 0;
committed.dimension_m = ma;
committed.dimension_n = 0; /* the B are not valid any more */
committed.matrix_a_num = qa;
/* B must be re read after reading A we invalidate all the B markers*/
committed.matrix_b_num = 0;
committed.is_bn1=0; 
committed.is_b0=0;
committed.is_b=0;
/* remember that the edit a preference has a block number to reset ! */
pea.block=1;

if (is_debug==1) printf("on_ok3_button_fsreada_clicked: committed .type=%d, .allocated=%d, .committed.dimension_m=%d .committed.matrix_a_num=%d\n",committed.type,committed.allocated,committed.dimension_m,committed.matrix_a_num);

fclose(readfile);
is_reada_open=0;
g_idle_add((GtkFunction) selection_uptodaten,NULL);
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button))); /* close file selection dialog Save A */

} 
/******************************/

/* Read A File Selection Dialog: cancel ***** Callback */
void
on_cancel_button_fsreada_clicked      (GtkButton   * button, gpointer user_data )
{
/* int is_reada_open; global */
if(is_debug==1) printf("Read A File Selection Dialog: quit\n");
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
}
/*****************************/

/* Read A File Selection Dialog: destroy ***** Callback */
void
on_destroy_fsreada      (GtkWidget   * ww, gpointer user_data )
{
/* int is_reada_open; global */
if(is_debug==1) printf("Read A File Selection Dialog: destroy\n");
is_reada_open=0;
}
/*****************************/


/* Read B: File Selection Dialog Interface  ***** Interface */
GtkWidget*
create_fileselection_readb(void)
{
GtkWidget *fileselection;
GtkWidget *ok_button;
GtkWidget *cancel_button;
GtkWidget *close_button;
GtkWidget *button1,*button2,*button3;
GtkWidget *hbox1,*hbox2,*hbox3;
GtkWidget *label1,*label2,*label3;
/* all this mess to show the icon we want in the buttons OK */
GtkWidget *pixmapwid1,*pixmapwid2,*pixmapwid3;
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkStyle *style;
GdkColormap *mappacolor;
/* end  mess                                             */

if(committed.type==1) fileselection = gtk_file_selection_new ("QBD Problem: Read B  ");
if(committed.type==2) fileselection = gtk_file_selection_new ("M/G/1 Problem: Read B  ");
if(committed.type==3) fileselection = gtk_file_selection_new ("GI/M/1 Problem: Read B  ");
gtk_container_set_border_width (GTK_CONTAINER (fileselection), 10);

gtk_file_selection_set_filename (GTK_FILE_SELECTION(fileselection),pathgru_fs);
ok_button = GTK_FILE_SELECTION (fileselection)->ok_button;
gtk_widget_hide (ok_button);
/* GTK_WIDGET_SET_FLAGS (ok_button, GTK_CAN_DEFAULT);*/

cancel_button = GTK_FILE_SELECTION (fileselection)->cancel_button;
/* gtk_widget_show (cancel_button);
GTK_WIDGET_SET_FLAGS (cancel_button, GTK_CAN_DEFAULT);*/
gtk_widget_hide (cancel_button);

close_button =  gtk_button_new_from_stock (GTK_STOCK_CLOSE);
gtk_widget_show (close_button);

/* build out icons */
style = gtk_widget_get_style(fileselection);
mappacolor = gdk_colormap_get_system ();
pixmap =gdk_pixmap_colormap_create_from_xpm_d(fileselection->window,mappacolor,&mask,&style->bg[GTK_STATE_NORMAL],stock_ok_20);
pixmapwid1 = gtk_pixmap_new(pixmap,mask);
pixmapwid2 = gtk_pixmap_new(pixmap,mask);
pixmapwid3 = gtk_pixmap_new(pixmap,mask);
gtk_widget_show(pixmapwid1);
gtk_widget_show(pixmapwid2);
gtk_widget_show(pixmapwid3);
/*  
button_new = gtk_dialog_add_button(GTK_DIALOG(fileselection),"Maple\nOK",GTK_RESPONSE_DELETE_EVENT);
*/
label1 = gtk_label_new("Read First:\n  B0 ");
if(committed.type==1) { /* QBD has B optional */
label2 = gtk_label_new("Read Then:\n B  (optional) ");
label3 = gtk_label_new("Read Then:\n BN1");
} else { /* MG1 and GIM1 have BN1 optional */
label2 = gtk_label_new("Read Then:\n B ");
label3 = gtk_label_new("Read Then:\n BN1 (optional) ");
}
gtk_widget_show(label1);
gtk_widget_show(label2);
gtk_widget_show(label3);
hbox1 = gtk_hbox_new(TRUE,0);
hbox2 = gtk_hbox_new(TRUE,0);
hbox3 = gtk_hbox_new(TRUE,0);
gtk_box_pack_start (GTK_BOX (hbox1), pixmapwid1, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), pixmapwid2, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), pixmapwid3, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox1), label1, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), label2, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox3), label3, TRUE, TRUE, 0);
gtk_widget_show(hbox1);
gtk_widget_show(hbox2);
gtk_widget_show(hbox3);
button1 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button1),hbox1);
gtk_widget_show(button1); 
button2 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button2),hbox2);
gtk_widget_show(button2);
button3 = gtk_button_new();
gtk_container_add (GTK_CONTAINER(button3),hbox3);
gtk_widget_show(button3);

/* GTK_RESPONSE_DELETE_EVENT */
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),close_button,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button1,GTK_RESPONSE_DELETE_EVENT);
if (committed.type==1) { /* QBD has B optional */
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button3,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button2,GTK_RESPONSE_DELETE_EVENT);
} else {
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button2,GTK_RESPONSE_DELETE_EVENT);
gtk_dialog_add_action_widget (GTK_DIALOG(fileselection),button3,GTK_RESPONSE_DELETE_EVENT);

}
g_signal_connect ((gpointer) close_button, "clicked", G_CALLBACK (on_cancel_button_fsreadb_clicked), NULL);
g_signal_connect ((gpointer) cancel_button, "clicked", G_CALLBACK (on_cancel_button_fsreadb_clicked), NULL);
g_signal_connect ((gpointer) fileselection, "destroy", G_CALLBACK (on_destroy_fsreada),NULL);
g_signal_connect ((gpointer)button1,"clicked", G_CALLBACK (on_ok2_button_fsreadb_clicked), NULL);
g_signal_connect ((gpointer)button2,"clicked", G_CALLBACK (on_ok3_button_fsreadb_clicked), NULL);
g_signal_connect ((gpointer)button3,"clicked", G_CALLBACK (on_ok1_button_fsreadb_clicked), NULL);

return fileselection;

}
/*****************************/

/* Read B File Selection Dialog: ok1 ***** Callback  READ ASCII FILE BN1 
 * we know the type of the problem 1=QBD, 2=M/G/1 3=GI/M/1 
 * we know the dimensions n of matrix A 
 * B0 is m x m 
 * B  nbb blocks m x n (optional for QBD) or for GIM1  nbb blocks n x m
 * BN1 (optional for MG1 and GIM1) is   n x m or for GIM1 m x n
 * first read B0, so we shall know both n and m, then B, BN1 !
 * 1. scan file to get some structure data
 * 2. check 
 * 3. read
 * sparse matrices syntax not allowed here
 */

void
on_ok1_button_fsreadb_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *readb_fs; global    */
/* struct running_problem_str  completed;  */
/* int is_readb_open; global */
gchar * filename;
FILE * readfile;
int c;                  /* read from file one char by one */
char num_str[1024];     /* a number with more then 1024 digits will crash the program ... to fix later ...*/
long int fl, ln, nonasc;/* file length, number of lines, non ascii chars not in comment line */
int kl;                 /* comment lines */
int totint;             /* total trings corresponding to integers number */
long int totfl,ckfl;    /* total strings corresponding to floating point numbers and number of floats really read from file */
int i,j,nb,mb,err; /* ma,na,qa dimensions of blocks and # of blocks, i,j,k indexes, err error flag */
double  r;              /* float value to read */
int int1,int2,int3,ii;  /* first 3 integers present in the file, if any, and how many (0,1,2,3) of them */
char buf[256] ;
int matlab_valid,rows,columns, oldcolumns;   /* matlab_valid=1 if the file is NOT a matlab matrix */

/* check that B0 has been read first */
if(committed.is_b0==0) {
	sprintf(buf,"\n READ B0 FIRST PLEASE !\n");
        gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
	return;
	}
/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(readb_fs));
if(is_debug) printf("on_ok1_button_fsreadb_clicked: algorithm=%d,  filename = %s\n",selected_a_problem,filename);
if ((readfile = fopen(filename,"r+")) == NULL) {  /* "r" should be enougth.. but with "r" dir can be opended too, and a check will be needed */
        /* File not readable popup  */
        gtk_widget_show(create_dialog_noreadable(readb_fs));
        return;
        }
/* file is open ok  */
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, */
/* first step: scan the file to get length, check if ascii or not, check line separators, count possible integers and float 
 * read, if present, the first 3 integers, count sparse matrix pattern (I I I F ), check for regular rows of floats for 
 * matlab ASCII matrix format - for valid matlab ascii we require no integers, floats only, same number in each line.
 */
err = 0; /* no error till now */
fl=0; /* file length */
ln=0; /* lines */
nonasc=0; /* ascii >128 */
kl=0; /* comment lines */
totint=0; /* strings corresponding to integers */
totfl=0;  /* strings corresponding to floats */
ii=0;     /* count if preset first 3 integers */
int1=0;
int2=0;
int3=0;
matlab_valid=0; /* if this =1 we are shure that the file is not compatible with pure float ascii matrix matlab style */
rows=0;  /* number of rows of pure float ascii matrix matlab style */
columns=0;  /* number of columns of pure float ascii matrix matlab style (counting variable) */
oldcolumns=0; /* number of columns of pure float ascii matrix matlab style (first line - if any - ) */
if (is_debug==1) printf("on_ok1_button_fsreadb_clicked:  file scan begins\n");
/* watch_for_number: initialize with watch_for_number(0, 0,num_str); and fill num_str with 0 before using; add watch_for_number('\n', 1,num_str) at last.
 * return value: 0=other ASCII <128   1=considering a number    2=comment line and new line    3=new line    4=new line following a new line
                 5=int   6=int and new line   7=floatFP   8=floatEX   9=floatFP and new line   10 floatEX and new line  11 ASCII > 127 not in comment line */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */
/* main loop for scanning file begins */
while((c = getc(readfile)) != EOF) {
        fl++; /* file length */
        switch(watch_for_number(c, 1,num_str)) {
                case 2:  kl++; matlab_valid=1; break; /* comments lines not allowed in matlab ascii matrix */
                case 3:  ln++; 
			rows++;
			if(oldcolumns==0) oldcolumns=columns; /* first row only */
			if (oldcolumns!=columns) matlab_valid=1;
			columns=0;
			break;
		case 6:  ln++;
                case 5:  totint++; matlab_valid=1; /* integers not allowed in matlab ascii matrix */
				switch(ii){
				case 0: sscanf(num_str,"%d",&int1);ii=1;break;
				case 1: sscanf(num_str,"%d",&int2);ii=2;break;
				case 2: sscanf(num_str,"%d",&int3);ii=3;break;
				}
				break;
                case 7: totfl++;  
			columns++;
			break;
                case 8: totfl++;
			columns++;
			break;
                case 9: ln++;totfl++;
			columns++;
			rows++;
			if(oldcolumns==0) oldcolumns=columns; /* first row only */
			if (oldcolumns!=columns) matlab_valid=1;
			columns=0;
			break;
                case 10: ln++;totfl++;
			columns++;
			rows++;
			if(oldcolumns==0) oldcolumns=columns; /* first row only */
			if (oldcolumns!=columns) matlab_valid=1;
                        columns=0;
			break;
                case 11: nonasc++;matlab_valid=1;break; /* nonascii not allowed in matlab ascii matrix */
                default:break;
                };
        }
/* main loop for scanning file ends */
if (is_debug==1) printf("on_ok1_button_fsreadb_clicked:  file scan ends\n");
if (is_debug==1) printf("on_ok1_button_fsreadb_clicked: filelength=%ld, lines=%ld, nonascii chars = %ld, comment lines=%d,\n",fl,ln,nonasc,kl);
if (is_debug==1) printf("on_ok1_button_fsreadb_clicked: integers=%d, floats=%ld \n",totint,totfl);
if (is_debug==1) if (ii==0) printf("on_ok1_button_fsreadb_clicked: no integers\n");
if (is_debug==1) if (ii==1) printf("on_ok1_button_fsreadb_clicked: int1=%d \n",int1);
if (is_debug==1) if (ii==2) printf("on_ok1_button_fsreadb_clicked: int1=%d int2=%d \n",int1,int2);
if (is_debug==1) if (ii==3) printf("on_ok1_button_fsreadb_clicked: int1=%d int2=%d int3=%d\n",int1,int2,int3);
if (is_debug==1) printf("on_ok1_button_fsreadb_clicked: matlab valid=%d, rows=%d columns=%d places =%d\n",matlab_valid,rows,oldcolumns,oldcolumns*rows);

/* second step: if the file structure is compatible with the required problem, dimension the matrices and read the data */
if(nonasc > 10) {
        /* non ascii chars in the file ! reject ! */
           gtk_widget_show(create_dialog_data_noreadable(readb_fs,"\nThe file contains NON ASCII chars !\n"));
           return;
        }
if(totfl < 3) {
	/* too little floats in the file ! reject ! */
           gtk_widget_show(create_dialog_data_noreadable(readb_fs,"\nThe file contains very few Floats !\n"));
	   return;
	}
/* check that the number of floats is correct */
if(totfl != committed.dimension_m*committed.dimension_n) {
        sprintf(buf,"\nThe number of floats in the file is not correct!\nReading %ld floats instead of %d (= %d * %d)\n\n",totfl,committed.dimension_m*committed.dimension_n,committed.dimension_m,committed.dimension_n);
 	gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
        return;
	}
/* the only difference between Matlab and Fortran is that matlab files has a clear row columns structure */
if(committed.type==3) { /* GIM1 has BN1 n x m */
nb=committed.dimension_n;
mb=committed.dimension_m;
} else {  /* instead of m x n */
nb=committed.dimension_m;
mb=committed.dimension_n;
}
if (matlab_valid==0) if ((rows!=nb)||(oldcolumns!=mb)) matlab_valid=1;
if(is_debug==1) if (matlab_valid==0) printf("on_ok1_button_fsreadb_clicked: is matlab valid rows=%d columns=%d\n",rows, oldcolumns);
if(is_debug==1) if (matlab_valid==1) printf("on_ok1_button_fsreadb_clicked: is Fortran valid\n");
/* if it looks a Fortran file, it must have some headers with the dimensions in it */
if ((matlab_valid==1)&&(ii<2)) {
	gtk_widget_show(create_dialog_data_noreadable(readb_fs,"\nProblem dimensioning:\nEither a Matlab File with trasnsposed data\n or a Fortran File without headers\n"));
        return;
  }
/* some dubious case reache this point: Fortran files with inconsistent dimensioning */
if ((matlab_valid==1)&&(ii>=2)) if ((int1!=nb)||(int2!=mb)) {
		sprintf(buf,"\nFortran file dimensions:\n      %d    %d    \nversus expected:\n      %d    %d    \n",int1,int2,nb,mb);
		gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
                return;
}
/* from now on the old BN1 data are not valid any more   */
committed.is_bn1=0;
/* allocate BN1A and initialize to 0.0E0 all terms */
alloc_matbn1_(&nb,&mb,&err);
if (err !=0) {
        sprintf(buf,"\n  Allocation of BN1 did Fail !\n(%ld Floats needed)\n",totfl);
        gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
        return;
        }

/* rewind the file */
fseek(readfile,(long int) 0,SEEK_SET); 
/* read the data */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */

i=1;
j=1;
ckfl=0; /* will count real really read */
  while(((c = getc(readfile)) != EOF)&&(err==0)) {
        switch(watch_for_number(c, 1,num_str)) {
                case 7:
                case 8:
                case 9:
                case 10:
                        if(sscanf(num_str,"%lf",&r)==0) err=1;   /* printf(" %s --> BN1(%d,%d)=%g\n",num_str,j,i,r);*/
                        ckfl++;
                         write_matbn1_(&j,&i,&r);
                        if(matlab_valid==0) {
                                i++; if (i>mb) {i=1; j++;}
                                } else {
                                j++; if (j>nb) {j=1;i++;}; 
                                }
                        break;
                default:break;
                };
	}

 if (err!=0) {
        sprintf(buf,"\n Some Error in reading floats !  " );
        gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
        return;
        }
 if (ckfl!=totfl) {
        sprintf(buf,"\n We did skip some float ! " );
        gtk_widget_show(create_dialog_data_noreadable(reada_fs,buf));
        return;
        }

/* chk stocasticity mv in a ad hoc window
*/

/* no errors, we did read the file ! take note that we did it */

fclose(readfile);

if (is_debug==1) printf("on_ok1_button_fsreadb_clicked: Read BN1  %d x %d \n",nb , mb);
committed.is_bn1=1;
gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"Matrix BN1 has been read from file");
} 
/******************************/

/* Read B File Selection Dialog: ok2 ***** Callback  READ ASCII FILE B0 
 * we know the type of the problem 1=QBD, 2=M/G/1 3=GI/M/1 
 * we know the dimensions n of matrix A 
 * B0 is m x m 
 * B consist of a certain number nbb of blocks m x n 
 * BN1 is optional  n x m 
 * first read B0, so we shall know both n and m, then B, BN1 !
 * 1. scan file to get some structure data
 * 2. check 
 * 3. read
 * sparse matrices syntax not allowed here
 */

void
on_ok2_button_fsreadb_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *readb_fs; global    */
/* struct running_problem_str  completed;  */
/* int is_readb_open; global */
gchar * filename;
FILE * readfile;
int c;                  /* read from file one char by one */
char num_str[1024];     /* a number with more then 1024 digits will crash the program ... to fix later ...*/
long int fl, ln, nonasc;/* file length, number of lines, non ascii chars not in comment line */
int kl;                 /* comment lines */
int totint;             /* total trings corresponding to integers number */
long int totfl,ckfl;    /* total strings corresponding to floating point numbers and number of floats really read from file */
int i,j,mb,err; /* ma,na,qa dimensions of blocks and # of blocks, i,j,k indexes, err error flag */
double  r;              /* float value to read */
int int1,int2,int3,ii;  /* first 3 integers present in the file, if any, and how many (0,1,2,3) of them */
char buf[256] ;
int matlab_valid,rows,columns, oldcolumns;   /* matlab_valid=1 if the file is NOT a matlab matrix */

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(readb_fs));
if(is_debug) printf("on_ok2_button_fsreadb_clicked: algorithm=%d,  filename = %s\n",selected_a_problem,filename);
if ((readfile = fopen(filename,"r+")) == NULL) {  /* "r" should be enougth.. but with "r" dir can be opended too, and a check will be needed */
        /* File not readable popup  */
        gtk_widget_show(create_dialog_noreadable(readb_fs));
        return;
        }
/* file is open ok  */
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, */
/* first step: scan the file to get length, check if ascii or not, check line separators, count possible integers and float 
 * read, if present, the first 3 integers, count sparse matrix pattern (I I I F ), check for regular rows of floats for 
 * matlab ASCII matrix format - for valid matlab ascii we require no integers, floats only, same number in each line.
 */
err = 0; /* no error till now */
fl=0; /* file length */
ln=0; /* lines */
nonasc=0; /* ascii >128 */
kl=0; /* comment lines */
totint=0; /* strings corresponding to integers */
totfl=0;  /* strings corresponding to floats */
ii=0;     /* count if preset first 3 integers */
int1=0;
int2=0;
int3=0;
matlab_valid=0; /* if this =1 we are shure that the file is not compatible with pure float ascii matrix matlab style */
rows=0;  /* number of rows of pure float ascii matrix matlab style */
columns=0;  /* number of columns of pure float ascii matrix matlab style (counting variable) */
oldcolumns=0; /* number of columns of pure float ascii matrix matlab style (first line - if any - ) */
oldcolumns=0; /* number of columns of pure float ascii matrix matlab style (first line - if any - ) */
if (is_debug==1) printf("on_ok2_button_fsreadb_clicked:  file scan begins\n");
/* watch_for_number: initialize with watch_for_number(0, 0,num_str); and fill num_str with 0 before using; add watch_for_number('\n', 1,num_str) at last.
 * return value: 0=other ASCII <128   1=considering a number    2=comment line and new line    3=new line    4=new line following a new line
                 5=int   6=int and new line   7=floatFP   8=floatEX   9=floatFP and new line   10 floatEX and new line  11 ASCII > 127 not in comment line */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */
/* main loop for scanning file begins */
while((c = getc(readfile)) != EOF) {
        fl++; /* file length */
        switch(watch_for_number(c, 1,num_str)) {
                case 2:  kl++; matlab_valid=1; break; /* comments lines not allowed in matlab ascii matrix */
                case 3:  ln++;
                        rows++;
                        if(oldcolumns==0) oldcolumns=columns; /* first row only */
                        if (oldcolumns!=columns) matlab_valid=1;
                        columns=0;
                        break;
                case 6:  ln++;
                case 5:  totint++; matlab_valid=1; /* integers not allowed in matlab ascii matrix */
                                switch(ii){
                                case 0: sscanf(num_str,"%d",&int1);ii=1;break;
                                case 1: sscanf(num_str,"%d",&int2);ii=2;break;
                                case 2: sscanf(num_str,"%d",&int3);ii=3;break;
                                }
                                break;
                case 7: totfl++;
                        columns++;
                        break;
                case 8: totfl++;
                        columns++;
                        break;
                case 9: ln++;totfl++;
                        columns++;
                        rows++;
                        if(oldcolumns==0) oldcolumns=columns; /* first row only */
                        if (oldcolumns!=columns) matlab_valid=1;
                        columns=0;
                        break;
                case 10: ln++;totfl++;
                        columns++;
                        rows++;
                        if(oldcolumns==0) oldcolumns=columns; /* first row only */
                        if (oldcolumns!=columns) matlab_valid=1;
                        columns=0;
                        break;
                case 11: nonasc++;matlab_valid=1;break; /* nonascii not allowed in matlab ascii matrix */
                default:break;
                };
        }
/* main loop for scanning file ends */
if (is_debug==1) printf("on_ok2_button_fsreadb_clicked:  file scan ends\n");
if (is_debug==1) printf("on_ok2_button_fsreadb_clicked: filelength=%ld, lines=%ld, nonascii chars = %ld, comment lines=%d,\n",fl,ln,nonasc,kl);
if (is_debug==1) printf("on_ok2_button_fsreadb_clicked: integers=%d, floats=%ld \n",totint,totfl);
if (is_debug==1) if (ii==0) printf("on_ok2_button_fsreadb_clicked: no integers\n");
if (is_debug==1) if (ii==1) printf("on_ok2_button_fsreadb_clicked: int1=%d \n",int1);
if (is_debug==1) if (ii==2) printf("on_ok2_button_fsreadb_clicked: int1=%d int2=%d \n",int1,int2);
if (is_debug==1) if (ii==3) printf("on_ok2_button_fsreadb_clicked: int1=%d int2=%d int3=%d\n",int1,int2,int3);
if (is_debug==1) printf("on_ok2_button_fsreadb_clicked: matlab valid=%d, rows=%d columns=%d places =%d\n",matlab_valid,rows,oldcolumns,oldcolumns*rows);

/* second step: if the file structure is compatible with the required problem, dimension the matrices and read the data */
if(nonasc > 10) {
        /* non ascii chars in the file ! reject ! */
           gtk_widget_show(create_dialog_data_noreadable(readb_fs,"\nThe file contains NON ASCII chars !\n"));
           return;
        }
if(totfl < 3) {
        /* too little floats in the file ! reject ! */
           gtk_widget_show(create_dialog_data_noreadable(readb_fs,"\nThe file contains very few Floats !\n"));
           return;
        }
/* check that the number of floats is correct */
mb=sqrt((double)totfl);
if(totfl != mb*mb) {
        sprintf(buf,"\n\nThe number of floats in the file is not a square !\n\nReading %ld floats, nearest square %d = %d * %d\n\n",totfl,mb*mb,mb,mb);
        gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
        return;
        }
/* the only difference between Matlab and Fortran is that matlab files has a clear row columns structure */
if (matlab_valid==0) if ((rows!=mb)||(oldcolumns!=mb)) matlab_valid=1;
if(is_debug==1) if (matlab_valid==0) printf("on_ok2_button_fsreadb_clicked: is matlab valid rows=%d columns=%d\n",rows, oldcolumns);
if(is_debug==1) if (matlab_valid==1) printf("on_ok2_button_fsreadb_clicked: is Fortran valid\n");
/* if it looks a Fortran file, it must have some headers with the dimensions in it */
if ((matlab_valid==1)&&(ii==0)) {
        gtk_widget_show(create_dialog_data_noreadable(readb_fs,"\n\n No Matlab File and no Header !\n "));
        return;
  }
/* some dubious case reache this point: Fortran files with inconsistent dimensioning */
if ((matlab_valid==1)&&(ii>0)&&(int1!=mb)) {
                sprintf(buf,"\n Incorrect dimension in Fortran file: \n      ( %d versus expected %d ) \n",int1,mb);
                gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
                return;
}

/* from now on the old B0 B BN1 data are not valid any more   */
committed.is_b0=0;
committed.is_b=0;
committed.is_bn1=0;
/* allocate B0 and initialize to 0.0E0 all terms */
alloc_matb0_(&mb,&err);
if (err !=0) {
        sprintf(buf,"\n  Allocation of B0 did Fail !\n(%ld Floats needed)\n",totfl);
        gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
        return;
        }
/* rewind the file */
fseek(readfile,(long int) 0,SEEK_SET);
/* read the data */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */

i=1;
j=1;
ckfl=0; /* will count real really read */
  while(((c = getc(readfile)) != EOF)&&(err==0)) {
        switch(watch_for_number(c, 1,num_str)) {
                case 7:
                case 8:
                case 9:
                case 10:
                        if(sscanf(num_str,"%lf",&r)==0) err=1;  /* printf(" %s --> A(%d,%d)=%g\n",num_str,i,j,r);*/
                        ckfl++;
                         write_matb0_(&j,&i,&r);
                        if(matlab_valid==0) {
                                i++; if (i>mb) {i=1; j++;}
                                } else {
                                j++; if (j>mb) {j=1;i++;};
                                }
                        break;
                default:break;
                };
        }

 if (err!=0) {
        sprintf(buf,"\n Some Error in reading floats !  " );
        gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
        return;
        }
 if (ckfl!=totfl) {
        sprintf(buf,"\n We did skip some float ! " );
        gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
        return;
        }

/* chk stocasticity mv in a ad hoc window
*/

/* no errors, we did read the file ! take note that we did it */


fclose(readfile);
if (is_debug==1) printf("on_ok2_button_fsreadb_clicked: Read B0  %d x %d \n",mb , mb);
committed.is_b0=1;
committed.dimension_n=mb;
if (committed.dimension_n!=committed.dimension_m) {
gtk_widget_show(create_dialog_rectangular(readb_fs));
}
g_idle_add((GtkFunction) selection_uptodaten,NULL);
gtk_statusbar_push(GTK_STATUSBAR(statusb),0," Matrix B0 has been read from file");
}
/******************************/

/* Read B File Selection Dialog: ok3 ***** Callback  READ ASCII FILE  B 
 * we know the type of the problem 1=QBD, 2=M/G/1 3=GI/M/1 
 * we know the dimensions n of matrix A 
 * B0 is m x m 
 * B consist of a certain number nbb of blocks m x n one after the other.
 * BN1 is optional  n x m 
 * first read B0, so we shall know both n and m, then B, BN1 !
 * note that in GI/M/1 nbb must be = nba - 1 !
 * 1. scan file to get some structure data
 * 2. check 
 * 3. read
 * sparse matrices syntax not allowed here
 */

void
on_ok3_button_fsreadb_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget *readb_fs; global    */
/* struct running_problem_str  completed;  */
/* int is_readb_open; global */
gchar * filename;
FILE * readfile;
int c;                  /* read from file one char by one */
char num_str[1024];     /* a number with more then 1024 digits will crash the program ... to fix later ...*/
long int fl, ln, nonasc;/* file length, number of lines, non ascii chars not in comment line */
int kl;                 /* comment lines */
int totint;             /* total trings corresponding to integers number */
long int totfl,ckfl;    /* total strings corresponding to floating point numbers and number of floats really read from file */
int i,j,k,nb,mb,qb,err; /* ma,na,qa dimensions of blocks and # of blocks, i,j,k indexes, err error flag */
double  r;              /* float value to read */
int int1,int2,int3,ii;  /* first 3 integers present in the file, if any, and how many (0,1,2,3) of them */
char buf[256] ;
int ksparse,is_sparse;    /* count sparse matrix patterns */
struct sparse_four dims,actual; /* try to detect dimension of sparse matrix */
int matlab_valid,rows,columns, oldcolumns;   /* matlab_valid=1 if the file is NOT a matlab matrix */

/* check that B0 has been read first */
if(committed.is_b0==0) {
        sprintf(buf,"\n READ B0 FIRST PLEASE !\n");
        gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
        return;
        }

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(readb_fs));
if(is_debug) printf("on_ok3_button_fsreadb_clicked: algorithm=%d,  filename = %s\n",selected_a_problem,filename);
if ((readfile = fopen(filename,"r+")) == NULL) {  /* "r" should be enougth.. but with "r" dir can be opended too, and a check will be needed */
        /* File not readable popup  */
        gtk_widget_show(create_dialog_noreadable(readb_fs));
        return;
        }
/* file is open ok  */
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, */
/* first step: scan the file to get length, check if ascii or not, check line separators, count possible integers and float 
 * read, if present, the first 3 integers, count sparse matrix pattern (I I I F ), check for regular rows of floats for 
 * matlab ASCII matrix format - for valid matlab ascii we require no integers, floats only, same number in each line.
 */
err = 0; /* no error till now */
fl=0; /* file length */
ln=0; /* lines */
nonasc=0; /* ascii >128 */
kl=0; /* comment lines */
totint=0; /* strings corresponding to integers */
totfl=0;  /* strings corresponding to floats */
ii=0;     /* count if preset first 3 integers */
int1=0;
int2=0;
int3=0;
is_sparse=0; /* 0=not sparse 1=sparse matrix */
sparse_detect(0, &ksparse, NULL, &actual, &dims); /* initilize sparse detect status machine  */
matlab_valid=0; /* if this =1 we are shure that the file is not compatible with pure float ascii matrix matlab style */
rows=0;  /* number of rows of pure float ascii matrix matlab style */
columns=0;  /* number of columns of pure float ascii matrix matlab style (counting variable) */
oldcolumns=0; /* number of columns of pure float ascii matrix matlab style (first line - if any - ) */
if (is_debug==1) printf("on_ok3_button_fsreadb_clicked:  file scan begins\n");
/* watch_for_number: initialize with watch_for_number(0, 0,num_str); and fill num_str with 0 before using; add watch_for_number('\n', 1,num_str) at last.
 * return value: 0=other ASCII <128   1=considering a number    2=comment line and new line    3=new line    4=new line following a new line
                 5=int   6=int and new line   7=floatFP   8=floatEX   9=floatFP and new line   10 floatEX and new line  11 ASCII > 127 not in comment line */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */
/* main loop for scanning file begins */
while((c = getc(readfile)) != EOF) {
        fl++; /* file length */
        switch(watch_for_number(c, 1,num_str)) {
                case 2:  kl++; matlab_valid=1; break; /* comments lines not allowed in matlab ascii matrix */
                case 3:  ln++; 
			rows++;
			if(oldcolumns==0) oldcolumns=columns; /* first row only */
			if (oldcolumns!=columns) matlab_valid=1;
			columns=0;
			break;
		case 6:  ln++;
                case 5:  totint++; matlab_valid=1; /* integers not allowed in matlab ascii matrix */
				switch(ii){
				case 0: sscanf(num_str,"%d",&int1);ii=1;break;
				case 1: sscanf(num_str,"%d",&int2);ii=2;break;
				case 2: sscanf(num_str,"%d",&int3);ii=3;break;
				}
				sparse_detect('I',&ksparse,num_str,&actual,&dims);
				break;
                case 7: totfl++;  
			columns++;
			sparse_detect('F',&ksparse,num_str,&actual,&dims);
			break;
                case 8: totfl++;
			columns++;
			sparse_detect('F',&ksparse,num_str,&actual,&dims);
			break;
                case 9: ln++;totfl++;
			columns++;
			rows++;
			if(oldcolumns==0) oldcolumns=columns; /* first row only */
			if (oldcolumns!=columns) matlab_valid=1;
			columns=0;
			sparse_detect('F',&ksparse,num_str,&actual,&dims);
			break;
                case 10: ln++;totfl++;
			columns++;
			rows++;
			if(oldcolumns==0) oldcolumns=columns; /* first row only */
			if (oldcolumns!=columns) matlab_valid=1;
                        columns=0;
			sparse_detect('F',&ksparse,num_str,&actual,&dims);
			break;
                case 11: nonasc++;matlab_valid=1;break; /* nonascii not allowed in matlab ascii matrix */
                default:break;
                };
        }
/* main loop for scanning file ends */
if (is_debug==1) printf("on_ok3_button_fsreadb_clicked:  file scan ends\n");
if (is_debug==1) printf("on_ok3_button_fsreadb_clicked: filelength=%ld, lines=%ld, nonascii chars = %ld, comment lines=%d,\n",fl,ln,nonasc,kl);
if (is_debug==1) printf("on_ok3_button_fsreadb_clicked: integers=%d, floats=%ld sparse matrix patterns=%d\n",totint,totfl,ksparse);
if (is_debug==1) if (ii==0) printf("on_ok3_button_fsreadsba_clicked: no integers\n");
if (is_debug==1) if (ii==1) printf("on_ok3_button_fsreadb_clicked: int1=%d \n",int1);
if (is_debug==1) if (ii==2) printf("on_ok3_button_fsreadb_clicked: int1=%d int2=%d \n",int1,int2);
if (is_debug==1) if (ii==3) printf("on_ok3_button_fsreadb_clicked: int1=%d int2=%d int3=%d\n",int1,int2,int3);
if (is_debug==1) printf("on_ok3_button_fsreadb_clicked: matlab valid=%d, rows=%d columns=%d places =%d\n",matlab_valid,rows,oldcolumns,oldcolumns*rows);

/* second step: if the file structure is compatible with the required problem, dimension the matrices and read the data */
if(nonasc > 10) {
        /* non ascii chars in the file ! reject ! */
           gtk_widget_show(create_dialog_data_noreadable(readb_fs,"\nThe file contains NON ASCII chars !\n"));
           return;
        }
if(totfl < committed.dimension_m*committed.dimension_n) {
	/* too little floats in the file ! less than a singel block m x n; reject ! */
           gtk_widget_show(create_dialog_data_noreadable(readb_fs,"\nThe file does not contain enougth Floats !\n\n          (less than a block)  \n"));
	   return;
	}
/* reading B we do not consider sparse matrix for now
 * sparse matrix will have totfl==ksparse, and ii-3*ksparse = 0,1,2,3,+4 at most 7 
if ((totfl==ksparse)&&(totint-3*ksparse >=0)&&(totint-3*ksparse <8)) {
                is_sparse=1;
                if (is_debug==1) printf("on_ok3_button_fsreadb_clicked: sparse matrix detected:");
                if (is_debug==1) printf(" max dimensions %d %d and blocks %d from status machine\n",dims.ii,dims.jj,dims.kk);
                }
*/


if(committed.type==3) { /* GIM1 has Bblocks  n x m */
nb=committed.dimension_n;
mb=committed.dimension_m;
} else {  /* instead of n x m */
nb=committed.dimension_m;
mb=committed.dimension_n;
}

/* from here on we reinforce the significance of matlab_valid, to be operative requires correct dimensioning */
/* problems GI/M/1 has blocks one after the other, problems M/G/1 have the bloks side by side */
if (committed.type==3) { /* GI/M/1 */
    if (matlab_valid==0) { 
                            qb=rows/mb;
                            if ((nb!=oldcolumns)||(totfl- qb*mb*nb !=0 )) matlab_valid=1; /* not matlab  */
                      }
   } else {  /* M/G/1 and QBD */
                            qb=oldcolumns/nb;
                            if ((mb!=rows)||(totfl- qb*mb*nb !=0 )) matlab_valid=1; /* not matlab  */
  }
if(is_debug==1) if (matlab_valid==0) printf("on_ok3_button_fsreadb_clicked: is matlab valid with %d blocks of %d rows and %d  columns=\n",qb,mb,nb);

/* from now on if matlab_valid==0 qb,mb,nb are computed accordingly */

/* is it a fortran matrix or not ? */
if (matlab_valid==1) {
	qb=totfl/(nb*mb);
	if (totfl != qb*nb*mb) {
	   /* wrong number of floats */
           sprintf(buf,"\n\n  The number of floats of the file (%ld)  \n\n                   IS NOT        \n\nan integer number of blocks (%d x %d each) \n",totfl,nb,mb);
           gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
           return;
	  }
        if(is_debug==1)  printf("on_ok3_button_fsreadb_clicked: is maybe Fortran valid with %d blocks of %d rows and %d columns \n",qb,mb,nb);
        /*if (ii==0)  no matlab and no integers in the file... is suspect ! */
	/* if(ii>=1)  al least first integer present , we presume it is qb sanity check to do */
        if (ii==0) {
           gtk_widget_show(create_dialog_data_noreadable(readb_fs,"\n\n      Problem dimensioning:\n Fortran File without headers ? \n"));
           return;
	   }
        if (ii<2) {
	   gtk_widget_show(create_dialog_data_noreadable(readb_fs,"\n\n       Problem dimensioning:\n Fortran File Header incorrect \n"));
           return;
          }
	/* if qb == 1 we can have just int1 and int2, otherwise we shall need at least int1,int2,int3 */
        if ((ii==2)&&(qb!=1)) {
			gtk_widget_show(create_dialog_data_noreadable(readb_fs,"\nProblem dimensioning:\n Fortran File Header incomplete ? \n"));
			return;
			}
	if ((ii==2)&&((int1!=mb)||(int2!=nb))) {
			sprintf(buf,"\n\n      Problem dimensioning:  \n\n Fortran File Headers:   %d   %d \n versus expected:    %d  %d\n",int1,int2,mb,nb);
			gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
			return;
			}
	if ((ii>=3)&&((int1!=qb)||(int2!=mb)||(int3!=nb))) {
             sprintf(buf,"\n\n        Problem dimensioning:\n Fortran File Headers:   %d  %d %d \n versus expected:   qb %d  %d\n",int1,int2,int3,mb,nb);
             gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
             return;
             }
	}

/* we now have qb matrices of dimension mb x nb to read */
/* last check: for GI/M/1 qb = qa-2      if not give a warning*/
if ((committed.type==3)&&(qb != committed.matrix_a_num-2)) {
	sprintf(buf,"\n\n      WARNING !!!    \n\n       in GI/M/1 Problem: \n\n  number of B Blocks in file = %d   \n  versus %d expected (A Blocks-2) \n \n",qb,committed.matrix_a_num-2);
        gtk_widget_show(create_dialog_gsw(readb_fs,buf));
  }
/* from now on the old B data are not valid any more   */
committed.is_b=0;
/* allocate B and initialize to 0.0E0 all terms */
alloc_matb_(&mb,&nb,&qb,&err);
if (err !=0) {
	sprintf(buf,"\n  Allocation of A did Fail !\n(%ld Floats needed)\n",totfl);
        gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
        return;
	}

/* rewind the file */
fseek(readfile,(long int) 0,SEEK_SET); 
/* read the data */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */
i=1;
j=1;
k=1;
ckfl=0; /* will count real really read */
  while(((c = getc(readfile)) != EOF)&&(err==0)) {
        switch(watch_for_number(c, 1,num_str)) {
                case 7:  
                case 8: 
                case 9:  
                case 10:
			if(sscanf(num_str,"%lf",&r)==0) err=1; /* printf(" %s --> A(%d,%d,%d)=%g\n",num_str,i,j,k,r);*/
			ckfl++;
			write_matb_(&j,&i,&k,&r);
                        if(committed.type==3) {  /* GI/M/1 */
			        if(matlab_valid==0) {
				i++; if (i>nb) {i=1;j++;} ; if(j>mb) {j=1;k++;};	
				} else {			
			        j++; if (j>mb) {j=1;i++;}; if(i>nb) {i=1;k++;}; 
			        }
			   } else { /* M/G/1 and QBD */
				if(matlab_valid==0) {
                                i++; if (i>nb) {i=1;k++;} ; if(k>qb) {k=1;j++;};
                                } else {
                                j++; if (j>mb) {j=1;i++;}; if(i>nb) {i=1;k++;};
                                }
			   }			
			break;
                default:break;
                };
        }
 if (err!=0) {
        sprintf(buf,"\n Some Error in reading floats !  " );
        gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
        return;
	}
 if (ckfl!=totfl) {
	sprintf(buf,"\n We did skip some float ! " );
        gtk_widget_show(create_dialog_data_noreadable(readb_fs,buf));
        return;
	}

fclose(readfile);
/* chk stocasticity mv in a ad hoc window
*/

/* no errors, we did read the file ! take note that we did it */
invalidate_completed(); /* data is not ready any more for writing results */

/* remember that the edit a preference has a block number to reset ! */

if (is_debug==1) printf("on_ok3_button_fsreadb_clicked: Read B %d blocks  %d x %d \n",qb,mb,nb);
committed.is_b=1;
committed.matrix_b_num=qb;
g_idle_add((GtkFunction) selection_uptodaten,NULL);
gtk_statusbar_push(GTK_STATUSBAR(statusb),0," Matrix B has been read from file");


} 
/******************************/


/* Read B File Selection Dialog: cancel ***** Callback */
void
on_cancel_button_fsreadb_clicked      (GtkButton   * button, gpointer user_data )
{
/* int is_readb_open; global */
if(is_debug==1) printf("Read B File Selection Dialog: quit\n");
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
}
/*****************************/

/* Read B File Selection Dialog: destroy ***** Callback */
void
on_destroy_fsreadb     (GtkWidget   * ww, gpointer user_data )
{
/* int is_readb_open; global */
if(is_debug==1) printf("Read B File Selection Dialog: destroy\n");
is_readb_open=0;
}
/*****************************/

/* Not possible to read file   ***** Interface */
GtkWidget*
create_dialog_noreadable(GtkWidget* my_window)
{
GtkWidget *noreadable_dialog;
GtkWidget  *label;
GtkWidget  *icon;
noreadable_dialog = gtk_dialog_new_with_buttons ("Failure",
                                         NULL,
                                         GTK_DIALOG_MODAL,
                                         GTK_STOCK_CANCEL,
                                         GTK_RESPONSE_NONE,
                                         NULL);
label = gtk_label_new ("\n  The selected file is NOT readable  ");
icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR,GTK_ICON_SIZE_DIALOG);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(noreadable_dialog)->vbox), label);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(noreadable_dialog)->vbox), icon);
gtk_window_set_transient_for (GTK_WINDOW (noreadable_dialog),GTK_WINDOW (my_window));
gtk_window_set_position (GTK_WINDOW (noreadable_dialog), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_button_box_set_layout (GTK_BUTTON_BOX (GTK_DIALOG (noreadable_dialog)->action_area), GTK_BUTTONBOX_SPREAD);
gtk_widget_show_all (noreadable_dialog);
g_signal_connect_swapped (noreadable_dialog, "response", G_CALLBACK (gtk_widget_destroy), noreadable_dialog);
return noreadable_dialog;
}
/****************************/

/* Not possible to read data   ***** Interface */
GtkWidget*
create_dialog_data_noreadable(GtkWidget* my_window,char * message)
{
GtkWidget *data_noreadable_dialog;
GtkWidget  *label;
GtkWidget  *icon;
data_noreadable_dialog = gtk_dialog_new_with_buttons ("Failure",
                                         NULL,
                                         GTK_DIALOG_MODAL,
                                         GTK_STOCK_CANCEL,
                                         GTK_RESPONSE_NONE,
                                         NULL);
label = gtk_label_new (message);
icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR,GTK_ICON_SIZE_DIALOG);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(data_noreadable_dialog)->vbox), label);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(data_noreadable_dialog)->vbox), icon);
gtk_window_set_transient_for (GTK_WINDOW (data_noreadable_dialog),GTK_WINDOW (my_window));
gtk_window_set_position (GTK_WINDOW (data_noreadable_dialog), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_button_box_set_layout (GTK_BUTTON_BOX (GTK_DIALOG (data_noreadable_dialog)->action_area), GTK_BUTTONBOX_SPREAD);
gtk_widget_show_all (data_noreadable_dialog);
g_signal_connect_swapped (data_noreadable_dialog, "response", G_CALLBACK (gtk_widget_destroy), data_noreadable_dialog);
return data_noreadable_dialog;
}
/****************************/


/* File Exists Overwrite ? Warning  ***** Interface */
/* use
 *  overwrite_dialog = create_dialog_overwrite(my_window); 
 *       gtk_widget_show(overwrite_dialog); 
 *       result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
 *       switch (result) {
 *         case GTK_RESPONSE_ACCEPT: ....; break;
 *         case GTK_RESPONSE_CANCEL: ....; break;
 *         default: ....;
 *         }
 *       gtk_widget_destroy(overwrite_dialog);
 * to poll result of dialog
 */
GtkWidget*
create_dialog_overwrite(GtkWidget* my_window)
{
GtkWidget  *label;
GtkWidget  *icon;
GtkWidget *my_dialog;

my_dialog = gtk_dialog_new_with_buttons ("Warning",
                                         NULL,
                                         GTK_DIALOG_MODAL,
                                         GTK_STOCK_CANCEL,
                                         GTK_RESPONSE_CANCEL,
                                         GTK_STOCK_OK,
                                         GTK_RESPONSE_ACCEPT,
                                         NULL);
label = gtk_label_new ("         Warning!        \nFile exist:  overwrite ?");
gtk_widget_show(label);
icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING,GTK_ICON_SIZE_DIALOG);
gtk_widget_show(icon);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(my_dialog)->vbox), label);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(my_dialog)->vbox), icon);
gtk_window_set_transient_for (GTK_WINDOW (my_dialog),GTK_WINDOW (my_window));
gtk_window_set_position (GTK_WINDOW (my_dialog), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_button_box_set_layout (GTK_BUTTON_BOX (GTK_DIALOG (my_dialog)->action_area), GTK_BUTTONBOX_SPREAD);
return my_dialog;
}
/****************************/

/* Write Sparse Format for non Sparse Matrix ? Warning  ***** Interface */
/* use
 *  overwrite_dialog = create_dialog_overwrite(my_window); 
 *       gtk_widget_show(overwrite_dialog); 
 *       result = gtk_dialog_run (GTK_DIALOG(overwrite_dialog));
 *       switch (result) {
 *         case GTK_RESPONSE_ACCEPT: ....; break;
 *         case GTK_RESPONSE_CANCEL: ....; break;
 *         default: ....;
 *         }
 *       gtk_widget_destroy(overwrite_dialog);
 * to poll result of dialog
 */
GtkWidget*
create_dialog_sparse(GtkWidget* my_window)
{
GtkWidget  *label;
GtkWidget  *icon;
GtkWidget *my_dialog;

my_dialog = gtk_dialog_new_with_buttons ("Warning",
                                         NULL,
                                         GTK_DIALOG_MODAL,
                                         GTK_STOCK_CANCEL,
                                         GTK_RESPONSE_CANCEL,
                                         GTK_STOCK_OK,
                                         GTK_RESPONSE_ACCEPT,
                                         NULL);
label = gtk_label_new ("         Warning!        \nMatrix is NOT Sparse !\nReally Write in Sparse Format ?");
gtk_widget_show(label);
icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING,GTK_ICON_SIZE_DIALOG);
gtk_widget_show(icon);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(my_dialog)->vbox), label);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(my_dialog)->vbox), icon);
gtk_window_set_transient_for (GTK_WINDOW (my_dialog),GTK_WINDOW (my_window));
gtk_window_set_position (GTK_WINDOW (my_dialog), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_button_box_set_layout (GTK_BUTTON_BOX (GTK_DIALOG (my_dialog)->action_area), GTK_BUTTONBOX_SPREAD);
return my_dialog;
}
/****************************/

/* B will be rectangular  Warning  ***** Interface */
GtkWidget*
create_dialog_rectangular(GtkWidget* my_window)
{
GtkWidget  *label;
GtkWidget  *icon;
GtkWidget *my_dialog;

my_dialog = gtk_dialog_new_with_buttons ("Warning",
                                         NULL,
                                         GTK_DIALOG_MODAL,
                                         GTK_STOCK_CLOSE,
                                         GTK_RESPONSE_CLOSE,
                                         NULL);
label = gtk_label_new ("           Warning!        \n\n Using Rectangular B Blocks !\n \n   No Optional Skip allowed. \n\n  B0, BN1, B must be all read \n       to compute Pi   \n\n");
gtk_widget_show(label);
icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING,GTK_ICON_SIZE_DIALOG);
gtk_widget_show(icon);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(my_dialog)->vbox), label);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(my_dialog)->vbox), icon);
gtk_window_set_transient_for (GTK_WINDOW (my_dialog),GTK_WINDOW (my_window));
gtk_window_set_position (GTK_WINDOW (my_dialog), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_button_box_set_layout (GTK_BUTTON_BOX (GTK_DIALOG (my_dialog)->action_area), GTK_BUTTONBOX_SPREAD);
g_signal_connect_swapped (my_dialog, "response", G_CALLBACK (gtk_widget_destroy), my_dialog);
return my_dialog;
}
/****************************/

/* Not possible to write to file   ***** Interface */
GtkWidget*
create_dialog_nowritable(GtkWidget* my_window)
{
GtkWidget *nowritable_dialog;
GtkWidget  *label;
GtkWidget  *icon;
nowritable_dialog = gtk_dialog_new_with_buttons ("Failure",
                                         NULL,
                                         GTK_DIALOG_MODAL,
                                         GTK_STOCK_CANCEL,
                                         GTK_RESPONSE_NONE,
                                         NULL);
label = gtk_label_new ("\n  The selected file is NOT writable  ");
icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR,GTK_ICON_SIZE_DIALOG);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(nowritable_dialog)->vbox), label);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(nowritable_dialog)->vbox), icon);
gtk_window_set_transient_for (GTK_WINDOW (nowritable_dialog),GTK_WINDOW (my_window));
gtk_window_set_position (GTK_WINDOW (nowritable_dialog), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_button_box_set_layout (GTK_BUTTON_BOX (GTK_DIALOG (nowritable_dialog)->action_area), GTK_BUTTONBOX_SPREAD);
gtk_widget_show_all (nowritable_dialog);
g_signal_connect_swapped (nowritable_dialog, "response", G_CALLBACK (gtk_widget_destroy), nowritable_dialog);
return nowritable_dialog;
}
/****************************/

/* */

/* Not possible to open directory   ***** Interface */
GtkWidget*
create_dialog_noolddir(GtkWidget* my_window)
{
GtkWidget *noolddir_dialog;
GtkWidget  *label;
GtkWidget  *icon;
noolddir_dialog = gtk_dialog_new_with_buttons ("Failure",
                                         NULL,
                                         GTK_DIALOG_MODAL,
                                         GTK_STOCK_CANCEL,
                                         GTK_RESPONSE_NONE,
                                         NULL);
label = gtk_label_new ("\n  Not possible to open the selected dir ");
icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR,GTK_ICON_SIZE_DIALOG);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(noolddir_dialog)->vbox), label);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(noolddir_dialog)->vbox), icon);
gtk_window_set_transient_for (GTK_WINDOW (noolddir_dialog),GTK_WINDOW (my_window));
gtk_window_set_position (GTK_WINDOW (noolddir_dialog), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_button_box_set_layout (GTK_BUTTON_BOX (GTK_DIALOG (noolddir_dialog)->action_area), GTK_BUTTONBOX_SPREAD);
gtk_widget_show_all (noolddir_dialog);
g_signal_connect_swapped (noolddir_dialog, "response", G_CALLBACK (gtk_widget_destroy), noolddir_dialog);
return noolddir_dialog;
}
/****************************/

/* Not possible to create new directory   ***** Interface */
GtkWidget*
create_dialog_nonewdir(GtkWidget* my_window)
{
GtkWidget *nonewdir_dialog;
GtkWidget  *label;
GtkWidget  *icon;
nonewdir_dialog = gtk_dialog_new_with_buttons ("Failure",
                                         NULL,
                                         GTK_DIALOG_MODAL,
                                         GTK_STOCK_CANCEL,
                                         GTK_RESPONSE_NONE,
                                         NULL);
label = gtk_label_new ("\n  Not possible to create new dir ");
icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR,GTK_ICON_SIZE_DIALOG);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(nonewdir_dialog)->vbox), label);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(nonewdir_dialog)->vbox), icon);
gtk_window_set_transient_for (GTK_WINDOW (nonewdir_dialog),GTK_WINDOW (my_window));
gtk_window_set_position (GTK_WINDOW (nonewdir_dialog), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_button_box_set_layout (GTK_BUTTON_BOX (GTK_DIALOG (nonewdir_dialog)->action_area), GTK_BUTTONBOX_SPREAD);
gtk_widget_show_all (nonewdir_dialog);
g_signal_connect_swapped (nonewdir_dialog, "response", G_CALLBACK (gtk_widget_destroy), nonewdir_dialog);
return nonewdir_dialog;
}
/****************************/


/* strip path from complete filename */
void 
pathstripper(char *filename, char *path)
{
int n;
n=strlen(filename);
while ((filename[n-1]!='/')&&(n>0)) n--;
strncpy(path,filename,n+1);
path[n]=0; /* fix string terminator 0 */
if(is_debug==1) printf("pathstripper: IN=%s   OUT=%s length=%d n=%d\n",filename,path,strlen(filename),n);
}
/*****************************/

/* status machine to read numbers
 * 
 * numbers separators are \n,\r,\f,' ',',', eof, bof
 * there must be a separator before and after a number
 * status0=0 ifor initialization, else normal behavious: initialize with        watch_for_number(0,0);
 * when eof is reached, add a call watch_for_number('\n', 1) to be shure last number is expelled.a
 * number_str must be filled with 0 before using the routine.
 * 
 */
int
watch_for_number(int c, int status0, char * number_str)
{
static int status;           /* status */
static int delayed_clean;    /* 0=no need to clean 1=need to clean - delayed clean allows exteral routines to read numbers */
static int number_i;         /* number of valid chars in number string */
static int cr;               /* if sequence 0x0D 0x0A (\r\n) is used, consider it a single new line. */
int i,w;

if (c < 128) w=0; else w=11;
/* return value: 0=other ASCII <128   1=considering a number    2=comment line and new line    3=new line    4=new line following a new line
                 5=int   6=int and new line   7=floatFP   8=floatEX   9=floatFP and new line   10 floatEX and new line  11 ASCII > 127 not in comment line */
/* \n=new line  \r=carriage return  \t=tab \f=form feed ' ' ',' E e D d + - . 0123456789 chars of interest here     \v ?? to add ??  */
/* comment lines begins with # or ! or % or @ */
if (c=='\r') cr=1;
if ((c=='\n')&&(cr==1)) {cr=0; return(0);}
if (c!='\r') cr=0;

if (status0==0) status=0;    /* initialization */
switch (status) {
	case 0: /* initialization at beginning of the operations:  c is not yet a  char */
       		number_i=0;
                delayed_clean=0;
                cr=0;
		status =3;
		return(0);
		break;                	
	case 1: /* comment line : we are waiting eol and discarding anything else */
		if (c=='\n'||c=='\r'||c=='\f') {status=3; return(2);}
		else return(0);		
		break;
	case 2:/*  we are not at newline and waiting a separator before number */
                if(delayed_clean==1) {for (i=0;i<number_i;i++) number_str[i]=0; number_i=0; delayed_clean=0;}
		if(c=='\n'||c=='\r'||c=='\f') {status=3; return(3);}
                if(c==' '||c=='\t'||c==',') {status=4; return(0);}
                else {status=2;return(w);}
		break;
	case 3:/* we are at newline ready to get a number */
		if(delayed_clean==1) {for (i=0;i<number_i;i++) number_str[i]=0; number_i=0; delayed_clean=0;}
		if(c=='#'||c=='!'||c=='%'||c=='@') {status=1; return(0);}
		if(c=='\n'||c=='\r'||c=='\f') {status=3; return(4);}
 		if(c==' '||c=='\t'||c==',') {status=4; return(0);}
		if(c=='+'||c=='-') {number_str[number_i]=c; number_i++; status=5 ; return(1);}
		if(c=='.') {number_str[number_i]=c; number_i++; status=7 ; return(1);}
		if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9')
 			{number_str[number_i]=c; number_i++; status= 6; return(1);}
		else {status=2;return(w);}
		break;
	case 4:/* we got a separator and we are waiting a possible number */
		if(delayed_clean==1) {for (i=0;i<number_i;i++) number_str[i]=0; number_i=0; delayed_clean=0;}
		if(c=='\n'||c=='\r'||c=='\f') {status=3; return(3);}
		if(c==' '||c=='\t'||c==',') {status=4; return(0);}
		if(c=='+'||c=='-') {number_str[number_i]=c; number_i++; status=5 ; return(1);}
                if(c=='.') {number_str[number_i]=c; number_i++; status=7 ; return(1);}
                if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9')
                        {number_str[number_i]=c; number_i++; status= 6; return(1);}
                else {status=2;return(w);}
		break;
	case 5:/* we got +/- and we are waiting digits */
		if(c=='.') {number_str[number_i]=c; number_i++; status=7 ; return(1);}
		if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9')
                        {number_str[number_i]=c; number_i++; status= 6; return(1);}
		if(c=='\n'||c=='\r'||c=='\f') {status=3; return(3);}
		if(c==' '||c=='\t'||c==',') {status=4; return(0);}
		else {status=2; for (i=0;i<number_i;i++) number_str[i]=0; number_i=0;  return(w);}
		break;
	case 6:/* we got some digits and waiting more */
		if(c=='.') {number_str[number_i]=c; number_i++; status=8 ; return(1);}
		if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9')
                        {number_str[number_i]=c; number_i++; status= 6; return(1);}
		if(c=='e'||c=='E'||c=='d'||c=='D') {status =9; number_str[number_i]='E'; number_i++;return(1);} 
		if(c=='\n'||c=='\r'||c=='\f') { status = 3; delayed_clean=1; return(6); } /* INTEGER AND NEW LINE */
		if(c==' '||c=='\t'||c==',') { status = 4; delayed_clean=1; return(5); } /* INTEGER */
 		else {status=2; for (i=0;i<number_i;i++) number_str[i]=0; number_i=0;  return(w);}
		break;
	case 7:/* we got +/-. and we need some digit now */
		if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9')
                        {number_str[number_i]=c; number_i++; status= 8; return(1);}
		if(c=='\n'||c=='\r'||c=='\f') {status = 3; for (i=0;i<number_i;i++) number_str[i]=0; number_i=0; return(3);}
		if(c==' '||c=='\t'||c==',') {status=4; for (i=0;i<number_i;i++) number_str[i]=0;number_i=0;  return(0);}
		else {status=2;for (i=0;i<number_i;i++) number_str[i]=0; number_i=0;  return(w);}
		break;
	case 8:/* we got some digits and . and waiting futher part of number */
		if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9')
                        {number_str[number_i]=c; number_i++; status= 8; return(1);}
		if(c=='e'||c=='E'||c=='d'||c=='D') {status =9; number_str[number_i]='E'; number_i++;return(1);}
		if(c=='\n'||c=='\r'||c=='\f') { status = 3; delayed_clean=1; return(9); } /* FLOAT FP  AND NEW LINE */
		if(c==' '||c=='\t'||c==',') { status = 4; delayed_clean=1; return(7); } /* FLOAT FP */
		else {status=2; for (i=0;i<number_i;i++) number_str[i]=0;number_i=0;  return(w);}
		break;
	case 9:/* we got mantissa end E/e/d/D waiting for exponent */
		if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9')
                        {number_str[number_i]=c; number_i++; status= 10; return(1);}
		if(c=='+'||c=='-') {number_str[number_i]=c; number_i++; status=10 ; return(1);}
		if(c=='\n'||c=='\r'||c=='\f') {status = 3; for (i=0;i<number_i;i++) number_str[i]=0; number_i=0; return(0);}
                if(c==' '||c=='\t'||c==',') {status=4; for (i=0;i<number_i;i++) number_str[i]=0; number_i=0;  return(0);}
		else {status=2;for (i=0;i<number_i;i++) number_str[i]=0; number_i=0; return(w);}
                break;
	case 10:/* we got mantissa end E/e/d/D+/- and waiting for exponent digits */
		if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9')
                        {number_str[number_i]=c; number_i++; status= 11; return(1);}
                if(c=='\n'||c=='\r'||c=='\f') {status = 3; for (i=0;i<number_i;i++) number_str[i]=0; number_i=0;  return(3);}
                if(c==' '||c=='\t'||c==',') {status=4; for (i=0;i<number_i;i++) number_str[i]=0; number_i=0; return(0);}
		else {status=2;for (i=0;i<number_i;i++) number_str[i]=0; number_i=0; return(w);}
		break;
	case 11:/* we got mantissa and exponent and waiting further digits */
		if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9')
                        {number_str[number_i]=c; number_i++; status= 11; return(1);}
		if(c=='\n'||c=='\r'||c=='\f') { status = 3; delayed_clean=1; return(10); } /* FLOAT EX AND NEW LINE */
		if(c==' '||c=='\t'||c==',') { status = 4; delayed_clean=1; return(8); }  /* FLOAT EX */
		else {status=2;for (i=0;i<number_i;i++) number_str[i]=0; number_i=0;  return(w);}
		break;
	default:/* this should never happen ...*/
		printf("watch_for_number: something wrong here !\n");
	}
return(0); /* never used hopefully */
}
/*****************************/


/* status machine to detect and read sparse matrix pattern (I I I F) and dimensions
 * s is the symbol (I or F)        k the counter   snum the string
 * actual   the sparse matrix structure read,   dim the dimensions as max indexes
 *                returns 0 (no) or 1 (actual valid)
 * (I I I F) ---> (ii jj kk ff) in actual and dim structures
 */
int
sparse_detect(int s, int * k, char * snum, struct sparse_four * actual,struct sparse_four * dim)
{
static int status;
if (s==0) { /* reset status machine */
     	status=0; 
	*k = 0; 
	dim->ii=0; dim->jj=0;dim->kk=0; 
	} 


switch (status) {
	case 0: /* waiting for new I */
		if (s=='I') { status=1; sscanf(snum,"%d",&(actual->ii)); }
		break;	
	case 1: /* waiting for second I */
		if (s=='I') { status=2; sscanf(snum,"%d",&(actual->jj)); } 
	        else  { status=0; actual->ii=0; actual->jj=0; actual->kk=0;}
		break;
	case 2: /* waiting for third I */
		if (s=='I') { status=3; sscanf(snum,"%d",&(actual->kk)); }
		else { status=0; actual->ii=0; actual->jj=0; actual->kk=0;}
		break;	
	case 3: /* waiting for F after 3 or more I */
		if (s=='F') {
			(*k)++; 
			status=0;
                        sscanf(snum,"%lf",&(actual->ff));
			if (actual->ii > dim->ii) dim->ii=actual->ii;
			if (actual->jj > dim->jj) dim->jj=actual->jj;
			if (actual->kk > dim->kk) dim->kk=actual->kk;
			return(1);
			}
		else { 
			actual->ii=actual->jj; 
			actual->jj=actual->kk;
			sscanf(snum,"%d",&(actual->kk));
			 }
		break;
	default: /* never here ...*/
		if (is_debug==1) printf("sparse_detect: some error here !\n");	
	}
return(0);
}
/*****************************/

/* Generic Simple Warning */
GtkWidget*
create_dialog_gsw(GtkWidget* my_window, char *buffer)
{
GtkWidget  *label;
GtkWidget  *icon;
GtkWidget *my_dialog;

my_dialog = gtk_dialog_new_with_buttons ("Warning",
                                         NULL,
                                         GTK_DIALOG_MODAL,
                                         GTK_STOCK_CLOSE,
                                         GTK_RESPONSE_CLOSE,
                                         NULL);
label = gtk_label_new (buffer);
gtk_widget_show(label);
icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING,GTK_ICON_SIZE_DIALOG);
gtk_widget_show(icon);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(my_dialog)->vbox), label);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG(my_dialog)->vbox), icon);
gtk_window_set_transient_for (GTK_WINDOW (my_dialog),GTK_WINDOW (my_window));
gtk_window_set_position (GTK_WINDOW (my_dialog), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_button_box_set_layout (GTK_BUTTON_BOX (GTK_DIALOG (my_dialog)->action_area), GTK_BUTTONBOX_SPREAD);
g_signal_connect_swapped (my_dialog, "response", G_CALLBACK (gtk_widget_destroy), my_dialog);
return my_dialog;
}
/****************************/


/* Read  File X0 Selection Dialog Interface  ***** Interface */
GtkWidget*
create_fileselection_X(void)
{
GtkWidget *fileselection;
GtkWidget *ok_button;
GtkWidget *cancel_button;
fileselection = gtk_file_selection_new("Read Initial Matrix X0 for Functional Iterations");
gtk_widget_show(fileselection);
gtk_container_set_border_width (GTK_CONTAINER (fileselection), 10);
gtk_file_selection_set_filename (GTK_FILE_SELECTION(fileselection),pathgru_fs);
ok_button = GTK_FILE_SELECTION (fileselection)->ok_button;
gtk_widget_show (ok_button);
GTK_WIDGET_SET_FLAGS (ok_button, GTK_CAN_DEFAULT);
cancel_button = GTK_FILE_SELECTION (fileselection)->cancel_button;
gtk_widget_show (cancel_button);
GTK_WIDGET_SET_FLAGS (cancel_button, GTK_CAN_DEFAULT);

/* GTK_RESPONSE_DELETE_EVENT */
g_signal_connect ((gpointer) cancel_button, "clicked", G_CALLBACK (on_cancel_button_fsX_clicked), NULL);
g_signal_connect ((gpointer) fileselection, "destroy", G_CALLBACK (on_destroy_fsX),NULL);
g_signal_connect ((gpointer) fileselection, "destroy_event", G_CALLBACK (on_cancel_button_fsX_clicked),NULL);
g_signal_connect ((gpointer) ok_button,"clicked", G_CALLBACK (on_ok_button_fsX_clicked), NULL);

return fileselection;
}
/*****************************/

/* Read  File X0 Selection Dialog: cancel ***** Callback */
void
on_cancel_button_fsX_clicked      (GtkButton   * button, gpointer user_data )
{
if(is_debug==1) printf("Read File X0 Selection Dialog: quit\n");
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
}
/*****************************/

/* Read  File X0 Selection Dialog: destroy ***** Callback */
void
on_destroy_fsX      (GtkWidget   * ww, gpointer user_data )
{
if(is_debug==1) printf("Read File X0 Selection Dialog: destroy\n");
is_readX_open=0; /* 0=not open  1=open */
}
/*****************************/


/* Read File X0 Selection Dialog: ok ***** Callback    ONE ASCII FILE  */
/* we look for an ASCII file containing a single square matrix, either matlab of fortran style */
/* some integers at the beginning are clues for dimension in fortran style */
/* comments and void lines are ignored */
void
on_ok_button_fsX_clicked      (GtkButton   *button, gpointer user_data)
{
/* GtkWidget  *view_file_read; global */

gchar * filename;
FILE * readfile;
int c;                  /* read from file one char by one */
char num_str[1024];     /* a number with more then 1024 digits will crash the program ... to fix later ...*/
long int fl, ln, nonasc;/* file length, number of lines, non ascii chars not in comment line */
int kl;                 /* comment lines */
int totint;             /* total strings corresponding to integers number */
long int totfl,ckfl;    /* total strings corresponding to floating point numbers and number of floats really read from file */
int i,j,ma,err; /* ma,na dimensions  i,j,k indexes, err error flag */
double  r;              /* float value to read */
int int1,int2,int3,ii;  /* first 3 integers present in the file, if any, and how many (0,1,2,3) of them */
char buf[256] ;
int matlab_valid,rows,columns, oldcolumns;   /* matlab_valid=1 if the file is NOT a matlab matrix */

/* Extract filename from the file selection dialog */
filename = (char *)gtk_file_selection_get_filename(GTK_FILE_SELECTION(readX_fs));
if(is_debug) printf("on_ok_button_fsX0_clicked:  filename = %s\n",filename);
if ((readfile = fopen(filename,"r+")) == NULL) {  /* "r" should be enougth.. but with "r" dir can be opended too, and a check will be needed */
        /* File not readable popup  */
        gtk_widget_show(create_dialog_noreadable(readX_fs));
        return;
        }
/* file is open ok  */
pathstripper(filename,pathgru_fs);   /* save the path the same as for saving g,r,u, */
/* first step: scan the file to get length, check if ascii or not, check line separators, count possible integers and float 
 * read, if present, the first 3 integers, count sparse matrix pattern (I I I F ), check for regular rows of floats for 
 * matlab ASCII matrix format - for valid matlab ascii we require no integers, floats only, same number in each line.
 */
err = 0; /* no error till now */
fl=0; /* file length */
ln=0; /* lines */
nonasc=0; /* ascii >128 */
kl=0; /* comment lines */
totint=0; /* strings corresponding to integers */
totfl=0;  /* strings corresponding to floats */
ii=0;     /* count if preset first 3 integers */
int1=0;
int2=0;
int3=0;
matlab_valid=0; /* if this =1 we are shure that the file is not compatible with pure float ascii matrix matlab style */
rows=0;  /* number of rows of pure float ascii matrix matlab style */
columns=0;  /* number of columns of pure float ascii matrix matlab style (counting variable) */
oldcolumns=0; /* number of columns of pure float ascii matrix matlab style (first line - if any - ) */
if (is_debug==1) printf("on_ok_button_fsX0_clicked:  file scan begins\n");
/* watch_for_number: initialize with watch_for_number(0, 0,num_str); and fill num_str with 0 before using; add watch_for_number('\n', 1,num_str) at last.
 * return value: 0=other ASCII <128   1=considering a number    2=comment line and new line    3=new line    4=new line following a new line
                 5=int   6=int and new line   7=floatFP   8=floatEX   9=floatFP and new line   10 floatEX and new line  11 ASCII > 127 not in comment line */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */
/* main loop for scanning file begins */
while((c = getc(readfile)) != EOF) {
        fl++; /* file length */
        switch(watch_for_number(c, 1,num_str)) {
                case 2:  kl++; matlab_valid=1; break; /* comments lines not allowed in matlab ascii matrix */
                case 3:  ln++;
                        rows++;
                        if(oldcolumns==0) oldcolumns=columns; /* first row only */
                        if (oldcolumns!=columns) matlab_valid=1;
                        columns=0;
                        break;
                case 6:  ln++;
                case 5:  totint++; matlab_valid=1; /* integers not allowed in matlab ascii matrix */
                                switch(ii){
                                case 0: sscanf(num_str,"%d",&int1);ii=1;break;
                                case 1: sscanf(num_str,"%d",&int2);ii=2;break;
                                case 2: sscanf(num_str,"%d",&int3);ii=3;break;
                                }
                                break;
                case 7: totfl++;
                        columns++;
                        break;
                case 8: totfl++;
                        columns++;
                        break;
                case 9: ln++;totfl++;
                        columns++;
                        rows++;
                        if(oldcolumns==0) oldcolumns=columns; /* first row only */
                        if (oldcolumns!=columns) matlab_valid=1;
                        columns=0;
                        break;
                case 10: ln++;totfl++;
                        columns++;
                        rows++;
                        if(oldcolumns==0) oldcolumns=columns; /* first row only */
                        if (oldcolumns!=columns) matlab_valid=1;
                        columns=0;
                        break;
                case 11: nonasc++;matlab_valid=1;break; /* nonascii not allowed in matlab ascii matrix */
                default:break;
                };
        }
/* main loop for scanning file ends */
if (is_debug==1) printf("on_ok_button_fsX0_clicked:  file scan ends\n");
if (is_debug==1) printf("on_ok_button_fsX0_clicked: filelength=%ld, lines=%ld, nonascii chars = %ld, comment lines=%d,\n",fl,ln,nonasc,kl);
if (is_debug==1) printf("on_ok_button_fsX0_clicked: integers=%d, floats=%ld \n",totint,totfl);
if (is_debug==1) if (ii==0) printf("on_ok_button_fsX0_clicked: no integers\n");
if (is_debug==1) if (ii==1) printf("on_ok_button_fsX0_clicked: int1=%d \n",int1);
if (is_debug==1) if (ii==2) printf("on_ok_button_fsX0_clicked: int1=%d int2=%d \n",int1,int2);
if (is_debug==1) if (ii==3) printf("on_ok_button_fsX0_clicked: int1=%d int2=%d int3=%d\n",int1,int2,int3);
if (is_debug==1) printf("on_ok_button_fsX0_clicked: matlab valid=%d, rows=%d columns=%d places =%d\n",matlab_valid,rows,oldcolumns,oldcolumns*rows);
/* second step: if the file structure is compatible with the required problem, dimension the matrices and read the data */
if(nonasc > 10) {
        /* non ascii chars in the file ! reject ! */
           gtk_widget_show(create_dialog_data_noreadable(readX_fs,"\nThe file contains NON ASCII chars !\n"));
           fclose(readfile);
           return;
        }
if(totfl < 4) {
        /* too little floats in the file ! reject ! */
           gtk_widget_show(create_dialog_data_noreadable(readX_fs,"\nThe file contains very few Floats !\n"));
           fclose(readfile);
           return;
        }

/* check that the number of floats is correct */
ma=sqrt((double)totfl);
if(totfl != ma*ma) {
        sprintf(buf,"\n\nThe number of floats in the file is not a square !\n\nReading %ld floats, nearest square %d = %d * %d\n\n",totfl,ma*ma,ma,ma);
        gtk_widget_show(create_dialog_data_noreadable(readX_fs,buf));
        return;
        }
/* the only difference between Matlab and Fortran is that matlab files has a clear row columns structure */
if (matlab_valid==0) if ((rows!=ma)||(oldcolumns!=ma)) matlab_valid=1;
if(is_debug==1) if (matlab_valid==0) printf("on_ok2_button_fsreadX_clicked: is matlab valid rows=%d columns=%d\n",rows, oldcolumns);
if(is_debug==1) if (matlab_valid==1) printf("on_ok2_button_fsreadX_clicked: is Fortran valid\n");
/* if it looks a Fortran file, it must have some headers with the dimensions in it */
if ((matlab_valid==1)&&(ii==0)) {
        gtk_widget_show(create_dialog_data_noreadable(readX_fs,"\n\n No Matlab File and no Header !\n "));
        return;
  }
/* some dubious case reache this point: Fortran files with inconsistent dimensioning */
if ((matlab_valid==1)&&(ii>0)&&(int1!=ma)) {
                sprintf(buf,"\n Incorrect dimension in Fortran file: \n      ( %d versus expected %d ) \n",int1,ma);
                gtk_widget_show(create_dialog_data_noreadable(readX_fs,buf));
                return;
}
/* here ma is the dimension and we have ma*ma floats; fortran or matlab style */

/* from now on the old X0 data are not valid any more   */
committed.fi_file_read=0;
committed.fi_file_dim=0;
selected.fi_file_read=0;
selected.fi_file_dim=0;
err=0;
alloc_matx0_(&ma,&err);
if (err!=0) {
	  gtk_statusbar_push(GTK_STATUSBAR(statusb),0,"  *** Memory Allocation for Matrix data did fail !  not enougth memory ?? ***");
          return;
      }
/* rewind the file */
fseek(readfile,(long int) 0,SEEK_SET);
/* read the data */
for(i=0;i<1024;i++)num_str[i]=0; /* clean input string */
watch_for_number(0, 0,num_str);  /* initialization     */
i=1;
j=1;
ckfl=0; /* will count real really read */
  while(((c = getc(readfile)) != EOF)&&(err==0)) {
        switch(watch_for_number(c, 1,num_str)) {
                case 7:
                case 8:
                case 9:
                case 10:
                        if(sscanf(num_str,"%lf",&r)==0) err=1;  /* printf(" %s --> X0(%d,%d)=%g\n",num_str,i,j,r);*/
                        ckfl++;
                         write_matx0_(&j,&i,&r);
                        if(matlab_valid==0) {
                                i++; if (i>ma) {i=1; j++;}
                                } else {
                                j++; if (j>ma) {j=1;i++;};
                                }
                        break;
                default:break;
                };
        }

 if (err!=0) {
        sprintf(buf,"\n Some Error in reading floats !  " );
        gtk_widget_show(create_dialog_data_noreadable(readX_fs,buf));
        fclose(readfile);
        return;
        }
 if (ckfl!=totfl) {
        sprintf(buf,"\n We did skip some float ! " );
        gtk_widget_show(create_dialog_data_noreadable(readX_fs,buf));
        fclose(readfile);
        return;
        }
fclose(readfile);
/* now it should be ok */
selected.fi_file_read=1;
selected.fi_file_dim=ma;
if (is_debug==1) printf("on_ok_button_fsX0_clicked: read X0 size %d x %d\n",ma,ma);
gtk_statusbar_push(GTK_STATUSBAR(statusb),0," Matrix X0 has been read from file");
gtk_widget_destroy(gtk_widget_get_toplevel(GTK_WIDGET(button)));
is_readX_open=0; /* 0=not open  1=open */

}
/*********************************/

