

#define DATUM                "2009_08_15"
/****************************************************
This is the file 'file_read.c.2009_08_15', 
genuine name:    'file_read.c'.         

The aim of this software is 


Max-Planck-Institut fuer Metallforschung (Stuttgart). 


Authors:  Agnes Szoekefalvi-Nagy, Janos Major (major@mf.mpg.de) 

The program 'file_read' is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as published 
by the Free Software Foundation; either version 2 of the License, or (at 
your option) any later version.

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

You can obtain a copy of the GNU General Public License
from   http://www.gnu.org/copyleft/gpl.html; if not, write to 
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 
Boston, MA  02110-1301, USA.
**************************************************
   First version: file_read.c.2009_08_14
   The standard site for this file is: $HOME/c-gcc/

   To compile and link please use:    
   cc -lm file_read.c -Wall -o ~/bin/file_read

   Adjustable parameters in the lines with: */      /*P*/         /*            
                                  
*************************************************/
 
#define __NO_MATH_INLINES    /* makes slower but, may be, more precise */ 

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define EICHUNG 0.00804 /* mythen detector: degree/channel */              /*P*/
#define MAX_FILE 5100    /* max. number of files */
#define MAX_PIXEL 2500   /* max. number a pixels along the ppm axes */
#define MAX_CHANNEL 1400 /* max. number of detector channels*/
#define MAX_LEN 256      /* max. number of input characters */
#define EFFZERO 1e-40    /* my definition of zero */
#define NEARZERO 1e-10   /* zero for the matrix functions */
#define LIM_EXP 70.      /* limit for the function exp */
#define SCREEN_WRITE 20  /* screen write out period during interpolation */ /*P*/
#define PLOTZERO 1.e-6   /* smaller values are not plotted in gnuplot */
#define RAD 0.0174532925199433 /* 1 degree in radian */ 
#define PI 3.1415926535897932384626433832795028841971693993751
#define MAX_MESSPUNKT 10000000 /* max. number of measuring points */


/* function prototypes: */

void message (char *text, char *text1);
void error (char *text);
void terminate (char *text);
void wait (char *text);
void read_dat_files(void);
void gnuplot_read_dat_files(void);
/* global declarations: */
int    counts [MAX_FILE][MAX_CHANNEL];  /* experimental results */
double q_x[MAX_FILE][MAX_CHANNEL];
double q_y[MAX_FILE][MAX_CHANNEL];
double eichung=EICHUNG;                 /* PSD degree/channel */
double channel_m;                 /* PSD reference channel tth=0->direct beam*/
double PPM[MAX_PIXEL][MAX_PIXEL];   /* array to be transfered to a ppm file */
double GNU[MAX_PIXEL][MAX_PIXEL];   /* array to be transferred to gnuplot */
double a_i[MAX_FILE][MAX_CHANNEL];  /* the corresponding q_x values */
double a_f[MAX_FILE][MAX_CHANNEL];  /* the corresponding alpha_j values */


double H[MAX_MESSPUNKT],  K[MAX_MESSPUNKT], L[MAX_MESSPUNKT];
double max=0; /* MAX(det/mon) */

int time[MAX_MESSPUNKT], mon[MAX_MESSPUNKT], det[MAX_MESSPUNKT];


char *datfile;            /* first (common) part of the file names */
char *datpath;            /* path of the file names */
char ppmfile [MAX_LEN];
char psfile [MAX_LEN];
char pngfile [MAX_LEN];
char gnuplotfile [MAX_LEN];
char gnuplot2Dfile [MAX_LEN];
int first,last;

double lambda=1.54;        /* wavelength of the X-ray beam in Angstrom ??????  */
int imean=640;             /* Mythen channel number corresponding to
			      spec ?????   */
double d_mythen=0.05;      /* 60 mm/1280 ch = 0.05 mm/ch ???????  */ 
double D_mythen=350.;       /* motion radius of the mean (spec) Mythen
			       channel ???? */

int m_all, m_act; /*  number of files: mythen_all, mythen_actual*/

/* parameters of the ppm file: */
int pixel;                        /* number of pixels along the ppm axes */      
int GEO=0;                          /* tth=th: 2 tth=th: 1 tth=const: 0 */
int LOG;                          /* 1 for log; 0 for lin */
double BG;                        /* background for the log plot */
double q_x_min;               /* range of q_x (th) */
double q_x_max;               /* range of q_x (th) */

int errorcount = 0;     /* for the function error */

/* for the functions ppm + colour: */
float colour_min = 0.79, colour_max = 0.0;                   /*P*/
int gnuplotversion;      /* 0 if >= 4.0; >0 if <=3.7 */           


/**********************    function: main    ***************/
int main(int argc, char *argv[]){
  char *kontr;

  if (argc != 5) {message("\n You have made a mistake in the input,",
                          "please try again using the format:\n");
    message (" ", 
	     "file_read <path> <file> <first> <last> \n");
    message ("<path> =","path of the data files (e.g. . or ../)");
    message ("<file> =","first (common) part of the file names");
    message ("<first> =","first data file to be considered");
    message ("<last> =","last data file to be considered");
    message ("","");
    terminate ("  input error  ");}
  
  datpath = argv[1];
  message("path of the data files=       ", datpath);

  datfile = argv[2];
  message("common part of the file names=", datfile);
  
  first = strtod(argv[3], &kontr);
  if(kontr == argv[3]) terminate(" wrong third parameter\n");
  
  last = strtod(argv[4], &kontr);
  if(kontr == argv[4]) terminate(" wrong fourth parameter\n");
  
  
  /* the gnuplot version will be asked: */
  {FILE *pipe;
    pipe = popen("gnuplot", "w");
    fprintf(pipe, "set terminal png \n");
    gnuplotversion =  pclose(pipe);
    if (gnuplotversion == 0) message("A new gnuplot version is present.","\n");
    else message
      ("An old gnuplot version is present: no png files will be available.",
       "\n");}
  /* ready: gnuplot version */  
  
  read_dat_files ();
  gnuplot_read_dat_files();
  message ("Program version:   file_read.c." DATUM, "\n" );
  error ("terminal"); 
  return 0;}
/**********************    function: main    ***************/


/**********************    function: read_dat_files    ***************/
void read_dat_files () {
  
  /* experimental counts will be read in:  */
  int ii, index=0, mtime, lineindex;
  char filename [MAX_LEN];
  char line [MAX_LEN+1];
  float fH, fK, fL;           /* segedvaltozo */
  int imon, idet;      /* segedvaltozo egesztipusu */
  char dummy[MAX_LEN];
  FILE *file; 
  
  for (ii=first; ii<=last; ii++){
    sprintf(filename, "%s/%s%i%s", datpath, datfile,ii,".dat");
    //printf("%s \n", filename);
    printf("%i ", ii); fflush(stdout);
    file=fopen(filename,"r"); 
    mtime=0; lineindex=0;
    if (file==NULL)  terminate(" The desired file does not exist.  ");
    while (fgets (line, MAX_LEN, file) != NULL) {
      lineindex=lineindex+1;
      if (lineindex==9) sscanf (line, "%s%f%f%f", dummy, &fH, &fK, &fL);
      else if (lineindex>12) {sscanf (line, "%i%i", &imon, &idet);
	mtime=mtime+1;
	index=index+1;
	time[index]=mtime;
	H[index]=fH; 
	K[index]=fK; 
	L[index]=fL;
	mon[index]=imon; 
	det[index]=idet;
	if (max<(double)idet/(double)imon) max=(double)idet/(double)imon;
	//printf("%i  H= %f  K=%f  L=%f  time=%i  mon=%i  det=%i \n  ",
	//index,H[index],K[index],L[index],time[index],mon[index],det[index]);
      } }
    fclose(file);}
  printf ("\nMAX(det/mon)= %f \n",max);
  return;}
/**********************    function: read_dat_files    ***************/


/**********************    function: gnuplot_read_dat_files    ***************/
void gnuplot_read_dat_files () {
  
  /* constructs graphic files by gnuplot  */
  int ii, mtime, lineindex;
  char filename [MAX_LEN];
  char gfilename [MAX_LEN];
  char line [MAX_LEN+1];
  float fH, fK, fL;           /* segedvaltozo */
  char dummy[MAX_LEN]; 
  FILE *file; 
  FILE *pipe; 

  /* H, K, L values will be read in:  */
  for (ii=first; ii<=last; ii++){
    sprintf(filename, "%s/%s%i%s", datpath, datfile,ii,".dat");
    //sprintf(gfilename, "%s%i%s", datfile,ii,".ps");
    //sprintf(gfilename, "%s%i%s", datfile,ii,".png");
    sprintf(gfilename, "%s%03i%s", datfile,ii,".gif");
    //printf("%s \n", filename);
    printf("%i ", ii); fflush(stdout);
    file=fopen(filename,"r");
    mtime=0; lineindex=0;
    if (file==NULL)  terminate(" The desired file does not exist.  ");
    while (fgets (line, MAX_LEN, file) != NULL) {
      lineindex=lineindex+1;
      if (lineindex==9) sscanf (line, "%s%f%f%f", dummy, &fH, &fK, &fL);
      //printf("%i  H= %f  K=%f  L=%f  time=%i  mon=%i  det=%i \n  ",
      //index,H[index],K[index],L[index],time[index],mon[index],det[index]);
    }
    fclose(file);
    
    /* gnuplot settings: */  
    pipe = popen("gnuplot -geometry 900x900+10+10", "w");
    //  fprintf (pipe, "set logscale z \n");
    fprintf (pipe, "set title '<%s     H=%f  K=%f  L=%f>' \n", filename,fH,fK,fL);
    //	fprintf(pipe, "set terminal postscript color solid lw 2\n");      
    //	fprintf(pipe, "set terminal png \n");
    fprintf(pipe, "set terminal gif \n");
    fflush(pipe);
    fprintf(pipe, "set output '%s' \n", gfilename);  
    fflush(pipe);
    /* gnuplot command: */
    /* version constant scaling: */ 
    fprintf (pipe,    
	     "plot [0:1000][0:%.0f] '%s' using ($0):($2)/($1) t '' w l lw 2 lt 1 \n",
	     ceil(max), filename); /**/
      /* version auto scaling:*//*
    fprintf (pipe,    
	     "plot [0:1000][0:] '%s' using ($0):($2)/($1) t '' w l lw 2 lt 1 \n",
	     filename); */
    fclose (pipe);
  }    
  printf("\n");
  return;}
/**********************    function:gnuplot_read_dat_files    ***************/









/**********************    function: terminate    ***************/
void terminate (char *text){                   /* Text bei Fehler */
message("terminate:", text);
exit (1);}
/**********************    function: terminate    ***************/


/**********************      function: message    ***************/
void message (char *text1, char *text2){        /*Text beim Suchen*/
fprintf(stderr, "%s %s \n", text1, text2);}
/**********************      function: message    ***************/


/**********************      function: error    ***************/
void error (char *ref){                /* reports on runtime errors 
                                          Usage:       error ("label");
                          #include <fenv.h> and #include <errno.h> and 
                          int errorcount = 0;  (global) are necessary.*/
#ifdef _FENV_H   
  int raised;  
#endif /* fenv.h*/
  char text[MAX_LEN];  

  strcpy(text, "errno error message (");
  strcat(text, ref);  strcat(text, ")");
  perror(text);

#ifdef _FENV_H 
  raised = fetestexcept 
    (FE_DIVBYZERO | FE_UNDERFLOW | FE_OVERFLOW | FE_INVALID);
  /*(FE_INEXACT | FE_DIVBYZERO | FE_UNDERFLOW | FE_OVERFLOW | FE_INVALID);*/
  if (raised) {errorcount = errorcount + 1; 
  sprintf(text, "%-3i", errorcount);
  strcat(text, "fp error message (");
  strcat(text, ref);  strcat(text, "):");
  /*if (raised & FE_INEXACT)   strcat(text, " INEXACT ");*/  
  if (raised & FE_DIVBYZERO) strcat(text, " DIVBYZERO ");
  if (raised & FE_UNDERFLOW) strcat(text, " UNDERFLOW ");
  if (raised & FE_OVERFLOW)  strcat(text, " OVERFLOW ");
  if (raised & FE_INVALID)   strcat(text, " INVALID ");
  /* putchar('\a'); fflush(stdout); */
  message (text, " ");    
  whistle();}
  /* if (raised) terminate("floating point error"); */
  feclearexcept (FE_ALL_EXCEPT);    /**/  
#endif /* fenv.h*/
  errno = 0; /**/                  }
/**********************      function: error    ***************/


/**********************     wait      ********************/
void wait (char *text){
  char ch[MAX_LEN];  
  fprintf(stderr, "Further with RETURN:  %s", text);
  fgets(ch, MAX_LEN-1, stdin);}
/**********************     wait      ********************/


/**********************   whistle      ********************/
void whistle (void){putchar('\a'); fflush(stdout);}
/**********************   whistle     ********************/


