Skip to content

AFNI/NIfTI Server

Sections
Personal tools
You are here: Home » AFNI » Documentation

Doxygen Source Code Documentation


Main Page   Alphabetical List   Data Structures   File List   Data Fields   Globals   Search  

FD2.c

Go to the documentation of this file.
00001 /*      This program displays functional EPI of the form 64x64 or 128x128
00002         in X11 windows. Keys and subWindow are added. The ar is malloc().
00003         It uses 8 or 12 bitplanes, and own solid color map.
00004         Extras: image marker, continuous X,Y position.
00005         EPI part based on Eric C. Wong program fd_multi.c .
00006         Added RGB mode, 10-14-2001 AJ.
00007         Andre Jesmanowicz, 9-24-1992, Medical College of Wisconsin. */
00008 
00009 #define CONTRAST_CHANGE_STEP 15000/* larger step => slower change AJ 11.1.96 */
00010 
00011 #define ASC_NUL '\0'
00012 
00013 #ifndef COPYRIGHT_STRING
00014 #define COPYRIGHT_STRING "Copyright"
00015 #endif
00016 
00017 #define MAIN
00018 
00019 #ifdef DEBUG
00020 # define STATUS(str) ( printf("%s\n",str) , fflush(stdout) )
00021 #else
00022 # define STATUS(str)
00023 #endif
00024 
00025 /***---------------- additions for use of array of MRI_IMAGE --------------***/
00026 
00027 #undef USE_TRACING  /* not for use in this old program */
00028 
00029 #include "mrilib.h"
00030 #include "overfim.h"
00031 #include "pcor.h"
00032 
00033 #define INC_ALLIM 8
00034 
00035 #define MRIDEB(str) fprintf(stderr,"MRI: %s\n",str)
00036 
00037 int dim_allim = 0 ;
00038 
00039 MRI_IMAGE ** allim   = NULL ;
00040 MRI_IMAGE ** t_allim = NULL ;  /* tmp pointer of allim when FFT done AJJ */
00041 
00042 MRI_IMAGE * im_tmp_ar = NULL ;  /* the working array for displays, etc */
00043 short * tmp_ar = NULL ;
00044 #define SIZE_tmp_ar(n) im_tmp_ar->nx = im_tmp_ar->ny = (n)
00045 
00046 short * nowim = NULL ;
00047 int     nowsize ;
00048 
00049 #define SAR(k) (allim[k]->im.short_data)  /* get pointer to data for image k */
00050 #define T_SAR(k) (t_allim[k]->im.short_data) /* pointer to temp data of im k */
00051 #define SIZ(k) (allim[k]->nx * allim[k]->ny)
00052 #define DIM(k) (allim[k]->nx)
00053 
00054 void add_extra_image() ;
00055 
00056 MRI_IMAGE * RWC_pcim = NULL , * RWC_alpim = NULL ;
00057 
00058 int RWC_autoscale = 0 ;  /* to autoscale image intensities */
00059 int RWC_overhide  = 0 ;  /* to hide overlay in image */
00060 int RWC_framehide = 0 ;  /* to hide frame in image */
00061 int RWC_checker   = 0 ;  /* to checkerboard or not to checkerboard */
00062 int RWC_groupbase = 0 ;  /* to use a group baseline or not */
00063 int AJ_base = 0;         /* to set base to zero when group baseline is on */
00064 int RCR_swap = 0;        /* default is no swap, even for LINUX */
00065 
00066 /***-----------------------------------------------------------------------***/
00067 /*  int discard(int, XEvent*) ; */
00068 /***-----------------------------------------------------------------------***/
00069 
00070 /* additions for use of MCW logo */
00071 
00072 #ifdef USE_MCW
00073    extern int mcw_load() ;  /* prototype */
00074    extern short mcw_im[] ;  /* image array */
00075 #include <unistd.h>
00076 #endif
00077 
00078 /***-----------------------------------------------------------------------***/
00079 
00080 #include <stdio.h>
00081 #include <math.h>
00082 #include <ctype.h>
00083 #include <sys/types.h>
00084 #include <sys/stat.h>
00085 #ifdef   SYSV
00086 #include <sys/fcntl.h>
00087 #endif
00088 
00089 #include <X11/Xos.h>
00090 #include <X11/Xlib.h>
00091 #include <X11/Xutil.h>
00092 #include <X11/cursorfont.h>
00093 #include <X11/keysym.h>
00094 #include <sys/ioctl.h>
00095 
00096 #define IM_HEIGHT 256
00097 #define NUM_STD_COLORS 16
00098 #define IM_ARR    (IM_HEIGHT*IM_HEIGHT)
00099 #if 0
00100 #define NCOLORS   208  /* default # of colors */
00101 #define MCOLORS   256  /* maximum # of colors: NCOLORS + NUM_STD_COLORS (16) */
00102                        /*                    + MAX_EXTRA_COLORS (32) */
00103 #endif
00104 #define NCOLORS   808  /* default # of colors */
00105 #define MCOLORS   856  /* maximum # of colors: NCOLORS + NUM_STD_COLORS (16) */
00106                        /*                    + MAX_EXTRA_COLORS (32) */
00107 #define N_SPCTR   240                 /* def degree of color spectrum */
00108 #define M_SP_COL  360                 /* max degree of color spectrum */
00109 #define BELT_W    24                  /* reference color belt width */
00110 #define BELT_S    3                   /* color belt sides width */
00111 #define BELT_A    (BELT_W*IM_HEIGHT)
00112 #define NF_MAX    10000               /* Max # of files */
00113 #define STR_L     256                 /* Max length of string */
00114 
00115 #define COL_MIN    0
00116 #define MAX_WIDTH  2048  /* Never less then screen max_width */
00117 
00118 #define EPX1      64                   /* List of supported EPI image sizes */
00119 #define EPY1      64                   /* Each triple is: */
00120 #define EPS1      (2*EPX1*EPY1)        /* xsize, ysize, filesize */
00121 
00122 #define EPX2      128
00123 #define EPY2      128
00124 #define EPS2      (2*EPX2*EPY2)
00125 
00126 #define EPX3      256
00127 #define EPY3      256
00128 #define EPS3      (2*EPX3*EPY3)
00129 
00130 #define EPX4      32
00131 #define EPY4      32
00132 #define EPS4      (2*EPX4*EPY4)
00133 
00134 #define OFFSET    (28*IM_HEIGHT)       /* offset to data in 145408 bytes im */
00135 #define H_SIZE    (OFFSET+IM_ARR)      /* 256x256 image with header */
00136 #define IM_SIZE   (2*H_SIZE)
00137 
00138 #define GX_MAX    512                  /* Horizontal size of graph window */
00139 #define GY_MAX    512                  /* Vertical size of graph window */
00140 #define GR_DLX    3                    /* Horizontal delta to right edge */
00141 #define GT_DLY    21                   /* Vertical delta to top edge */
00142 #define GL_DLX    50                   /* Horizontal delta to left edge */
00143 #define GB_DLY    50                   /* Vertical delta to bottom edge */
00144 #define MAT_MAX   25                   /* Maximum array size of graphs */
00145 #define GRID_NUM  8                    /* Maximum grid index */
00146 #define COL_NUM   5                    /* Number of colors */
00147 #define GRID_COEF 50.                  /* alternate for slow scannings */
00148 
00149 /***************************************************************************/
00150 
00151 #ifdef RWCOX_LINUX      /* for the smaller screen */
00152 
00153 #undef GX_MAX
00154 #undef GY_MAX
00155 #define GX_MAX  403
00156 #define GY_MAX  403
00157 
00158 #endif  /* RWCOX_LINUX */
00159 
00160 int RWC_GX_MAX = GX_MAX ;  /* for new option -gsize xx yy */
00161 int RWC_GY_MAX = GY_MAX ;
00162 
00163 /**************************************************************************/
00164 
00165 #define min_max_col(a) ((a) < (256) ? (256) : ((a) > (65280) ? (65280) : (a)))
00166 #define min(a,b) ((a) < (b) ? (a) : (b))
00167 #define max(a,b) ((a) > (b) ? (a) : (b))
00168 
00169 /* keys (small subwindows) stuff ----- vvvvvvvvv ------  AJ */
00170 
00171 #define KFONT     "lucidasanstypewriter-bold-12"  /* defaults */
00172 #define TFONT     "pellucidatypewriter10"
00173 #define PADDINGW  3
00174 #define PADDINGH  5
00175 #define KEY_1_Y   50
00176 
00177 /* fonts to try if the defaults fail */
00178 
00179 static char * tfont ,
00180             * tfont_hopefuls[] = {
00181                "filled-in-by-default" ,
00182                "lucidasanstypewriter-10" ,
00183                "-adobe-courier-medium-r-normal--12-120-75-75-m-70-iso8859-1" ,
00184                "-misc-fixed-medium-r-normal--13-100-100-100-c-70-iso8859-1" ,
00185                "7x14" , "6x13" , "vtsingle" , "fixed" ,
00186                NULL } ;
00187 
00188 struct _key {
00189            char   *st;
00190            int    code;
00191            int    (*fun)();
00192            Window wid;
00193            short  x,y,width,height;
00194   unsigned long   fore,back;
00195            void   (*func)();
00196             };
00197 
00198 struct _key *key;
00199 
00200 #define N_KEYS 18
00201 #define LAST_K 7    /* RWC: incremented this to put FIM key in */
00202 
00203 #define kROT   0
00204 #define kHLP   1
00205 #define kAVR   2
00206 #define kDIF   3
00207 #define kSIG   4
00208 #define kFFT   5
00209 #define kFIM   6    /* RWC: put this in as new permanent button */
00210 #define kNRM   7
00211 #define kAV1   8
00212 #define kAV2   9
00213 #define kIR1  10
00214 #define kIR2  11
00215 
00216 #define kFI1  12   /* RWC: new buttons when FIM key is pressed */
00217 #define kFI2  13
00218 #define kFI3  14   /* the POWER KEY (named by Lloyd Estkowski) */
00219 
00220 #define kFT1  15
00221 #define kFT2  16
00222 #define kFT3  17
00223 
00224 int  Ims_rot(), Im_help(), Im_diff(), Ref_im1(), Ref_im2();
00225 int  Im_Aver(), Im_norm(), Av_im1(), Av_im2(), Smooth_line();
00226 
00227 #define FFT_first_key kFT1
00228 #define FFT_last_key  kFT3
00229 
00230 int  FFT_action(), FFT_selection();
00231 int  FFT_pressed = 0;
00232 int  FT1_pressed = 0, FT2_stat = 0, FT3_stat = 0;
00233 int  z_im1=0, z_imL=0;
00234 char *key_kFFT_FFT   = "FFT" ;
00235 char *key_kFFT_noFT  = "noFT";
00236 char *key_kFT1[2]    = {"edit", "end"};
00237 char *key_kFT2[4]    = {" FT ", "0..0", "from", " to "};
00238 char *key_kFT3[3]     ={"    ", "i FT", "zero"};
00239 
00240 
00241 #define FIM_first_key kFI1
00242 #define FIM_last_key  kFI3
00243 
00244 int  FIM_action() , FIM_selection() ;
00245 int  FIM_pressed = 0 , FIM_modified = 0 ;
00246 
00247 char *FIM_selection_name[FIM_last_key-FIM_first_key+1] =
00248       { "Correlation Coefficient Threshold (0..1)"    , /* dialog box labels */
00249         "Vector Filename ('!nofim'==none)"            ,
00250         NULL                                          /* don't use dialog box */
00251       } ;
00252 
00253 char *key_kFIM_FIM = "FIM" ;
00254 char *key_kFIM_GO  = "GO!" ;
00255 
00256 /*** DFILT stuff has been deactivated -- RWCox July 1995 ***/
00257 
00258 #define DFILT_NONE   0                 /* no derivative filtering */
00259 #define DFILT_TIME   1                 /* temporal mode */
00260 #define DFILT_SIGMA  (4.0*0.42466090)  /* FHWM = 4.0 pixels */
00261 #define DFILT_THRESH 0.05              /* threshold for using 'fit' */
00262 #define DFILT_NREF   3
00263 static char * DFILT_fimcode[2] = { "FIM" , "DFIM" } ;
00264 static int DFILT_code = DFILT_NONE ;   /* flag to do DFILT */
00265 
00266 #define MAX_TOTAL_REF (MAX_NUMORT+MAX_POLORT+DFILT_NREF+4)
00267 
00268 #define LSQ_NONE     0                     /* no Least square remove in graphs */
00269 #define LSQ_SUBORT   1                     /* remove Orts but not ideal */
00270 #define LSQ_SUBALL   2                     /* remove Orts and Ideal */
00271 #define LSQ_FITORT   3                     /* show fit of Orts */
00272 #define LSQ_FITALL   4                     /* show fit of Orts and Ideal */
00273 #define LSQ_SORFID   5                     /* remove orts, show Ideal fit */
00274 
00275 #define LSQ_LASTCODE 5
00276 
00277 #define LSQ_EDIT_NONE -1
00278 #define LSQ_EDIT_ORT   1
00279 #define LSQ_EDIT_ALL   0
00280 
00281 static int LSQ_imedit[LSQ_LASTCODE+1] =
00282  { LSQ_EDIT_NONE, LSQ_EDIT_ORT, LSQ_EDIT_ALL, LSQ_EDIT_NONE, LSQ_EDIT_NONE, LSQ_EDIT_NONE } ;
00283 static char * LSQ_fimcode[LSQ_LASTCODE+1] =
00284  { " " , "SUB:ort" , "SUB:all" , "FIT:ort" , "FIT:all" ,"SUB:ort FIT:ideal"} ;
00285 static int LSQ_code = LSQ_NONE ;
00286 static int LSQ_refcount = 0 ;
00287 static time_series * LSQ_ref[MAX_TOTAL_REF] ;
00288 static MRI_IMARR *   LSQ_fitim = NULL ;
00289 static float * LSQ_fit[MAX_TOTAL_REF] ;
00290 
00291 #define kFI3_NUM  11   /* number of options on the POWER KEY */
00292 
00293 char *key_kFI3[kFI3_NUM] = { "ref =pixel ->" ,   /* labels for POWER KEY */
00294                              "ref+=pixel ->" ,
00295                              "smooth ref ->" ,
00296                              "thresh -+  ->" ,
00297                              "  NO FIM   ->" ,
00298                              "refplt -+  ->" ,
00299                              "save ref   ->" ,
00300                              "polort -+  ->" ,
00301                              "ort = ref  ->" ,
00302                              "clear orts ->" ,
00303                              "SubFit -+  ->"
00304                            } ;
00305 
00306 char *key_kFI3_help[kFI3_NUM] = { "set reference function = central pixel" ,
00307                                   "add central pixel to reference function" ,
00308                                   "median (of 3) filter reference function" ,
00309                                   "- or + correlation coefficient threshold" ,
00310                                   "turn fimming off" ,
00311                                   "- or + number of reference function plots" ,
00312                                   "save reference function in a file" ,
00313                                   "- or + number of polynomial ort functions" ,
00314                                   "make current ref an ort instead" ,
00315                                   "clear all current ort functions" ,
00316                                   "set least squares removal in graphs"
00317                                 } ;
00318 
00319 int kFI3_status       = -1 ;
00320 int kFI3_show_ref     = 1 ;
00321 int kFI3_refsum_count = 0 ;
00322 
00323 int kROT_doall      = 1 ;
00324 char * key_kROT_all = "Rot" ;
00325 char * key_kROT_one = "Rot1" ;
00326 
00327 struct _key xtkeys[N_KEYS] = { {"Rot"  , kROT, Ims_rot},
00328                                {"Help" , kHLP, Im_help},
00329                                {"AvIm" , kAVR, Im_Aver},
00330                                {"Diff" , kDIF, Im_diff},
00331                                {"Smth" , kSIG, Smooth_line},
00332                                {"FFT"  , kFFT, FFT_action} ,
00333                                {"FIM"  , kFIM, FIM_action} ,
00334                                {"Norm" , kNRM, Im_norm},
00335                                {"Average: from this image" , kAV1 , Av_im1},
00336                                {"Average: to this one.   " , kAV2 , Av_im2},
00337                                {"Ref. level first image"   , kIR1 , Ref_im1},
00338                                {"Ref. level last  image"   , kIR1 , Ref_im2},
00339                                {"set threshold"  , kFI1 , FIM_selection},
00340                                {"ref/ort file "  , kFI2 , FIM_selection},
00341                                {"PUSH BUTTON 3"  , kFI3 , FIM_selection},
00342                                {"edit", kFT1 , FFT_selection},
00343                                {" FT ", kFT2 , FFT_selection},
00344                                {"    ", kFT3 , FFT_selection}
00345                              };
00346 
00347 char          *kfont, *ffc, *fbc;
00348 unsigned long ForeColor, BackColor, FKeyFore, FKeyBack;
00349 XColor        xcsd, xced;
00350 XFontStruct   *kfontinfo;
00351 Font          keyfont;
00352 int           keywide[N_KEYS], minwide, keyhigh;
00353 GC            Fkeyigc, Fkeygc;
00354 int           invkey    = -1;
00355 int           exp_done[N_KEYS+3];   /* GWindow + subWindow +topWindow + keys */
00356 short   int   a_rot[H_SIZE], rot_nr = 0, rot_direct , rot_state ;
00357 int           sub_W_x, sub_W_y, top_W_x, top_W_y;
00358 int           v_point_x = -20, v_point_y = 0, move_Vpointer = 0;
00359 int           diff_im = 0, Im_1, Im_2, im1_done = 0, extra_im = 0;
00360 int           avr_grp = 0, Av_1, Av_2, av1_done = 0, Av_length = 1;
00361 int           fim_dif = 0, fim_avr = 0, redraw;
00362 int           txtW_ON = 0;
00363 
00364 
00365 /* keys (small subwindows) stuff ----- ^^^^^^^^^ ------  AJ */
00366 
00367 /*---------------------------------------------------------------------------*/
00368 #ifdef NEED_DEFS
00369 extern double   strtod();
00370 char            *malloc();
00371 char            *realloc();
00372 #endif
00373 /*---------------------------------------------------------------------------*/
00374 
00375 int             STD_colors();
00376 
00377 void x_events_loop();
00378 void Resample();
00379 void Put_image();
00380 void plot_line();
00381 void draw_marker();
00382 void scale_up();
00383 void scale_down();
00384 void mat_up();
00385 void mat_down();
00386 void init_mat();
00387 void grid_up();
00388 void grid_down();
00389 void print_plot();
00390 void redo_graph_window();
00391 void window_plane();
00392 void graphic_store();
00393 void plotx();
00394 void plx_txt();
00395 void plx_TXT();
00396 void subW_TXT();
00397 void line_color();
00398 void txt_color();
00399 void DrawSubWindow();
00400 void DrawTopWindow();
00401 int  FIM_edit_time_series() ;
00402 
00403 int  c_f = 0;
00404 int    st_8[] = {
00405      1,  2,  3,  4,  5,  6,  7,  8,  7,  6,  5,  4,  3,  2,  1,  0,
00406      2,  4,  6,  8, 10, 12, 14, 16, 14, 12, 10,  8,  6,  4,  2,  0,
00407      3,  6,  9, 12, 15, 18, 21, 24, 21, 18, 15, 12,  9,  6,  3,  0,
00408      4,  8, 12, 16, 20, 24, 28, 32, 28, 24, 20, 16, 12,  8,  4,  0,
00409      5, 10, 15, 20, 25, 30, 35, 40, 35, 30, 25, 20, 15, 10,  5,  0,
00410      6, 12, 18, 24, 30, 36, 42, 48, 42, 36, 30, 24, 18, 12,  6,  0,
00411      7, 14, 21, 28, 35, 42, 49, 56, 49, 42, 35, 28, 21, 14,  7,  0,
00412      8, 16, 24, 32, 40, 48, 56, 64, 56, 48, 40, 32, 24, 16,  8,  0,
00413      7, 14, 21, 28, 35, 42, 49, 56, 49, 42, 35, 28, 21, 14,  7,  0,
00414      6, 12, 18, 24, 30, 36, 42, 48, 42, 36, 30, 24, 18, 12,  6,  0,
00415      5, 10, 15, 20, 25, 30, 35, 40, 35, 30, 25, 20, 15, 10,  5,  0,
00416      4,  8, 12, 16, 20, 24, 28, 32, 28, 24, 20, 16, 12,  8,  4,  0,
00417      3,  6,  9, 12, 15, 18, 21, 24, 21, 18, 15, 12,  9,  6,  3,  0,
00418      2,  4,  6,  8, 10, 12, 14, 16, 14, 12, 10,  8,  6,  4,  2,  0,
00419      1,  2,  3,  4,  5,  6,  7,  8,  7,  6,  5,  4,  3,  2,  1,  0,
00420      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0 };
00421 
00422 int    st_4[] = { 1,  2,  3,  4,  3,  2,  1,  0,      /* resampling array */
00423                   2,  4,  6,  8,  6,  4,  2,  0,
00424                   3,  6,  9, 12,  9,  6,  3,  0,
00425                   4,  8, 12, 16, 12,  8,  4,  0,
00426                   3,  6,  9, 12,  9,  6,  3,  0,
00427                   2,  4,  6,  8,  6,  4,  2,  0,
00428                   1,  2,  3,  4,  3,  2,  1,  0,
00429                   0,  0,  0,  0,  0,  0,  0,  0 };
00430 int    st_2[] = { 1, 2, 1, 0,
00431                   2, 4, 2, 0,
00432                   1, 2, 1, 0,
00433                   0, 0, 0, 0 };
00434 
00435 struct S_16_c {
00436               int red;
00437               int green;
00438               int blue;
00439               };
00440 struct S_16_c Solid_color[16] = {
00441    {0xffff, 0xffff, 0xffff}, {0xffff, 0x0000, 0x0000},   /* white,  red     */
00442    {0x0000, 0xffff, 0x0000}, {0x0000, 0x0000, 0xffff},   /* green,  blue    */
00443    {0x0000, 0xffff, 0xffff}, {0xffff, 0x0000, 0xd3d3},   /* cyan,   magenta */
00444    {0xffff, 0xffff, 0x0000}, {0xffff, 0x8a8a, 0xffff},   /* yellow, brown   */
00445    {0x0000, 0x7000, 0x0fff}, {0x0000, 0xffff, 0x9f9f},   /* green,  green   */
00446    {0x0000, 0x8a8a, 0xffff}, {0x9494, 0x0000, 0xd3d3},   /* blue,   violet  */
00447    {0xffff, 0x0000, 0x9494}, {0x6969, 0x6969, 0x6969},   /* pink,   gray    */
00448    {0xaeae, 0xaeae, 0xaeae}, {0x0000, 0x0000, 0x0000}    /* gray,   black   */
00449   };
00450 
00451 short int       color_x11[16] = { -1, -1, -1, -1, -1, -1, -1, -1,
00452                                   -1, -1, -1, -1, -1, -1, -1, -1 };
00453 
00454 XPoint          sm_cir[12] = { {-1,-2},{ 0,-2}, { 1,-2},  /* small circle */
00455                                { 2,-1},{ 2, 0}, { 2, 1},
00456                                { 1, 2},{ 0, 2}, {-1, 2},
00457                                {-2, 1},{-2, 0}, {-2,-1} };
00458 char            *f_name[NF_MAX];
00459 char            *ProgramName = NULL;
00460 char            *Xdef_Name   = "FD" ;      /* name to look for resources under */
00461 char            *display, *geom, **ptr;
00462 
00463 int             FIRST = 1, SQUE_NR;
00464 int             x00 = 0, y00 = 0;
00465 int             back_to_main = 0;
00466 XEvent          event, w_event, first_event;
00467 
00468 Display         *theDisp;
00469 int             theScreen;
00470 Window          rootW, theWindow, GWindow, subWindow, topWindow;
00471 GC              theGC, txtGC;
00472 unsigned long   fcol, bcol;
00473 Font            mfont;
00474 XFontStruct     *afinfo, *mfinfo;
00475 Visual          *theVisual;
00476 XImage          *theImage, *expImage, *theBelt, *expBelt;
00477 int             eWIDE, eHIGH, aWIDE, eW, eH, iWIDE, iHIGH;
00478 
00479 /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
00480 
00481 void RWC_setup_fims() ;
00482 
00483 int    FIM_opt_colors = 0 ;               /* these are for the data */
00484 float  FIM_opt_thr[MAX_FIM_COLORS] ;      /* from the -fim_colors option */
00485 char * FIM_opt_pos[MAX_FIM_COLORS] ,
00486      * FIM_opt_neg[MAX_FIM_COLORS] ;
00487 
00488 int check_color() ;
00489 
00490 /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
00491 
00492 unsigned short  tmp1[NCOLORS], tmp2[NCOLORS], tmp3[NCOLORS];
00493 int             No_Color_init = 1, No_Grey_init = 1;
00494 int             Dispcells, Planes;
00495 int             repeat_status = 0, ncolors, YES_color = 0, INgrey[NCOLORS];
00496 XColor          MYcol[NCOLORS], MYgrey[NCOLORS], any_col, rgb_col;
00497 Colormap        CMap;
00498 unsigned long   plane_masks[1], pixels[MCOLORS];
00499 unsigned int    nplmsk = 0, ucolors, uucolors;
00500 Pixmap          pxWind ;
00501 
00502 int             max_xlines = 0 ;
00503 int             use_pixmap = 1 ;
00504 #define GRWIND  ((use_pixmap)?((Drawable)pxWind):((Drawable)GWindow))
00505 
00506 int             spectrum = N_SPCTR; /* up to 360 degree of colors */
00507 int             Im_Nr = 0, N_im = 0, I_lck = 0, tmp_Nr = 0;
00508 int             N_lck = 0,  old_grid, old_im = -1;
00509 int             x_mag, ref_ar[H_SIZE], av_ar[H_SIZE], Cx, Cy;
00510 short int       imx[IM_ARR], tmp_imx[IM_ARR] ;
00511 short int       belt_ar[BELT_A], belt_arr[BELT_A];
00512 int             Mltx[MAX_WIDTH], Mlty[MAX_WIDTH];
00513 XPoint          a_line[NF_MAX];
00514 
00515 float           del1, coef1, auto_scale;
00516 int             min1;
00517 int             fsize, isize, ar_size;
00518 int             NC;
00519 int             nc_option = 0 ;
00520 char            T_name[STR_L], I_name[STR_L], G_name[STR_L];
00521 int             B1_action = 0, Im_frst = 0, fr_index = -7;
00522 
00523 int             Argc;
00524 char            **Argv = NULL;
00525 
00526 /* these are my own ... EW */
00527 
00528 /* int     plot[MAT_MAX][MAT_MAX][NF_MAX],val[MAT_MAX][MAT_MAX][NF_MAX]; */
00529 
00530 int     * plot[MAT_MAX][MAT_MAX] , * val[MAT_MAX][MAT_MAX] ;
00531 int     * LSQ_val , * LSQ_plot ;
00532 
00533 int     pmin[MAT_MAX][MAT_MAX],pmax[MAT_MAX][MAT_MAX],mat,xc,yc,mark;
00534 int     xorigin[MAT_MAX][MAT_MAX],yorigin[MAT_MAX][MAT_MAX];
00535 int     i,j,xpoint,ypoint,npoints,iscale,gx,gy;
00536 int     xspace,yspace,grid_index, color_index;
00537 char    plotbuf[10*NF_MAX],pfname[80],fnum[80];
00538 int     xpoint_0 = -1, ypoint_0 = -1; /* old xpoint & ypoint */
00539 float   grid_far[2*GRID_NUM], grid_coef = 1.;
00540 
00541 int           mytxt, idx, idy;
00542 int           mdx1, mdy1;
00543 char          strp[STR_L], strF[STR_L], strT[STR_L];
00544 char          *color[5] = {"cyan","red","yellow","green","cornflowerblue"};
00545 
00546 int           im_size, offs;
00547 float         gamm;
00548 
00549 /* Stuff for gausian smoothing of time course lines */
00550 #define MAX_SMOOTH 301
00551 int           AJ_nr, AJ_off, i_plot[NF_MAX];
00552 float         AJ_sigma, AJ_norm;
00553 float         AJ_gauss[MAX_SMOOTH];
00554 float         f_plot[NF_MAX+MAX_SMOOTH];
00555 
00556 /* FFT stuff */
00557 char      *formt[4][4] = {
00558           {     "%s.%d",      "%s.%02d",      "%s.%03d",      "%s.%04d"},
00559           {  "%s_%d.%d",   "%s_%d.%02d",   "%s_%d.%03d",   "%s_%d.%04d"},
00560           {"%s_%02d.%d", "%s_%02d.%02d", "%s_%02d.%03d", "%s_%02d.%04d"},
00561           {"%s_%03d.%d", "%s_%03d.%02d", "%s_%03d.%03d", "%s_%03d.%04d"} };
00562 
00563 void          csfft();
00564 int           t_points, t_N_im; /* keep npoints & N_im FFT done AJJ */
00565 float         t_coef1;
00566 int           t_min1;
00567 complex       *c_arr = NULL;    /* order: [pixel][time] AJJ */
00568 complex       *r_arr = NULL;    /* for reference line */
00569 int           FT_dim;           /* size of single FT */
00570 int           FT_size;          /* size of all FT */
00571 int           FT_disp;          /* size of displayed FT elements */
00572 int           FT_done = 0;
00573 int           FT_grid = 0;      /* = GRID_NUM for FFT graph */
00574 int           FT_graph_on = 0;  /* FT graph is on */
00575 int           grid_timed = 0;
00576 struct _undo_buf {
00577                  int   im;
00578                  int   pix;
00579                  float r;
00580                  float i;
00581                  float r2;
00582                  float i2;
00583                  };
00584 struct _undo_buf *undo_buf = NULL;
00585 struct _undo_buf *undo_ref = NULL; /* for reference line */
00586 int           act_undo = -1, ref_undo = -1;
00587 char          FT_name[100];
00588 int           im_f, phase = 0;
00589 #define FFT_MAG .2
00590 float         fft_mag = FFT_MAG; /* fft amplitude magnify factor AJJ */
00591 float         *T_ref; /* tmp pointer of LSQ_ref[0]->ts when FFT done AJJ */
00592 
00593 float         *avr_A = NULL;     /* array of average over several pixels */
00594 int           avr_nr = 0; /* for time course average over several pixels AJ */
00595 int           cancell_FT = 0;
00596 /* ------ vvvvv ------ RGB mode 10.17.2001 AJ ----- vvvvv ------ */
00597 XImage        *Load_Any_Arr();
00598 XImage        *Load_Any_ind();
00599 XImage        *Load_Any_RGB();
00600 int           Load_Next_Arr();
00601 int           Load_Next_ind();
00602 int           Load_Next_RGB();
00603 int           AJ_StoreColors();
00604 int           AJ_init_RGB();
00605 int           Make_RGB_lookup();
00606 static int    highbit();
00607 
00608 typedef struct { unsigned short r;
00609                  unsigned short g;
00610                  unsigned short b; } AJ_rgb_str;
00611 int           AJ_PseudoColor = 1; /* as original pseudocolor max 12 bpp FD2 */
00612                                   /* reg. colors 0-207, 208-223 std colors, */
00613                                   /* 224-255 fim colors */
00614 AJ_rgb_str    AJ_rgb[MCOLORS];    /* local lookup RGB array */
00615 unsigned long AJ_RGB[MCOLORS];    /* local lookup machine color packed array */
00616 int           bperpix=8, border;
00617 int           STD_indx[NUM_STD_COLORS + MAX_EXTRA_COLORS];
00618 
00619 /****************************************************************************/
00620 
00621 /* ---------------- */
00622    main(argc, argv)
00623    int  argc;
00624    char *argv[];
00625 /* ---------------- */
00626 {
00627    int    i, j, k, m, max1;
00628    char * xdef ;
00629 
00630    Argc = argc;
00631    Argv = argv;
00632    NC = 64;
00633 
00634    ProgramName = argv[0];  if( Xdef_Name == NULL ) Xdef_Name = ProgramName ;
00635 
00636    if (argc <  2)  { Syntax(); The_Help(1); }
00637    display = NULL;
00638    npoints = 0;
00639    gamm = 1.4 ;
00640    LSQ_ref[0] = NULL ;
00641    init_grid();
00642 
00643    get_line_args(argc, argv);       /* get command line arguments and files */
00644 
00645 /*** ---- allocate memory for plot[][] and val[][] ---- ***/
00646 
00647 STATUS("allocating graph memory") ;
00648 
00649    m = sizeof(int) * npoints ;
00650 
00651    LSQ_plot = (int *) malloc( m ) ;
00652    LSQ_val  = (int *) malloc( m ) ;
00653    if( LSQ_plot == NULL || LSQ_val == NULL ){
00654       fprintf(stderr,"\n*** failure in malloc for graphs! ***\a\n");
00655       exit(-1);
00656    }
00657 
00658    for( i=0 ; i < MAT_MAX ; i++ ){
00659       for( j=0 ; j < MAT_MAX ; j++ ){
00660          plot[i][j] = (int *) malloc( m ) ;
00661          val[i][j]  = (int *) malloc( m ) ;
00662 
00663          if( plot[i][j] == NULL || val[i][j] == NULL ){
00664             fprintf(stderr,"\n*** failure in malloc for graphs! ***\a\n");
00665             exit(-1);
00666          }
00667       }
00668    }
00669 
00670 /* ---------- Open the display. --------- */
00671 
00672 STATUS("opening X11 display") ;
00673 
00674    if ( (theDisp=XOpenDisplay(display)) == NULL) {
00675      fprintf(stderr, "%s: Can't open display (are X11 windows running ?). AJ\a\n"
00676              ,ProgramName);
00677      exit(1);
00678    }
00679 
00680    if( !nc_option ){
00681       xdef = XGetDefault(theDisp,Xdef_Name,"NColors") ;
00682       if( xdef != NULL ){
00683          i = strtol(xdef,NULL,0) ;
00684          if( i > 4 ) NC = i ;
00685       }
00686    }
00687 
00688 /* set some image dimensions for everybody to use */
00689 
00690    if      ( fsize == EPS1) {
00691       im_size = 64;
00692       x_mag = 4;  /* 64x64 pixels format => mag = 4 */
00693    }
00694    else if (fsize == EPS2) {
00695      im_size = 128;
00696      x_mag = 2;  /* 128x128 pixels format */
00697    }
00698    else if (fsize == EPS3) {
00699      im_size = 256;
00700      x_mag = 1;  /* 256x256 pixels format */
00701    }
00702    else if (fsize == EPS4) {
00703      im_size = 32;
00704      x_mag = 8;  /* 32x32 pixels format */
00705    }
00706 
00707    init_const();
00708 
00709 STATUS("computing image statistics") ;
00710 
00711    min1 =  32767;    /* find deviation fot central frame and set scale */
00712    max1 = -32768;
00713    i = ypoint*im_size + xpoint;
00714    for (k=0; k < npoints; k++) {
00715       if ( SAR(k)[i] < min1 ) min1 = SAR(k)[i];
00716       if ( SAR(k)[i] > max1 ) max1 = SAR(k)[i];
00717    }
00718    del1 = max1 - min1;
00719    if ( (int) del1 > 1) {
00720       k = (int) (log(del1*auto_scale)/log(2.) + .5) - iscale;
00721       for (i=0; i < abs(k); i++) {       /* scale graph */
00722          if ( k < 0 ) scale_up();
00723          else         scale_down();
00724       }
00725    }
00726 
00727    min1 =  32767;
00728    max1 = -32768;
00729    for (k=0; k < npoints; k++) {    /* find global min and max for main set */
00730       nowim = SAR(k) ;
00731       for (i=0; i < ar_size; i++) {
00732          if ( nowim[i] < min1 ) min1 = nowim[i] ;
00733          if ( nowim[i] > max1 ) max1 = nowim[i] ;
00734       }
00735    }
00736    del1 = max1 - min1;
00737    if (del1 < 1.) del1 = 1.;
00738    coef1 = ( (float) NC - 1.) / del1;
00739 
00740 STATUS("loading reference color belt") ;
00741 
00742    make_belt(belt_ar, BELT_W, IM_HEIGHT);     /* make reference color belt */
00743    load_rect_str(belt_ar, belt_arr, BELT_W, IM_HEIGHT,
00744                  BELT_S, 15, BELT_S, 15, 0, NC);
00745 
00746    main_FD_EPI();          /* Make image in the window and return Drawable */
00747 
00748    /** if -fim_colors was specified, check its colors for legality now **/
00749 
00750    if( FIM_opt_colors > 0 ){
00751       for( i=0 ; i < FIM_opt_colors ; i++ ){
00752          if( !check_color( FIM_opt_pos[i] ) )
00753            fprintf(stderr,"\n*** color %s invalid\n",FIM_opt_pos[i]) ;
00754 
00755          if( !check_color( FIM_opt_neg[i] ) )
00756            fprintf(stderr,"\n*** color %s invalid\n",FIM_opt_neg[i]) ;
00757       }
00758    }
00759 
00760    /* Initialize extra E.C.W. graph stuff here.  AJ */
00761 
00762 STATUS("creating graph windows") ;
00763    window_plane();  /* create graphic window with extra subwindows and keys */
00764 
00765 STATUS("calling redraw_graph") ;
00766    redraw_graph();                       /* draw frame and text in it */
00767 STATUS("calling DrawSubWindow") ;
00768    DrawSubWindow();
00769 STATUS("calling DrawTopWindow") ;
00770    DrawTopWindow();
00771 
00772 STATUS("calling Put_image(0)") ;
00773    Put_image(0) ;                     /* put the first image */
00774    XRaiseWindow(theDisp,theWindow) ;  /* bring image to top  */
00775 
00776 STATUS("begin X event loop") ;
00777 
00778    x_events_loop();                              /* Main events check loop */
00779 
00780    exit(0);
00781 
00782 }       /* --- End of main() --- */
00783 
00784 
00785 
00786 /* -------- */
00787    Syntax()
00788 /* -------- */
00789 {
00790   fprintf (stderr, "\n Functional Display (32x32, 64x64, 128x128, 256x256) in X11 window.");
00791   fprintf (stderr, "\n EPI images in 256x256 Signa format are accepted too.");
00792   fprintf (stderr, "\n It displays EPI time or frequency course window.");
00793   fprintf (stderr, "\n\n Usage: %s [options] image1, [image2, ..., image%d]\n", ProgramName, NF_MAX);
00794   fprintf (stderr, "\n Where options are:");
00795   fprintf (stderr, "\n    -d display       - X11 display");
00796   fprintf (stderr, "\n    -geom geometry   - initial geometry");
00797   fprintf (stderr, "\n    -nc #_of_colors  - initial number of colors [2-%d] (def %d)", 200, NC);
00798   fprintf (stderr, "\n    -sp #_of_degree  - range of color spectrum [0-%d] degree (def %d)", M_SP_COL, N_SPCTR);
00799   fprintf (stderr, "\n    -gam gamma       - gamma correction (1 for no correction)");
00800   fprintf (stderr, "\n    -num #_of_images - # of images in time course [2-%d].", NF_MAX);
00801   fprintf (stderr, "\n    -im1 image_#     - first image in time course. Previous images will be ");
00802   fprintf (stderr, "\n                       filled with this one for proper timing of others.");
00803   fprintf (stderr, "\n    -ideal ref_file  - use ref_file for fim-like calculations" ) ;
00804   fprintf (stderr, "\n    -pcthresh #      - use # as threshold for correlation" ) ;
00805   fprintf (stderr, "\n    -extra           - files after this are not used in time course" );
00806   fprintf (stderr, "\n                       (used instead of -num option)" );
00807   fprintf (stderr, "\n    -fim_colors L thr1 pos1 neg2 ... thrL posL negL" );
00808   fprintf (stderr, "\n                     - set up L thresholds and colors for FIM overlay");
00809   fprintf (stderr, "\n    -gsize x y       - set graph window size to x by y pixels");
00810   fprintf (stderr, "\n    -fmag val        - magnify scale of FFT by val");
00811   fprintf (stderr, "\n    -grid val        - initial grid separation ");
00812   fprintf (stderr, "\n    -phase           - image has negative values (for FFT)");
00813   fprintf (stderr, "\n    -cf              - center image to the frame");
00814   fprintf (stderr, "\n    -swap            - byte-swap data (default is no)");
00815   fprintf (stderr, "\n                       *** this is a new default!");
00816   fprintf (stderr, "\n");
00817 }
00818 
00819 /* ------------ */
00820    The_Help(ex)
00821    int ex;
00822 /* ------------ */
00823 {
00824   fprintf (stderr, "\n Events:\n");
00825   fprintf (stderr,"\n  Program quit      : <q> or <Q>");
00826   fprintf (stderr,"\n  Change to colors  : <C>");
00827   fprintf (stderr,"\n  Change to B & W   : <B>");
00828   fprintf (stderr,"\n  Swap colors       : <s>");
00829   fprintf (stderr,"\n  Restore colors    : Button_3 at image center ");
00830   fprintf (stderr,"\n  Squeeze colors    : #2 or #3 button - right side of image");
00831   fprintf (stderr,"\n  Expand  colors    :                   left  side of image");
00832   fprintf (stderr,"\n  Circ. color bar   : #2 or #3 button at the color bar");
00833   fprintf (stderr,"\n  Color saturation  : #2 or #3 button - the top or bottom");
00834   fprintf (stderr,"\n  Exact image number: press <I>, enter_number, <CR>");
00835   fprintf (stderr,"\n  First image       : 1");
00836   fprintf (stderr,"\n  Last image        : l");
00837   fprintf (stderr,"\n  Next     image    : >");
00838   fprintf (stderr,"\n  Previous image    : <");
00839   fprintf (stderr,"\n                      dragging red pointer works too");
00840   fprintf (stderr,"\n  Scale Plot up         : +");
00841   fprintf (stderr,"\n  Scale Plot down       : -");
00842   fprintf (stderr,"\n  Increase Grid Spacing : G");
00843   fprintf (stderr,"\n  Decrease Grid Spacing : g");
00844   fprintf (stderr,"\n  Toggle Grid and Colors: r");
00845   fprintf (stderr,"\n  Toggle Frame colors   : R");
00846   fprintf (stderr,"\n  Increase matrix size  : M");
00847   fprintf (stderr,"\n  Decrease matrix size  : m");
00848   fprintf (stderr,"\n  Exact matrix size     : N #of_size <CR> (1 to %d only)", MAT_MAX);
00849   fprintf (stderr,"\n  Save minigraph in ASCII file   : press <p>");
00850   fprintf (stderr,"\n    [with xxx_yyy.suffix filename] press <w>");
00851   fprintf (stderr,"\n  Save current image to a file   : press <S>");
00852   fprintf (stderr,"\n  Save averaged image (not norm) : press <X>");
00853   fprintf (stderr,"\n  Position frame in the image    : press Button_1 in the image area,");
00854   fprintf (stderr,"\n                                    drag cursor, and release button.");
00855   fprintf (stderr,"\n  Center frame on desired pixel  : press Button_1 over desired minigraph.");
00856   fprintf (stderr,"\n  Rotate image 90 deg. clockwise : press Button_3 in [Rot] window.");
00857   fprintf (stderr,"\n                counterclockwise : press Button_1 in [Rot] window.");
00858   fprintf (stderr,"\n  Change to differential display : press [Diff] window. Set first and");
00859   fprintf (stderr,"\n                                   last image for averaged reference.");
00860   fprintf (stderr,"\n  Average of set of images       : press [AvIm] (can be used in Diff mode).");
00861   fprintf (stderr,"\n  Compute FIM overlay            : press [FIM], choose ref file,threshold,");
00862   fprintf (stderr,"\n                                   then press [GO]");
00863   fprintf (stderr,"\n") ;
00864   fprintf (stderr,"\n  Last image in time course      : L") ;
00865   fprintf (stderr,"\n  Toggle autoscale of images     : A") ;
00866   fprintf (stderr,"\n  Hide FIM overlay               : H") ;
00867   fprintf (stderr,"\n  Hide frame in image            : h") ;
00868   fprintf (stderr,"\n  Toggle overlay checkerboard    : O") ;
00869   fprintf (stderr,"\n  Read image into program        : F (for file)") ;
00870   fprintf (stderr,"\n  Remove image from program      : K (for kill)") ;
00871   fprintf (stderr,"\n  Move to image 1..9             : 1,2,...9") ;
00872   fprintf (stderr,"\n  Toggle common graph baselines  : b") ;
00873   fprintf (stderr,"\n  Toggle baseline to zero        : x") ;
00874   fprintf (stderr,"\n");
00875   fprintf (stderr,"\n  Add/[subtract] 3600 from pixel : D / [d]");
00876   fprintf (stderr,"\n  In FT edit mode: ");
00877   fprintf (stderr,"\n                increase value   : Arrow Up");
00878   fprintf (stderr,"\n                decrease value   : Arrow Down");
00879   fprintf (stderr,"\n          Shift or Control Arrow : larger changes ");
00880   fprintf (stderr,"\n                undo last change : u");
00881   fprintf (stderr,"\n                undo all changes : U");
00882 
00883 #ifdef USE_MCW
00884   fprintf (stderr,"\n  Show MCW logo              : 0") ;
00885 #endif
00886   fprintf (stderr,"\n\n ");
00887 
00888   if (ex == 1) exit(1);
00889 }
00890 
00891 /* ------------------------- */
00892    get_line_args(argc, argv)
00893    int  argc;
00894    char *argv[];
00895 /* ------------------------- */
00896 {
00897    register int i, j, k, nopt, nnn;
00898    int          sp;
00899    float        fff;
00900 
00901    MRI_IMAGE * imtemp ;
00902    int input_conversion = 0 ;
00903    int nextra = -1 ;
00904 
00905    nopt = 0;
00906    for (i = 1; i < argc; i++) { /* ------- Options ------- */
00907 
00908       if (!strncmp(argv[i], "-d", 2)) {          /* display */
00909          if (++i >= argc) { Syntax (); exit(1); }
00910          display = argv[i];
00911          nopt++; nopt++;
00912          continue;
00913       }
00914       if (!strncmp(argv[i], "-geo", 4)) {          /* initial geometry */
00915          if (++i >= argc) { Syntax (); exit(1); }
00916          geom  = argv[i];
00917          nopt++; nopt++;
00918          continue;
00919       }
00920       if (!strncmp(argv[i], "-h", 2)) {          /* help */
00921          Syntax();
00922          The_Help(1);
00923       }
00924       if (!strncmp(argv[i], "-nc", 3)) {         /* # of colors */
00925          if (++i >= argc) { Syntax (); exit(1); }
00926          nnn = atoi(argv [i]);
00927          if (nnn < 2 || nnn > NCOLORS ) { Syntax(); exit(1); }
00928          NC = nnn;  nc_option = 1 ;
00929          nopt++; nopt++;
00930          continue;
00931       }
00932       if (strncmp(argv [i], "-sp", 3) == 0) {
00933          if (++i >= argc) { Syntax(); exit(1); }
00934          ptr = argv;
00935          sp = strtod(argv[i], ptr);
00936          if ( **ptr || (sp < 1) || (sp > M_SP_COL) ) {
00937             fprintf (stderr, "\n !!! Wrong degree value: -sp %d !!!\a\n",sp);
00938             fprintf (stderr, "\n !!! For help type: %s -h \a\n\n", ProgramName);
00939             exit(3);
00940          }
00941          spectrum = sp;
00942          nopt++; nopt++;
00943          continue;
00944       }
00945       if (strncmp(argv [i], "-fmag", 5) == 0) {
00946          if (++i >= argc) Syntax ();
00947          ptr = argv;
00948          fff = strtod(argv[i], ptr);
00949          if ( **ptr || (fff <= 0.) ) {
00950             fprintf (stderr, "\n !!! Wrong fft magnify value: %g !!!\n\n",fff);
00951             Syntax();
00952          }
00953          fft_mag = fff * FFT_MAG;
00954          nopt++; nopt++;
00955          continue;
00956       }
00957       if (strncmp(argv [i], "-gam", 4) == 0) {
00958          if (++i >= argc) Syntax ();
00959          ptr = argv;
00960          fff = strtod(argv[i], ptr);
00961          if ( **ptr || (fff <= 0.) ) {
00962             fprintf (stderr, "\n !!! Wrong gamma value: %g !!!\a\n\n",fff);
00963             exit(3) ;
00964          }
00965          gamm = fff;
00966          nopt++; nopt++;
00967          continue;
00968       }
00969       if (strncmp(argv [i], "-num", 4) == 0) {
00970          if (++i >= argc) { Syntax(); exit(1); }
00971          ptr = argv;
00972          npoints = strtod(argv[i], ptr) + .5;
00973          if ( **ptr || (npoints < 1)) {
00974             fprintf (stderr, "\n !!! Too few images specified !!!\a\n\n");
00975             exit(1); /* now symbolic for min npoints = 1 . AJ */
00976          }
00977          nopt++; nopt++;
00978          continue;
00979       }
00980       if (strncmp(argv [i], "-pha", 4) == 0) {
00981          phase = 1;
00982          nopt++;
00983          continue;
00984       }
00985       if (strncmp(argv [i], "-cf", 3) == 0) {
00986          c_f = 1;
00987          nopt++;
00988          continue;
00989       }
00990       if (strncmp(argv [i], "-grid", 4) == 0) {
00991          if (++i >= argc) { Syntax(); exit(1); }
00992          ptr = argv;
00993          fff = strtod(argv[i], ptr);
00994          if ( **ptr || (fff < .1)) {
00995             fprintf (stderr,
00996             "\n !!! grid spacing too small [< .1]: %g !!!\a\n\n", fff);
00997             exit(1);
00998          }
00999          if ( fff < 2 ) grid_coef = GRID_COEF;
01000          else           grid_coef = 1.;
01001          grid_index = 0;
01002          grid_far[0] = fff;
01003          grid_far[1] = 2.*fff;
01004          grid_far[2] = 5.*fff;
01005          grid_timed = 1;
01006          nopt++; nopt++;
01007          continue;
01008       }
01009       if (strncmp(argv [i], "-im1", 4) == 0) {
01010          if (++i >= argc) { Syntax(); exit(1); }
01011          ptr = argv;
01012          Im_frst = strtod(argv[i], ptr) + .5;
01013          if ( **ptr || (Im_frst < 1)) {
01014             fprintf (stderr, "\n !!! First_image_# < 1 in -im1 !!!\a\n\n");
01015             exit(1);
01016          }
01017          nopt++; nopt++;
01018          continue;
01019       }
01020       if (strncmp(argv [i], "-mag", 4) == 0) {
01021          fprintf (stderr, "\n !!! No more -mag option in use !!!");
01022          fprintf (stderr, "\n !!! Resize window using mouse  !!!\a\n\n");
01023          if (++i >= argc) { Syntax(); exit(1); }
01024          nopt++; nopt++;
01025          continue;
01026       }
01027 
01028       /* allow the user to specify swapping bytes */
01029       if (strncmp(argv [i], "-swap", 5) == 0) {
01030          RCR_swap = 1;
01031          nopt++; nopt++;
01032          continue;
01033       }
01034 
01035 /***************************************************************************/
01036 
01037      if( strncmp(argv[i],"-grwind",6) == 0 ){
01038         use_pixmap = 0 ;
01039         nopt++ ;
01040         continue ;
01041      }
01042 
01043      if( strncmp(argv[i],"-pcthresh",4) == 0 ){
01044         if( ++i >= argc ) { Syntax(); exit(1); }
01045         RWC_pcthresh = strtod( argv[i] , NULL ) ;
01046         if( RWC_pcthresh <= 0.0 || RWC_pcthresh >= 1.0 ){
01047            fprintf(stderr,"-pcthresh %11.4g is illegal!\a\n",RWC_pcthresh) ;
01048            exit(1);
01049         }
01050 #ifdef OV_DEBUG1
01051    fprintf(stderr,"-pcthresh read as %11.4g\n",RWC_pcthresh) ; fflush(stderr);
01052 #endif
01053         nopt++ ; nopt++ ;
01054         continue ;
01055      }
01056 
01057      if( strncmp(argv[i],"-ideal",4) == 0 ){
01058         if( RWC_ideal != NULL ){
01059            fprintf(stderr,"cannot have 2 -ideal options!\a\n") ;
01060            exit(1) ;
01061         }
01062         if( ++i >= argc ) { exit(1); }
01063 
01064         RWC_ideal = RWC_read_time_series( argv[i] ) ;
01065 
01066         if( RWC_ideal == NULL ){
01067            fprintf(stderr,"cannot read -ideal %s\a\n",argv[i]) ;
01068            exit(1);
01069         }
01070 #ifdef OV_DEBUG1
01071    fprintf(stderr,"-ideal file %s read OK\n",argv[i]) ; fflush(stderr);
01072 #endif
01073         RWC_do_overfim = 1 ;
01074         nopt++ ; nopt++ ;
01075         continue ;
01076      }
01077 
01078      if( strncmp(argv[i],"-extra",3) == 0 ){
01079         if( nextra > 0 ){
01080            fprintf(stderr,"cannot have 2 -extra options!\a\n") ;
01081            exit(1) ;
01082         }
01083         nextra = i ;  /* do NOT count this in nopt! */
01084         continue ;
01085      }
01086 
01087      if( strncmp(argv[i],"-gsize",4) == 0 ){
01088         if( i+2 >= argc ){
01089            fprintf(stderr,"\n*** nothing follows -gsize!\a\n");
01090            exit(1) ;
01091         }
01092         RWC_GX_MAX = strtod( argv[++i] , NULL ) ;
01093         RWC_GY_MAX = strtod( argv[++i] , NULL ) ;
01094         if( RWC_GX_MAX <  100 || RWC_GY_MAX <  100 ||
01095             RWC_GX_MAX > 1024 || RWC_GY_MAX > 1024   ){
01096            fprintf(stderr,"\n*** illegal values following -gsize!\n");
01097            exit(1) ;
01098         }
01099         nopt += 3 ;
01100         continue ;
01101      }
01102 
01103      if( strncmp(argv[i],"-fim_colors",8) == 0 ){
01104         int   ival , ii , good ;
01105         float fval ;
01106 
01107         if( FIM_opt_colors > 0 ){
01108            fprintf(stderr,"\n*** cannot have 2 -fim_colors options!\a\n") ;
01109            exit(1) ;
01110         }
01111         if( ++i >= argc ){
01112            fprintf(stderr,"\n*** nothing follows -fim_colors!\a\n") ;
01113            exit(1) ;
01114         }
01115 
01116         ival = strtol( argv[i] , NULL , 10 ) ;
01117         if( ival <= 0 || ival > MAX_FIM_COLORS ){
01118            fprintf(stderr,"\n*** illegal value for -fim_colors: %d\a\n",ival) ;
01119            exit(1) ;
01120         }
01121         FIM_opt_colors = ival ;
01122         if( i + 3*FIM_opt_colors >= argc ){
01123            fprintf(stderr,"\n*** not enough values follow -fim_colors!\a\n");
01124            exit(1) ;
01125         }
01126 
01127         good = 1 ;
01128         for( ii=0 ; ii < FIM_opt_colors ; ii++ ){
01129            fval = strtod( argv[++i] , NULL ) ;
01130            if( fval <= 0.0 || fval >= 1.0 ){
01131               fprintf(stderr,"\n*** illegal fim_colors threshold %s\a\n",argv[i]);
01132               good = 0 ;
01133            }
01134            FIM_opt_thr[ii] = fval ;      /* store threshold and color strings */
01135            FIM_opt_pos[ii] = argv[++i] ;
01136            FIM_opt_neg[ii] = argv[++i] ;
01137         }
01138         if( !good ){
01139            fprintf(stderr,"\n*** cannot continue from fim_colors errors!\n");
01140            exit(1) ;
01141         }
01142         nopt += 3 * FIM_opt_colors + 2 ;
01143         continue ;
01144      }
01145 
01146 /***************************************************************************/
01147 
01148    }
01149    nopt++;                                   /* Files to read (minimum one) */
01150 
01151    if( nextra > 0 && nextra <= nopt ){
01152       fprintf(stderr,"\n*** -extra option too early!\a\n"); exit(1) ;
01153    }
01154 
01155    if( nextra > nopt && npoints > 0 ){
01156       fprintf(stderr,"\n*** -extra option conflicts with -num option!\a\n");
01157       exit(1) ;
01158    }
01159 
01160    if ( nopt > (argc-1) || nopt < (argc - NF_MAX) ) {  /* Nr of files check */
01161       fprintf (stderr, "\n Wrong # of files. %d files entered :\a\n", argc-nopt);
01162       for(i=nopt, j=1; i < argc; i++, j++)
01163          fprintf (stderr, "  %3d -  %s\n", j, argv[i]);
01164       exit(1);
01165    }
01166 
01167    N_im = argc-nopt;                                /* # of images */
01168 
01169    if( nextra > nopt ){
01170       N_im -- ;                                     /* -1 for -extra option */
01171       npoints = nextra - nopt ;                     /* no. points in series */
01172    } else if( npoints == 0 || npoints > N_im ){
01173       npoints = N_im ;
01174    }
01175 
01176    if( N_im < 1 || N_im > NF_MAX ){
01177       fprintf (stderr, "\n Wrong # of files. %d files entered :\a\n", argc-nopt);
01178       exit(1) ;
01179    }
01180 
01181   if ( Im_frst > N_im ) {
01182       fprintf (stderr,
01183                "\n!!! First_im_# in -im1 is bigger than number of images!!!\a\n");
01184       exit(1);
01185    }
01186 
01187    for( i=0,k=0 ; i < N_im ; i++,k++){
01188       if( strncmp(Argv[k+nopt],"-extra",3) == 0 ) k++ ;  /* skip -extra */
01189       f_name[i] = Argv[k+nopt] ;
01190    }
01191    if( N_im == 1 ){
01192       N_im = npoints = 2 ;
01193       f_name[1] = malloc( strlen(f_name[0]) + 1 ) ;
01194       strcpy( f_name[1] , f_name[0] ) ;
01195    }
01196 
01197    for (i=0; i < Im_frst-1; i++) f_name[i] = f_name[Im_frst-1];
01198 
01199    dim_allim = N_im + INC_ALLIM ;  /* allow for some extra images */
01200 
01201    allim = (MRI_IMAGE **) malloc( sizeof(MRI_IMAGE *) * dim_allim ) ;
01202    if( allim == NULL ){
01203       fprintf(stderr,"\n*** cannot malloc allim\a\n") ;
01204       MRI_FATAL_ERROR ;
01205    }
01206 
01207    /* read and check the length of the first file for validity */
01208 
01209    imtemp = mri_read_nsize( f_name[0] ) ;
01210 
01211    /* swap based on command-line now                   27 Aug 2004 [rickr] */
01212 
01213    if ( RCR_swap && imtemp->kind == MRI_short ) {
01214      swap_2(MRI_SHORT_PTR(imtemp), imtemp->nx*imtemp->ny*2);
01215    }
01216    else if ( RCR_swap && imtemp->kind == MRI_float ) {
01217      swap_4(MRI_FLOAT_PTR(imtemp), imtemp->nx*imtemp->ny*4);
01218    }
01219 
01220    if( imtemp == NULL ) exit(-1) ;
01221    if( imtemp->kind == MRI_short ){
01222       allim[0] = imtemp ;
01223    } else {
01224       allim[0] = mri_to_short( 0.0 , imtemp ) ;
01225       mri_free( imtemp ) ;
01226       mri_add_name( f_name[0] , allim[0] ) ;
01227       input_conversion++ ;
01228    }
01229 
01230    isize = 2 * allim[0]->nx * allim[0]->ny ;
01231    if ( (isize != EPS1) && (isize != EPS2)
01232      && (isize != EPS3) && (isize != EPS4) ) {
01233       fprintf (stderr, "\n\n !!! File %s has illegal dimensions !!!\a\n", f_name[0]);
01234       exit(-1);
01235    }
01236 
01237    im_tmp_ar = mri_new( IM_HEIGHT , IM_HEIGHT , MRI_short ) ; /* max size */
01238    tmp_ar    = mri_data_pointer( im_tmp_ar ) ;
01239 
01240    fsize   = isize;
01241    ar_size = fsize / 2 ;
01242 
01243 #ifndef DEBUG
01244    printf("\nReading files ") ; fflush(stdout) ;
01245 #endif
01246 
01247    for( i=1 ; i < N_im ; i++ ){
01248 
01249 #ifdef DEBUG
01250    printf(" about to read image file %s\n",f_name[i]) ; fflush(stdout) ;
01251 #else
01252    if( i%10 == 9 ){ printf(".") ; fflush(stdout) ; }
01253 #endif
01254 
01255       imtemp = mri_read_nsize( f_name[i] ) ;
01256 
01257       /* we already know whether to swap     26 Aug 2004 [rickr] */
01258       if ( RCR_swap && imtemp->kind == MRI_short ) {
01259         swap_2(MRI_SHORT_PTR(imtemp), imtemp->nx*imtemp->ny*2);
01260       }
01261       else if ( RCR_swap && imtemp->kind == MRI_float ) {
01262         swap_4(MRI_FLOAT_PTR(imtemp), imtemp->nx*imtemp->ny*4);
01263       }
01264 
01265       if( imtemp == NULL ){
01266          fprintf(stderr,"\n*** %s does not have exactly one image!\a\n",
01267                  f_name[i]) ;
01268          exit(1) ;
01269       }
01270 
01271       if( imtemp->kind == MRI_short ){
01272          allim[i] = imtemp ;
01273       } else {
01274          allim[i] = mri_to_short( 0.0 , imtemp ) ;
01275          mri_free( imtemp ) ;
01276          mri_add_name( f_name[i] , allim[i] ) ;
01277          input_conversion++ ;
01278       }
01279       isize = 2 * allim[i]->nx * allim[i]->ny ;
01280       if ( i < npoints && isize != fsize) {  /* check lengths of other files */
01281          fprintf (stderr, "\n\n !!! File %s has different dimensions !!!\a\n",
01282                   f_name[i]);
01283          exit(1);
01284       } else if( isize != EPS1 && isize != EPS2
01285               && isize != EPS3 && isize != EPS4 ){
01286          fprintf(stderr,"\n*** file %s has illegal dimensions!\a\n",f_name[i]);
01287          exit(1) ;
01288       }
01289    }
01290 #ifndef DEBUG
01291    printf("\n"); fflush(stdout) ;
01292 #endif
01293    if( input_conversion ){
01294       fprintf(stderr,
01295               "\n*** %d files converted to shorts on input!\n",
01296               input_conversion ) ;
01297    }
01298 
01299    if( RWC_ideal != NULL ){
01300       FIM_edit_time_series( RWC_ideal ) ;
01301       if( RWC_ideal->len < npoints ){
01302          fprintf(stderr,"*** -ideal %s too short!\n",RWC_ideal->fname) ;
01303          RWC_free_time_series( RWC_ideal ) ;
01304          RWC_ideal = NULL ;
01305          RWC_do_overfim = 0 ;
01306          if( RWC_imover != NULL ) { free(RWC_imover) ; RWC_imover = NULL ; }
01307       } else {
01308          kFI3_refsum_count = -1 ;
01309       }
01310    }
01311 
01312 }
01313 
01314 /* ------------------------------------------- Main link from main() C */
01315    main_FD_EPI()
01316 /* ------------------------------------------------------------------- */
01317 {
01318    int        i;
01319    XGCValues  gcv;
01320 
01321    ucolors = SQUE_NR = ncolors = NC;
01322    uucolors = NC - 1;
01323    expImage = NULL;
01324 
01325    for (i=0; i<IM_HEIGHT; i++) {   /* init MResize() lookup tables */
01326       Mltx[i] = i;
01327       Mlty[i] = i;
01328    }
01329 
01330    top_nr_name(allim[0]->name);
01331 
01332 /* ---------- Open the display. --------- */
01333 #if 0
01334    if ( (theDisp=XOpenDisplay(display)) == NULL) {
01335      fprintf(stderr, "%s: Can't open display (are X11 windows running ?). AJ\a\n"
01336              ,ProgramName);
01337      exit(1);
01338    }
01339 #endif
01340 
01341 STATUS("creating image window") ;
01342 
01343    theScreen = DefaultScreen(theDisp);          /* Set Graphic variables */
01344    rootW     = RootWindow(theDisp,theScreen);
01345    theGC     = DefaultGC(theDisp,theScreen);
01346    theVisual = DefaultVisual(theDisp,theScreen);
01347    CMap      = DefaultColormap(theDisp, theScreen);
01348    Planes    = DisplayPlanes(theDisp, theScreen);
01349 
01350 #if defined(__cplusplus) || defined(c_plusplus)
01351 
01352    if ( (theVisual->c_class != PseudoColor) &&
01353         (theVisual->c_class != TrueColor) &&
01354         (theVisual->c_class != DirectColor) )
01355       FatalError("This program requires PseudoColor or TrueColor or DirectColor modes only. AJ");
01356 
01357    if ( theVisual->c_class != PseudoColor ) AJ_PseudoColor = 0;
01358 #else
01359 
01360    if ( (theVisual->class != PseudoColor) &&
01361         (theVisual->class != TrueColor) &&
01362         (theVisual->class != DirectColor) )
01363       FatalError("This program requires PseudoColor or TrueColor or DirectColor modes only. AJ");
01364 
01365    if ( theVisual->class != PseudoColor ) AJ_PseudoColor = 0;
01366 #endif
01367 
01368    if (!(XAllocNamedColor(theDisp, CMap, "black", &any_col, &rgb_col)))
01369       FatalError ("XAllocNamedColor problem. AJ");
01370    fcol = any_col.pixel;
01371 
01372    if (!(XAllocNamedColor(theDisp, CMap, "grey35", &any_col, &rgb_col)))
01373       FatalError ("XAllocNamedColor problem. AJ");
01374    bcol = any_col.pixel;
01375 
01376    if ( AJ_PseudoColor ) {
01377       if (!(XAllocColorCells(theDisp, CMap, True, plane_masks, nplmsk,
01378          pixels, ucolors))) FatalError ("XAllocColorCells problem. AJ");
01379    }
01380    else {
01381       if ( (AJ_init_RGB()) )
01382          FatalError ("AJ_init_RGB problem. AJ");;
01383       AJ_make_STDcol(Solid_color, NUM_STD_COLORS);
01384    }
01385 
01386    colmap_init();                              /* Initialize color map */
01387 
01388 
01389 #ifdef USE_MCW
01390    mcw_load() ;
01391    for( i=0 ; i < IM_ARR ; i++ ) tmp_ar[i] = mcw_im[i] ;
01392    SIZE_tmp_ar( IM_HEIGHT ) ;
01393 #else
01394          /* Create theImage from ar[] #1. Do NOT use here Put_image() ! AJ */
01395    nowim = SAR(0) ;
01396    for (i=0; i < ar_size; i++)                   /* renormalize data */
01397       tmp_ar[i] = (int)((float)(nowim[i]-min1)*coef1 + .5);
01398    SIZE_tmp_ar( allim[0]->nx ) ;
01399 #endif
01400 
01401    Resample(im_tmp_ar);
01402 
01403 #if 0
01404    if( RWC_do_overfim ){
01405       short dont_overlay ;
01406       dont_overlay = fr_index ;
01407 
01408       RWC_setup_fims( 0 ) ;  /* 0 => don't use Put_image in routine */
01409 #ifdef OV_DEBUG1
01410    fprintf(stderr,"overlaying image #0\n") ; fflush(stderr) ;
01411 #endif
01412       RWC_short_overlay( IM_HEIGHT,IM_HEIGHT, imx , RWC_nxim,RWC_nyim ,
01413                          RWC_OVFLAG,dont_overlay , RWC_checker, RWC_imover ) ;
01414    }
01415 #endif
01416 
01417    theImage = Load_Any_Arr(imx,IM_HEIGHT,IM_HEIGHT);
01418 
01419    theBelt  = Load_Any_Arr(belt_arr,BELT_W,IM_HEIGHT);
01420 
01421    eWIDE = theImage->width;  eHIGH = theImage->height;
01422    eW = theBelt->width;      eH = theBelt->height;
01423    aWIDE = eWIDE + eW;
01424 
01425    if (!(afinfo = XLoadQueryFont(theDisp, KFONT)))
01426       if (!(afinfo = XLoadQueryFont(theDisp, "fixed"))) {
01427          sprintf(strp, "Can't open %s or fixed fonts\n", KFONT);
01428          FatalError (strp);
01429       }
01430 
01431    mfont=afinfo->fid;
01432    XSetFont(theDisp,theGC,mfont);
01433    XSetForeground(theDisp,theGC,fcol);
01434    XSetBackground(theDisp,theGC,bcol);
01435 
01436    CreateMainWindow(geom, Argc, Argv);   /* Set theWindow properties */
01437 
01438    gcv.function = GXcopy;                /* Extra, Small Text Graphic Context */
01439    gcv.foreground = fcol;
01440    txtGC = XCreateGC(theDisp, theWindow, GCForeground|GCFunction, &gcv);
01441 
01442    /** load text font from one of the candidate list **/
01443 
01444    tfont = XGetDefault(theDisp, Xdef_Name , "TextFont");
01445    if( tfont != NULL ) tfont_hopefuls[0] = tfont ;
01446    else                tfont_hopefuls[0] = TFONT ;
01447    { int ifont ;
01448      for( ifont=0 ; tfont_hopefuls[ifont] != NULL ; ifont++ ){
01449         mfinfo = XLoadQueryFont(theDisp, tfont_hopefuls[ifont]) ;
01450         if( mfinfo != NULL ) break ;
01451      }
01452      if( mfinfo == NULL ){
01453          FatalError("Can't open any text font!\n") ;
01454      }
01455      tfont = tfont_hopefuls[ifont] ;
01456 STATUS(tfont) ;
01457    }
01458    mfont=mfinfo->fid;
01459    XSetFont(theDisp,txtGC,mfont);
01460    XSetForeground(theDisp,txtGC,fcol);
01461    XSetBackground(theDisp,txtGC,bcol);
01462 
01463    New_Cursor(theDisp, theWindow, XC_left_ptr, "red", "white"); /* cursor */
01464 
01465                                                   /* Adjust size before Show */
01466    MResize(&expImage,&eWIDE,&eHIGH,theImage,eWIDE,eHIGH);
01467    MResize(&expBelt,&eW,&eH,theBelt,eW,eH);
01468 
01469    XSelectInput(theDisp, theWindow, ExposureMask | KeyPressMask
01470            | ButtonPressMask | ButtonReleaseMask | StructureNotifyMask);
01471 
01472    XMapWindow(theDisp,theWindow);               /* Show theImage first time */
01473 
01474    while (1) {
01475       XNextEvent(theDisp, &first_event);        /* Wait for window on */
01476       switch (first_event.type) {
01477          case Expose: {
01478            XExposeEvent *e = (XExposeEvent *) &first_event;
01479            if (e->window == theWindow) {
01480             XPutImage(theDisp, theWindow, theGC, expImage,
01481                       e->x, e->y, e->x, e->y, e->width, e->height);
01482             XPutImage(theDisp, theWindow, theGC, expBelt,
01483                       0, 0, eHIGH, 0, eW, eH);
01484              Allow_smaller_im(Argc, Argv);
01485          }
01486 #ifdef USE_MCW
01487    sleep(1) ;    /* show the logo for a second! */
01488 #endif
01489          return 0;
01490        }
01491 
01492          case KeyPress:
01493          case ButtonPress:
01494          case ButtonRelease:
01495          case ConfigureNotify:
01496          case CirculateNotify:
01497          case MapNotify:
01498          case DestroyNotify:
01499          case GravityNotify:
01500          case ReparentNotify:
01501          case UnmapNotify:
01502          break;
01503 
01504          default:                /* ignore unexpected events */
01505          break;
01506       }
01507    }
01508 }        /* end of main_FD_EPI() */
01509 
01510 /* ----------------------- */
01511    void x_events_loop()
01512 /* ----------------------- */
01513 {
01514    register int i, n, m;
01515 
01516    for (i=LAST_K; i<N_KEYS; i++) XUnmapWindow(theDisp,  key[i].wid);
01517    back_to_main = 0;
01518    while (1) {
01519      if (repeat_status) {       /* For repeated action when button pressed */
01520        if (XCheckWindowEvent(theDisp, theWindow, ButtonReleaseMask, &w_event))
01521          event = w_event;
01522      }
01523      else {
01524        XNextEvent(theDisp, &event);  /* single event loop */
01525      }
01526      HandleEvent(&event);
01527      if(back_to_main) return;
01528    }
01529 }
01530 
01531 int C_count = -1;
01532 /* ------------------ */
01533    HandleEvent(event)
01534    XEvent *event;
01535 /* ------------------ */
01536 {
01537    Window wind;
01538 
01539  switch (event->type) {
01540 
01541    case Expose: {
01542       XExposeEvent *e = (XExposeEvent *) event;
01543 STATUS("-Expose event") ;
01544       wind = e->window;
01545       if (wind == theWindow) {
01546          XPutImage(theDisp, theWindow, theGC, expImage,
01547                    e->x, e->y, e->x, e->y, e->width, e->height);
01548          XPutImage(theDisp, theWindow, theGC, expBelt,
01549                    0, 0, eHIGH, 0, eW, eH);
01550       }
01551       else if (wind == subWindow) {
01552          DrawSubWindow();
01553       }
01554       else if (wind == topWindow) {
01555          DrawTopWindow();
01556       }
01557       else {
01558          int  i;
01559          for (i=0; i < N_KEYS; i++)
01560             if (key[i].wid==wind) DrawKey(i);
01561          }
01562       }
01563        break;
01564 
01565    case KeyPress: {
01566       XKeyEvent *key_event = (XKeyEvent *) event;
01567       char      buf[128];
01568       int       i;
01569       KeySym    ks;
01570       XComposeStatus status;
01571 
01572 STATUS("-KeyPress event") ;
01573       buf[0] = 0;
01574       XLookupString(key_event, buf, 128, &ks, &status);
01575       if (buf[0]=='q' || buf[0]=='Q'){
01576 #ifdef USE_MCW
01577          XRaiseWindow(theDisp,theWindow) ;
01578          Put_image(-1) ;
01579          sleep(1) ;
01580 #endif
01581          if( use_pixmap ) XFreePixmap( theDisp , pxWind ) ;
01582          XCloseDisplay( theDisp ) ;
01583          exit(0);
01584       }
01585       if ( (I_lck == 0) && (buf[0]=='I') ) {    /* init image number */
01586          I_lck = 1;
01587          New_Cursor(theDisp, theWindow, XC_hand2, "red", "white");
01588          New_Cursor(theDisp,   GWindow, XC_hand2, "yellow", "red");
01589          break;
01590       }
01591       if ( (N_lck == 0) && (buf[0]=='N') ) {  /* init grid resol. number */
01592          N_lck = 1;
01593          old_grid = mat;
01594          New_Cursor(theDisp, theWindow, XC_hand2, "red", "white");
01595          New_Cursor(theDisp,   GWindow, XC_hand2, "yellow", "red");
01596          break;
01597       }
01598 
01599       /* Arrows keys for edit YYY */
01600       if ( FT1_pressed ) {
01601          if ( ks == XK_Right ) {
01602             int i_tmp = Im_Nr;
01603 
01604             if ( Im_Nr < (npoints - 1) ) Im_Nr += 1;
01605             if ( i_tmp != Im_Nr ) {
01606                XClearWindow(theDisp, GWindow);
01607                Put_image(Im_Nr);
01608                DrawSubWindow();
01609                DrawTopWindow();
01610                discard(KeyPressMask, event);
01611             }
01612             break;
01613          }
01614          else if ( ks == XK_Left ) {
01615             int min_im = 0, i_tmp = Im_Nr;
01616 
01617             if(Im_Nr > min_im) Im_Nr -= 1;
01618             if ( i_tmp != Im_Nr ) {
01619                XClearWindow(theDisp, GWindow);
01620                Put_image(Im_Nr);
01621                DrawSubWindow();
01622                DrawTopWindow();
01623                discard(KeyPressMask, event);
01624             }
01625             break;
01626          }
01627          else if ( ks == XK_Up ) {
01628             int   i, j, k, nn;
01629             float f0 = fft_mag, f1, f2, f3, fff = 1.1;
01630 
01631             if ( key_event->state & ShiftMask )   fff = 1.5;
01632             if ( key_event->state & ControlMask ) fff = 2.3;
01633             nn = act_undo + 1;
01634             act_undo += ar_size;
01635             undo_buf = AFREALL(undo_buf, struct _undo_buf,
01636                               (act_undo+1)*sizeof(struct _undo_buf) ); 
01637             if ( undo_buf != NULL ) {
01638                for ( i=0, j=nn; i < ar_size; j++, i++) {
01639                   undo_buf[j].im  = Im_Nr;
01640                   undo_buf[j].pix = i;
01641                   undo_buf[j].r   = c_arr[i*FT_dim+Im_Nr+1].r;
01642                   undo_buf[j].i   = c_arr[i*FT_dim+Im_Nr+1].i;
01643                   undo_buf[j].r2  = c_arr[(i+1)*FT_dim-Im_Nr-1].r;
01644                   undo_buf[j].i2  = c_arr[(i+1)*FT_dim-Im_Nr-1].i;
01645                   f1 = c_arr[i*FT_dim+Im_Nr+1].r *= fff;
01646                   f2 = c_arr[i*FT_dim+Im_Nr+1].i *= fff;
01647                   c_arr[(i+1)*FT_dim-Im_Nr-1].r  *= fff;
01648                   c_arr[(i+1)*FT_dim-Im_Nr-1].i  *= fff;
01649 
01650                   f3 = f0 * sqrt(f1*f1 + f2*f2);
01651                   if ( f3 > 32767. ) f3 = 32767.;
01652                   SAR(Im_Nr)[i] = f3;
01653                }
01654                redraw_graph() ;
01655                DrawSubWindow();
01656             }
01657             else {
01658                act_undo = -1;
01659                fprintf(stderr,"\n*** cannot realloc undo_buf\a\n") ;
01660                XBell(theDisp, 100);
01661             }
01662 
01663             if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
01664                ref_undo += 1;
01665                undo_ref = AFREALL(undo_ref, struct _undo_buf,
01666                                  (ref_undo+1)*sizeof(struct _undo_buf) ); 
01667                if ( undo_ref != NULL ) {
01668                   j = ref_undo;
01669                   undo_ref[j].im  = Im_Nr;
01670                   undo_ref[j].r   = r_arr[Im_Nr+1].r;
01671                   undo_ref[j].i   = r_arr[Im_Nr+1].i;
01672                   undo_ref[j].r2  = r_arr[FT_dim-Im_Nr-1].r;
01673                   undo_ref[j].i2  = r_arr[FT_dim-Im_Nr-1].i;
01674                   f1 = r_arr[Im_Nr+1].r   *= fff;
01675                   f2 = r_arr[Im_Nr+1].i   *= fff;
01676                   r_arr[FT_dim-Im_Nr-1].r *= fff;
01677                   r_arr[FT_dim-Im_Nr-1].i *= fff;
01678                   f3 = f0 * sqrt(f1*f1 + f2*f2);
01679                   if ( f3 > 32767. ) f3 = 32767.;
01680                   RWC_ideal->ts[Im_Nr] = f3;
01681                   redraw_graph() ;
01682                   DrawSubWindow();
01683                }
01684             }
01685             else {
01686                ref_undo = -1;
01687                fprintf(stderr,"\n*** cannot realloc undo_ref\a\n") ;
01688                XBell(theDisp, 100);
01689             }
01690             discard(KeyPressMask, event);
01691             break;
01692          }
01693          else if ( ks == XK_Down ) {
01694             int   i, j, k, nn;
01695             float f0 = fft_mag, f1, f2, f3, fff = 1./1.1;
01696 
01697             if ( key_event->state & ShiftMask )   fff = 1./1.5;
01698             if ( key_event->state & ControlMask ) fff = 1./2.3;
01699             nn = act_undo + 1;
01700             act_undo += ar_size;
01701             undo_buf = AFREALL(undo_buf, struct _undo_buf,
01702                               (act_undo+1)*sizeof(struct _undo_buf) ); 
01703             if ( undo_buf != NULL ) {
01704                for ( i=0, j=nn; i < ar_size; j++, i++) {
01705                   undo_buf[j].im  = Im_Nr;
01706                   undo_buf[j].pix = i;
01707                   undo_buf[j].r   = c_arr[i*FT_dim+Im_Nr+1].r;
01708                   undo_buf[j].i   = c_arr[i*FT_dim+Im_Nr+1].i;
01709                   undo_buf[j].r2  = c_arr[(i+1)*FT_dim-Im_Nr-1].r;
01710                   undo_buf[j].i2  = c_arr[(i+1)*FT_dim-Im_Nr-1].i;
01711                   f1 = c_arr[i*FT_dim+Im_Nr+1].r *= fff;
01712                   f2 = c_arr[i*FT_dim+Im_Nr+1].i *= fff;
01713                   c_arr[(i+1)*FT_dim-Im_Nr-1].r  *= fff;
01714                   c_arr[(i+1)*FT_dim-Im_Nr-1].i  *= fff;
01715 
01716                   f3 = f0 * sqrt(f1*f1 + f2*f2);
01717                   if ( f3 > 32767. ) f3 = 32767.;
01718                   SAR(Im_Nr)[i] = f3;
01719                }
01720                redraw_graph() ;
01721                DrawSubWindow();
01722             }
01723             else {
01724                act_undo = -1;
01725                fprintf(stderr,"\n*** cannot realloc undo_buf\a\n") ;
01726                XBell(theDisp, 100);
01727             }
01728 
01729             if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
01730                ref_undo += 1;
01731                undo_ref = AFREALL(undo_ref, struct _undo_buf,
01732                               (ref_undo+1)*sizeof(struct _undo_buf) ); 
01733                if ( undo_ref != NULL ) {
01734                   j = ref_undo;
01735                   undo_ref[j].im  = Im_Nr;
01736                   undo_ref[j].r   = r_arr[Im_Nr+1].r;
01737                   undo_ref[j].i   = r_arr[Im_Nr+1].i;
01738                   undo_ref[j].r2  = r_arr[FT_dim-Im_Nr-1].r;
01739                   undo_ref[j].i2  = r_arr[FT_dim-Im_Nr-1].i;
01740                   f1 = r_arr[Im_Nr+1].r   *= fff;
01741                   f2 = r_arr[Im_Nr+1].i   *= fff;
01742                   r_arr[FT_dim-Im_Nr-1].r *= fff;
01743                   r_arr[FT_dim-Im_Nr-1].i *= fff;
01744                   f3 = f0 * sqrt(f1*f1 + f2*f2);
01745                   if ( f3 > 32767. ) f3 = 32767.;
01746                   RWC_ideal->ts[Im_Nr] = f3;
01747                   redraw_graph() ;
01748                   DrawSubWindow();
01749                }
01750             }
01751             else {
01752                ref_undo = -1;
01753                fprintf(stderr,"\n*** cannot realloc undo_ref\a\n") ;
01754                XBell(theDisp, 100);
01755             }
01756  
01757             discard(KeyPressMask, event);
01758             break;
01759          }
01760          else if ( buf[0]=='u' ) {
01761             if ( ref_undo > -1 ) {
01762                int   i, j, k;
01763                float f0 = fft_mag, f1, f2, f3;
01764                if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
01765                   j = ref_undo;
01766                   k = undo_ref[j].im;
01767                   f1 = r_arr[k+1].r = undo_ref[j].r;
01768                   f2 = r_arr[k+1].i = undo_ref[j].i;
01769                   r_arr[FT_dim-k-1].r = undo_ref[j].r2;
01770                   r_arr[FT_dim-k-1].i = undo_ref[j].i2;
01771                   f3 = f0 * sqrt(f1*f1 + f2*f2);
01772                   if ( f3 > 32767. ) f3 = 32767.;
01773                   RWC_ideal->ts[k] = f3;
01774                   ref_undo -= 1;
01775                   undo_ref = AFREALL(undo_ref, struct _undo_buf,
01776                               (ref_undo+1)*sizeof(struct _undo_buf) ); 
01777                   if ( undo_ref == NULL ) {
01778                      ref_undo = -1;
01779                      fprintf(stderr, "\n*** cannot realloc undo_ref\a\n") ;
01780                      XBell(theDisp, 100);
01781                   }
01782                }
01783             }
01784             if ( act_undo > -1 ) {
01785                int   i, j, k;
01786                float f0 = fft_mag, f1, f2, f3;
01787                for ( i=0, j = act_undo; i < ar_size; i++, j--) {
01788                   Im_Nr = undo_buf[j].im;
01789                   k = undo_buf[j].pix;
01790                   f1 = c_arr[k*FT_dim+Im_Nr+1].r = undo_buf[j].r;
01791                   f2 = c_arr[k*FT_dim+Im_Nr+1].i = undo_buf[j].i;
01792                   c_arr[(k+1)*FT_dim-Im_Nr-1].r  = undo_buf[j].r2;
01793                   c_arr[(k+1)*FT_dim-Im_Nr-1].i  = undo_buf[j].i2;
01794                   f3 = f0 * sqrt(f1*f1 + f2*f2);
01795                   if ( f3 > 32767. ) f3 = 32767.;
01796                   SAR(Im_Nr)[k] = f3;
01797                }
01798 
01799                act_undo -= ar_size;
01800                undo_buf = AFREALL(undo_buf, struct _undo_buf,
01801                               (act_undo+1)*sizeof(struct _undo_buf) ); 
01802 
01803                if ( undo_buf != NULL ) {
01804                   redraw_graph() ;
01805                   DrawSubWindow();
01806  
01807                }
01808                else {
01809                   act_undo = -1;
01810                   fprintf(stderr,
01811                           "\n*** cannot realloc undo_buf or undo_ref\a\n") ;
01812                   XBell(theDisp, 100);
01813                }
01814             } 
01815 
01816             discard(KeyPressMask, event);
01817             break;
01818          }
01819          else if ( buf[0]=='U' ) {
01820             int   i, j, k;
01821             float f0 = fft_mag, f1, f2, f3;
01822             for (j=act_undo; j >= 0; j--) {
01823                Im_Nr = undo_buf[j].im;
01824                k = undo_buf[j].pix;
01825                f1 = c_arr[k*FT_dim+Im_Nr+1].r = undo_buf[j].r;
01826                f2 = c_arr[k*FT_dim+Im_Nr+1].i = undo_buf[j].i;
01827                c_arr[(k+1)*FT_dim-Im_Nr-1].r  = undo_buf[j].r2;
01828                c_arr[(k+1)*FT_dim-Im_Nr-1].i  = undo_buf[j].i2;
01829                f3 = f0 * sqrt(f1*f1 + f2*f2);
01830                if ( f3 > 32767. ) f3 = 32767.;
01831                SAR(Im_Nr)[k] = f3;
01832             }
01833             if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
01834                for (j=ref_undo; j >= 0; j--) {
01835                   k = undo_ref[j].im;
01836                   f1 = r_arr[k+1].r = undo_ref[j].r;
01837                   f2 = r_arr[k+1].i = undo_ref[j].i;
01838                   r_arr[FT_dim-k-1].r  = undo_ref[j].r2;
01839                   r_arr[FT_dim-k-1].i  = undo_ref[j].i2;
01840                   f3 = f0 * sqrt(f1*f1 + f2*f2);
01841                   if ( f3 > 32767. ) f3 = 32767.;
01842                   RWC_ideal->ts[k] = f3;
01843                }
01844                free(undo_ref);
01845                ref_undo = -1;
01846             }
01847             free(undo_buf);
01848             act_undo = -1;
01849             redraw_graph();
01850             DrawSubWindow();
01851             discard(KeyPressMask, event);
01852             break;
01853          }
01854       }
01855 
01856       if ( (I_lck == 1) && (buf[0] == 13) ) { /* make image number */
01857          if ( tmp_Nr >= 0 ) {
01858             int aaa = avr_grp, ddd = diff_im;
01859 
01860             if ( tmp_Nr > 0 ) Im_Nr = min(N_im - 1, tmp_Nr - 1);
01861             New_Cursor(theDisp, theWindow, XC_left_ptr, "red", "white");
01862             New_Cursor(theDisp,   GWindow, XC_left_ptr, "blue", "yellow");
01863             XClearWindow(theDisp, GWindow);
01864             diff_im = fim_dif;
01865             avr_grp = fim_avr;
01866             if ( Im_Nr >= npoints ) {
01867                avr_grp = 0;
01868                diff_im = 0;
01869             }
01870             else
01871                if ( Im_Nr > npoints - Av_length )
01872                   Im_Nr = npoints - Av_length;
01873             redraw =  avr_grp * 4 + (aaa - avr_grp) *2 + ddd - diff_im;
01874             Put_image(Im_Nr);
01875             if ( redraw ) redraw_graph();
01876             DrawSubWindow();
01877             DrawTopWindow();
01878             I_lck = 0;
01879             tmp_Nr = 0;
01880          }
01881          break;
01882       }
01883       if ( (N_lck == 1) && (buf[0] == 13) ) { /* make grid resol. number */
01884          if ( tmp_Nr >= 0 ) {
01885             if ( tmp_Nr > 0 ) mat = min(MAT_MAX, tmp_Nr);
01886             New_Cursor(theDisp, theWindow, XC_left_ptr, "red", "white");
01887             New_Cursor(theDisp,   GWindow, XC_left_ptr, "blue", "yellow");
01888             if (mat != old_grid) {
01889                init_mat();
01890                redraw_graph();
01891             }
01892             RWC_framehide = 0 ;
01893             Put_image(Im_Nr);
01894             DrawSubWindow();
01895             N_lck = 0;
01896             tmp_Nr = 0;
01897          }
01898          break;
01899       }
01900       if ( (I_lck == 1) || (N_lck == 1) ) {   /* make a number from digits */
01901          if ( isdigit(buf[0]) ) {
01902             i = buf[0] - 48;
01903             tmp_Nr = min(10000, 10*tmp_Nr + i);
01904          }
01905          break;
01906       }
01907       else {
01908          switch (buf[0]) {
01909             /* make time course array of the sum of several pixels */
01910             case 'a': {   
01911                int i, index;
01912                if ( FT_graph_on ) {
01913                   if ( avr_A == NULL ) {
01914                      avr_A = (float *) malloc(t_points*sizeof(float));
01915                      if( avr_A == NULL ){
01916                         fprintf(stderr,"\n*** cannot malloc avr_A\a\n") ;
01917                         XBell(theDisp, 100); break;
01918                      }
01919                      else {
01920                         for (i=0; i < t_points; i++) avr_A[i] = 0.;
01921                      }
01922                      avr_nr = 0;
01923                   }
01924                   index = ypoint*im_size+xpoint;
01925                   for (i=0; i < t_points; i++) 
01926                      avr_A[i] += (float) T_SAR(i)[index];
01927                   avr_nr++;
01928                }
01929                discard(KeyPressMask, event);
01930                break ;
01931             }
01932             case 'e': {  /* average to the last pixel */
01933                int i, index = ar_size - 1;
01934                float f0;
01935                if ( FT_graph_on && (avr_A != NULL) ) {
01936                   if ( avr_nr > 0 ) {
01937                      f0 = 1. / (float) avr_nr;
01938                      for (i=0; i < t_points; i++) {
01939                         T_SAR(i)[index-allim[0]->nx] =
01940                         T_SAR(i)[index] = f0 * avr_A[i];
01941                      }
01942 printf(" t_points = %d, avr_nr = %d\n", t_points, avr_nr);
01943                      free(avr_A);
01944                      avr_nr = 0;
01945                      cancell_FT = 1;
01946                   }
01947                }
01948                discard(KeyPressMask, event);
01949                break ;
01950             }
01951             case '~': {
01952                save_all_images();
01953                break;
01954             }
01955             case '^': {
01956                New_Cursor(theDisp, theWindow, XC_left_ptr, "red", "white");
01957                break;
01958             }
01959             case 's': {
01960                c_swap();
01961                break;
01962             }
01963             case 'S': {
01964                save_act_im();
01965                discard(KeyPressMask, event);
01966                break;
01967             }
01968             case 'X': {          /* AAJ tmp to save average array as is */
01969                save_avr_array();
01970                discard(KeyPressMask, event);
01971                break;
01972             }
01973             case 'f': {
01974                if ( FT_graph_on ) get_fft_mag(&fft_mag);
01975                discard(KeyPressMask, event);
01976                break ;
01977             }
01978             case 'F': {
01979                read_new_im() ;
01980                discard(KeyPressMask, event);
01981                break ;
01982             }
01983             case 'K': {
01984                kill_curr_im() ;
01985                discard(KeyPressMask, event);
01986                break ;
01987             }
01988             case 'A': {
01989                RWC_autoscale = ! RWC_autoscale ;
01990                old_im = -1 ;
01991                Put_image( Im_Nr ) ;
01992                discard(KeyPressMask, event);
01993                break ;
01994             }
01995             case 'h': {
01996                RWC_framehide = ! RWC_framehide ;
01997                Put_image( Im_Nr ) ;
01998                break ;
01999             }
02000             case 'H': {
02001                RWC_overhide = ! RWC_overhide ;
02002                Put_image( Im_Nr ) ;
02003                break ;
02004             }
02005             case 'O': {
02006                RWC_checker  = ! RWC_checker ;
02007                RWC_overhide = 0 ;
02008                Put_image( Im_Nr ) ;
02009                break ;
02010             }
02011             case 'C': {
02012                YES_color = 1;
02013                colmap_init();
02014                break;
02015             }
02016             case 'B': {
02017                YES_color = 0;
02018                colmap_init();
02019                break;
02020             }
02021 #ifdef USE_MCW
02022             case '0': {
02023                Put_image(-1) ;
02024                sleep(1) ;
02025                Put_image(Im_Nr) ;
02026                discard(KeyPressMask, event);
02027                break ;
02028             }
02029 #endif
02030             case '1':   /* move to image with this number */
02031             case '2':
02032             case '3':
02033             case '4':
02034             case '5':
02035             case '6':
02036             case '7':
02037             case '8':
02038             case '9': {
02039                int aaa = avr_grp, ddd = diff_im , itmp;
02040 
02041                itmp = buf[0] - '1' ; if( itmp >= N_im ) itmp = N_im - 1 ;
02042 
02043                if( itmp >= npoints ) {   /* past time course => no averaging, etc */
02044                   avr_grp = 0;
02045                   diff_im = 0;
02046                }
02047                else {
02048                   diff_im = fim_dif;
02049                   avr_grp = fim_avr;
02050                   if( itmp > npoints-Av_length ) itmp = npoints - Av_length;
02051                }
02052                if( itmp != Im_Nr ){
02053                   Im_Nr = itmp ;
02054                   redraw =  avr_grp * 4 + (aaa - avr_grp) *2 + ddd - diff_im;
02055 
02056                   XClearWindow(theDisp, GWindow);
02057                   Put_image(Im_Nr);
02058                   if ( redraw ) redraw_graph();
02059                   DrawSubWindow();
02060                   DrawTopWindow();
02061                }
02062                discard(KeyPressMask, event);
02063                break;
02064             }
02065             case 'L':
02066             case 'l': {
02067                int max_im ;
02068                int aaa = avr_grp, ddd = diff_im;
02069 
02070                if( buf[0] == 'L' ) max_im = npoints - 1 ;
02071                else                max_im = N_im - 1 ;
02072 
02073                if ( max_im >= npoints ) {
02074                   avr_grp = 0;
02075                   diff_im = 0;
02076                }
02077                else {
02078                   diff_im = fim_dif;
02079                   avr_grp = fim_avr;
02080                   max_im = npoints - Av_length;
02081                }
02082                redraw =  avr_grp * 4 + (aaa - avr_grp) *2 + ddd - diff_im;
02083                Im_Nr = max_im;
02084                XClearWindow(theDisp, GWindow);
02085                Put_image(Im_Nr);
02086                if ( redraw ) redraw_graph();
02087                DrawSubWindow();
02088                DrawTopWindow();
02089                discard(KeyPressMask, event);
02090                break;
02091             }
02092             case '>': {
02093                int max_im, i_tmp = Im_Nr;
02094                int aaa = avr_grp, ddd = diff_im;
02095 
02096                max_im = npoints - Av_length;
02097 
02098                if ( Im_Nr >= npoints ) {
02099                   if ( Im_Nr < (N_im - 1) ) Im_Nr += 1;
02100                }
02101                else if ( Im_Nr < max_im ) Im_Nr += 1;
02102                else if ( npoints < N_im ) {
02103                   avr_grp = 0;
02104                   diff_im = 0;
02105                   Im_Nr = npoints;
02106                }
02107                if ( i_tmp != Im_Nr ) {
02108                   redraw =  avr_grp * 4 + (aaa - avr_grp) *2 + ddd - diff_im;
02109                   XClearWindow(theDisp, GWindow);
02110                   Put_image(Im_Nr);
02111                   if ( redraw ) redraw_graph();
02112                   DrawSubWindow();
02113                   DrawTopWindow();
02114                   discard(KeyPressMask, event);
02115                }
02116                break;
02117             }
02118             case '<': {
02119                int min_im = 0, i_tmp = Im_Nr;
02120                int aaa = avr_grp, ddd = diff_im;
02121 
02122 #ifdef USE_MCW
02123                if( Im_Nr == 0 ){
02124                   Put_image(-1) ;
02125                   sleep(1) ;
02126                   Put_image(0) ;
02127                   discard(KeyPressMask, event);
02128                   break ;
02129                }
02130 #endif
02131 
02132                if ( Im_Nr > npoints ) Im_Nr -= 1;
02133                else {
02134                   diff_im = fim_dif;
02135                   avr_grp = fim_avr;
02136                   if(Im_Nr > min_im) Im_Nr -= 1;
02137                   if ( avr_grp )
02138                      if ( Im_Nr > (npoints - Av_length) )
02139                         Im_Nr = npoints - Av_length;
02140                }
02141                if ( i_tmp != Im_Nr ) {
02142                   redraw =  avr_grp * 4 + (aaa - avr_grp) *2 + ddd - diff_im;
02143                   XClearWindow(theDisp, GWindow);
02144                   Put_image(Im_Nr);
02145                   if ( redraw ) redraw_graph();
02146                   DrawSubWindow();
02147                   DrawTopWindow();
02148                   discard(KeyPressMask, event);
02149                }
02150                break;
02151             }
02152                    /* + and - keys used for adjusting scale */
02153             case '-': {
02154                scale_down();
02155                redraw_graph();
02156                DrawSubWindow();
02157                break;
02158             }
02159             case '+': {
02160                scale_up();
02161                redraw_graph();
02162                DrawSubWindow();
02163                break;
02164             }
02165             case 'b': {
02166                RWC_groupbase = ! RWC_groupbase ;
02167                redraw_graph();
02168                DrawSubWindow();
02169                break;
02170             }
02171             case 'x': {
02172                AJ_base = ! AJ_base;
02173                redraw_graph();
02174                DrawSubWindow(); 
02175                break; } /* p used to write plot to file */ case 'w': case 'p': {
02176                int ask_file = (buf[0] == 'p') ;
02177 
02178                print_plot(ask_file);
02179                discard(KeyPressMask, event);
02180                break;
02181             }
02182                    /* m and M keys used for adjusting matrix */
02183             case 'm': {
02184                mat_down();
02185                discard(KeyPressMask, event);
02186                break;
02187             }
02188             case 'M': {
02189                mat_up();
02190                discard(KeyPressMask, event);
02191                break;
02192             }
02193                    /* g and G keys used for adjusting grid lines */
02194             case 'g': {
02195                grid_down();
02196                discard(KeyPressMask, event);
02197                break;
02198             }
02199             case 'G': {
02200                grid_up();
02201                discard(KeyPressMask, event);
02202                break;
02203             }
02204             case 'r': {
02205                color_index++;
02206                if (color_index >= COL_NUM) color_index = -1;
02207                if (color_index < 1) mark = 1 - mark;
02208                redraw_graph();
02209                DrawSubWindow();
02210                discard(KeyPressMask, event);
02211                break;
02212             }
02213             case 'R': {
02214                fr_index--;
02215                if (fr_index < -16){
02216                   fr_index = -1;
02217 #ifdef USE_MCW
02218                   Put_image(-1) ;
02219 #endif
02220                }
02221                RWC_framehide = 0 ;
02222                Put_image(Im_Nr);
02223                discard(KeyPressMask, event);
02224                break;
02225             }
02226             case 'd': {
02227                int xx, index = ypoint*im_size+xpoint;
02228                xx = (int) (SAR(Im_Nr)[index]) - 3600;
02229                if ( xx > 32767 ) SAR(Im_Nr)[index] = 32767;
02230                else              SAR(Im_Nr)[index] = xx;
02231                redraw_graph() ;
02232                DrawSubWindow();
02233                old_im = -1;
02234                Put_image(Im_Nr);
02235                discard(KeyPressMask, event);
02236                break;
02237             }
02238             case 'D': {
02239                int xx, index = ypoint*im_size+xpoint;
02240                xx = (int) (SAR(Im_Nr)[index]) + 3600;
02241                if ( xx < -32768 ) SAR(Im_Nr)[index] = -32768;
02242                else               SAR(Im_Nr)[index] = xx;
02243                redraw_graph() ;
02244                DrawSubWindow();
02245                old_im = -1;
02246                Put_image(Im_Nr);
02247                discard(KeyPressMask, event);
02248                break;
02249             }
02250 
02251          }
02252       } /* end I_lck = 0 */
02253 
02254    }  /* end of KeyPress */
02255    break;
02256 
02257    case ButtonPress: {
02258       XButtonPressedEvent *b = (XButtonPressedEvent *) event;
02259       int delta = 1;
02260 
02261 STATUS("-ButtonPress event") ;
02262 
02263       wind = b->window;
02264       if (wind == theWindow ) {
02265 
02266          if (b->button == Button1 && repeat_status == 0) {
02267             if (b->x > eWIDE) break;
02268             B1_action = 1;
02269             Track_Cursor(b->x, b->y);
02270             discard(ButtonPressMask, event);
02271             break;
02272          }
02273 
02274          if ( b->button == Button2 ) {        /* contrast and brightness */
02275             repeat_status = 1;
02276             if ( C_count <= 0 ) {
02277                if (b->x <   eWIDE/3) {
02278                   c_squeeze( delta);
02279                }
02280                if ((b->x > 2*eWIDE/3) && (b->x < eWIDE)) {
02281                   c_squeeze(-delta);
02282                }
02283                if ((b->y <   eHIGH/3) && (b->x < eWIDE)) {
02284                   c_bright(-delta);
02285                }
02286                if ((b->y > 2*eHIGH/3) && (b->x < eWIDE)) {
02287                   c_bright( delta);
02288                }
02289                if ((b->y >   eHIGH/2) && (b->x > eWIDE) && (b->x < eWIDE+eW)) {
02290                   c_rotate(-delta);
02291                }
02292                if ((b->y <   eHIGH/2) && (b->x > eWIDE) && (b->x < eWIDE+eW)) {
02293                   c_rotate(delta);
02294                }
02295                if ( AJ_PseudoColor )
02296                   C_count = CONTRAST_CHANGE_STEP;
02297                else
02298                   C_count = 0;
02299                break;
02300             }
02301             if ( C_count > -1 ) C_count--;
02302          }
02303 
02304          if (b->button == Button3 && repeat_status == 0) {
02305             delta = 1;
02306             if (b->x <   eWIDE/3) {
02307                c_squeeze( delta); break;
02308             }
02309             if ((b->x > 2*eWIDE/3) && (b->x < eWIDE)) {
02310                c_squeeze(-delta); break;
02311             }
02312             if ((b->y <   eHIGH/3) && (b->x < eWIDE)) {
02313                c_bright(-delta); break;
02314             }
02315             if ((b->y > 2*eHIGH/3) && (b->x < eWIDE)) {
02316                c_bright( delta); break;
02317             }
02318             if ((b->y >   eHIGH/3) && (b->y < 2*eHIGH/3) &&
02319                 (b->x >   eWIDE/3) && (b->x < 2*eWIDE/3)) {
02320                if (YES_color) No_Color_init = 1;
02321                else           No_Grey_init  = 1;
02322                colmap_init(); break;
02323             }
02324             if ((b->y >   eHIGH/2) && (b->x > eWIDE) && (b->x < eWIDE + eW)) {
02325                c_rotate(-delta); break;
02326             }
02327             if ((b->y <   eHIGH/2) && (b->x > eWIDE) && (b->x < eWIDE + eW)) {
02328                c_rotate(delta); break;
02329             }
02330          }
02331       }   /* for theWindow */
02332       else if (wind == GWindow) {
02333          int i, j, kx , ky;
02334 
02335          if( (b->button == Button1) && (b->x > GL_DLX) ){
02336             kx = RWC_GX_MAX/mat;
02337             ky = RWC_GY_MAX/mat;
02338             i = (b->x - GL_DLX + kx)*mat/RWC_GX_MAX;
02339             j = (b->y - GT_DLY + ky)*mat/RWC_GY_MAX;
02340             xpoint += i - (mat + 2)/2;
02341             ypoint += j - (mat + 2)/2;
02342             if (xpoint < 0)        xpoint += im_size;
02343             if (xpoint >= im_size) xpoint -= im_size;
02344             if (ypoint < 0)        ypoint += im_size;
02345             if (ypoint >= im_size) ypoint -= im_size;
02346 
02347             if ( (xpoint == xpoint_0 ) && (ypoint == ypoint_0) ) ;
02348             else {
02349                RWC_framehide = 0 ;
02350                Put_image(Im_Nr);
02351                redraw_graph();
02352                DrawSubWindow();
02353                xpoint_0 = xpoint;
02354                ypoint_0 = ypoint;
02355             }
02356          }
02357          discard(ButtonPressMask, event);
02358          break;
02359       }   /* for GWindow */
02360       else if (wind == subWindow) {
02361          if (b->button == Button1) {
02362             if ( (abs(b->x - v_point_x) < 5 ) &&
02363                  (abs(b->y - v_point_y) < 9 ) ) {
02364                move_Vpointer = 1;
02365                Track_Vpointer();
02366             }
02367          }
02368       }   /* for subWindow */
02369 
02370       if ( (b->button == Button1) || (b->button == Button2)
02371                                   || (b->button == Button3) ) {
02372          int  i;
02373          if( invkey < 0 ){
02374             if      (b->button == Button1) rot_direct = -1;
02375             else if (b->button == Button2) rot_direct =  0;
02376             else if (b->button == Button3) rot_direct =  1;
02377             rot_state = b->state ;
02378             for (i=0; i < N_KEYS; i++) {
02379                if (key[i].wid==wind) { InvertKey(i); invkey=i; break; }
02380             }
02381          }
02382       }   /* for keys */
02383    }   /* end of ButtonPress */
02384    break;
02385 
02386    case ButtonRelease: {
02387       XButtonReleasedEvent *b = (XButtonReleasedEvent *) event;
02388 
02389 STATUS("-ButtonRelease event") ;
02390       wind = b->window;
02391 
02392       if (wind == theWindow ) {
02393          if (B1_action == 1) {
02394             B1_action = 0;
02395             xpoint = Mltx[b->x]/x_mag;
02396             ypoint = Mlty[b->y]/x_mag;
02397 
02398             if ( (xpoint == xpoint_0 ) && (ypoint == ypoint_0) ) ;
02399             else {
02400                RWC_framehide = 0 ;
02401                Put_image(Im_Nr);
02402                redraw_graph();
02403                DrawSubWindow();
02404                xpoint_0 = xpoint;
02405                ypoint_0 = ypoint;
02406             }
02407          }
02408          if (b->button == Button2) {
02409             repeat_status = 0;
02410          }
02411       }
02412       else if (wind == subWindow ) {
02413          discard_Key(wind, ButtonPressMask, event);
02414          discard_Key(wind, ButtonReleaseMask, event);
02415       }
02416       else if ( (b->button == Button1) || (b->button == Button2)
02417                                        || (b->button == Button3) ) {
02418          int i;
02419          if( invkey >= 0 ){
02420             for (i=0; i < N_KEYS; i++) {
02421                if (wind == key[i].wid) { LetGoKey(invkey); break; }
02422             }
02423             invkey = -1;
02424          }
02425          discard_Key(wind, ButtonPressMask, event);
02426          discard_Key(wind, ButtonReleaseMask, event);
02427       }
02428    }
02429    break;
02430 
02431    case ConfigureNotify: {
02432       XConfigureEvent *conf_event = (XConfigureEvent *) event;
02433       int wb;
02434 STATUS("-ConfigureNotify event") ;
02435       wb = conf_event->height*BELT_W/IM_HEIGHT;
02436       if ( (conf_event->window == theWindow) &&
02437            (conf_event->height != eHIGH)) {
02438             MResize(&expImage, &eWIDE, &eHIGH, theImage,
02439                   conf_event->height, conf_event->height);
02440             MResize(&expBelt, &eW, &eH, theBelt,
02441                   wb, conf_event->height);
02442       }
02443       else if ( (conf_event->window == GWindow) &&
02444            ((conf_event->height != iHIGH) || (conf_event->width != iWIDE)) ) {
02445          redo_graph_window(conf_event->width, conf_event->height);
02446       }
02447    }
02448    break;
02449 
02450    case CirculateNotify:
02451    case MapNotify:
02452    case DestroyNotify:
02453    case GravityNotify:
02454    case ReparentNotify:
02455    case UnmapNotify:
02456 STATUS("-Ignored event") ;
02457       break;
02458 
02459    default:      /* ignore unexpected events */
02460       break;
02461  }   /* end of switch event->type */
02462 }   /* end of HandleEvent() */
02463 
02464 /* It loads color strip made by make_belt() & adds unit color stips */
02465 /* ------------------------------------------------------------- */
02466    load_rect_str(idata, ipx, x, y, i1, x1, i2, x2, amin, nshade)
02467    short int idata[], ipx[];
02468    int       x, y, i1, i2, x1, x2, amin, nshade;
02469 /* ------------------------------------------------------------- */
02470 {
02471    register int i, ii, j, k;
02472    int          min0, max1;
02473    float        adel0, coef;
02474 
02475    min0 =  32767;
02476    max1 = -32768;
02477    ii = x*y;
02478    for (i=0; i < ii; i++) {
02479       if ( idata[i] < min0 ) min0 = idata[i];
02480       if ( idata[i] > max1 ) max1 = idata[i];
02481    }
02482    adel0 = max1 - min0;
02483 
02484    /* set image shades */
02485 
02486    if (adel0 < 1.) adel0 = 1.;
02487    coef = ( (float) nshade - 1. ) / adel0;
02488 
02489    k = x - i2;
02490    for (i=0; i < y; i++) {
02491       ii = i*x;
02492       for (j=0; j < i1; j++)
02493          ipx[ii+j] = -x1;
02494       for (j=x-i2; j < x; j++)
02495          ipx[ii+j] = -x2;
02496       for (j=i1; j < k; j++)
02497          ipx[ii+j] = (int) ( (float) (idata[ii+j] - min0) * coef + .5) + amin;
02498    }
02499 }
02500 
02501 /* ------------------- */       /* It makes data belt (ramp of indices) */
02502    make_belt(id, x, y)
02503    short int *id;
02504    int       x, y;
02505 /* ------------------- */
02506 {
02507    register int i, j, ii;
02508 
02509    for(i=0; i < y; i++) {
02510       ii = i*x;
02511       for(j=0; j < x; j++)
02512          id[ii+j] = x - i;
02513    }
02514 }
02515 
02516 /* ------------------------------ */ /* It resizes images universally  */
02517    MResize(emage,eW,eH,image,w,h)    /* for 12 and 8 bit planes. */
02518    int     w, h, *eW, *eH;
02519    XImage  *image,*(*emage);
02520 /* ------------------------------ */
02521 {
02522    int          lt[MAX_WIDTH];
02523    register int iy, ex, ey, iW, iH, iG, iN, w2, tmp;
02524    char         *ximag;
02525    char         *Ep, *El, *Ip, *Il, *Id;
02526 
02527 STATUS("ENTER MResize") ;
02528 
02529     iN = image->bits_per_pixel/8;    /* 1 or 2, pointer increment */
02530     iG = image->bytes_per_line;      /* Number of bytes in line */
02531     w2 = w * iN;
02532     iW = image->width;
02533     iH = image->height;
02534     if (w==iW && h==iH) {       /* very special case */
02535         if (*emage != image) {
02536             if (*emage) XDestroyImage(*emage);
02537             *emage = image;
02538             *eW = iW;  *eH = iH;
02539         }
02540     }
02541 
02542     else {                              /* have to do some work */
02543 
02544         /* first, kill the old emage, if one exists */
02545         if (*emage && *emage != image) {
02546            free((*emage)->data);  (*emage)->data = NULL;
02547            XDestroyImage(*emage);
02548         }
02549 
02550         /* create emage of the appropriate size */
02551 
02552         *eW = w;  *eH = h;
02553         ximag = (char *) malloc(w2 * h);
02554 
02555         *emage = XCreateImage(theDisp, theVisual, Planes, ZPixmap, 0, ximag,
02556                         w, h, 32, w2);
02557 
02558         if (!ximag || !*emage) {
02559            fprintf(stderr,"ERROR: unable to create a %dx%d image\a\n",w,h);
02560            exit(1);
02561         }
02562 
02563         El = Ep = (char *) (*emage)->data;
02564         Id = (char *) image->data;
02565 
02566         /* ---- Set look up table and Reframe fast ---- */
02567 
02568         for (ex = 0; ex < w; ex++)  {
02569             tmp = (iW * ex)/w;
02570             lt[ex] = iN * tmp;
02571             Mltx[ex] = tmp;
02572         }
02573 
02574         for (ey = 0; ey < h; ey++, El += w2) {
02575             iy = (iH * ey)/h;
02576             Mlty[ey] = iy;
02577             Ep = El;
02578             Il = Id + iG * iy;
02579             for(ex = 0; ex < w; ex++, Ep += iN) {
02580                 Ip = Il + lt[ex];
02581                 if ( iN == 1 ) {
02582                    *Ep = *Ip;
02583                 }
02584                 else if ( iN == 2) {
02585                    *Ep = *Ip;
02586                    *(Ep+1) = *(Ip+1);
02587                 }
02588                 else if ( iN == 3) {
02589                    *Ep = *Ip;
02590                    *(Ep+1) = *(Ip+1);
02591                    *(Ep+2) = *(Ip+2);
02592                 }
02593                 else if ( iN == 4) {
02594                    *Ep = *Ip;
02595                    *(Ep+1) = *(Ip+1);
02596                    *(Ep+2) = *(Ip+2);
02597                    *(Ep+3) = *(Ip+3);
02598                 }
02599             }
02600         }
02601     }
02602 }
02603 
02604 /* ---------------------------- */
02605    Allow_smaller_im(argc, argv)
02606    int  argc;
02607    char *argv[];
02608 /* ---------------------------- */
02609 {
02610    XSizeHints           hints;
02611 
02612 STATUS("ENTER Allow_smaller_im") ;
02613 
02614    hints.min_height = 0;
02615    hints.min_width = 0;
02616    hints.flags = PMinSize;
02617 
02618    hints.min_aspect.x = IM_HEIGHT + BELT_W;
02619    hints.max_aspect.x = IM_HEIGHT + BELT_W;
02620    hints.min_aspect.y = IM_HEIGHT;
02621    hints.max_aspect.y = IM_HEIGHT;
02622    hints.flags |= PAspect;
02623 
02624    hints.max_height = DisplayHeight(theDisp, theScreen);
02625    hints.max_width = hints.max_height *
02626                      (IM_HEIGHT + BELT_W)/IM_HEIGHT;
02627    hints.flags |= PMaxSize;
02628    XSetStandardProperties(theDisp, theWindow, T_name, T_name, None,
02629                           argv, argc, &hints);
02630 }
02631 
02632 /* ---------------------------------- */
02633    CreateMainWindow(geom, argc, argv)
02634    char *geom;
02635    int  argc;
02636    char *argv[];
02637 /* ---------------------------------- */
02638 {
02639    XClassHint           classKRH;
02640    XSetWindowAttributes attr;
02641    unsigned int         attrmask;
02642    XSizeHints           hints;
02643    int                  mask, x, y, w, h, i;
02644 
02645 STATUS("ENTER CreateMainWindow") ;
02646 
02647    x = y = w = h = 1;
02648    mask = XParseGeometry(geom, &x, &y, (unsigned int *)&w, (unsigned int *)&h);
02649 
02650    if (mask & HeightValue) {
02651      i = IM_HEIGHT + BELT_W;
02652      if ( i > MAX_WIDTH ) h = (MAX_WIDTH * IM_HEIGHT) / i;
02653      eH = eHIGH = h;
02654      eWIDE = eHIGH;
02655      eW = eH * BELT_W / IM_HEIGHT;
02656      aWIDE = eWIDE + eWIDE*BELT_W/IM_HEIGHT;
02657    }
02658 
02659    if (mask & XValue || mask & YValue) hints.flags = USPosition;
02660    else                                hints.flags = PPosition;
02661 
02662    hints.flags |= USSize;
02663 
02664    if (mask & XValue && mask & XNegative)
02665         x = XDisplayWidth(theDisp, theScreen)-eWIDE-abs(x);
02666    if (mask & YValue && mask & YNegative)
02667         y = XDisplayHeight(theDisp, theScreen)-eHIGH-abs(y);
02668 
02669    classKRH.res_name  = "ImageX";
02670    classKRH.res_class = "ImageX";
02671 
02672    hints.min_aspect.x = IM_HEIGHT + BELT_W;
02673    hints.max_aspect.x = IM_HEIGHT + BELT_W;
02674    hints.min_aspect.y = IM_HEIGHT;
02675    hints.max_aspect.y = IM_HEIGHT;
02676    hints.flags |= PAspect;
02677 
02678    hints.x = x;                 hints.y = y;
02679    hints.width = aWIDE;         hints.height = eHIGH;
02680    hints.max_width = aWIDE;     hints.max_height = eHIGH;
02681    hints.flags |= PMaxSize;
02682 
02683    hints.min_width = aWIDE;     hints.min_height = eHIGH;;
02684    hints.flags |= PMinSize;
02685 
02686    attr.background_pixel = bcol;
02687    attr.border_pixel     = fcol;
02688    attrmask = CWBackPixel | CWBorderPixel;
02689 
02690    theWindow = XCreateWindow(theDisp, rootW, x, y, aWIDE, eHIGH, 2,
02691       CopyFromParent, CopyFromParent, CopyFromParent, attrmask, &attr);
02692 
02693    if (!theWindow)
02694       FatalError("Can't open window (are X11 windows running ?). AJ");
02695 
02696    XSetClassHint(theDisp, theWindow, &classKRH);
02697    XSetStandardProperties(theDisp, theWindow, T_name, T_name, None,
02698                           argv, argc, &hints);
02699 }
02700 
02701 /* ----------------- */ /* Set color or grey array of the Image */
02702    colmap_init()
02703 /* ----------------- */
02704 {
02705    if (YES_color)  color_init(COL_MIN, spectrum);
02706    else            grey_init();
02707 }
02708 
02709 /* -------------------- */       /* Set grey array of the Image  */
02710    grey_init()
02711 /* -------------------- */
02712 {
02713    register int i, k, m;
02714    float a;
02715 
02716    a = 200./ncolors;
02717 
02718    if (No_Grey_init) {
02719       for (i=0; i < ncolors; i++) {
02720          k = 255.*pow((a*i+55.)/255., gamm) + .5;
02721          m = min_max_col(k << 8);
02722          INgrey[i] = m;
02723          MYgrey[i].pixel = pixels[i];
02724          MYgrey[i].red   = m;
02725          MYgrey[i].green = m;
02726          MYgrey[i].blue  = m;
02727          MYgrey[i].flags = DoRed|DoGreen|DoBlue;
02728       }
02729       No_Grey_init = 0;
02730    }
02731    if ( AJ_PseudoColor ) XStoreColors(theDisp, CMap, MYgrey, ncolors);
02732    else                AJ_StoreColors(theDisp, CMap, MYgrey, ncolors, 0);
02733 }
02734 
02735 /* ----------------- */ /* Set color array of the Image */
02736    color_init(a1,a2)    /* OK but sharp edge on green near yellow */
02737    int a1, a2;
02738 /* ----------------- */
02739 {
02740    double da, an, c, n, s, sb, cb, ak, ab;
02741    register int k, i, m, r, g, b;
02742 
02743    if (No_Color_init) {
02744       FIRST = 1;        SQUE_NR = ncolors;
02745       n = ncolors;
02746       ak = 105.; s = 150.; c = s/60.;
02747       ab = 65.; sb = 190.; cb = s/60.;
02748       m=256;
02749       an = a1;
02750       da = a2 - a1;     da = da/n;
02751       an = an-da+360.;
02752 
02753       for(i=0; i < ncolors; i++) {
02754         an += da;   an=fmod(an,360.);
02755         if((an >= 0) && (an < 120.)) {
02756           r = 255.*pow((ak + min(s,(120. - an)*c))/255., gamm) +.5;
02757           g = 255.*pow((ak + min(s,an*c))/255., gamm) +.5;
02758           b=0;
02759         }
02760         if((an >= 120.) && (an < 240.)) {
02761           r = 0;
02762           g = 255.*pow((ak + min(s ,(240. - an)*c))/255., gamm) +.5;
02763           b = 255.*pow((ab + min(sb,(an - 120.)*cb))/255., gamm) +.5;
02764         }
02765         if(an >= 240.) {
02766           r =  255.*pow((ak + min(s,(an - 240.)*c))/255., gamm) +.5;
02767           g = 0;
02768           b = 255.*pow((ak + min(s,(360. - an)*c))/255., gamm) +.5;
02769         }
02770         MYcol[i].pixel = pixels[ncolors-1-i];
02771         MYcol[i].red   = r*m;
02772         MYcol[i].green = g*m;
02773         MYcol[i].blue  = b*m;
02774         MYcol[i].flags = DoRed|DoGreen|DoBlue;
02775       }
02776       No_Color_init = 0;
02777    }
02778    if ( AJ_PseudoColor ) XStoreColors(theDisp, CMap, MYcol, ncolors);
02779    else                AJ_StoreColors(theDisp, CMap, MYcol, ncolors, 1);
02780 }
02781 
02782 /* --------------- */
02783    c_rotate(k)
02784    int k;
02785 /* --------------- */
02786 {
02787    if (YES_color) color_rotate(k);
02788    else           grey_rotate(-k);
02789 }
02790 
02791 
02792 /* --------------- */
02793    color_rotate(k)
02794    int k;
02795 /* --------------- */
02796 {
02797    register int i, j;
02798 
02799    FIRST = 1;
02800    SQUE_NR = ncolors;
02801 
02802 
02803    if(k >= 0) {
02804      for(i=0; i < k; i++) {
02805      tmp1[i] = MYcol[i].red;
02806      tmp2[i] = MYcol[i].green;
02807      tmp3[i] = MYcol[i].blue;
02808      }
02809      for(i=0; i < ncolors - k; i++) {
02810        MYcol[i].red   = MYcol[i+k].red;
02811        MYcol[i].green = MYcol[i+k].green;
02812        MYcol[i].blue  = MYcol[i+k].blue;
02813      }
02814      for(i = ncolors - k, j = 0; i < ncolors; i++, j++) {
02815        MYcol[i].red   = tmp1[j];
02816        MYcol[i].green = tmp2[j];
02817        MYcol[i].blue  = tmp3[j];
02818      }
02819    }
02820    else {
02821      k = -k;
02822      for(i = ncolors - 1; i >= ncolors - k; i--) {
02823      tmp1[i] = MYcol[i].red;
02824      tmp2[i] = MYcol[i].green;
02825      tmp3[i] = MYcol[i].blue;
02826      }
02827      for(i = ncolors - 1; i >= k; i--) {
02828        MYcol[i].red   = MYcol[i-k].red;
02829        MYcol[i].green = MYcol[i-k].green;
02830        MYcol[i].blue  = MYcol[i-k].blue;
02831      }
02832      for(i = k-1, j = ncolors - 1; i >=0; i--, j--) {
02833        MYcol[i].red   = tmp1[j];
02834        MYcol[i].green = tmp2[j];
02835        MYcol[i].blue  = tmp3[j];
02836      }
02837    }
02838    if ( AJ_PseudoColor ) XStoreColors(theDisp, CMap, MYcol, ncolors);
02839    else                AJ_StoreColors(theDisp, CMap, MYcol, ncolors, 1);
02840 }
02841 
02842 /* --------------- */
02843    grey_rotate(k)
02844    int k;
02845 /* --------------- */
02846 {
02847    register int i, j;
02848 
02849    FIRST = 1;
02850    SQUE_NR = ncolors;
02851 
02852 
02853    if(k >= 0) {
02854      for(i=0; i < k; i++) {
02855      tmp1[i] = MYgrey[i].red;
02856      tmp2[i] = MYgrey[i].green;
02857      tmp3[i] = MYgrey[i].blue;
02858      }
02859      for(i=0; i < ncolors - k; i++) {
02860        MYgrey[i].red   = MYgrey[i+k].red;
02861        MYgrey[i].green = MYgrey[i+k].green;
02862        MYgrey[i].blue  = MYgrey[i+k].blue;
02863      }
02864      for(i = ncolors - k, j = 0; i < ncolors; i++, j++) {
02865        MYgrey[i].red   = tmp1[j];
02866        MYgrey[i].green = tmp2[j];
02867        MYgrey[i].blue  = tmp3[j];
02868      }
02869    }
02870    else {
02871      k = -k;
02872      for(i = ncolors - 1; i >= ncolors - k; i--) {
02873      tmp1[i] = MYgrey[i].red;
02874      tmp2[i] = MYgrey[i].green;
02875      tmp3[i] = MYgrey[i].blue;
02876      }
02877      for(i = ncolors - 1; i >= k; i--) {
02878        MYgrey[i].red   = MYgrey[i-k].red;
02879        MYgrey[i].green = MYgrey[i-k].green;
02880        MYgrey[i].blue  = MYgrey[i-k].blue;
02881      }
02882      for(i = k-1, j = ncolors - 1; i >=0; i--, j--) {
02883        MYgrey[i].red   = tmp1[j];
02884        MYgrey[i].green = tmp2[j];
02885        MYgrey[i].blue  = tmp3[j];
02886      }
02887    }
02888    if ( AJ_PseudoColor ) XStoreColors(theDisp, CMap, MYgrey, ncolors);
02889    else                AJ_StoreColors(theDisp, CMap, MYgrey, ncolors, 0);
02890 }
02891 
02892 /* -------- */
02893    c_swap()
02894 /* -------- */
02895 {
02896    if (YES_color) color_swap();
02897 }
02898 
02899 /* --------------- */
02900    color_swap()
02901 /* --------------- */
02902 {
02903    register int i, k;
02904 
02905    FIRST = 1; SQUE_NR = ncolors;
02906    k = ncolors - 1;
02907 
02908    for(i=0; i < ncolors; i++) {
02909     tmp1[i] = MYcol[i].red;
02910     tmp2[i] = MYcol[i].green;
02911     tmp3[i] = MYcol[i].blue;
02912    }
02913    for(i=0; i < ncolors ; i++) {
02914      MYcol[i].red   = tmp1[k-i];
02915      MYcol[i].green = tmp2[k-i];
02916      MYcol[i].blue  = tmp3[k-i];
02917    }
02918    if ( AJ_PseudoColor ) XStoreColors(theDisp, CMap, MYcol, ncolors);
02919    else                AJ_StoreColors(theDisp, CMap, MYcol, ncolors, 1);
02920 }
02921 
02922 /* ------------- */ /* Modify span or contrast */
02923    c_squeeze(d)
02924    int d;
02925 /* ------------- */
02926 {
02927    if (YES_color) color_squeeze(d);
02928    else           grey_contrast(-2*d);
02929 }
02930 
02931 /* -------------------- */      /* Modify contrast of the Image */
02932    grey_contrast(d_lev)
02933    int d_lev;
02934 /* -------------------- */
02935 {
02936    register int i, k, m, delta, dx;
02937 
02938    dx = max(((abs(INgrey[ncolors-1] - INgrey[0])>>6)/ncolors), 1);
02939    delta = d_lev*dx;
02940    for(i=0; i < ncolors; i++) {
02941       k = INgrey[i] += i*delta;
02942       m = min_max_col(k);
02943       MYgrey[i].red   = m;
02944       MYgrey[i].green = m;
02945       MYgrey[i].blue  = m;
02946    }
02947    if ( AJ_PseudoColor ) XStoreColors(theDisp, CMap, MYgrey, ncolors);
02948    else                AJ_StoreColors(theDisp, CMap, MYgrey, ncolors, 0);
02949 }
02950 
02951 /* -------------------- */ /* Modify span of colors*/
02952    color_squeeze(d)
02953    int d;
02954 /* -------------------- */
02955 {
02956    static unsigned int x_arr[NCOLORS];
02957    register int i, ex, w;
02958 
02959    w = ncolors/2;
02960    SQUE_NR = max(1, SQUE_NR - d);
02961    for (ex = 0; ex < ncolors; ex++)  x_arr[ex] = SQUE_NR*(ex - w)/ncolors + w;
02962 
02963    if(FIRST)
02964    for(i=0; i < ncolors; i++) {
02965      tmp1[i] = MYcol[i].red;
02966      tmp2[i] = MYcol[i].green;
02967      tmp3[i] = MYcol[i].blue;
02968      FIRST = 0;
02969    }
02970    for(i=0; i < ncolors; i++) {
02971      if(x_arr[i] > uucolors) {
02972        MYcol[i].red   = 0;
02973        MYcol[i].green = 0;
02974        MYcol[i].blue  = 0;
02975      }
02976      else {
02977        MYcol[i].red   = tmp1[x_arr[i]];
02978        MYcol[i].green = tmp2[x_arr[i]];
02979        MYcol[i].blue  = tmp3[x_arr[i]];
02980      }
02981    }
02982    if ( AJ_PseudoColor ) XStoreColors(theDisp, CMap, MYcol, ncolors);
02983    else                AJ_StoreColors(theDisp, CMap, MYcol, ncolors, 1);
02984 }
02985 
02986 /* ------------------ */ /* Modify brightness (color or B&W) */
02987    c_bright(d)
02988    int d;
02989 /* ------------------ */
02990 {
02991    if (YES_color) color_bright(d);
02992    else           grey_change(-2*d);
02993 }
02994 
02995 /* ------------------ */   /* Modify brightness of the Image  */
02996    grey_change(d_lev)
02997    int d_lev;
02998 /* ------------------ */
02999 {
03000    register int i, k, m, delta, dx;
03001 
03002    dx = abs((INgrey[ncolors-1] - INgrey[0])/ncolors);
03003    delta = d_lev*dx;
03004    for (i=0; i < ncolors; i++) {
03005       k = INgrey[i] += delta;
03006       m = min_max_col(k);
03007       MYgrey[i].red   = m;
03008       MYgrey[i].green = m;
03009       MYgrey[i].blue  = m;
03010    }
03011    if ( AJ_PseudoColor ) XStoreColors(theDisp, CMap, MYgrey, ncolors);
03012    else                AJ_StoreColors(theDisp, CMap, MYgrey, ncolors, 0);
03013 }
03014 
03015 /* ------------------ */ /* Modify brightness of the Image */
03016    color_bright(d)
03017    int d;
03018 /* ------------------ */
03019 {
03020    double c;
03021    register int i;
03022    c = d; c = 1. - c*.005;
03023    FIRST = 1; SQUE_NR = ncolors;
03024 
03025    for(i=0; i < ncolors; i++) {
03026      MYcol[i].red   = min_max_col(c*MYcol[i].red);
03027      MYcol[i].green = min_max_col(c*MYcol[i].green);
03028      MYcol[i].blue  = min_max_col(c*MYcol[i].blue);
03029    }
03030    if ( AJ_PseudoColor ) XStoreColors(theDisp, CMap, MYcol, ncolors);
03031    else                AJ_StoreColors(theDisp, CMap, MYcol, ncolors, 1);
03032 }
03033 
03034 /* -------------- */ /* It assigns index for one of standard 16 colors */
03035    STD_colors(cx)    /* First index is 1, last 16 (equv. to 0 - black col.). */
03036    int cx;
03037 /* -------------- */
03038 {
03039    XColor  any_col;
03040 
03041  if ( AJ_PseudoColor ) {
03042    if( cx > NUM_STD_COLORS ) return extra_color_x11[cx-NUM_STD_COLORS-1] ;
03043 
03044    if ( color_x11[cx-1] + 1 ) return(color_x11[cx-1]);
03045    else {
03046       any_col.red   = Solid_color[cx-1].red;
03047       any_col.green = Solid_color[cx-1].green;
03048       any_col.blue  = Solid_color[cx-1].blue;
03049       any_col.flags = DoRed | DoGreen | DoBlue;
03050 
03051 #ifdef RWCOX_LINUX
03052       if ( !XAllocColor(theDisp, CMap, &any_col) ){
03053          int ii ;
03054 
03055          fprintf(stderr,"cannot XAllocColor in STD_colors(). RWC\n") ;
03056          for( ii=0 ; ii < 16 ; ii++ ){
03057             if( color_x11[ii] != -1 ) break ;
03058          }
03059 
03060          if( ii == 16 ){
03061             FatalError("cannot continue! RWC") ;
03062          } else {
03063             any_col.pixel = color_x11[ii] ;
03064          }
03065       }
03066 #else
03067       if ( !XAllocColor(theDisp, CMap, &any_col) )
03068          FatalError ("XAllocColor problem in STD_colors(). AJ");
03069 #endif  /* RWCOX_LINUX */
03070 
03071       return( color_x11[cx-1] = any_col.pixel );
03072    }
03073  }
03074 }
03075 
03076 /* ---------------------------------- */   /* Create Image from the im_arr */
03077    XImage *Load_Any_Arr(im_arr, x, y)      /* Usage: theImage = Load_An... */
03078    short int im_arr[];                     /* indexed or RGB colors        */
03079    int       x, y;
03080 /* ---------------------------------- */
03081 {
03082    XImage    *image;
03083 
03084    if ( AJ_PseudoColor ) image = Load_Any_ind(im_arr, x, y);
03085    else                  image = Load_Any_RGB(im_arr, x, y);
03086 
03087    return image;
03088 }
03089 
03090 /* ---------------------------------- */   /* Create Image from the im_arr */
03091    XImage *Load_Any_RGB(im_arr, x, y)      /* Indices for RGB screen       */
03092    short int im_arr[];
03093    int       x, y;
03094 /* ---------------------------------- */
03095 {
03096    register char *ptr;
03097    register int   i, j, k, iN, iE, w2;
03098    int        Width, Hight, last;
03099    char      *Image;
03100    XImage    *image;
03101    byte      *a8, *i8, *m8;
03102    unsigned short *a16, *i16;
03103    unsigned long  *a32, *i32;
03104  
03105    Width = x;      /* Image width  */
03106    Hight = y;      /* Image higth  */
03107    last  = x * y;
03108 
03109    for (i=0; i < last; i++)
03110       if ( im_arr[i] < 0 ) im_arr[i] = STD_indx[-im_arr[i]-1];
03111 
03112    image = XCreateImage(theDisp, theVisual, Planes, ZPixmap, 0, NULL,
03113                                 Width, Hight, 32, 0);
03114    if (! image) FatalError("Unable create image in Load_R_G_B_Arr().");
03115 
03116    Image = (char *) malloc(image->bytes_per_line*Hight);
03117    if (!Image) FatalError("Not enough memory for the Image");
03118    image->data = Image;
03119 
03120    k = 0;
03121    switch( bperpix ) {
03122       case 32:
03123          a32 = (unsigned long *) image->data;
03124          i32 = (unsigned long *) AJ_RGB;
03125          for (i=0; i < last; i++) {
03126             *a32++ =  i32[im_arr[k++]];
03127          }
03128       break ;
03129  
03130       case 24:
03131          a8 = (byte *) image->data;
03132          i8 = (byte *) AJ_RGB;
03133          for (i=0; i < last; i++) {
03134             m8 =  i8 + im_arr[k++] * 3;
03135             *a8++ = *m8++;
03136             *a8++ = *m8++;
03137             *a8++ = *m8++;
03138          }
03139       break ;
03140 
03141       case 16:
03142          a16 = (unsigned short *) image->data;
03143          i16 = (unsigned short *) AJ_RGB;
03144          for (i=0; i < last; i++) {
03145             *a16++ =  i16[im_arr[k++]];
03146          }
03147       break ;
03148  
03149       case 8:
03150          a8 = (byte *) image->data;
03151          i8 = (byte *) AJ_RGB;
03152          for (i=0; i < last; i++) {
03153             *a8++ =  i8[im_arr[k++]];
03154          }
03155       break ;
03156    }
03157    return image;
03158 }
03159 
03160 /* ---------------------------------- */   /* Create Image from the im_arr */
03161    XImage *Load_Any_ind(im_arr, x, y)      /* Usage: theImage = Load_An... */
03162    short int im_arr[];                     /* Uses own 16 colors for nega- */
03163    int       x, y;                         /* tive numbers (-1 - -16).     */
03164 /* ---------------------------------- */   /* 8 and 12 bit planes work OK. */
03165 {
03166   register char *ptr;
03167   register int   i, j, k, iN, iE, w2;
03168   int        Width, Hight;
03169   char      *Image;
03170   XImage    *image;
03171 
03172 STATUS("ENTER Load_index_Arr") ;
03173 
03174   Width = x;      /* Image width  */
03175   Hight = y;      /* Image higth  */
03176 
03177   image = XCreateImage(theDisp, theVisual, Planes, ZPixmap, 0, NULL,
03178                                 Width, Hight, 32, 0);
03179   if (! image) FatalError("Unable create image in Load_index_Arr().");
03180 
03181   Image = (char *) malloc(image->bytes_per_line*Hight);
03182   if (!Image) FatalError("Not enough memory for the Image");
03183   image->data = Image;
03184   iN = (image->bits_per_pixel + 7) / 8;    /* 1 or 2 pointer increment */
03185   iE = iN - 1;                             /* 0 or 1 for next pointer */
03186 
03187   ptr = Image;
03188   k = 0;
03189   for (i=0; i<Hight; i++)
03190      for (j=0; j<Width; j++, ptr += iN)
03191         if(im_arr[k] >= 0) {
03192           *ptr = pixels[im_arr[k]] >> 8;
03193           *(ptr + iE) = pixels[im_arr[k++]];
03194         }
03195         else {
03196           *ptr = STD_colors(-im_arr[k]) >> 8;
03197           *(ptr + iE) = STD_colors(-im_arr[k++]);
03198         }
03199 
03200   return image;
03201 }
03202 
03203 /* -------------------------------------------- */
03204    New_Cursor(Disp, Wind, shape, fg_col, bg_col)
03205    Display     *Disp;
03206    Window       Wind;
03207    unsigned int shape;
03208    char        *fg_col, *bg_col;
03209 /* -------------------------------------------- */
03210 /* Assigns new cursor to the Window. Call after creating the Window */
03211 {
03212    XColor       Im_cur_fg, Im_cur_bg;
03213    Colormap     CM;
03214    Cursor       cursor;
03215 
03216    CM = DefaultColormap(Disp, DefaultScreen(Disp));
03217 
03218    cursor = XCreateFontCursor(Disp, shape);        /* new cursor shape */
03219    XDefineCursor(Disp, Wind, cursor);
03220    XParseColor(Disp, CM, fg_col, &Im_cur_fg);    /* forground  color */
03221    XParseColor(Disp, CM, bg_col, &Im_cur_bg);    /* background color */
03222    XRecolorCursor(Disp, cursor, &Im_cur_fg, &Im_cur_bg);
03223 }
03224 
03225 /* ----------------------------------------------------------------
03226    Read file subroutine fo use in C.        A.Jesmanowicz, MCW 1991
03227         return error :  0 - OK,
03228                         1 - opening problem,
03229                         2 - file longer then array.
03230         fname : file name.
03231         size  : on input - max size of the arr or 0 for any length,
03232                 on output- real size of the file (and arr in bytes).
03233         arr   : returned file as array.
03234    ---------------------------------------------------------------- */
03235 /* ----------------------------- */
03236    int  read_iqm(fname,size,arr)
03237    int  *size;
03238    char fname[],arr[];
03239 /* ----------------------------- */
03240 {
03241         int     isize = *size;
03242         int     fp;                             /* file descriptor  */
03243         struct  stat file_stat;                 /* status structure */
03244 
03245         if ((fp = open(fname, O_RDONLY)) <= 0)  /* file must exist */
03246            return(1);                           /* or error = 1.   */
03247 
03248         fstat(fp, &file_stat);                  /* get file size in bytes   */
03249 
03250         if(file_stat.st_size > isize && isize)  /* file can not be too long */
03251            return(2);                           /* or error = 2.            */
03252 
03253         *size =  file_stat.st_size;             /* return file size */
03254 
03255         read(fp, arr, file_stat.st_size);       /* read whole file  */
03256         close(fp);
03257         return(0);                              /* no error : 0 */
03258 }
03259 
03260 /* ----------------------------------------------------------------
03261    Write file subroutine fo use in C.       A.Jesmanowicz, MCW 1991
03262         return error :  0 - OK,
03263                         1 - opening problem,
03264                         2 - negative length.
03265         fname : file name.
03266         size  : size of the file.
03267         arr   : file array.
03268    ---------------------------------------------------------------- */
03269 /* ----------------------------- */
03270    int WRite_iqm(fname,size,arr)
03271    int  *size;
03272    char fname[],arr[];
03273 /* ----------------------------- */
03274 {
03275         int     isize = *size;
03276         int     fp;                             /* file descriptor  */
03277 
03278         if(isize < 0)                           /* size has to be real */
03279            return(2);                           /* or error = 2.       */
03280 
03281         if ((fp = open(fname, O_WRONLY|O_CREAT|O_EXCL,0644)) <= 0)
03282            return(1);                           /* file must not exist */
03283                                                 /* or error = 1.       */
03284 
03285         write(fp, arr, isize);                  /* write whole file */
03286         close(fp);
03287         return(0);
03288 }
03289 
03290 
03291 /*  Directory names (if present) are skipped. and number is added in front */
03292 /* -------------- */
03293    top_nr_name(name)
03294    char *name;
03295 /* -------------- */
03296 {
03297    register int i, k;
03298    char         *p_name;
03299 
03300    k = strlen( name );
03301    p_name = name;
03302    for(i = 0; i < k; i++) {
03303       if(name[i] != 32 && name[i]) {
03304          if(name[i] == 47) p_name = &name[i+1];
03305       }
03306       else {
03307          name[i] = 0;
03308          break;
03309       }
03310    }
03311    sprintf(T_name, "#%d   %s", Im_Nr+1, p_name);
03312    sprintf(I_name, "G %s", p_name);
03313    sprintf(G_name, "G %s , EPI_grid", p_name);
03314 }
03315 
03316 /* ------------------ */ /* resample image into 256x256 frame using st_? */
03317    void Resample(im)
03318    MRI_IMAGE * im ;
03319 /* ------------------ */
03320 {
03321    register short int *a;
03322    register int       *s, i1, ix, lx, i, j, k, l, kk, mm, dkk, ii, ij, is;
03323    register int       II, J, IJ, IJk, ijl, k0, IM2, lx2, ly, IJK;
03324    int ndim ;
03325    short * all ;
03326 
03327 STATUS("ENTER Resample") ;
03328 
03329    ndim = im->nx ;
03330    all  = im->im.short_data ;
03331 
03332    if(ndim == EPX4 ) {                    /* 32x32 pixels format */
03333       s  = st_8;
03334       i1 = 3;
03335       is = 6;
03336       ix = 8;
03337       lx = 32;
03338       ly = 32;
03339    }
03340    else if(ndim == EPX1 ) {                    /* 64x64 pixels format */
03341       s  = st_4;
03342       i1 = 1;
03343       is = ix = 4;
03344       lx = 64;
03345       ly = 64;
03346    }
03347    else if(ndim == EPX2) {             /* 128x128 pixels format */
03348       s  = st_2;
03349       i1 = 0;
03350       is = ix = 2;
03351       lx = 128;
03352       ly = 128;
03353    }
03354    else if (ndim == EPX3){ /* 256x256 pixels => no resample  */
03355       a = all;
03356       lx = ndim * ndim ;
03357       for (i=0; i < lx ; i++)
03358          tmp_imx[i] = imx[i] =  a[i];
03359       return;
03360    }
03361    else {
03362       printf("\n\n !!! Wrong file format in Resample() function !!!\n\n");
03363       exit(3);
03364    }
03365 
03366    /* Images of different resolutions will register for c_f=0 (and i1=0)  */
03367    /* For c_f=1 frame will be centered on the pixel!         AJ 10.18.2000 */
03368    if ( c_f == 0 ) i1 = 0;
03369 
03370    a = all;
03371 
03372    lx2 = lx*ly;
03373    IM2 = IM_HEIGHT*IM_HEIGHT;
03374    k0  = ix*(2*ix-1) - 1;
03375    dkk = 2*ix*ix;
03376 
03377    i = ly - 1;                     /* horizontal edge with wrap around */
03378    ii = i*lx;
03379    II = (i*ix+i1)*IM_HEIGHT + i1;
03380    for (j=0; j < lx - 1; j++) {
03381       ij  = ii+j;
03382       ijl = ij+lx;
03383       if ( ijl >= lx2 ) ijl -= lx2;
03384       IJ  = II + j*ix;
03385       for (k=0; k < ix; k++) {
03386          IJk = IJ + k*IM_HEIGHT ;
03387          if ( IJk >= IM2 ) IJk -= IM2;
03388          kk = k0 - ((k * ix) << 1);
03389          mm = kk + dkk;
03390          for (l=0; l < ix; l++) {
03391             tmp_imx[IJk+l]
03392               = imx[IJk+l] = ( a[ij]    * s[kk-l]
03393                              + a[ij+1]  * s[kk-l+ix]
03394                              + a[ijl]   * s[mm-l]
03395                              + a[ijl+1] * s[mm-l+ix]) >> is;
03396          }
03397       }
03398    }
03399 
03400    j = lx - 1;
03401    for (i=0; i < ly - 1; i++) {       /* vertical edge with wrap around */
03402       ii = i*lx;
03403       II = (i*ix+i1)*IM_HEIGHT;
03404       ij  = ii+j;
03405       ijl = ij+lx;
03406       J   = j*ix + i1;
03407       IJ  = II + J;
03408       for (k=0; k < ix; k++) {
03409          IJk = IJ + k*IM_HEIGHT ;
03410          kk = k0 - ((k * ix) << 1);
03411          mm = kk + dkk;
03412          for (l=0; l < ix; l++) {
03413             IJK = IJk;
03414             if ( (J + l) >= IM_HEIGHT ) IJK = IJk - IM_HEIGHT;
03415             if ( IJK >= IM2 ) IJK -= IM2;
03416             tmp_imx[IJK+l]
03417               = imx[IJK+l] = ( a[ij]      * s[kk-l]
03418                              + a[ij-lx+1] * s[kk-l+ix]
03419                              + a[ijl]     * s[mm-l]
03420                              + a[ijl-lx+1]* s[mm-l+ix]) >> is;
03421          }
03422       }
03423    }
03424 
03425    i = ly - 1;                /* last lower right corner with wrap around */
03426    j = lx - 1;
03427    ij = lx*ly - 1;
03428    ijl = lx - 1;
03429    IJ = (i*ix+i1)*IM_HEIGHT + j*ix + i1;
03430    for (k=0; k < ix; k++) {
03431       IJk = IJ + k*IM_HEIGHT ;
03432       if ( IJk >= IM2 ) IJk -= IM2;
03433       kk = k0 - ((k * ix) << 1);
03434       mm = kk + dkk;
03435       for (l=0; l < ix; l++) {
03436          IJK = IJk;
03437          if ( (J + l) >= IM_HEIGHT ) IJK = IJk - IM_HEIGHT;
03438          tmp_imx[IJK+l]
03439            = imx[IJK+l] = ( a[ij]      * s[kk-l]
03440                           + a[ij-lx+1] * s[kk-l+ix]
03441                           + a[ijl]     * s[mm-l]
03442                           + a[ijl-lx+1]* s[mm-l+ix]) >> is;
03443       }
03444    }
03445 
03446    for (i=0; i < ly - 1; i++) {        /* the rest of the field */
03447       ii = i*lx;
03448       II = (i*ix+i1)*IM_HEIGHT + i1;
03449       for (j=0; j < lx - 1; j++) {
03450          ij  = ii+j;
03451          ijl = ij+lx;
03452          J   = j*ix;
03453          IJ  = II + J;
03454          for (k=0; k < ix; k++) {
03455             IJk = IJ + k*IM_HEIGHT ;
03456             kk = k0 - ((k * ix) << 1);
03457             mm = kk + dkk;
03458             for (l=0; l < ix; l++) {
03459                tmp_imx[IJk+l]
03460                  = imx[IJk+l] = ( a[ij]    * s[kk-l]
03461                                 + a[ij+1]  * s[kk-l+ix]
03462                                 + a[ijl]   * s[mm-l]
03463                                 + a[ijl+1] * s[mm-l+ix]) >> is;
03464             }
03465          }
03466       }
03467    }
03468 }
03469 
03470 /* ------------ */ /* Don't use before first Resample() and Load_Any_Arr(). */
03471    void            /* Load_Any_Arr() allocate memory for theImage. */
03472    Put_image(n)    /* Put_image() needs THIS memory. */
03473    int n;
03474 /* ------------ */
03475 {
03476    register int    min2, max2, i, m;
03477    register float  coef2, del2;
03478    int             xtemp1, xtemp2, ytemp1, ytemp2, xmat, xm, ym, xxx;
03479 
03480 STATUS("ENTER Put_image") ;
03481 
03482    if ( (n == old_im) && AJ_PseudoColor ) {
03483       for (i = 0; i < IM_ARR; i++) imx[i] = tmp_imx[i];
03484    }
03485 #ifdef USE_MCW
03486    else if ( n < 0 ){
03487       mcw_load() ;
03488       for( i=0 ; i < IM_ARR ; i++ ) tmp_ar[i] = mcw_im[i] ;
03489       SIZE_tmp_ar( IM_HEIGHT ) ;
03490       Resample(im_tmp_ar);
03491       strcpy(T_name,"Medical College of Wisconsin") ;
03492       strcpy(G_name,"Medical College of Wisconsin") ;
03493       strcpy(I_name,"MCW") ;
03494       Allow_new_name(Argc, Argv);
03495       old_im = -9999 ;
03496    }
03497 #endif
03498    else {
03499       nowim   = SAR(n) ;
03500       nowsize = SIZ(n) ;
03501       if( RWC_autoscale || (n >= npoints) ){   /* Autoscale these */
03502          min2 =  32767;
03503          max2 = -32768;
03504          for (i=0; i < nowsize; i++) {
03505             if ( nowim[i] < min2 ) min2 = nowim[i];
03506             if ( nowim[i] > max2 ) max2 = nowim[i];
03507          }
03508          del2 = max2 - min2;
03509          if (del2 < 1.) del2 = 1.;
03510          coef2 = ( (float) NC - 1.) / del2;
03511       }
03512       else {
03513          coef2 = coef1;
03514          min2 = min1;
03515       }
03516                              /* make differential single image */
03517       if ( (n<npoints) && (diff_im || avr_grp) ) {
03518          if ( ! avr_grp )
03519             for (i=0; i < ar_size; i++) tmp_ar[i] = nowim[i] - ref_ar[i];
03520 
03521                               /* make average image */
03522          else {
03523             Av_1 = n;
03524             Av_2 = Av_1 + Av_length - 1;
03525             for (i=0; i< ar_size; i++) av_ar[i] = 0;
03526             for (i=0; i < ar_size; i++) {
03527                for (j=Av_1; j <= Av_2; j++) av_ar[i] += SAR(j)[i];
03528             }
03529             for (i=0; i < ar_size; i++)  av_ar[i] /= Av_length;
03530 
03531                               /* average against ref image */
03532             if ( avr_grp && diff_im )
03533                for (i=0; i < ar_size; i++) tmp_ar[i] = av_ar[i] - ref_ar[i];
03534 
03535                               /* pure average image */
03536             else
03537                for (i=0; i < ar_size; i++) tmp_ar[i] = av_ar[i];
03538 
03539          }
03540                               /* renormalize image */
03541          min2 =  32767;
03542          max2 = -32768;
03543          for (i=0; i < ar_size; i++) {
03544             if ( tmp_ar[i] < min2 ) min2 = tmp_ar[i];
03545             if ( tmp_ar[i] > max2 ) max2 = tmp_ar[i];
03546          }
03547          del2 = max2 - min2;
03548          if (del2 < 1.)  del2 = 1.;
03549          coef2 = ( (float) NC - 1.) / del2;
03550          for (i=0; i < ar_size; i++)
03551             tmp_ar[i] = (int)((float)(tmp_ar[i]-min2)*coef2 + .5);
03552       }
03553       else if( LSQ_imedit[LSQ_code] != LSQ_EDIT_NONE ){
03554          int lsqnum , i,j ;
03555          float sum ;
03556 
03557          lsqnum = LSQ_refcount - LSQ_imedit[LSQ_code] ;
03558 
03559          min2 =  32767;
03560          max2 = -32768;
03561          for( i=0 ; i < nowsize ; i++ ){
03562             sum = nowim[i] ;
03563             for(j=0 ; j < lsqnum ; j++ )
03564                sum -= LSQ_ref[j]->ts[n] * LSQ_fit[j][i] ;
03565             tmp_ar[i] = sum ;
03566             if ( tmp_ar[i] < min2 ) min2 = tmp_ar[i];
03567             if ( tmp_ar[i] > max2 ) max2 = tmp_ar[i];
03568          }
03569          del2 = max2 - min2;
03570          if (del2 < 1.)  del2 = 1.;
03571          coef2 = ( (float) NC - 1.) / del2;
03572          for (i=0; i < ar_size; i++)
03573             tmp_ar[i] = (int)((float)(tmp_ar[i]-min2)*coef2 + .5);
03574       }
03575       else{                                       /* Normal Image */
03576          for (i=0; i < nowsize; i++)              /* renormalize data */
03577             tmp_ar[i] = (int)((float)(nowim[i]-min2)*coef2 + .5);
03578       }
03579 
03580       SIZE_tmp_ar( allim[n]->nx ) ;
03581 
03582       Resample(im_tmp_ar);
03583       top_nr_name(allim[n]->name) ;
03584       Allow_new_name(Argc, Argv);
03585       DrawTopWindow();
03586       old_im = n;
03587    }
03588 
03589    if( !RWC_framehide ){
03590 
03591       xxx = max(0, x_mag/2 - 1);        /* stuff for proper pivot and frame */
03592       xm = x_mag - 1;
03593       ym = x_mag - 1;
03594       xmat = x_mag * (mat - 1) + x_mag/2 + 1;
03595 
03596       ytemp1 = x_mag * (ypoint + yc) + ym ;
03597       if (ytemp1 < 0)          ytemp1 += IM_HEIGHT;
03598       if (ytemp1 >= IM_HEIGHT) ytemp1 -= IM_HEIGHT;
03599 
03600       ytemp2 = x_mag * (ypoint + yc - mat + 1);
03601       if (ytemp2 < 0)          ytemp2 += IM_HEIGHT;
03602       if (ytemp2 >= IM_HEIGHT) ytemp2 -= IM_HEIGHT;
03603 
03604       for (i=0; i < xmat + xxx; i++) {
03605         xtemp1 = x_mag * (xpoint - xc) + i;
03606         if (xtemp1 < 0)          xtemp1 += IM_HEIGHT;
03607         if (xtemp1 >= IM_HEIGHT) xtemp1 -= IM_HEIGHT;
03608 
03609         imx[ytemp1 * IM_HEIGHT + xtemp1] = fr_index;
03610         imx[ytemp2 * IM_HEIGHT + xtemp1] = fr_index;
03611       }
03612 
03613       xtemp1 = x_mag * (xpoint - xc);
03614       if (xtemp1 < 0)          xtemp1 += IM_HEIGHT;
03615       if (xtemp1 >= IM_HEIGHT) xtemp1 -= IM_HEIGHT;
03616 
03617       xtemp2 = x_mag * (xpoint - xc + mat - 1) + xm;
03618       if (xtemp2 < 0)          xtemp2 += IM_HEIGHT;
03619       if (xtemp2 >= IM_HEIGHT) xtemp2 -= IM_HEIGHT;
03620 
03621       for (i=0; i < xmat; i++) {
03622          ytemp1 = x_mag * (ypoint + yc) - i + ym;
03623          if (ytemp1 < 0)          ytemp1 += IM_HEIGHT;
03624          if (ytemp1 >= IM_HEIGHT) ytemp1 -= IM_HEIGHT;
03625 
03626          imx[ytemp1 * IM_HEIGHT + xtemp1] = fr_index;
03627          imx[ytemp1 * IM_HEIGHT + xtemp2] = fr_index;
03628       }
03629    } /* end if !RWC_framehide */
03630 
03631    if( RWC_do_overfim && !RWC_overhide ){
03632       short dont_overlay ;
03633       dont_overlay = fr_index ;
03634 #ifdef OV_DEBUG1
03635    fprintf(stderr,"overlaying image #%d\n",n) ; fflush(stderr) ;
03636 #endif
03637       RWC_short_overlay( IM_HEIGHT,IM_HEIGHT,imx , RWC_nxim,RWC_nyim ,
03638                          RWC_OVFLAG,dont_overlay, RWC_checker , RWC_imover ) ;
03639    }
03640 
03641    if ( !AJ_PseudoColor ) {
03642       Load_Next_Arr(theBelt, belt_arr,BELT_W,IM_HEIGHT);
03643       MResize(&expBelt,&eW,&eH,theBelt,eW,eH);
03644       }XPutImage(theDisp, theWindow, theGC, expBelt, 0, 0, eHIGH, 0, eW, eH);
03645 
03646    Load_Next_Arr(theImage, imx,IM_HEIGHT,IM_HEIGHT);
03647    MResize(&expImage,&eWIDE,&eHIGH,theImage,eWIDE,eHIGH);
03648    XPutImage(theDisp, theWindow, theGC, expImage,0, 0, 0, 0, eWIDE, eHIGH);
03649 }
03650 
03651 /* ---------------------------------- */   /* Create Image from the im_arr */
03652    Load_Next_Arr(Image, im_arr, x, y)      /* Usage: Load_Next... */
03653    short int im_arr[];
03654    int       x, y;
03655    XImage    *Image;
03656 /* ---------------------------------- */
03657 {
03658 
03659    if ( AJ_PseudoColor ) Load_Next_ind(Image, im_arr, x, y);
03660    else                  Load_Next_RGB(Image, im_arr, x, y);
03661 }
03662 
03663 /* ---------------------------------- */
03664    Load_Next_RGB(Image, im_arr, x, y)
03665    short int im_arr[];
03666    int       x, y;
03667    XImage    *Image;
03668 /* ---------------------------------- */   /* RGB version */
03669 {
03670    register int   i, k, last;
03671    byte      *a8, *i8, *m8;
03672    unsigned short *a16, *i16;
03673    unsigned long  *a32, *i32;
03674  
03675    last  = x * y;
03676  
03677    for (i=0; i < last; i++)
03678       if ( im_arr[i] < 0 ) im_arr[i] = STD_indx[-im_arr[i]-1];
03679  
03680    k = 0;
03681    switch( bperpix ) {
03682       case 32:
03683          a32 = (unsigned long *) Image->data;
03684          i32 = (unsigned long *) AJ_RGB;
03685          for (i=0; i < last; i++) {
03686             *a32++ =  i32[im_arr[k++]];
03687          }
03688       break ;
03689  
03690       case 24:
03691          a8 = (byte *) Image->data;
03692          i8 = (byte *) AJ_RGB;
03693          for (i=0; i < last; i++) {
03694             m8 =  i8 + im_arr[k++] * 3;
03695             *a8++ = *m8++;
03696             *a8++ = *m8++;
03697             *a8++ = *m8++;
03698          }
03699       break ;
03700 
03701       case 16:
03702          a16 = (unsigned short *) Image->data;
03703          i16 = (unsigned short *) AJ_RGB;
03704          for (i=0; i < last; i++) {
03705             *a16++ =  i16[im_arr[k++]];
03706          }
03707       break ;
03708  
03709       case 8:
03710          a8 = (byte *) Image->data;
03711          i8 = (byte *) AJ_RGB;
03712          for (i=0; i < last; i++) {
03713             *a8++ =  i8[im_arr[k++]];
03714          }
03715       break ;
03716    }
03717 }
03718 
03719 /* ---------------------------------- */   /* Create Image from the im_arr */
03720    Load_Next_ind(Image, im_arr, x, y)      /* Usage: Load_Next... */
03721    short int im_arr[];                     /* Uses own 16 colors for nega- */
03722    int       x, y;                         /* tive numbers (-1 - -16).     */
03723    XImage    *Image;
03724 /* ---------------------------------- */   /* 8 and 12 bit planes work OK. */
03725 {
03726   register char *ptr;
03727   register int   i, j, k, iN, iE;
03728   int        Width, Hight;
03729 
03730 STATUS("ENTER Load_Next_ind") ;
03731 
03732   iN = (Planes + 7)/8;             /* 1 or 2, pointer increment */
03733   iE = iN - 1;                     /* 0 or 1 for next pointer */
03734 
03735   Width = x;      /* Image width  */
03736   Hight = y;      /* Image higth  */
03737 
03738   ptr = Image->data;
03739   k = 0;
03740   for (i=0; i<Hight; i++)
03741      for (j=0; j<Width; j++, ptr += iN)
03742         if(im_arr[k] >= 0) {
03743           *ptr = pixels[im_arr[k]] >> 8;
03744           *(ptr + iE) = pixels[im_arr[k++]];
03745         }
03746         else {
03747           *ptr = STD_colors(-im_arr[k]) >> 8;
03748           *(ptr + iE) = STD_colors(-im_arr[k++]);
03749         }
03750 }
03751 
03752 /* ---------------------------- */
03753    Allow_new_name(argc, argv)
03754    int  argc;
03755    char *argv[];
03756 /* ---------------------------- */
03757 {
03758    XSetStandardProperties(theDisp, theWindow, T_name, T_name, None,
03759                           argv, argc, NULL);
03760    XSetStandardProperties(theDisp, GWindow, G_name, I_name, None,
03761                           argv, argc, NULL);
03762 }
03763 
03764 /* ----------------------------- */   /* plot scaled new_line to pixmap  */
03765    void plot_line()
03766 /* ----------------------------- */
03767 {
03768    register int i,j, m, temp, index, ix, iy, xtemp, ytemp;
03769    int lsqnum , lsqfit , base , use_base , bb ;
03770    float f0;
03771 
03772 STATUS("ENTER plot_line") ;
03773 
03774    m = ar_size;
03775 
03776    lsqnum = 0 ;
03777    lsqfit = 0 ;
03778    if( RWC_do_overfim && RWC_ideal != NULL && LSQ_fitim != NULL ){
03779       switch( LSQ_code ){
03780          default:          lsqnum = 0                ; lsqfit = 0 ; break ;
03781          case LSQ_FITORT:  lsqnum = LSQ_refcount - 1 ; lsqfit = 1 ; break ;
03782          case LSQ_SUBORT:  lsqnum = LSQ_refcount - 1 ; lsqfit = 0 ; break ;
03783          case LSQ_FITALL:  lsqnum = LSQ_refcount     ; lsqfit = 1 ; break ;
03784          case LSQ_SUBALL:  lsqnum = LSQ_refcount     ; lsqfit = 0 ; break ;
03785          case LSQ_SORFID:  lsqnum = LSQ_refcount - 1 ; lsqfit = 2 ; break ;
03786       }
03787    }
03788 
03789    /** RWCox: 2 Aug 1996
03790               load data from images into "val" array here,
03791               instead of in main loop.  this allows loading of 'base' **/
03792 
03793    base = 40000 ;
03794    for (ix=0;ix<mat;ix++) {
03795       xtemp = xpoint + ix - xc;
03796       if (xtemp < 0)        xtemp += im_size;
03797       if (xtemp >= im_size) xtemp -= im_size;
03798       for (iy=0;iy<mat;iy++) {
03799          ytemp = ypoint - iy + yc;
03800          if (ytemp < 0)        ytemp += im_size;
03801          if (ytemp >= im_size) ytemp -= im_size;
03802          index = ytemp * im_size + xtemp;
03803          for (i=0; i < npoints; i++){
03804             val[ix][iy][i] = bb = SAR(i)[index] ;
03805             if( bb < base ) base = bb ;
03806          }
03807       }
03808    }
03809 
03810    use_base = (RWC_groupbase && lsqnum == 0) ;
03811 
03812    for (ix=0;ix<mat;ix++) {
03813       xtemp = xpoint + ix - xc;
03814       if (xtemp < 0)        xtemp += im_size;
03815       if (xtemp >= im_size) xtemp -= im_size;
03816       for (iy=0;iy<mat;iy++) {
03817          ytemp = ypoint - iy + yc;
03818          if (ytemp < 0)        ytemp += im_size;
03819          if (ytemp >= im_size) ytemp -= im_size;
03820          index = ytemp * im_size + xtemp;
03821 
03822          if( lsqnum > 0 ){
03823             float sum ;
03824             for( i=0 ; i < npoints ; i++ ){
03825                sum = 0.0 ;
03826                for(j=0 ; j < lsqnum ; j++ )
03827                   sum += LSQ_ref[j]->ts[i] * LSQ_fit[j][index] ;
03828 
03829                switch( lsqfit ){
03830                   case 2: LSQ_val[i] = LSQ_ref[j]->ts[i] * LSQ_fit[j][index] ; /*fall*/
03831                   case 0: val[ix][iy][i] -= sum ;
03832                           break ;
03833                   case 1: LSQ_val[i]      = sum ;
03834                           break ;
03835                }
03836             }
03837 
03838 #ifdef DEBUG
03839             if( ix==xc && iy==yc ){
03840                printf("*** LSQ: num=%d fit=",lsqnum) ;
03841                for( j=0 ; j < lsqnum ; j++ ) printf(" %g",LSQ_fit[j][index]) ;
03842                printf("\n") ;
03843             }
03844 #endif
03845          }
03846 
03847          /** scale data **/
03848 
03849          if( use_base ){
03850             if ( AJ_base ) pmin[ix][iy] = 0;
03851             else           pmin[ix][iy] = base ;
03852          } else {
03853             pmin[ix][iy] = 40000;
03854             for (i=0; i < npoints; i++)
03855                pmin[ix][iy] = min(pmin[ix][iy],val[ix][iy][i]);
03856          }
03857 
03858          if (iscale > 0) {
03859            for (i=0; i < npoints; i++)
03860               plot[ix][iy][i] = (val[ix][iy][i]-pmin[ix][iy])*iscale;
03861            pmax[ix][iy] = pmin[ix][iy] + gy / iscale;
03862          }
03863          else {
03864             temp = -iscale;
03865             for (i=0; i < npoints; i++)
03866                plot[ix][iy][i] = (val[ix][iy][i]-pmin[ix][iy])/temp;
03867             pmax[ix][iy] = pmin[ix][iy] + gy * temp;
03868          }
03869 
03870          /** plot scaled data **/
03871 
03872          line_color("black");
03873          if ( AJ_sigma > 0. ) {
03874             AJ_off = AJ_nr/2;
03875             for (i=0; i < AJ_off; i++) {
03876                f_plot[i] = 0.;
03877                f_plot[npoints+i] = 0.;
03878             }
03879             f_plot[npoints+AJ_nr+1] = 0.;
03880             for (i=0; i < npoints; i++)
03881                f_plot[AJ_off+i] = plot[ix][iy][i];
03882             for (m=0; m < npoints; m++) {
03883                f0 = 0.;
03884                for (i=0; i <= AJ_nr; i++) f0 += AJ_gauss[i] * f_plot[m+i];
03885                i_plot[m] = f0 * AJ_norm;
03886             }
03887             for (i=0; i < npoints; i++) {
03888                a_line[i].x = xorigin[ix][iy] + i*gx/(npoints-1);
03889                a_line[i].y = iHIGH - yorigin[ix][iy] - i_plot[i];
03890             }
03891          }
03892          else {
03893             for (i=0; i < npoints; i++) {
03894                a_line[i].x = xorigin[ix][iy] + i*gx/(npoints-1);
03895                a_line[i].y = iHIGH - yorigin[ix][iy] - plot[ix][iy][i];
03896             }
03897          }
03898          XDrawLines(theDisp, GRWIND, theGC, a_line, npoints, CoordModeOrigin);
03899 
03900          /*** draw the LSQ_val fit to the data as well **/
03901 
03902          if( lsqnum > 0 && lsqfit ){
03903             float *id = RWC_ideal->ts ;
03904             int xx , yy ;
03905 
03906             if (iscale > 0) {
03907               for (i=0; i < npoints; i++)
03908                  LSQ_plot[i] = (LSQ_val[i]-pmin[ix][iy])*iscale;
03909             }
03910             else {
03911                temp = -iscale;
03912                for (i=0; i < npoints; i++)
03913                   LSQ_plot[i] = (LSQ_val[i]-pmin[ix][iy])/temp;
03914             }
03915             for (i=0; i < npoints; i++) {
03916                a_line[i].x = xorigin[ix][iy] + i*gx/(npoints-1);
03917                a_line[i].y = iHIGH - yorigin[ix][iy] - LSQ_plot[i];
03918                if( mat <= 3 && fabs(id[i]) >= 33333.0 )
03919                   Cpointer_PIXWIN( a_line[i].x , a_line[i].y , "blue" ) ;
03920             }
03921             line_color("red3");
03922             XDrawLines(theDisp, GRWIND, theGC, a_line, npoints, CoordModeOrigin);
03923          }
03924 
03925       } /* end loop iy */
03926       XFlush(theDisp);
03927    } /* end loop ix */
03928 
03929    /*** draw FIM ref function ***/
03930 
03931    if( RWC_do_overfim             &&
03932        RWC_ideal != NULL          &&
03933        RWC_ideal->len >= npoints  &&
03934        kFI3_show_ref > 0             ){
03935 
03936       float idmax , idmin , val , yscal,yoff ;
03937       float *id = RWC_ideal->ts ;
03938       int ii , xg,yg , xbot,ybot,xtop,ytop ;
03939       XPoint one_line[2] ;
03940 
03941 #define REFTS_FRAC 0.369  /* fraction of one graph that this takes up */
03942 
03943       idmax = -99999.0 ;
03944       idmin =  99999.0 ;
03945 
03946       /*** find scale factor for plot ***/
03947 
03948       for( ii=0 ; ii < npoints ; ii++ ){
03949          val = id[ii] ;
03950          if( fabs(val) < 33333.0 ){
03951             idmax = MAX(idmax,val) ;
03952             idmin = MIN(idmin,val) ;
03953          }
03954       }
03955       if( idmax >= 33333.0 || idmax <= -33333.0 || idmax <= idmin ) return ;
03956 
03957       yscal = REFTS_FRAC * gy / (idmax-idmin) ;
03958       yoff  = (0.97-REFTS_FRAC) * gy ;
03959 
03960       /*** scale into a_line (with no origins yet) ***/
03961 
03962       for (i=0; i < npoints; i++) {
03963          a_line[i].x = i*gx/(npoints-1);
03964          val = ( fabs(id[i]) < 33333.0 ) ? (id[i]) : (idmin) ;
03965          a_line[i].y = iHIGH - (yoff+yscal*(val-idmin));
03966       }
03967 
03968       /*** for each line, for each plot, put into pixmap ***/
03969 
03970       line_color("red") ;
03971 
03972       for (i=0; i < npoints-1 ; i++) {
03973          if( fabs(id[i]) < 33333.0 && fabs(id[i+1]) < 33333.0 ){
03974             line_color("red") ;   /* red for "good" lines */
03975          } else {
03976             line_color("blue") ;  /* blue for "bad" lines */
03977          }
03978 
03979         /*** draw into every plot in matrix ***/
03980 
03981         if( kFI3_show_ref == 1 ){
03982            xbot = xc ; xtop = xbot+1 ;  /* just do center plot */
03983            ybot = yc ; ytop = ybot+1 ;
03984         } else {
03985            xbot = ybot = 0 ;            /* do all plots */
03986            xtop = ytop = mat ;
03987         }
03988 
03989         for( yg=ybot ; yg < ytop ; yg++ ){
03990            for( xg=xbot ; xg < xtop ; xg++ ){
03991               one_line[0].x = a_line[i].x   + xorigin[xg][yg] ;
03992               one_line[1].x = a_line[i+1].x + xorigin[xg][yg] ;
03993               one_line[0].y = a_line[i].y   - yorigin[xg][yg] ;
03994               one_line[1].y = a_line[i+1].y - yorigin[xg][yg] ;
03995               XDrawLines(theDisp, GRWIND, theGC, one_line, 2, CoordModeOrigin);
03996               if( mat <= 3 && kFI3_show_ref == 1 && fabs(id[i]) >= 33333.0 )
03997                  Cpointer_PIXWIN( one_line[0].x , one_line[0].y , "blue" ) ;
03998            }
03999         }  /* end of loops over boxes */
04000       } /* end of loop over points in plot */
04001 
04002    } /* end of FIM stuff */
04003 
04004 }
04005 
04006 /* ----------------------------- */ /* draw marker for current image  */
04007    void draw_marker()
04008 /* ----------------------------- */ /* marker fixed (shifted by one im) AJJ */
04009 {
04010    register int i, j, k, xo, yo, x1, dx;
04011    register float g, f0;
04012 
04013    if (mark) {
04014      line_color(color[color_index]);
04015      g = grid_coef * grid_far[grid_index + FT_grid];
04016      for (i=0;i<mat;i++) {
04017         for (j=1;j<=npoints/g;j++) {
04018               f0 = ((float) j * g - 1.) * (float) gx / (float) (npoints - 1);
04019               k = xorigin[i][0] + (int) f0;
04020           plotx(k,mdy1, 0);
04021           plotx(k,mdy1+mat*gy, 1);
04022             }
04023      }
04024    }
04025 
04026 #ifdef FILL_WITH_CYAN
04027    line_color("cyan");
04028    xo = xorigin[xc][yc];
04029    yo = iHIGH - yorigin[xc][yc] - gy;
04030    XFillRectangle(theDisp, GRWIND, theGC, xo, yo, gx, gy);
04031 #else
04032    xo = xorigin[xc][yc] ; yo = yorigin[xc][yc] ;
04033    g  = 5 ;
04034    for( j=1 ; j <= g ; j++ ){
04035       plotx( xo+j    , yo+j    , 0 ) ; 
04036       plotx( xo+j    , yo+gy-j , 1 ) ; 
04037       plotx( xo+gx-j , yo+gy-j , 1 ) ;
04038       plotx( xo+gx-j , yo+j    , 1 ) ; 
04039       plotx( xo+j    , yo+j    , 1 ) ; 
04040    }
04041 #endif
04042 
04043    xo = xorigin[xc][yc];
04044    yo = iHIGH - yorigin[xc][yc] - gy;
04045 
04046    if (diff_im) {
04047       line_color("blue");
04048       x1 = Im_1*gx/(npoints-1);
04049       dx = (Im_2 - Im_1)*gx/(npoints-1) + 1;
04050       XFillRectangle(theDisp, GRWIND, theGC, xo + x1, yo, dx, gy);
04051    }
04052 
04053    if (avr_grp) {
04054       line_color("red");
04055       x1 = Av_1*gx/(npoints-1);
04056       dx = (Av_2 - Av_1)*gx/(npoints-1) + 1;
04057       XFillRectangle(theDisp, GRWIND, theGC, xo + x1, yo, dx, gy);
04058    }
04059 
04060    if (mark) {
04061 #ifdef FILL_WITH_CYAN
04062      line_color("white");
04063 #else
04064      line_color(color[color_index]);
04065 #endif
04066      g = grid_coef * grid_far[grid_index + FT_grid];
04067      for (j=1;j<=npoints/g;j++) {
04068         f0 = ((float) j * g - 1.) * (float) gx / (float) (npoints - 1);
04069         k = xorigin[xc][yc] + (int) f0;
04070         plotx(k,yorigin[xc][yc]   , 0);
04071         plotx(k,yorigin[xc][yc]+gy, 1);
04072      }
04073    }
04074 }
04075 
04076 /* ----------------------------- */   /* scale plot up and redraw  */
04077    void scale_up()
04078 /* ----------------------------- */
04079 {
04080    if (iscale > 0) iscale *= 2;
04081    else if (iscale < -2) iscale /= 2;
04082    else iscale = 1;
04083 }
04084 
04085 /* ----------------------------- */   /* scale plot up and redraw  */
04086    void scale_down()
04087 /* ----------------------------- */
04088 {
04089    if (iscale > 1) iscale /= 2;
04090    else if (iscale < 0) iscale *= 2;
04091    else iscale = -2;
04092 }
04093 
04094 /* ----------------------------- */   /* decrease matrix and redraw  */
04095    void mat_down()
04096 /* ----------------------------- */
04097 {
04098    int old;
04099 
04100    old = mat;
04101    mat--;
04102    if (mat < 1) mat = 1;
04103    else if (mat > MAT_MAX) mat = MAT_MAX;
04104    if (mat!= old) {
04105       init_mat();
04106       RWC_framehide = 0 ;
04107       Put_image(Im_Nr);
04108       redraw_graph();
04109       DrawSubWindow();
04110    }
04111 }
04112 
04113 /* ----------------------------- */   /* increase matrix and redraw  */
04114    void mat_up()
04115 /* ----------------------------- */
04116 {
04117    int old;
04118 
04119    old = mat;
04120    mat++;
04121    if (mat < 1) mat = 1;
04122    else if (mat > MAT_MAX) mat = MAT_MAX;
04123    if (mat!= old) {
04124       init_mat();
04125       RWC_framehide = 0 ;
04126       Put_image(Im_Nr);
04127       redraw_graph();
04128       DrawSubWindow();
04129    }
04130 }
04131 
04132 /* ----------------------------- */   /* initialize matrix stuff  */
04133    void init_mat()
04134 /* ----------------------------- */
04135 {
04136    gx = RWC_GX_MAX / mat;
04137    gy = RWC_GY_MAX / mat;
04138    for (i=0;i<mat;i++) {
04139      for (j=0;j<mat;j++) {
04140            xorigin[i][j] = mdx1 + i * gx;
04141            yorigin[i][j] = mdy1 + j * gy;
04142          }
04143    }
04144    xc = mat/2;
04145    yc = (mat-1)/2;
04146 }
04147 
04148 /* ----------- */
04149    init_grid()
04150 /* ----------- */
04151 {
04152    grid_far[GRID_NUM]   = grid_far[0] = 2;
04153    grid_far[GRID_NUM+1] = grid_far[1] = 5.;
04154    grid_far[GRID_NUM+2] = grid_far[2] = 10.;
04155    grid_far[GRID_NUM+3] = grid_far[3] = 20.;
04156    grid_far[GRID_NUM+4] = grid_far[4] = 50.;
04157    grid_far[GRID_NUM+5] = grid_far[5] = 100.;
04158    grid_far[GRID_NUM+6] = grid_far[6] = 200.;
04159    grid_far[GRID_NUM+7] = grid_far[7] = 500.;
04160    grid_index = 3;
04161 }
04162 
04163 /* ----------------------------- */   /* decrease grid spacing and redraw  */
04164    void grid_down()
04165 /* ----------------------------- */
04166 {
04167    int old;
04168 
04169    old = grid_index;
04170    grid_index--;
04171    if (grid_index < 0) grid_index = 0;
04172    if (grid_index!= old) {
04173       redraw_graph();
04174       DrawSubWindow();
04175    }
04176 }
04177 
04178 /* ----------------------------- */   /* increase grid spacing and redraw  */
04179    void grid_up()
04180 /* ----------------------------- */
04181 {
04182    int old;
04183 
04184    old = grid_index;
04185    grid_index++;
04186    if (grid_index >= GRID_NUM) grid_index = GRID_NUM - 1;
04187    if (grid_index!= old) {
04188       redraw_graph();
04189       DrawSubWindow();
04190    }
04191 }
04192 
04193 /* ------------ */
04194    init_const()
04195 /* ------------ */
04196 {
04197    iscale = 4;
04198    auto_scale = .4;
04199 
04200    xpoint = im_size/2;
04201    ypoint = im_size/2;
04202 
04203    xspace = 5;
04204    yspace = 20;
04205    mytxt = 20;
04206    mdx1   = GL_DLX + 1;
04207    mdy1   = GB_DLY + 1;
04208    idx   = GL_DLX + RWC_GX_MAX + GR_DLX;
04209    idy   = GB_DLY + RWC_GY_MAX + GT_DLY;
04210    mark = 1;
04211    color_index = 0;
04212    mat = 3;
04213    init_mat();
04214 }
04215 
04216 /* ------------------------------  resize graph window */
04217    void redo_graph_window(xs, ys)
04218    int xs, ys;
04219 /* ------------------------------ */
04220 {
04221    iWIDE = xs; iHIGH = ys;
04222    idx = xs;   idy = ys;
04223    RWC_GX_MAX = idx - GL_DLX - GR_DLX;
04224    RWC_GY_MAX = idy - GB_DLY - GT_DLY;
04225    if( use_pixmap ) {
04226       XFreePixmap(theDisp, pxWind) ;
04227       pxWind = XCreatePixmap(theDisp, GWindow, iWIDE, iHIGH, Planes);
04228    }
04229    XMoveResizeWindow(theDisp, subWindow, 0, RWC_GY_MAX + GT_DLY, idx, GB_DLY);
04230    XMoveResizeWindow(theDisp, topWindow, 0, 0, idx, GT_DLY - 2);
04231    init_mat();
04232    redraw_graph();
04233 }
04234 
04235 /* ------------------------------------------------- Main link from main() C */
04236    void window_plane()
04237 /* --------------------------------------------------- */
04238 {
04239    int  i, out_loop = 0, tmpx;
04240 
04241    XGCValues   gcv;
04242 
04243    iWIDE = idx; iHIGH = idy;
04244 
04245     CreateGraphWindow(NULL, 0);      /* Set theWindow properties */
04246 /* subWindow, topWindow and keys stuff is here ------- vvvvvvv ------- AJ*/
04247 
04248     ffc = XGetDefault(theDisp, Xdef_Name, "FKeyFore");
04249     fbc = XGetDefault(theDisp, Xdef_Name, "FKeyBack");
04250 
04251     /* Set normal default colors */
04252     ForeColor = BlackPixel(theDisp, theScreen);
04253     BackColor = WhitePixel(theDisp, theScreen);
04254 
04255     FKeyFore =  ForeColor;
04256     FKeyBack =  BackColor;
04257 
04258     if ( (ffc != NULL) && XAllocNamedColor(theDisp, CMap, ffc, &xcsd, &xced));
04259     else if (XAllocNamedColor(theDisp, CMap, "blue", &xcsd, &xced));
04260     else    FatalError ("XAllocNamedColor problem. AJ");
04261     FKeyFore=xcsd.pixel;
04262 
04263     if ( (fbc != NULL) && XAllocNamedColor(theDisp, CMap, fbc, &xcsd, &xced));
04264     else if (XAllocNamedColor(theDisp, CMap, "cyan", &xcsd, &xced));
04265     else    FatalError ("XAllocNamedColor problem. AJ");
04266     FKeyBack=xcsd.pixel;
04267 
04268    /** load key font from one of the candidate list **/
04269 
04270    tfont = XGetDefault(theDisp, Xdef_Name , "KeyFont");
04271    if( tfont != NULL ) tfont_hopefuls[0] = tfont ;
04272    else                tfont_hopefuls[0] = KFONT ;
04273    { int ifont ;
04274      for( ifont=0 ; tfont_hopefuls[ifont] != NULL ; ifont++ ){
04275         kfontinfo = XLoadQueryFont(theDisp, tfont_hopefuls[ifont]) ;
04276         if( kfontinfo != NULL ) break ;
04277      }
04278      if( kfontinfo == NULL ){
04279          FatalError("Can't open any text font!\n") ;
04280      }
04281      kfont = tfont_hopefuls[ifont] ;
04282 STATUS(kfont) ;
04283    }
04284     keyfont = kfontinfo->fid;
04285 
04286     minwide = XTextWidth(kfontinfo, "MMMM", 4);
04287     keyhigh = kfontinfo->ascent + 7;
04288     for (i=0; i<N_KEYS; i++) {
04289        tmpx = XTextWidth(kfontinfo, xtkeys[i].st, strlen(xtkeys[i].st));
04290        keywide[i] = max(minwide, tmpx) + 2;
04291     }
04292 
04293     gcv.foreground = FKeyFore;
04294     gcv.function = GXcopy;
04295     gcv.font = keyfont;
04296     Fkeygc = XCreateGC(theDisp, GWindow, GCForeground|GCFunction|GCFont, &gcv);
04297 
04298     gcv.function = GXinvert;
04299     gcv.plane_mask = FKeyFore ^ FKeyBack;
04300     Fkeyigc = XCreateGC(theDisp, GWindow, GCFunction|GCPlaneMask, &gcv);
04301 
04302 STATUS("  calling Setup_subWindow()") ;
04303     Setup_subWindow();
04304 
04305 STATUS("  calling Setup_topWindow()") ;
04306     Setup_topWindow();
04307 
04308 STATUS("  calling Setup_keys()") ;
04309     Setup_keys();
04310 
04311 /* SUbWindow, topWindow and keys stuff is here ------- ^^^^^^^ ------- AJ*/
04312 
04313                          /* Make dummy window for text and graphic entry */
04314 
04315 STATUS("  making Pixmap") ;
04316    if( use_pixmap )
04317       pxWind = XCreatePixmap(theDisp, GWindow, iWIDE, iHIGH, Planes);
04318 
04319    New_Cursor(theDisp, GWindow, XC_left_ptr, "blue", "yellow"); /* cursor */
04320 
04321    /* Text color and font */
04322 
04323    XSelectInput(theDisp, GWindow, ExposureMask | KeyPressMask
04324                  | ButtonPressMask | StructureNotifyMask);
04325    XMapWindow(theDisp,GWindow);         /* Show window first time */
04326    XMapSubwindows(theDisp, GWindow);    /* All keys stuff */
04327 
04328 
04329    for (i = 0; i < N_KEYS+2; i++) exp_done[i] = 0;
04330 
04331    while (1) {
04332       Window wind;
04333 
04334       XNextEvent(theDisp, &first_event);
04335                                           /* Wait for window on */
04336       switch (first_event.type) {
04337          case Expose: {
04338             XExposeEvent *exp_event = (XExposeEvent *) &first_event;
04339             wind = exp_event->window;
04340 
04341             if (wind ==   GWindow)
04342                exp_done[N_KEYS] = 1;
04343             else if (wind == subWindow) {
04344 STATUS("  calling DrawSubWindow()") ;
04345                DrawSubWindow();
04346                exp_done[N_KEYS+1] = 1;
04347             }
04348             else if (wind == topWindow) {
04349 STATUS("  calling DrawTopWindow()") ;
04350                DrawTopWindow();
04351                exp_done[N_KEYS+2] = 1;
04352             }
04353             else {
04354                for (i=0; i < N_KEYS; i++) {
04355                   if (wind == key[i].wid) {
04356 STATUS("  calling DrawKey(i)") ;
04357                      DrawKey(i);
04358                      exp_done[i] = 1;
04359                   }
04360                }
04361             }
04362             out_loop = exp_done[N_KEYS] * exp_done[N_KEYS+1]
04363                                         * exp_done[N_KEYS+2];
04364             for (i = 0; i < N_KEYS; i++)  out_loop *= exp_done[i];
04365             if (out_loop){
04366                return;
04367 STATUS("leaving window_plane()") ;
04368             }
04369             Allow_smaller_gr(Argc, Argv);
04370          }
04371          break;
04372 
04373          default:                /* ignore unexpected events */
04374          break;
04375       }
04376    }
04377 STATUS("leaving window_plane()") ;
04378 }
04379 
04380 /* ----------------- */
04381    Setup_subWindow()
04382 /* ----------------- */
04383 {
04384    unsigned long white;
04385 
04386    if (!(XAllocNamedColor(theDisp, CMap, "white", &any_col, &rgb_col)))
04387    FatalError ("XAllocNamedColor problem. AJ in Setup_subWindow()");
04388    white = any_col.pixel;
04389 
04390    sub_W_x = idx;
04391    sub_W_y = GB_DLY;
04392    subWindow = XCreateSimpleWindow(theDisp, GWindow, 0, RWC_GY_MAX + GT_DLY,
04393                      sub_W_x, sub_W_y, 1, white, white);
04394    XSelectInput(theDisp, subWindow, ExposureMask | ButtonPressMask |
04395                   ButtonReleaseMask);
04396 }
04397 
04398 /* --------------- */ /* Draw subWindow containing text info */
04399    void
04400    DrawSubWindow()
04401 /* --------------- */
04402 {
04403    float   diff_prcnt, f0, f1, f2;
04404    int     str_x = 5, x, y, loc, i;
04405 
04406    line_color("white");
04407    XFillRectangle(theDisp, subWindow, theGC, 0, 0, idx, GB_DLY);
04408 
04409    sprintf (strp,"Im. rot.");
04410    subW_TXT(str_x, 35, strp);
04411    sprintf (strp,"clockwise");
04412    subW_TXT(str_x, 20, strp);
04413    sprintf(strp, "%d*90 deg.", rot_nr);
04414    subW_TXT(str_x,  5, strp);
04415    str_x += XTextWidth(mfinfo ,"clockwise", strlen("clockwise")) + 30;
04416 
04417    sprintf (strp,"X: %d", xpoint);
04418    subW_TXT(str_x, 28, strp);
04419    sprintf (strp,"Y: %d", ypoint);
04420    subW_TXT(str_x, 13, strp);
04421    str_x += XTextWidth(mfinfo, "X: 000", strlen("X: 000")) + 20;
04422 
04423    if( SIZ(Im_Nr) == ar_size ){
04424       int cenval = SAR(Im_Nr)[ypoint*im_size + xpoint] ;
04425 
04426       if ( grid_timed && (FT_grid == GRID_NUM) ) {
04427          f0 = (float) (Im_Nr+1) / grid_far[FT_grid];
04428          sprintf (strp,"Pix. value:%6d at im #%d  %5.2f Hz",
04429                         cenval, Im_Nr+1, f0);
04430       }
04431       else
04432          sprintf (strp,"Pix. value: %d at im #%d", cenval, Im_Nr+1);
04433       subW_TXT(str_x, 20, strp);
04434       loc = str_x;
04435 
04436       if ( grid_timed && (FT_grid == GRID_NUM) ) {
04437          f0 = grid_coef * grid_far[grid_index + FT_grid] / grid_far[FT_grid];
04438          sprintf (strp,"Grid:%5.2f Hz", f0);
04439       }
04440       else
04441          sprintf (strp,"Grid:%g", grid_coef * grid_far[grid_index + FT_grid]);
04442       subW_TXT(str_x, 35, strp);
04443 
04444       str_x += XTextWidth(mfinfo, "Grid:00000f Hz",
04445                            strlen("Grid:00000f Hz")) + 20;
04446       sprintf(strp, "Num: %d", npoints);
04447       subW_TXT(str_x, 35, strp);
04448 
04449       if ( AJ_sigma > 0. ) {
04450          sprintf(strp, "Sig: %g", AJ_sigma);
04451          subW_TXT(GL_DLX + 440, 5, strp);
04452       }
04453 
04454       if( Im_Nr < npoints ){
04455          i = ypoint*im_size + xpoint;
04456          if ( diff_im) {
04457             if ( avr_grp ) {
04458                diff_prcnt = (float) (200 * (av_ar[i] - ref_ar[i]))
04459                                  / (float) (av_ar[i] + ref_ar[i]);
04460             }
04461             else {
04462                diff_prcnt = (float) (200 * (val[xc][yc][Im_Nr] - ref_ar[i]))
04463                                  / (float) (val[xc][yc][Im_Nr] + ref_ar[i]);
04464             }
04465             sprintf(strp, "Deviation from ref base: %.2f%%", diff_prcnt);
04466             txt_color("red");
04467             subW_TXT(loc, 5, strp);
04468             txt_color("black");
04469 
04470          } else if( avr_grp ){  /** RWCox: 4 March 1996 **/
04471 
04472             sprintf(strp, "Averaged pixel: %d",
04473                     av_ar[ypoint*im_size + xpoint] ) ;
04474 
04475             if( mat > 1 ){  /** RWCox: 2 Aug 1996 **/
04476                int ix,iy , xtemp,ytemp , index ;
04477                float sum = 0.0 ;
04478                for( ix=0 ; ix < mat ; ix++ ){
04479                   xtemp = xpoint + ix - xc;
04480                   if (xtemp < 0)        xtemp += im_size;
04481                   if (xtemp >= im_size) xtemp -= im_size;
04482                   for( iy=0 ; iy < mat ; iy++ ){
04483                      ytemp = ypoint - iy + yc;
04484                      if (ytemp < 0)        ytemp += im_size;
04485                      if (ytemp >= im_size) ytemp -= im_size;
04486                      index = ytemp * im_size + xtemp;
04487                      sum  += av_ar[index] ;
04488                   }
04489                }
04490                sum /= (mat*mat) ;
04491                ix   = strlen(strp) ;
04492                sprintf(strp+ix , " [%.1f]" , sum ) ;
04493             }
04494 
04495             txt_color("red");
04496             subW_TXT(loc, 5, strp);
04497             txt_color("black");
04498          } /* end of pure average */
04499          else {
04500             f1 = f0 = 0.;
04501             for (i=0; i < npoints; i++) f0 += val[xc][yc][i];
04502             f0 = f0 / (float) npoints;
04503             for (i=0; i < npoints; i++) {
04504                f2 = (float) val[xc][yc][i] - f0;
04505                f1 += f2 * f2;
04506             }
04507 
04508             f1 = f1 / (float) npoints;
04509             f1 = sqrt(f1);
04510             sprintf(strp, "Avr: %.1f, Std dev: %.1f", f0, f1);
04511             txt_color("blue");
04512             subW_TXT(loc, 5, strp);
04513             txt_color("black");
04514          }
04515 
04516          x = xorigin[xc][yc] + Im_Nr*gx/(npoints-1);
04517          y = iHIGH - yorigin[xc][yc] - plot[xc][yc][Im_Nr];
04518          v_point_x = x;
04519          Vpointer(x, 0);
04520          Cpointer(x, y );
04521 
04522       }  /* end if */
04523    }  /* end if */
04524    return ;
04525 }
04526 
04527 /* ----------------- */
04528    Setup_topWindow()
04529 /* ----------------- */
04530 {
04531    unsigned long white;
04532 
04533    if (!(XAllocNamedColor(theDisp, CMap, "white", &any_col, &rgb_col)))
04534    FatalError ("XAllocNamedColor problem. AJ in Setup_topWindow()");
04535    white = any_col.pixel;
04536 
04537    top_W_x = idx;
04538    top_W_y = GT_DLY - 2;
04539    topWindow = XCreateSimpleWindow(theDisp, GWindow, 0, 0,
04540                      top_W_x, top_W_y, 1, white, white);
04541    XSelectInput(theDisp, topWindow, ExposureMask);
04542 }
04543 
04544 /* --------------- */ /* Draw topWindow with text info */
04545    void
04546    DrawTopWindow()
04547 /* --------------- */
04548 {
04549    int  strwide , xmin , xleft ;
04550    char *str = "Differential Image";
04551    char str_fim[128] ;
04552 
04553    line_color("white");
04554    XFillRectangle(theDisp, topWindow, theGC, 0, 0, idx, top_W_y);
04555 
04556    txt_color("black");
04557 STATUS("   about to draw T_name") ;
04558    XDrawString(theDisp, topWindow, txtGC, 12,
04559                top_W_y - 5, T_name, strlen(T_name));
04560 STATUS("   finished drawing T_name") ;
04561 #ifdef DEBUG
04562   sleep(1) ;
04563 #endif
04564 
04565    xmin = 3 + 12 + XTextWidth(mfinfo,T_name,strlen(T_name)) ;
04566 
04567    if ( diff_im ) {
04568       txt_color("red");
04569       strwide = XTextWidth(mfinfo,str,strlen(str));
04570       xleft   = GL_DLX + (RWC_GX_MAX-strwide)/2 ;
04571       xleft   = MAX(xmin,xleft) ;
04572       XDrawString(theDisp, topWindow, txtGC,
04573                   xleft , top_W_y - 5, str, strlen(str));
04574       txt_color("black");
04575    } else if( RWC_do_overfim && RWC_ideal != NULL ){
04576 
04577       sprintf( str_fim , "%s %s:ref=%s thresh=%5.3f #ort=%d #pol=%d",
04578                LSQ_fimcode[LSQ_code] , DFILT_fimcode[DFILT_code] ,
04579                RWC_ideal->fname , RWC_pcthresh , RWC_numort,RWC_polort ) ;
04580 
04581       if( FIM_pressed ) txt_color("blue") ;
04582       else              txt_color("red");
04583 
04584       if( FFT_pressed ) txt_color("blue") ;
04585       else              txt_color("red");
04586 
04587       strwide = XTextWidth(mfinfo,str_fim,strlen(str_fim));
04588       xleft   = GL_DLX + (RWC_GX_MAX-strwide)/2 ;
04589       xleft   = MAX(xmin,xleft) ;
04590       XDrawString(theDisp, topWindow, txtGC,
04591                   xleft , top_W_y - 5, str_fim, strlen(str_fim) );
04592       txt_color("black");
04593    }
04594 #ifndef KILL_COPYRIGHT
04595    else {
04596       char * str_cpy1 = COPYRIGHT_STRING ;
04597       char * str_cpy2 = " 1994 Medical College of Wisconsin" ;
04598       int wide1 , wide2 ;
04599 
04600       wide1 = XTextWidth( mfinfo , str_cpy1 , strlen(str_cpy1) ) ;
04601       wide2 = XTextWidth( mfinfo , str_cpy2 , strlen(str_cpy2) );
04602 
04603       xleft = GL_DLX + (RWC_GX_MAX-(wide1+wide2))/2 ;
04604       xleft = MAX(xmin,xleft) ;
04605 
04606       txt_color("cyan");
04607 
04608       XDrawString(theDisp, topWindow, txtGC,
04609                   xleft      , top_W_y - 5, str_cpy1, strlen(str_cpy1) );
04610       XDrawString(theDisp, topWindow, txtGC,
04611                   xleft+wide1, top_W_y - 5, str_cpy2, strlen(str_cpy2) );
04612 
04613       txt_color("black");
04614    }
04615 #endif
04616 }
04617 
04618 /* ------------ */
04619    Setup_keys()
04620 /* ------------ */
04621 {
04622    int i;
04623 
04624    key = &xtkeys[0];
04625 
04626    for (i=0; i < N_KEYS; i++) {
04627        key[i].x = PADDINGW;
04628        key[i].y = KEY_1_Y + i*(keyhigh + PADDINGH);
04629        key[i].width = keywide[i];
04630        key[i].height = keyhigh;
04631 
04632        key[i].fore=FKeyFore;
04633        key[i].back=FKeyBack;
04634 
04635        key[i].wid=XCreateSimpleWindow(theDisp, GWindow, key[i].x, key[i].y,
04636                                       key[i].width, key[i].height, 1,
04637                                       key[i].fore, key[i].back);
04638        New_Cursor(theDisp,  key[i].wid, XC_left_ptr, "yellow", "red");
04639        XSelectInput(theDisp, key[i].wid, ExposureMask | ButtonPressMask |
04640                   ButtonReleaseMask | EnterWindowMask | LeaveWindowMask);
04641    }
04642 }
04643 
04644 /* --------------- */
04645    DrawKey(keynum)
04646    int keynum;
04647 /* --------------- */
04648 {
04649    char        *str;
04650    int         strwide;
04651    struct _key *kp;
04652    GC          AJkeygc; /* AJ new for proper color of the text */
04653 
04654    if( keynum < 0 || keynum >= N_KEYS ) return 0 ;
04655 
04656    kp = &key[keynum];
04657    str = kp->st;
04658    strwide = XTextWidth(kfontinfo,str,strlen(str));
04659 
04660    AJkeygc=Fkeygc;
04661 
04662    XClearWindow(theDisp,kp->wid) ;
04663 
04664    XDrawString(theDisp ,kp->wid, AJkeygc, (kp->width-strwide)/2,
04665                1 + kfontinfo->ascent, str, strlen(str));
04666 }
04667 
04668 /* ----------------- */
04669    InvertKey(keynum)
04670    int keynum;
04671 /* ----------------- */
04672 {
04673    struct _key *kp;
04674    GC           AJkeyigc;
04675 
04676    if( keynum < 0 || keynum >= N_KEYS ) return 0 ;
04677 
04678    AJkeyigc = Fkeyigc;
04679    kp = &key[keynum];
04680 
04681    XFillRectangle(theDisp, kp->wid, AJkeyigc, 0, 0, kp->width, kp->height);
04682 }
04683 
04684 /* ---------------- */
04685    LetGoKey(keynum)
04686    int keynum;
04687 /* ---------------- */
04688 {
04689    if( keynum < 0 || keynum >= N_KEYS ) return 0 ;
04690    InvertKey(keynum);
04691    (*(key[keynum].fun))(keynum);
04692 }
04693 
04694 /* ------------- */
04695    Ims_rot(ikey)
04696    int ikey;
04697 /* ------------- */
04698 {
04699    register int i, j, k, l, m, n, s;
04700 
04701    old_im = -1;            /* to avoid faster reload of not rotated image */
04702 
04703    if( rot_direct == 0 ){            /* change key label */
04704       kROT_doall = ! kROT_doall ;
04705       xtkeys[kROT].st = (kROT_doall) ? (key_kROT_all) : (key_kROT_one) ;
04706       DrawKey(kROT) ;
04707       return 0 ;
04708    }
04709 
04710    if( rot_direct == 1 || rot_direct == -1 ){
04711       RWC_do_overfim = 0 ;
04712       if( RWC_imover != NULL ) { free(RWC_imover) ; RWC_imover = NULL ; }
04713       RWC_framehide = 0 ;
04714    } else {
04715       fprintf(stderr,"\n*** illegal rot_direct in Ims_rot() ***\n") ;
04716       XBell(theDisp,100) ;
04717       return 0 ;
04718    }
04719 
04720    if ( rot_direct == 1 ) {                         /* clockwise rotation */
04721       nowim = SAR(Im_Nr) ; k = DIM(Im_Nr) ; l = k-1 ; s = SIZ(Im_Nr) ;
04722       for (i=0; i < k; i++) {          /* rotate and redisplay actual one */
04723          m = i * k;
04724          for (j=0; j < k; j++)
04725             a_rot[m+j] = nowim[(l-j)*k+i];
04726       }
04727       for (i=0; i < s; i++) nowim[i] = a_rot[i];
04728 
04729       if( ! kROT_doall ){
04730          Put_image(Im_Nr ) ;
04731          return 0 ;
04732       }
04733 
04734       if ( diff_im && Im_Nr < npoints ) { /* rotate reference array too */
04735          for (i=0; i < k; i++) {
04736             m = i * k;
04737             for (j=0; j < k; j++)
04738                a_rot[m+j] = ref_ar[(l-j)*k+i];
04739          }
04740          for (i=0; i < s; i++) ref_ar[i] = a_rot[i];
04741       }
04742       if ( !avr_grp ) Put_image(Im_Nr);         /* put single image here */
04743                                                      /* rotate other data */
04744       for (n=0; n < N_im; n++) {
04745          nowim = SAR(n) ; k = DIM(n) ; l = k-1 ; s = SIZ(n) ;
04746          if ( n != Im_Nr ) {
04747             for (i=0; i < k; i++) {
04748                m = i * k;
04749                for (j=0; j < k; j++)
04750                   a_rot[m+j] = nowim[(l-j)*k+i];
04751             }
04752             for (i=0; i < s; i++) nowim[i] = a_rot[i];
04753          }
04754       }
04755       rot_nr += rot_direct;
04756       if ( avr_grp ) Put_image(Im_Nr);  /* put average image after all rot */
04757    }
04758    else if ( rot_direct == -1 ) {            /* counterclockwise rotation */
04759       nowim = SAR(Im_Nr) ; k = DIM(Im_Nr) ; l = k-1 ; s = SIZ(Im_Nr) ;
04760       for (i=0; i < k; i++) {          /* rotate and redisplay actual one */
04761          m = i * k;
04762          for (j=0; j < k; j++)
04763             a_rot[m+j] = nowim[(j+1)*k-i-1];
04764       }
04765       for (i=0; i < s; i++) nowim[i] = a_rot[i];
04766 
04767       if( ! kROT_doall ){
04768          Put_image(Im_Nr ) ;
04769          return 0 ;
04770       }
04771 
04772       if ( diff_im && Im_Nr < npoints ) {  /* rotate reference array too */
04773          for (i=0; i < k; i++) {
04774             m = i * k;
04775             for (j=0; j < k; j++)
04776                a_rot[m+j] = ref_ar[(j+1)*k-i-1];
04777          }
04778          for (i=0; i < s; i++) ref_ar[i] = a_rot[i];
04779       }
04780       if ( !avr_grp ) Put_image(Im_Nr);         /* put single image here */
04781                                                      /* rotate other data */
04782       for (n=0; n < N_im; n++) {
04783          nowim = SAR(n) ; k = DIM(n) ; l = k-1 ; s = SIZ(n) ;
04784          if ( n != Im_Nr ) {
04785             for (i=0; i < k; i++) {
04786                m = i * k;
04787                for (j=0; j < k; j++)
04788                   a_rot[m+j] = nowim[(j+1)*k-i-1];
04789             }
04790             for (i=0; i < s; i++) nowim[i] = a_rot[i];
04791          }
04792       }
04793       rot_nr += rot_direct;
04794       if ( avr_grp ) Put_image(Im_Nr);  /* put average image after all rot */
04795    }
04796 
04797         if( rot_nr ==  3 ) rot_nr = -1 ;
04798    else if( rot_nr == -3 ) rot_nr =  1 ;
04799 
04800    redraw_graph();
04801    DrawSubWindow();
04802 }
04803 
04804 /* ----------------- */
04805    Smooth_line(ikey)
04806    int ikey;
04807 /* ----------------- */
04808 {
04809    int  i, x, y, hx;
04810    char *cpt, str[100];
04811    float fval, fmax, f0, f1, f2;
04812    XWindowAttributes  wat;
04813    Window             ww;
04814 
04815    if ( txtW_ON ) {
04816       XBell(theDisp, 100); return(2);
04817    }
04818 
04819    i = (MAX_SMOOTH - 1) / 10; /* +- 5 sigma range */
04820    fmax = i;
04821    sprintf(str, "Enter sigma value [.1-%d]:", i);
04822    txtW_ON = 1;
04823 
04824    x = 50 + GL_DLX;
04825    y = 50 + GT_DLY;
04826 
04827    strp[0] = ASC_NUL ;
04828    take_file_name(theDisp, GWindow , CMap, txtGC, mfinfo, x, y, strp, 41,
04829                   str, 0);
04830 
04831    fval = strtod( strp , &cpt ) ;
04832    if( *cpt != ASC_NUL || fval < .1 || fval > fmax ) {
04833       fprintf(stderr,
04834          "\n*** Sigma valule out of range [.1-%d] %s!\n" , (int) fmax, strp ) ;
04835       AJ_sigma = -1.;
04836       XBell(theDisp, 100);
04837    }
04838    else {
04839       AJ_sigma = fval ;
04840    }
04841    AJ_norm = 1.;
04842    if ( AJ_sigma > 0. ) {
04843       f2 = 0;
04844       AJ_nr = (int) (10.*AJ_sigma +.5);
04845       if ( AJ_nr%2 ) AJ_nr++;
04846       if ( AJ_nr < 4) AJ_nr = 4;
04847       hx = AJ_nr / 2;
04848       f0 = 1. / (2.* AJ_sigma  * AJ_sigma);
04849       for (i=0; i <= AJ_nr; i++) { /* make symmetrical gauss function */
04850          f1 = (float) ((i-hx)*(i-hx));
04851          AJ_gauss[i] = exp(-f1*f0);
04852          f2 += AJ_gauss[i];
04853       }
04854       if ( f2 != 0. ) AJ_norm = 1./ f2;
04855    }
04856 
04857    txtW_ON = 0;
04858    redraw_graph();
04859    DrawSubWindow();
04860 
04861    return(0);
04862 }
04863 
04864 /* ----------------- */
04865    get_fft_mag(fff)
04866    float *fff;
04867 /* ----------------- */
04868 {
04869    int  i, k, x, y, hx;
04870    char *cpt, str[100];
04871    float fval, fmax, fmin, f0, f1, f2, f3;
04872    int   max1;
04873    XWindowAttributes  wat;
04874    Window             ww;
04875 
04876    fmax = 100.;
04877    fmin = .01;
04878    if ( txtW_ON ) {
04879       XBell(theDisp, 100); return(2);
04880    }
04881 
04882    f0 = *fff / FFT_MAG;
04883    sprintf(str, "Enter new FT scale value [%g-%g]: %g", fmin, fmax, f0);
04884    txtW_ON = 1;
04885 
04886    x = 50 + GL_DLX;
04887    y = 50 + GT_DLY;
04888 
04889    strp[0] = ASC_NUL ;
04890    take_file_name(theDisp, GWindow , CMap, txtGC, mfinfo, x, y, strp, 46,
04891                   str, 0);
04892 
04893    fval = strtod( strp , &cpt ) ;
04894    if( *cpt != ASC_NUL || fval < fmin || fval > fmax ) {
04895       fprintf(stderr,
04896          "\n*** FT scale value out of range [%g-%g]: %s!\n", fmin, fmax, strp);
04897       XBell(theDisp, 100);
04898       txtW_ON = 0;
04899       redraw_graph();
04900       DrawSubWindow();
04901       return (0);
04902    }
04903    else {
04904       *fff = fval * FFT_MAG;
04905    }
04906    f0 = *fff;
04907    for (i=0; i < FT_disp; i++) {
04908       for (j=0; j < ar_size; j++) {
04909          f1 = c_arr[i+1+j*FT_dim].r; /* no zero component here */
04910          f2 = c_arr[i+1+j*FT_dim].i;
04911          f3 = f0 * sqrt(f1*f1 + f2*f2);
04912          if ( f3 > 32767. ) f3 = 32767.;
04913          SAR(i)[j] = f3;
04914       }
04915    }
04916    min1 =  32767;
04917    max1 = -32768;
04918    for (k=0; k < npoints; k++) { /* find global min and max */
04919       nowim = SAR(k) ;
04920       for (i=0; i < ar_size; i++) {
04921          if ( nowim[i] < min1 ) min1 = nowim[i] ;
04922          if ( nowim[i] > max1 ) max1 = nowim[i] ;
04923       }
04924    }
04925    del1 = max1 - min1;
04926    if (del1 < 1.) del1 = 1.;
04927    coef1 = ( (float) NC - 1.) / del1;
04928 
04929    old_im = -1;
04930    Put_image(Im_Nr);                      /* reload actual image */
04931    txtW_ON = 0;
04932    redraw_graph();
04933    DrawSubWindow();
04934 
04935    return(0);
04936 }
04937 /* ------------ */
04938    FFT_action()
04939 /* ------------ */
04940 {
04941    MRI_IMAGE **MM;
04942    int i;
04943    float *VV;
04944 
04945    if ( Im_Nr >= npoints) {
04946       Im_Nr = 0;
04947       XClearWindow(theDisp, GWindow);
04948       Put_image(Im_Nr);
04949       DrawSubWindow();
04950       DrawTopWindow();
04951       discard(KeyPressMask, &event);
04952    }
04953 
04954    if( FFT_pressed ) {                /* second press - back to normal graph */
04955       FT1_pressed = 0;
04956       FFT_pressed = 0 ;
04957       FT_graph_on = 0;
04958       xtkeys[kFFT].st = key_kFFT_FFT;
04959       DrawKey(kFFT) ;                  /* restore key label */
04960       FT2_stat = 0;
04961       z_imL = z_im1 = 0;
04962       if ( FT_done ) {
04963          int   mm, min_im = 0;
04964          float ff;
04965 
04966          if ( undo_buf != NULL ) {
04967             free(undo_buf);
04968             act_undo = -1;
04969          }
04970          if ( undo_ref != NULL ) {
04971             free(undo_ref);
04972             ref_undo = -1;
04973          }
04974          if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
04975             VV = RWC_ideal->ts; RWC_ideal->ts = T_ref; T_ref = VV;
04976          }
04977          MM = allim;     allim = t_allim;   t_allim = MM;
04978          mm = N_im;       N_im = t_N_im;     t_N_im = mm;
04979          mm = npoints; npoints = t_points; t_points = mm;
04980          mm = min1;       min1 = t_min1;     t_min1 = mm;
04981          ff = coef1;     coef1 = t_coef1;   t_coef1 = ff;
04982          if ( grid_timed ) if ( grid_coef < .5 ) grid_coef = GRID_COEF;
04983          Im_Nr = min_im;
04984          FT_grid = 0;
04985          redraw_graph();   /* draw frame and text in it */
04986          DrawSubWindow();
04987          DrawTopWindow();
04988          old_im = -1;
04989          Put_image(0);                      /* put the first image */
04990       }
04991       if ( cancell_FT ) {
04992          cancell_FT = 0;
04993          FT_done = 0;
04994          free(c_arr);
04995          c_arr = NULL;
04996          free(r_arr);
04997          r_arr = NULL;
04998       }
04999       FT3_stat = FT_done;
05000       xtkeys[kFT1].st = key_kFT1[FT1_pressed];
05001       xtkeys[kFT2].st = key_kFT2[FT2_stat];
05002       xtkeys[kFT3].st = key_kFT3[FT3_stat];
05003       for(i=FFT_first_key; i <= FFT_last_key; i++)
05004          XUnmapWindow(theDisp,  key[i].wid);  /* second press */
05005    }
05006    else {                            /* first press */
05007       FFT_pressed  = 1;
05008       xtkeys[kFFT].st = key_kFFT_noFT;
05009       DrawKey(kFFT);
05010       FT3_stat = FT_done;
05011       if ( FT_done ) {
05012          int   mm, min_im = 0;
05013          float ff;
05014 
05015          for(i=FFT_first_key; i <= FFT_last_key; i++)
05016             XMapWindow  (theDisp,  key[i].wid);  /* first press & FFT done */
05017 
05018          FT_graph_on = 1;
05019          if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
05020             VV = RWC_ideal->ts; RWC_ideal->ts = T_ref; T_ref = VV;
05021          }
05022          MM = allim;     allim = t_allim;   t_allim = MM;
05023          mm = N_im;       N_im = t_N_im;     t_N_im = mm;
05024          mm = npoints; npoints = t_points; t_points = mm;
05025          mm = min1;       min1 = t_min1;     t_min1 = mm;
05026          ff = coef1;     coef1 = t_coef1;   t_coef1 = ff;
05027          FT_grid = GRID_NUM;
05028          if ( grid_timed ) if ( grid_coef > 2. ) grid_coef = 1. / GRID_COEF;
05029          Im_Nr = min_im;
05030          redraw_graph();   /* draw frame and text in it */
05031          DrawSubWindow();
05032          DrawTopWindow();
05033          old_im = -1;
05034          Put_image(0);                      /* put the first image */
05035       }
05036       else {
05037          for(i=FFT_first_key + 1; i <= FFT_last_key; i++)
05038             XMapWindow  (theDisp,  key[i].wid);  /* first press & no FFT */
05039       }
05040    }
05041 }
05042 
05043 /* ------------------- */
05044    int
05045    FFT_selection(ikey)
05046    int ikey;
05047 /* ------------------- */
05048 {
05049    int  i, j, k, ii, mm, nn, index;
05050    int  fun_modified;
05051 
05052    fun_modified = 0;
05053 
05054    switch( ikey ) {
05055       /* toggle edit Function - end of Edit button */
05056       case kFT1:
05057          FT1_pressed = 1 - FT1_pressed;
05058          InvertKey(kFT1);
05059          xtkeys[kFT1].st = key_kFT1[FT1_pressed];
05060          if ( FT1_pressed ) {                    /* edit mode */
05061             FT2_stat = 1;
05062             z_imL = z_im1 = 0;
05063             FT3_stat = 2;
05064             xtkeys[kFT2].st = key_kFT2[FT2_stat];
05065             xtkeys[kFT3].st = key_kFT3[FT3_stat];
05066          }
05067          else {
05068             FT2_stat = 0;
05069             FT3_stat = FT_done;
05070             z_imL = z_im1 = 0;
05071             xtkeys[kFT2].st = key_kFT2[FT2_stat];
05072             xtkeys[kFT3].st = key_kFT3[FT3_stat];
05073          }
05074          DrawKey(kFT1);
05075          DrawKey(kFT2);
05076          DrawKey(kFT3);
05077       break ;  /* end of ikey=kFT1 */
05078 
05079       case kFT2:
05080          /* make FFT - when not in edit and FT2 = "FT" */
05081          if ( (FT1_pressed == 0) && (FT2_stat == 0) ) {
05082             register float f0, f1, f2, f3;
05083             int min_im = 0, max1;
05084             int Fnx = allim[0]->nx;
05085             int Fny = allim[0]->ny;
05086 
05087             if ( c_arr == NULL ) {
05088                FT_dim = 2;
05089                while ( FT_dim < npoints ) FT_dim *= 2;
05090                FT_disp = FT_dim / 2;
05091                im_f = min(3, dec_indx(FT_disp)-1);  /* 2d index in formt[][] */
05092                FT_size = FT_dim * ar_size;
05093                c_arr = (complex *) malloc(sizeof(complex) * FT_size);
05094                if( c_arr == NULL ){
05095                   fprintf(stderr,"\n*** cannot malloc c_arr\a\n") ;
05096                   XBell(theDisp, 100); return(1);
05097                }
05098                /* load complex array for FFT */
05099                for (i=0; i < ar_size; i++) {
05100                   ii = i * FT_dim;
05101                   for (j=0; j < npoints; j++) {
05102                      c_arr[ii+j].r = SAR(j)[i];
05103                      c_arr[ii+j].i = 0.;
05104                   }
05105                   for (j=npoints; j < FT_dim; j++) {
05106                      c_arr[ii+j].r = SAR(npoints-1)[i];
05107                      c_arr[ii+j].i = 0.;
05108                   }
05109                }
05110             }
05111             if ( r_arr == NULL ) {
05112                r_arr = (complex *) malloc(sizeof(complex) * FT_dim);
05113                if( r_arr == NULL ){
05114                   fprintf(stderr,"\n*** cannot malloc r_arr\a\n") ;
05115                   XBell(theDisp, 100); return(1);
05116                }
05117                /* load complex reference array for FFT */
05118                if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
05119                   for (j=0; j < npoints; j++) {
05120                      r_arr[j].r = RWC_ideal->ts[j];
05121                      r_arr[j].i = 0.;
05122                   }
05123                   for (j=npoints; j < FT_dim; j++) {
05124                      r_arr[j].r = RWC_ideal->ts[npoints-1];
05125                      r_arr[j].i = 0.;
05126                   }
05127                }
05128                else {
05129                   for (j=0; j < FT_dim; j++) {
05130                      r_arr[j].r = 0.;
05131                      r_arr[j].i = 0.;
05132                   }
05133                }
05134             }
05135             csfft( -1, FT_dim, r_arr);    /* FT of reference line */
05136             for (i=0; i < ar_size; i++) {
05137                if ( i%100 == 0 ) {
05138                   printf(".");
05139                   fflush(stdout);
05140                }
05141                ii = i * FT_dim;
05142                csfft( -1, FT_dim, &c_arr[ii]);
05143             }
05144             if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
05145                T_ref = RWC_ideal->ts;
05146                RWC_ideal->ts = NULL;
05147                RWC_ideal->ts = (float *) malloc( sizeof(float) * FT_disp);
05148                if( RWC_ideal->ts == NULL ) {
05149                   fprintf(stderr,
05150                      "\n*** cannot malloc RWC_ideal->ts for FT\a\n");
05151                   XBell(theDisp, 100);
05152                   DrawKey(kFT3);
05153                   return(2);
05154                }
05155             }
05156             t_allim = allim; t_N_im = N_im; t_points = npoints;
05157             N_im = npoints = FT_disp;
05158             allim = NULL;
05159             Im_Nr = min_im;
05160             allim = (MRI_IMAGE **) malloc( sizeof(MRI_IMAGE *) * FT_disp);
05161             if( allim == NULL ) {
05162                fprintf(stderr,"\n*** cannot malloc allim\a\n") ;
05163                XBell(theDisp, 100);
05164                DrawKey(kFT3);
05165                return(2);
05166             }
05167             for (i=0; i < FT_disp; i++) {
05168                allim[i] = mri_new( Fnx, Fny, MRI_short );
05169                if( allim == NULL ) {
05170                   fprintf(stderr,"\n*** cannot malloc allim[%d] in FT\a\n", i) ;
05171                   XBell(theDisp, 100); return(2);
05172                }
05173                sprintf(FT_name, formt[0][im_f], "FT", i+1);
05174                mri_add_name( FT_name, allim[i]);
05175             }
05176             XMapWindow  (theDisp,  key[FFT_first_key].wid); /* can edit now */
05177             f0 = fft_mag;
05178             for (i=0; i < FT_disp; i++) {
05179                for (j=0; j < ar_size; j++) {
05180                   f1 = c_arr[i+1+j*FT_dim].r; /* no zero component here */
05181                   f2 = c_arr[i+1+j*FT_dim].i;
05182                   f3 = f0 * sqrt(f1*f1 + f2*f2);
05183                   if ( f3 > 32767. ) f3 = 32767.;
05184                   SAR(i)[j] = f3;
05185                }
05186             }
05187             if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
05188                for (i=0; i < FT_disp; i++) {
05189                   f1 = r_arr[i+1].r; /* no zero component for reference too */
05190                   f2 = r_arr[i+1].i;
05191                   f3 = f0 * sqrt(f1*f1 + f2*f2);
05192                   if ( f3 > 32767. ) f3 = 32767.;
05193                   RWC_ideal->ts[i] = f3;
05194                }
05195             }
05196             t_min1 = min1; t_coef1 = coef1;
05197             min1 =  32767;
05198             max1 = -32768;
05199             for (k=0; k < npoints; k++) { /* find global min and max */
05200                nowim = SAR(k) ;
05201                for (i=0; i < ar_size; i++) {
05202                   if ( nowim[i] < min1 ) min1 = nowim[i] ;
05203                   if ( nowim[i] > max1 ) max1 = nowim[i] ;
05204                }
05205             }
05206             del1 = max1 - min1;
05207             if (del1 < 1.) del1 = 1.;
05208             coef1 = ( (float) NC - 1.) / del1;
05209 
05210             FT_grid = GRID_NUM;
05211             if ( grid_timed ) {
05212                f0 = 2. * (float) FT_disp / grid_far[0];
05213                grid_far[GRID_NUM]   = f0;
05214                grid_far[GRID_NUM+1] = 2.*f0;
05215                grid_far[GRID_NUM+2] = 5.*f0;
05216                if ( grid_coef > 2. ) grid_coef = 1. / GRID_COEF;
05217             }
05218 
05219             FT_graph_on = 1;
05220             redraw_graph();   /* draw frame and text in it */
05221             DrawSubWindow();
05222             DrawTopWindow();
05223             old_im = -1;
05224             Put_image(0);                      /* put the first image */
05225 
05226             FT3_stat = FT_done = 1;;
05227             xtkeys[kFT3].st = key_kFT3[FT3_stat];
05228             DrawKey(kFT3);
05229          }
05230          /* edit mode on and FT2 = "0..0" */
05231          else if ( (FT1_pressed == 1) && (FT2_stat == 1) ) {
05232             FT2_stat = 2;
05233             xtkeys[kFT2].st = key_kFT2[FT2_stat];
05234             DrawKey(kFT2);
05235          }
05236          else if ( (FT1_pressed == 1) && (FT2_stat == 2) ) {
05237             z_im1 = Im_Nr;
05238             FT2_stat = 3;
05239             xtkeys[kFT2].st = key_kFT2[FT2_stat];
05240             DrawKey(kFT2);
05241          }
05242          else if ( (FT1_pressed == 1) && (FT2_stat == 3) ) {
05243             int i, j, k, mm, nn;
05244 
05245             z_imL = Im_Nr + 1;
05246             /* swap order if last < first */
05247             if ( z_imL - z_im1 < 0) { 
05248                i = z_im1;
05249                z_im1 = z_imL;
05250                z_imL = i;
05251             }
05252             mm = act_undo + 1;
05253             act_undo += (z_imL - z_im1) * ar_size;
05254             undo_buf = AFREALL(undo_buf, struct _undo_buf,
05255                               (act_undo+1)*sizeof(struct _undo_buf) ); 
05256             if ( undo_buf != NULL ) {
05257                for ( k=z_im1, nn=mm; k < z_imL; k++, nn+=ar_size) { 
05258                   for ( i=0, j=nn; i < ar_size; j++, i++) {
05259                      undo_buf[j].im  = k;
05260                      undo_buf[j].pix = i;
05261                      undo_buf[j].r   = c_arr[i*FT_dim+k+1].r;
05262                      undo_buf[j].i   = c_arr[i*FT_dim+k+1].i;
05263                      undo_buf[j].r2  = c_arr[(i+1)*FT_dim-k-1].r;
05264                      undo_buf[j].i2  = c_arr[(i+1)*FT_dim-k-1].i;
05265                      SAR(k)[i]   = 0;
05266                      c_arr[i*FT_dim+k+1].r     = 0.;
05267                      c_arr[i*FT_dim+k+1].i     = 0.;
05268                      c_arr[(i+1)*FT_dim-k-1].r = 0.;
05269                      c_arr[(i+1)*FT_dim-k-1].i = 0.;
05270                   }
05271                }
05272             }
05273             if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
05274                mm = ref_undo + 1;
05275                ref_undo += (z_imL - z_im1);
05276                undo_ref = AFREALL(undo_ref, struct _undo_buf,
05277                               (ref_undo+1)*sizeof(struct _undo_buf) ); 
05278                if ( undo_ref != NULL ) {
05279                   for ( k=z_im1, j=mm; k < z_imL; k++, j++) { 
05280                      undo_ref[j].im  = k;
05281                      undo_ref[j].r   = r_arr[k+1].r;
05282                      undo_ref[j].i   = r_arr[k+1].i;
05283                      undo_ref[j].r2  = r_arr[FT_dim-k-1].r;
05284                      undo_ref[j].i2  = r_arr[FT_dim-k-1].i;
05285                      RWC_ideal->ts[k] = 0;
05286                      r_arr[k+1].r     = 0.;
05287                      r_arr[k+1].i     = 0.;
05288                      r_arr[FT_dim-k-1].r = 0.;
05289                      r_arr[FT_dim-k-1].i = 0.;
05290                   }
05291                }
05292             }
05293             redraw_graph() ;
05294             DrawSubWindow();
05295             old_im = -1;
05296             Put_image(Im_Nr);
05297             FT2_stat = 1;
05298             z_imL = z_im1 = 0;
05299             xtkeys[kFT2].st = key_kFT2[FT2_stat];
05300             DrawKey(kFT2);
05301          }
05302       break ;  /* end of ikey=kFT2 */
05303 
05304       /* make inv FFT */
05305       case kFT3:
05306          /* make inverse FFT */
05307          if ( (FT1_pressed == 0) && (FT_done == 1) ) {
05308             MRI_IMAGE **MM;
05309             int   mm, min_im = 0, max1;
05310             float ff;
05311             register float f0, f1, f2, f3, f4, fpi2;
05312             int Fnx = allim[0]->nx;
05313             int Fny = allim[0]->ny;
05314 
05315             im_f = min(3, dec_indx(npoints)-1);  /* 2d index in formt[][] */
05316 
05317             f0 = 1. / (float) FT_dim;
05318             for (i=0; i < ar_size; i++) {
05319                if ( i%100 == 0 ) {
05320                   printf(".");
05321                   fflush(stdout);
05322                }
05323                ii = i * FT_dim;
05324                csfft(1, FT_dim, &c_arr[ii]);
05325             }
05326             csfft(1, FT_dim, r_arr);
05327 
05328             MM = allim;     allim = t_allim;   t_allim = MM;
05329             mm = N_im;       N_im = t_N_im;     t_N_im = mm;
05330             mm = npoints; npoints = t_points; t_points = mm;
05331             if ( grid_timed ) if ( grid_coef < .5 ) grid_coef = GRID_COEF;
05332 
05333             fpi2 = .5 * PI;
05334             for (i=0; i < ar_size; i++) {
05335                ii = i * FT_dim;
05336                for (j=0; j < npoints; j++) {
05337                   f1 = c_arr[ii+j].r *= f0;;
05338                   f2 = c_arr[ii+j].i *= f0;;
05339                   f3 = sqrt(f1*f1 + f2*f2);
05340                   if ( f3 > 32767. ) f3 = 32767.;
05341                   if ( phase ) {
05342                      f4 = atan2(f2, f1);
05343                      if ( (f4 < fpi2) && (f4 > -fpi2) ) SAR(j)[i] =  f3;
05344                      else                               SAR(j)[i] = -f3;
05345                   }
05346                   else {
05347                      SAR(j)[i] = f3;
05348                   }
05349                }
05350             }
05351             if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
05352                for (j=0; j < npoints; j++) {
05353                   f1 = r_arr[j].r *= f0;;
05354                   f2 = r_arr[j].i *= f0;;
05355                   f3 = sqrt(f1*f1 + f2*f2);
05356                   if ( f3 > 32767. ) f3 = 32767.;
05357                   if ( phase ) {
05358                      f4 = atan2(f2, f1);
05359                      if ( (f4 < fpi2) && (f4 > -fpi2) ) RWC_ideal->ts[j] =  f3;
05360                      else                               RWC_ideal->ts[j] = -f3;
05361                   }
05362                   else {
05363                      RWC_ideal->ts[j] = f3;
05364                   }
05365                }
05366             }
05367             t_min1 = min1; t_coef1 = coef1;
05368             min1 =  32767;
05369             max1 = -32768;
05370             for (k=0; k < npoints; k++) { /* find global min and max */
05371                nowim = SAR(k) ;
05372                for (i=0; i < ar_size; i++) {
05373                   if ( nowim[i] < min1 ) min1 = nowim[i] ;
05374                   if ( nowim[i] > max1 ) max1 = nowim[i] ;
05375                }
05376             }
05377             del1 = max1 - min1;
05378             if (del1 < 1.) del1 = 1.;
05379             coef1 = ( (float) NC - 1.) / del1;
05380 
05381             Im_Nr = min_im;
05382             FT_grid = 0;
05383             redraw_graph();   /* draw frame and text in it */
05384             DrawSubWindow();
05385             DrawTopWindow();
05386             old_im = -1;
05387             Put_image(0);                      /* put the first image */
05388 
05389             for(i=FFT_first_key; i <= FFT_last_key; i++)
05390                XUnmapWindow(theDisp,  key[i].wid);  /* as second press */
05391 
05392             xtkeys[kFFT].st = key_kFFT_FFT;
05393             DrawKey(kFFT) ;                  /* restore key label */
05394             xtkeys[kFT1].st = key_kFT1[FT1_pressed];
05395             xtkeys[kFT2].st = key_kFT2[FT2_stat];
05396             xtkeys[kFT3].st = key_kFT3[FT3_stat];;
05397             FT1_pressed = 0;
05398             FFT_pressed = 0 ;
05399             FT_graph_on = 0;
05400             FT_done = 0;
05401             free(c_arr);
05402             c_arr = NULL;
05403          }
05404          /* edit mode on and FT3 pressed = "zero" */
05405          else if ( FT1_pressed == 1 ) {
05406             nn = act_undo + 1;
05407             act_undo += ar_size;
05408             undo_buf = AFREALL(undo_buf, struct _undo_buf,
05409                               (act_undo+1)*sizeof(struct _undo_buf) ); 
05410             if ( RWC_ideal != NULL  && RWC_ideal->len >= npoints ) {
05411                ref_undo += 1;
05412                undo_ref = AFREALL(undo_ref, struct _undo_buf,
05413                               (ref_undo+1)*sizeof(struct _undo_buf) ); 
05414                if ( undo_ref != NULL ) {
05415                   j = ref_undo;
05416                   undo_ref[j].im  = Im_Nr;
05417                   undo_ref[j].r   = r_arr[Im_Nr+1].r;
05418                   undo_ref[j].i   = r_arr[Im_Nr+1].i;
05419                   undo_ref[j].r2  = r_arr[FT_dim-Im_Nr-1].r;
05420                   undo_ref[j].i2  = r_arr[FT_dim-Im_Nr-1].i;
05421                   RWC_ideal->ts[Im_Nr] = 0;
05422                   r_arr[Im_Nr+1].r     = 0.;
05423                   r_arr[Im_Nr+1].i     = 0.;
05424                   r_arr[FT_dim-Im_Nr-1].r = 0.;
05425                   r_arr[FT_dim-Im_Nr-1].i = 0.;
05426                }
05427             }
05428             if ( undo_buf != NULL ) {
05429                for ( i=0, j=nn; i < ar_size; j++, i++) {
05430                   undo_buf[j].im  = Im_Nr;
05431                   undo_buf[j].pix = i;
05432                   undo_buf[j].r   = c_arr[i*FT_dim+Im_Nr+1].r;
05433                   undo_buf[j].i   = c_arr[i*FT_dim+Im_Nr+1].i;
05434                   undo_buf[j].r2  = c_arr[(i+1)*FT_dim-Im_Nr-1].r;
05435                   undo_buf[j].i2  = c_arr[(i+1)*FT_dim-Im_Nr-1].i;
05436                   SAR(Im_Nr)[i]   = 0;
05437                   c_arr[i*FT_dim+Im_Nr+1].r     = 0.;
05438                   c_arr[i*FT_dim+Im_Nr+1].i     = 0.;
05439                   c_arr[(i+1)*FT_dim-Im_Nr-1].r = 0.;
05440                   c_arr[(i+1)*FT_dim-Im_Nr-1].i = 0.;
05441                }
05442                redraw_graph() ;
05443                DrawSubWindow();
05444             }
05445             old_im = -1;
05446             Put_image(Im_Nr);
05447          }
05448       break ;  /* end of ikey=kFT3 */
05449 
05450    }  /* end of ikey switch */
05451 
05452 #if 0
05453    InvertKey(kFFT) ;  /* flash the FFT key */
05454    DrawTopWindow() ;  /* update the labels */
05455    InvertKey(kFFT) ;
05456 #endif
05457 
05458    if( fun_modified ){
05459       redraw_graph() ;
05460       fun_modified = 0;
05461    }
05462 
05463    return 0;
05464 }
05465 
05466 /* ------------- */
05467    Im_diff(ikey)
05468    int ikey;
05469 /* ------------- */
05470 {
05471    XUnmapWindow(theDisp,  key[kDIF].wid);
05472    XMapWindow  (theDisp,  key[kIR1].wid);
05473    XMapWindow  (theDisp,  key[kIR2].wid);
05474 }
05475 
05476 /* ------------- */
05477    Im_Aver(ikey)
05478    int ikey;
05479 /* ------------- */
05480 {
05481    avr_grp = fim_avr = 0;
05482    XMapWindow(theDisp,  key[kAV1].wid);
05483    XMapWindow(theDisp,  key[kAV2].wid);
05484 }
05485 
05486 /* ------------- */
05487    Im_norm(ikey)
05488    int ikey;
05489 /* ------------- */
05490 {
05491    diff_im = fim_dif = 0;
05492    avr_grp = fim_avr = 0;
05493    Av_length = 1;
05494    XUnmapWindow(theDisp,  key[kNRM].wid);
05495    XMapWindow  (theDisp,  key[kDIF].wid);
05496    old_im = -1;            /* to avoid faster reload of old data */
05497    Put_image(Im_Nr);
05498    redraw_graph();
05499    DrawSubWindow();
05500 }
05501 
05502 /* ------------ */
05503    Av_im1(ikey)
05504    int ikey;
05505 /* ------------ */  /* set first image for average one */
05506 {
05507    Av_1 = Im_Nr;
05508    av1_done = 1;
05509 }
05510 
05511 /* ------------ */
05512    Av_im2(ikey)
05513    int ikey;
05514 /* ------------ */  /* set second image for average one */
05515 {
05516    register int  i, j;
05517 
05518    if ( av1_done ) {
05519       Av_2 = Im_Nr;
05520       if ( Av_2 < Av_1 ) {
05521          i = Av_2; Av_2 = Av_1; Av_1 = i;
05522       }
05523       Im_Nr = Av_1;
05524    }
05525    else     Av_1 = Av_2 = Im_Nr;
05526 
05527    for (i=0; i< ar_size; i++) av_ar[i] = 0;
05528    for (i=0; i < ar_size; i++) {
05529       for (j=Av_1; j <= Av_2; j++) av_ar[i] += SAR(j)[i] ;
05530    }
05531    Av_length =  Av_2 - Av_1 + 1;
05532    for (i=0; i < ar_size; i++) av_ar[i] = av_ar[i] / Av_length;
05533 
05534    XUnmapWindow(theDisp,  key[kAV1].wid);
05535    XUnmapWindow(theDisp,  key[kAV2].wid);
05536    XMapWindow  (theDisp,  key[kNRM].wid);
05537    avr_grp = fim_avr = 1;
05538    av1_done = 0;
05539    old_im = -1;            /* to avoid faster reload of old data */
05540    Put_image(Im_Nr);
05541    redraw_graph();
05542    DrawSubWindow();
05543 }
05544 
05545 /* ------------- */
05546    Ref_im1(ikey)
05547    int ikey;
05548 /* ------------- */  /* set first image for average reference one */
05549 {
05550    Im_1 = Im_Nr;
05551    im1_done = 1;
05552 }
05553 
05554 /* ------------- */
05555    Ref_im2(ikey)
05556    int ikey;
05557 /* -------------  set second image for average and make refer im for diff */
05558 {
05559    register int  i, j, m;
05560 
05561    if ( im1_done ) {
05562       Im_2 = Im_Nr;
05563       if ( Im_2 < Im_1 ) {
05564          i = Im_2; Im_2 = Im_1; Im_1 = i;
05565       }
05566    }
05567    else     Im_1 = Im_2 = Im_Nr;
05568 
05569    for (i=0; i< ar_size; i++) ref_ar[i] = 0;
05570    for (i=0; i < ar_size; i++) {
05571       for (j=Im_1; j <= Im_2; j++) ref_ar[i] += SAR(j)[i] ;
05572    }
05573    m = Im_2 - Im_1 + 1;
05574    for (i=0; i < ar_size; i++) ref_ar[i] = ref_ar[i] / m;
05575 
05576    XUnmapWindow(theDisp,  key[kIR1].wid);
05577    XUnmapWindow(theDisp,  key[kIR2].wid);
05578    XMapWindow  (theDisp,  key[kNRM].wid);
05579 
05580    diff_im = fim_dif = 1;
05581    im1_done = 0;
05582    old_im = -1;            /* to avoid faster reload of old data */
05583    Put_image(Im_Nr);
05584    redraw_graph();
05585    DrawSubWindow();
05586 /*
05587    DrawTopWindow();
05588 */
05589 }
05590 
05591 /* ------------- */
05592    Im_help(ikey)
05593    int ikey;
05594 /* ------------- */
05595 {
05596    The_Help(0);
05597 }
05598 
05599 /* ------------ */
05600    draw_frame()
05601 /* ------------ */
05602 {
05603    register int i, yyy;
05604                                /* draw frame */
05605    line_color("black");
05606    for (i=0;i<=mat;i++) {
05607      yyy = mdy1+i*gy;
05608      if ( yyy > RWC_GY_MAX + GB_DLY ) yyy = RWC_GY_MAX + GB_DLY;
05609      plotx(mdx1       , yyy, 0);
05610      plotx(mdx1+mat*gx, yyy, 1);
05611    }
05612    for (i=0;i<=mat;i++) {       
05613      plotx(mdx1+i*gx,mdy1       , 0);
05614      plotx(mdx1+i*gx,mdy1+mat*gy, 1);
05615    }
05616 }
05617 
05618 /* --------------------- */     /* Reload pixmap pxWind to GWindow */
05619    void graphic_store()
05620 /* --------------------- */
05621 {
05622    if( use_pixmap ){
05623       XSetWindowBackgroundPixmap(theDisp, GWindow, pxWind);
05624       XClearWindow(theDisp, GWindow);
05625    }
05626    XFlush(theDisp);
05627 }
05628 
05629 /* ------------------- */       /* It plots line to point (x,y) for mod = 1 */
05630    void plotx(x,y,mod)          /* or moves to this point for mod = 0.      */
05631    int x, y, mod;               /* All into the pxWind.                     */
05632 /* ------------------- */
05633 {
05634    int  iy = iHIGH - y;
05635 
05636    if(mod == 0) { x00 = x; y00 = iy; }
05637    if(mod == 1) {
05638      XDrawLine(theDisp, GRWIND, theGC, x00, y00, x, iy);
05639      x00 = x;   y00 = iy;
05640    }
05641 }
05642 
05643 /* --------------------- */     /* Plot text in pxWind at x,y position */
05644    void plx_txt(x,y,str)        /*  relative to lower left corner (!). */
05645    int  x, y;
05646    char *str;
05647 /* --------------------- */
05648 {
05649    int  iy = iHIGH - y, n = strlen(str);;
05650    XDrawString(theDisp, GRWIND, txtGC, x, iy, str, n);
05651 }
05652 
05653 /* -------------------------- */ /* Plot text in any window w at x, y */
05654    void plx_TXT(w, x, y, str)    /* relative to lower left corner (!)   */
05655    Window w;
05656    int  x, y;
05657    char *str;
05658 /* -------------------------- */
05659 {
05660    Window r;
05661    int x0, y0;
05662    u_int  width, height, bw, dp;
05663 
05664    if (!XGetGeometry(theDisp, w, &r, &x0, &y0, &width, &height, &bw, &dp)) {
05665       printf("\n Problem in plx_TXT() with XGetGeometry\n");
05666       exit(10);
05667    }
05668    else
05669       XDrawString(theDisp, w, txtGC, x, height - y, str, strlen(str));
05670 }
05671 
05672 /* -------------------------- */ /* Plot text in subWindow  at x, y */
05673    void subW_TXT(x, y, str)      /* relative to lower left corner (!) */
05674    int  x, y;
05675    char *str;
05676 /* -------------------------- */
05677 {
05678    XDrawString(theDisp, subWindow, txtGC, x, sub_W_y - y, str, strlen(str));
05679 }
05680 
05681 /* ----------------------- */   /* erase to background color */
05682    erase_graph()        /*   */
05683 /* ----------------------- */
05684 {
05685    line_color("white");
05686    XFillRectangle(theDisp, GRWIND, theGC, 0, 0, iWIDE, iHIGH);
05687 }
05688 
05689 /* ----------------------- */   /* redraw entire graph */
05690    redraw_graph()
05691 /* ----------------------- */
05692 {
05693    erase_graph();
05694    draw_marker();
05695    draw_frame();
05696    plot_line();
05697                                       /* draw min & max values in GWindow */
05698    sprintf(strp, "%05d", pmax[xc][yc]);
05699    plx_txt(xspace, GB_DLY + RWC_GY_MAX - mytxt, strp);
05700    sprintf(strp, "%05d", pmin[xc][yc]);
05701    plx_txt(xspace, GB_DLY + 5, strp);
05702 
05703    graphic_store();
05704 }
05705 
05706 /* -------------------- */     /* Change color for plotting */
05707    void line_color(col)        /* col - named color         */
05708    char *col;
05709 /* -------------------- */
05710 {
05711    XColor  any_col, rgb_col;
05712    char old_color[64] = "RW Cox" ;
05713 
05714    if( strcmp(col,old_color) == 0 ) return ;
05715 
05716    if (!(XAllocNamedColor(theDisp, CMap, col, &any_col, &rgb_col)))
05717       FatalError ("XAllocNamedColor problem. AJ");
05718    XSetForeground(theDisp, theGC, any_col.pixel);
05719 
05720    strcpy( old_color , col ) ;
05721 }
05722 
05723 /* -------------------- */     /* Change color for plotting */
05724    void txt_color(col)         /* col - named color         */
05725    char *col;
05726 /* -------------------- */
05727 {
05728    XColor  any_col, rgb_col;
05729 
05730    if (!(XAllocNamedColor(theDisp, CMap, col, &any_col, &rgb_col)))
05731       FatalError ("XAllocNamedColor problem for text. AJ");
05732    XSetForeground(theDisp, txtGC, any_col.pixel);
05733 }
05734 
05735 /* ----------------------- */
05736    FatalError (identifier)
05737    char *identifier;
05738 /* ----------------------- */
05739 {
05740    fprintf(stderr, "%s: %s\a\n",ProgramName, identifier);
05741    exit(-1);
05742 }
05743 
05744 /* ----------------------------------- */
05745    CreateGraphWindow(argv, argc)
05746    int  argc;
05747    char *argv[];
05748 /* ----------------------------------- */
05749 {
05750    XClassHint           classKRH;
05751    XSetWindowAttributes attr;
05752    unsigned int         attrmask;
05753    XSizeHints           hints;
05754    int                  x = 0, y = 0;
05755 
05756 
05757    classKRH.res_name  = "Graph";
05758    classKRH.res_class = "Graph";
05759 
05760    hints.width = iWIDE;         hints.height = iHIGH;
05761    hints.max_width = iWIDE;     hints.max_height = iHIGH;
05762    hints.flags = PMaxSize;
05763 
05764    hints.min_width = iWIDE;     hints.min_height = iHIGH;
05765    hints.flags |= PMinSize;
05766 
05767    attr.background_pixel = bcol;
05768    attr.border_pixel     = fcol;
05769    attrmask = CWBackPixel | CWBorderPixel;
05770 
05771    GWindow = XCreateWindow(theDisp, rootW, x, y, iWIDE, iHIGH, 2,
05772         CopyFromParent, CopyFromParent, CopyFromParent, attrmask, &attr);
05773 
05774    if (!GWindow)
05775       FatalError("Can't open window (are X11 windows running ?). AJ");
05776 
05777    XSetClassHint(theDisp, GWindow, &classKRH);
05778    XSetStandardProperties(theDisp, GWindow, G_name, I_name, None,
05779                           argv, argc, &hints);
05780 }
05781 
05782 /* ---------------------------- */
05783    Allow_smaller_gr(argc, argv)
05784    int  argc;
05785    char *argv[];
05786 /* ---------------------------- */
05787 {
05788    XSizeHints           hints;
05789 
05790 STATUS("ENTER Allow_smaller_im") ;
05791 
05792    hints.min_height = 150;
05793    hints.min_width = 200;
05794    hints.flags = PMinSize;
05795 
05796    hints.max_height = DisplayHeight(theDisp, theScreen);
05797    hints.max_width  = DisplayWidth(theDisp, theScreen);
05798 
05799    hints.flags |= PMaxSize;
05800    XSetStandardProperties(theDisp, GWindow, G_name, I_name, None,
05801                           argv, argc, &hints);
05802 }
05803 
05804 /* -------------- */     /* discard events x (of ev) to stop faster */
05805    discard(x, ev)
05806    int x;
05807    XEvent *ev;
05808 /* -------------- */
05809 {
05810    XSync(theDisp,False) ;
05811    while ( XCheckWindowEvent(theDisp, theWindow, x, ev) ) ;
05812    while ( XCheckWindowEvent(theDisp,   GWindow, x, ev) ) ;
05813 }
05814 
05815 /* ------------------------ */
05816    discard_Key(keyW, x, ev)
05817    int    x;
05818    XEvent *ev;
05819    Window keyW;
05820 /* ------------------------ */
05821 {
05822    while ( XCheckWindowEvent(theDisp, keyW, x, ev) ) ;
05823 }
05824 
05825 /* -------------------- */
05826    Track_Cursor(mx, my)
05827    int mx, my;
05828 /* -------------------- */
05829 {
05830    Window       rW, cW;
05831    u_int        key;
05832    int          x, y, rx, ry;
05833 
05834    while (XQueryPointer(theDisp, theWindow, &rW, &cW,
05835                                 &rx, &ry, &x, &y, &key)) {
05836       if ( !(key & Button1Mask) ) break;    /* button released */
05837 
05838       if ( mx != x || my != y ) {   /* this marker was moved */
05839          xpoint = Mltx[x]/x_mag;
05840          ypoint = Mlty[y]/x_mag;
05841          DrawSubWindow();
05842       }
05843       mx = x;
05844       my = y;
05845    }
05846 }
05847 /* -------------- */
05848    Vpointer(x, y)
05849    int x, y;
05850 /* -------------- */
05851 {
05852    XPoint a[3];
05853                                  /* fill pattern is shifted by 1 pixel => -1 */
05854    a[0].x = x-1;    a[0].y = y-1;
05855    a[1].x = x-6;    a[1].y = y+10;
05856    a[2].x = x+4;    a[2].y = y+10;
05857 
05858    line_color("red");
05859    XFillPolygon(theDisp, subWindow, theGC, a, 3, Convex, CoordModeOrigin);
05860 }
05861 
05862 /* -------------- */
05863    Cpointer(x, y )
05864    int x, y;
05865 /* -------------- */
05866 {
05867    int  i;
05868    XPoint a[12];
05869 
05870    for (i=0; i < 12; i++) {
05871       a[i].x = sm_cir[i].x + x;
05872       a[i].y = sm_cir[i].y + y;
05873    }
05874 
05875    line_color("red");
05876    XDrawPoints(theDisp, GWindow, theGC, a, 12, CoordModeOrigin);
05877 }
05878 
05879 /* -------------- */
05880    Cpointer_PIXWIN(x, y,color )
05881    int x, y;
05882    char * color ;
05883 /* -------------- */
05884 {
05885    int  i;
05886    XPoint a[12];
05887 
05888    for (i=0; i < 12; i++) {
05889       a[i].x = sm_cir[i].x + x;
05890       a[i].y = sm_cir[i].y + y;
05891    }
05892 
05893    line_color(color);
05894    XDrawPoints(theDisp, GRWIND, theGC, a, 12, CoordModeOrigin);
05895 }
05896 
05897 /* ---------------- */ /* tracks continuousely v pointer and sets image nr */
05898    Track_Vpointer()
05899 /* ---------------- */
05900 {
05901    int          Im_Old, im, c_im;
05902    Window       rW, cW;
05903    u_int        key;
05904    int          x, y, rx, ry;
05905    int          aaa = avr_grp, ddd = diff_im, redr;
05906 
05907    im = Im_Old = Im_Nr;
05908 
05909    New_Cursor(theDisp, subWindow, XC_left_ptr, "red", "white");
05910 
05911    while (XQueryPointer(theDisp, subWindow, &rW, &cW,
05912                                 &rx, &ry, &x, &y, &key)) {
05913       if ( !(key & Button1Mask) ) break;    /* button released */
05914 
05915       if ( v_point_x != x ) {   /* the marker was moved */
05916 
05917          c_im = (min(gx, max(0, x - xorigin[xc][yc]))*npoints) / gx;
05918          if ( c_im < 0 )       c_im = 0;
05919          if ( c_im > npoints - Av_length ) c_im = npoints - Av_length;
05920          if ( im != c_im ) {
05921             Im_Nr = c_im;
05922             XClearWindow(theDisp, GWindow);
05923             DrawSubWindow();
05924          }
05925          im = c_im;
05926       }
05927    }
05928    v_point_x = xorigin[xc][yc] + Im_Nr*gx/(npoints-1);
05929 
05930    if ( Im_Nr != Im_Old ) {
05931       diff_im = fim_dif;
05932       avr_grp = fim_avr;
05933       Put_image(Im_Nr);
05934       redr =  avr_grp * 4 + (aaa - avr_grp) *2 + ddd - diff_im;
05935       if ( redr ) {
05936          old_im = -1;    /* to avoid faster reload of old data */
05937          redraw_graph();
05938          DrawTopWindow();
05939          DrawSubWindow();
05940       }
05941    }
05942 
05943    New_Cursor(theDisp, subWindow, XC_left_ptr, "blue", "yellow");
05944 }
05945 
05946 /* ------------------ */
05947    int is_file(fname)
05948    char  *fname;
05949 /* ------------------ */
05950 {
05951    FILE          *fp;
05952 
05953    if ( (fp = fopen(fname, "r")) != NULL ) {    /* return = 1 if file exist */
05954       fclose(fp);
05955       return(1);
05956    }
05957    else
05958       return(0);
05959 }
05960 
05961 /* ----------------------------- */   /* write plot to file  */
05962    void print_plot(ask_file)
05963    int ask_file ;
05964 /* ----------------------------- */
05965 {
05966    int  i, x, y;
05967    static char noask_suffix[40] = "\0" ;
05968 
05969    if( ask_file ){
05970       if ( txtW_ON ) {
05971          XBell(theDisp, 100); return;
05972       }
05973       txtW_ON = 1;
05974 
05975       x = 50 + GL_DLX;
05976       y = 50 + GT_DLY;
05977 
05978       strp[0] = ASC_NUL;
05979       take_file_name(theDisp, GWindow , CMap, txtGC, mfinfo, x, y, strp, 41,
05980                      "Enter output plot name:", 1 );
05981       txtW_ON = 0 ;
05982 
05983    } else {
05984 
05985      if( noask_suffix[0] == '\0' ){
05986        if ( txtW_ON ) {
05987           XBell(theDisp, 100); return;
05988        }
05989        txtW_ON = 1;
05990 
05991        x = 50 + GL_DLX;
05992        y = 50 + GT_DLY;
05993 
05994        strp[0] = ASC_NUL;
05995        take_file_name(theDisp, GWindow , CMap, txtGC, mfinfo, x, y, strp, 41,
05996                      "Enter suffix for plot filenames:" , 0 );
05997        txtW_ON = 0 ;
05998 
05999        i = strlen(strp) ;
06000        if( i <= 0 || i >= 38 ){
06001           XBell(theDisp, 100); return;
06002        }
06003 
06004        strncpy( noask_suffix , strp , 40 ) ;
06005      }
06006 
06007      sprintf( strp , "%03d_%03d%s" ,  xpoint,ypoint,noask_suffix ) ;
06008    }
06009 
06010    if ( strp[0] != ASC_NUL ) {
06011       sprintf(plotbuf,"%d\n", val[xc][yc][0]);
06012       for (i=1; i < npoints; i++) {
06013           sprintf(fnum,"%d\n", val[xc][yc][i]);
06014           strcat(plotbuf, fnum);
06015       }
06016 
06017       isize = strlen(plotbuf);
06018       i = WRite_iqm(strp, &isize, plotbuf);
06019       if ( i != 0 ){
06020          XBell(theDisp, 100);
06021       } else {
06022          fprintf(stderr,"*** wrote plot file %s\n",strp) ;
06023       }
06024    }
06025 
06026    txtW_ON = 0;
06027 }
06028 
06029 /* --------------------- */
06030    int save_all_images()
06031 /* --------------------- */
06032 {
06033    int  i, x, y;
06034    XWindowAttributes  wat;
06035    Window             ww;
06036 
06037    if ( txtW_ON ) {
06038       XBell(theDisp, 100); return(2);
06039    }
06040    txtW_ON = 1;
06041 
06042    x = 50 + GL_DLX;
06043    y = 50 + GT_DLY;
06044 
06045    strp[0] = ASC_NUL ;
06046    take_file_name(theDisp, GWindow , CMap, txtGC, mfinfo, x, y, strp, 45,
06047                   "Enter output root name:", 0);
06048    im_f = min(3, dec_indx(npoints)-1);  /* 2d index in formt[][] */
06049 
06050 try_again:
06051    if ( strp[0] != ASC_NUL ) {
06052       /* test for first file */
06053       sprintf(strF, formt[0][im_f], strp, 1);
06054       if ( is_file(strF) ) {
06055          strp[0] = ASC_NUL;
06056          sprintf (strT, "File exist: %s", strF);
06057          take_file_name(theDisp, GWindow , CMap, txtGC, mfinfo, x, y, strp, 50,
06058                   strT, 0);
06059          goto try_again;
06060       }
06061       for (i=0; i < npoints; i++) {
06062          sprintf(strF, formt[0][im_f], strp, i+1);
06063 
06064          /* we have already decided whether to swap */
06065          if ( RCR_swap && allim[i]->kind == MRI_short ) {
06066            swap_2(MRI_SHORT_PTR(allim[i]), allim[i]->nx*allim[i]->ny*2);
06067          }
06068          else if ( RCR_swap && allim[i]->kind == MRI_float ) {
06069            swap_4(MRI_FLOAT_PTR(allim[i]), allim[i]->nx*allim[i]->ny*4);
06070          }
06071 
06072          mri_write(strF, allim[i]) ;
06073 
06074          if ( RCR_swap && allim[i]->kind == MRI_short ) {
06075            swap_2(MRI_SHORT_PTR(allim[i]), allim[i]->nx*allim[i]->ny*2);
06076          }
06077          else if ( RCR_swap && allim[i]->kind == MRI_float ) {
06078            swap_4(MRI_FLOAT_PTR(allim[i]), allim[i]->nx*allim[i]->ny*4);
06079          }
06080       }
06081    }
06082 
06083    txtW_ON = 0;
06084    return(0);
06085 }
06086 
06087 /* -------------------- save not normalized average image - called by 'X' */
06088    int save_avr_array()
06089 /* -------------------- */
06090 {
06091    int  i, x, y;
06092    XWindowAttributes  wat;
06093    Window             ww;
06094 
06095    if ( txtW_ON ) {
06096       XBell(theDisp, 100); return(2);
06097    }
06098    txtW_ON = 1;
06099 
06100    x = 50 + GL_DLX;
06101    y = 50 + GT_DLY;
06102 
06103    strp[0] = ASC_NUL ;
06104    take_file_name(theDisp, GWindow , CMap, txtGC, mfinfo, x, y, strp, 41,
06105                   "Enter output image name:" , 1 );
06106    for( i=0 ; i < IM_ARR ; i++ ) a_rot[i] = tmp_ar[i];
06107    for( i=0 ; i < IM_ARR ; i++ ) tmp_ar[i] = av_ar[i];
06108    if ( strp[0] != ASC_NUL ) {
06109       mri_write( strp , im_tmp_ar ) ;
06110    }
06111    for( i=0 ; i < IM_ARR ; i++ ) tmp_ar[i] = a_rot[i];
06112 
06113    txtW_ON = 0;
06114    return(0);
06115 }
06116 
06117 /* ----------------- */
06118    int save_act_im()
06119 /* ----------------- */
06120 {
06121    int  i, x, y;
06122    XWindowAttributes  wat;
06123    Window             ww;
06124 
06125    if ( txtW_ON ) {
06126       XBell(theDisp, 100); return(2);
06127    }
06128    txtW_ON = 1;
06129 
06130 /* AJJ  OK in relation to the root window
06131    XGetWindowAttributes(theDisp, theWindow, &wat);
06132    XTranslateCoordinates(theDisp, theWindow, wat.root, -wat.border_width,
06133                         -wat.border_width, &x, &y, &ww);
06134    x += eWIDE/2;
06135    y += eHIGH/2;
06136 
06137    strp[0] = ASC_NUL ;
06138    take_file_name(theDisp, rootW, CMap, txtGC, mfinfo, x, y, strp, 40,
06139                   "Enter image name:" ,  1 );
06140 */
06141 
06142    x = 50 + GL_DLX;
06143    y = 50 + GT_DLY;
06144 
06145    strp[0] = ASC_NUL ;
06146    take_file_name(theDisp, GWindow , CMap, txtGC, mfinfo, x, y, strp, 41,
06147                   "Enter output image name:" , 1 );
06148    if ( strp[0] != ASC_NUL ) {
06149       /* we have already decided on swapping     27 Aug 2004 [rickr] */
06150 
06151       if ( RCR_swap && im_tmp_ar->kind == MRI_short ) {
06152         swap_2(MRI_SHORT_PTR(im_tmp_ar), im_tmp_ar->nx*im_tmp_ar->ny*2);
06153       }
06154       else if ( RCR_swap && im_tmp_ar->kind == MRI_float ) {
06155         swap_4(MRI_FLOAT_PTR(im_tmp_ar), im_tmp_ar->nx*im_tmp_ar->ny*4);
06156       }
06157 
06158       mri_write( strp , im_tmp_ar ) ;
06159 
06160       if ( RCR_swap && im_tmp_ar->kind == MRI_short ) {
06161         swap_2(MRI_SHORT_PTR(im_tmp_ar), im_tmp_ar->nx*im_tmp_ar->ny*2);
06162       }
06163       else if ( RCR_swap && im_tmp_ar->kind == MRI_float ) {
06164         swap_4(MRI_FLOAT_PTR(im_tmp_ar), im_tmp_ar->nx*im_tmp_ar->ny*4);
06165       }
06166    }
06167 
06168    txtW_ON = 0;
06169    return(0);
06170 }
06171 
06172 /* popup window which take a file name of max length str_l */
06173 /* --------------------------------------- return name of file in name */
06174    int take_file_name(theDisp, topW, CMap, txtGC, finf, x, y, name, str_l,
06175                       text, check)
06176    Display     *theDisp;
06177    Window      topW;                    /* top window of this popup one */
06178    Colormap    CMap;
06179    GC          txtGC;
06180    XFontStruct *finf;
06181    int         x, y;                    /* relative position */
06182    char *name, *text;                   /* name - file name, max str_l chars */
06183    int  str_l;                          /* text - window's header */
06184    int  check ;                         /* to check if name exists already? */
06185 /* --------------------------------------- */
06186 {
06187    int    w_l1, w_h1, w_l2, w_h2, h_txt, expose = 0, name_OK = 0, length;
06188    int    x_txt, y_txt, x_l2, y_l2, error = 0;
06189    int    eee[2];
06190    char   *errr = "File exist:", *DT = "_";
06191 
06192    XEvent ev;
06193    XColor             any_col, rgb_col;
06194    unsigned long      Border, back1, back2;
06195    Window             txtWindow1, txtWindow2, ww;
06196    XSizeHints         hints;
06197 
06198    eee[0] = eee[1] = 0;
06199 
06200    if (!(XAllocNamedColor(theDisp, CMap, "red", &any_col, &rgb_col)))
06201       FatalError ("XAllocNamedColor problem. AJ in save_act_im()");
06202    Border = any_col.pixel;
06203    if (!(XAllocNamedColor(theDisp, CMap, "yellow", &any_col, &rgb_col)))
06204       FatalError ("XAllocNamedColor problem. AJ in save_act_im()");
06205    back1= any_col.pixel;
06206    if (!(XAllocNamedColor(theDisp, CMap, "white", &any_col, &rgb_col)))
06207       FatalError ("XAllocNamedColor problem. AJ in save_act_im()");
06208    back2= any_col.pixel;
06209 
06210    hints.flags = USPosition;
06211    hints.x = x;
06212    hints.y = y;
06213 
06214    h_txt =  finf->max_bounds.ascent + finf->max_bounds.descent;
06215    w_l1 = (str_l - 1) * finf->max_bounds.width + 30;
06216    w_h1 = 3 * h_txt + 18;
06217    x_l2 = 10;
06218    y_l2 = 2 * h_txt + 5;
06219    w_l2 = w_l1 - 20;
06220    w_h2 = h_txt + 8;
06221    x_txt = 5;
06222    y_txt = h_txt;
06223 
06224    txtWindow1 =  XCreateSimpleWindow(theDisp, topW, x, y, w_l1, w_h1, 1,
06225                                      Border, back1);
06226    XSelectInput(theDisp, txtWindow1, ExposureMask);
06227    XSetStandardProperties(theDisp, txtWindow1 , "Text", "Text", None,
06228                           NULL, 0, &hints);
06229    txtWindow2 =  XCreateSimpleWindow(theDisp, txtWindow1, x_l2, y_l2,
06230                             w_l2, w_h2, 1, Border, back2);
06231    XSelectInput(theDisp, txtWindow2, ExposureMask | KeyPressMask);
06232    New_Cursor(theDisp, txtWindow1, XC_left_ptr, "blue", "white");
06233    New_Cursor(theDisp, txtWindow2, XC_xterm, "blue", "white");
06234    XMapWindow(theDisp, txtWindow1);
06235    XMapWindow(theDisp, txtWindow2);
06236 
06237    while ( !expose ) {                /* wait for expose */
06238       Window wind;
06239       XNextEvent(theDisp, &ev);
06240       switch (ev.type) {
06241          case Expose: {
06242             XExposeEvent *e = (XExposeEvent *) &ev;
06243             wind = e->window;
06244             if (wind ==  txtWindow1) eee[0] = 1;
06245             if (wind ==  txtWindow2) eee[1] = 1;
06246             expose = eee[0] * eee[1];
06247          }
06248          default:                /* ignore unexpected events */
06249             break;
06250       }
06251    } /* end of while( !expose ) */
06252 
06253    txt_color("red");
06254    XDrawString(theDisp, txtWindow1, txtGC, 9, h_txt + 3 ,
06255                text, strlen(text));
06256    strncat(name, DT, 1);
06257    txt_color("blue");
06258    XDrawString(theDisp, txtWindow2, txtGC, x_txt, y_txt,
06259                name, strlen(name));
06260 
06261    txt_color("black");
06262 
06263    while ( !name_OK ) {                /* wait for file name */
06264       Window wind;
06265       XNextEvent(theDisp, &ev);
06266       switch (ev.type) {
06267          case Expose: {
06268             XExposeEvent *e = (XExposeEvent *) &ev;
06269 
06270             wind = e->window;
06271             if (wind ==  txtWindow1) {
06272                txt_color("red");
06273                XDrawString(theDisp, txtWindow1, txtGC, 30, h_txt + 3 ,
06274                            text, strlen(text));
06275                txt_color("black");
06276             }
06277             if (wind ==  txtWindow2) {
06278                txt_color("blue");
06279                XDrawString(theDisp, txtWindow2, txtGC, x_txt, y_txt,
06280                            name, strlen(name));
06281                txt_color("black");
06282             }
06283          }
06284          case KeyPress: {
06285             XKeyEvent *key_event = (XKeyEvent *) &ev;
06286             u_char      buf[128];
06287             KeySym    ks;
06288             XComposeStatus status;
06289 
06290             wind = key_event->window;
06291             if (wind ==  txtWindow2) {
06292                if (error) {
06293                   XClearWindow(theDisp, txtWindow1);
06294                   txt_color("red");
06295                   XDrawString(theDisp, txtWindow1, txtGC, 25, h_txt + 3 ,
06296                               text, strlen(text));
06297                   txt_color("black");
06298                   error = 0;
06299                }
06300                buf[0] = 0;
06301                XLookupString(key_event, (char *)buf, 128, &ks, &status);
06302                if ( (ks == XK_Return)   ||
06303                     (ks == XK_Linefeed) ) {
06304                   length = strlen(name);
06305                   name[length-1] = ASC_NUL;
06306                   if ( name[0] == ASC_NUL ) name_OK = 1;
06307                   else if ( check && is_file(name) ) {
06308                      XClearWindow(theDisp, txtWindow1);
06309                      txt_color("red");
06310                      XDrawString(theDisp, txtWindow1, txtGC, 10, h_txt ,
06311                            errr, strlen(errr));
06312                      XDrawString(theDisp, txtWindow1, txtGC, 15, 2*h_txt ,
06313                            name, strlen(name));
06314                      txt_color("black");
06315                      name[0] = ASC_NUL;
06316                      strncat(name, DT, 1);
06317                      XBell(theDisp, 100);
06318                      error = 1;
06319                   }
06320                   else
06321                      name_OK = 1;
06322                }
06323                else if ( ((ks >= XK_plus) && (ks <= XK_9)) ||
06324                          ((ks >= XK_A) && (ks <= XK_Z))  ||
06325                          ((ks >= XK_asciicircum) && (ks <= XK_z)) ||
06326                           (ks == XK_asciitilde)                   ||
06327                           (ks == XK_numbersign)                   ||
06328                           (ks == XK_colon     )                   ||
06329                           (ks == XK_at        )                   ||
06330                           (ks == XK_underscore)                   ||
06331                           (ks == XK_exclam)     ) {
06332                   if ( (length = strlen(name)) + 1 > str_l ) {
06333                      name[length-1] = ' ';
06334                      XBell(theDisp, 100);
06335                   }
06336                   else if ( ((buf[0] >= 43) && (buf[0] <= 57)) ||
06337                             ((buf[0] >= 65) && (buf[0] <= 90)) ||
06338                             ((buf[0] >= 94) && (buf[0] <= 122))||
06339                              (buf[0] == 126)                   ||
06340                              (buf[0] == '!') ) {
06341                      name[length - 1] = ASC_NUL;
06342                      strncat(name, (char *)buf, 1);
06343                      strncat(name, DT, 1);
06344                   }
06345                }
06346                else if ( ((ks >= XK_Shift_L) && (ks <= XK_Hyper_R)) ||
06347                          ((ks >= XK_F1) && (ks <= XK_F35)) ||
06348                          ((ks >= XK_KP_0) && (ks <= XK_KP_9)) )
06349                      ;     /* do nothing */
06350                else if ((ks == XK_BackSpace) || (ks == XK_Delete)) {
06351                   if ( (length = strlen(name)) > 1 ) {
06352                      name[length - 2] = ASC_NUL;
06353                      strncat(name, DT, 1);
06354                   }
06355                   else
06356                      XBell(theDisp, 100);
06357                }
06358                else
06359                   XBell(theDisp, 100);
06360             }
06361             XClearWindow(theDisp, txtWindow2);
06362             txt_color("blue");
06363             XDrawString(theDisp, txtWindow2, txtGC, x_txt, y_txt,
06364                         name, strlen(name));
06365             txt_color("black");
06366          }
06367          default:                /* ignore unexpected events */
06368             break;
06369       }
06370 
06371    } /* end of while( !name_OK ) */
06372 
06373    txt_color("black");
06374    XDestroyWindow(theDisp, txtWindow1);
06375 }
06376 
06377 /**************************************************************************/
06378 /**************************************************************************/
06379 /**************************************************************************/
06380 
06381 #define MAX_NREF (MAX_NUMORT+MAX_POLORT+99)
06382 
06383 #if 0
06384 #define FLAG_PIX (31+29*64)
06385 #endif
06386 
06387 void RWC_setup_fims( imflag )
06388    int imflag ;
06389 {
06390    int kim , nref ;
06391    float current_refs[MAX_NREF] ;
06392    float *id ;
06393    float *pc , *alp ;
06394    thresh_result thr ;
06395 
06396    float        alp_max , alp_thr[MAX_FIM_COLORS] ;
06397    register int jj , ii , nvox ;
06398 
06399    static MRI_IMAGE * thrim = NULL ;
06400    static short *     thrar = NULL ;
06401    static short       imthr ;
06402 
06403    MRI_IMAGE * flim ;
06404    float     * flar ;
06405    double      scl , dkim , pval ;
06406    int         make_thrim , good ;
06407 
06408    static MRI_IMARR * DFILT_rim  = NULL ;
06409 
06410 #ifdef OV_DEBUG1
06411    fprintf(stderr,"initializing fim calculations:\n") ; fflush(stderr);
06412 #endif
06413 
06414    /*** check RWC_ideal for legality ***/
06415 
06416    if( RWC_ideal == NULL ){
06417       RWC_do_overfim = 0 ;
06418       if( RWC_imover != NULL ) { free(RWC_imover) ; RWC_imover = NULL ; }
06419       return ;
06420    }
06421 
06422    id = RWC_ideal->ts ;
06423 
06424    if( RWC_ideal->len < npoints ){
06425       fprintf(stderr,
06426               "\n*** reference vector time series file %s too short!\n",
06427               RWC_ideal->fname ) ;
06428 
06429       RWC_do_overfim = 0 ;
06430       RWC_free_time_series( RWC_ideal ) ; RWC_ideal = NULL ;
06431       if( RWC_imover != NULL ) { free(RWC_imover) ; RWC_imover = NULL ; }
06432       XBell(theDisp,100) ; return ;
06433    }
06434 
06435    for( ii=0 ; ii < RWC_numort ; ii++ ){
06436       if( RWC_ort[ii] == NULL || RWC_ort[ii]->len < npoints ){
06437          fprintf( stderr ,
06438                   "\n*** ort vector time series file %s too short!\n",
06439                   RWC_ort[ii]->fname ) ;
06440          RWC_do_overfim = 0 ;
06441          if( RWC_imover != NULL ) { free(RWC_imover) ; RWC_imover = NULL ; }
06442          XBell(theDisp,100) ; return ;
06443       }
06444    }
06445 
06446    /*** miscellaneous startup ***/
06447 
06448    if( RWC_fim_colors == 0 ) RWC_init_fim_colors() ;
06449 
06450    nref = RWC_numort + RWC_polort + 2 ;
06451 
06452    if( DFILT_code == DFILT_TIME ){
06453       nref += DFILT_NREF ;     /* number of refs from DFILT      */
06454    }
06455 
06456    if( LSQ_ref[0] == NULL ){
06457       for( ii=0 ; ii < MAX_TOTAL_REF ; ii++ )
06458          LSQ_ref[ii] = RWC_blank_time_series(NF_MAX) ;
06459    }
06460    LSQ_refcount = nref ;
06461 
06462    RWC_nxim = RWC_nyim = im_size ;  nvox = RWC_nxim * RWC_nyim ;
06463 
06464    RWC_refs   = new_references( nref ) ;
06465    RWC_voxcor = new_voxel_corr( RWC_nxim * RWC_nyim , nref ) ;
06466 
06467    if( RWC_pcim  != NULL ) mri_free( RWC_pcim ) ;
06468    if( RWC_alpim != NULL ) mri_free( RWC_alpim ) ;
06469 
06470    RWC_pcim  = mri_new( RWC_nxim , RWC_nyim , MRI_float ) ;
06471    RWC_alpim = mri_new( RWC_nxim , RWC_nyim , MRI_float ) ;
06472    pc        = mri_data_pointer( RWC_pcim ) ;
06473    alp       = mri_data_pointer( RWC_alpim ) ;
06474 
06475    if( RWC_refs == NULL || RWC_voxcor == NULL ){
06476       fprintf(stderr,"*** ==> malloc fail while fimming\a\n") ;
06477       mri_free( RWC_pcim )  ; RWC_pcim  = NULL ;
06478       mri_free( RWC_alpim ) ; RWC_alpim = NULL ;
06479       if( RWC_voxcor != NULL ) free_voxel_corr( RWC_voxcor ) ;
06480       if( RWC_refs   != NULL ) free_references( RWC_refs ) ;
06481       if( RWC_ideal  != NULL ) {RWC_free_time_series(RWC_ideal);RWC_ideal=NULL;}
06482       if( RWC_imover != NULL ) {free(RWC_imover) ; RWC_imover=NULL;}
06483       RWC_do_overfim = 0 ;
06484       return ;
06485    }
06486 
06487 /*** prepare to make thresholding image, if not already present ***/
06488 
06489    make_thrim = (thrim == NULL) ;
06490    if( make_thrim ){
06491       flim = mri_new( RWC_nxim , RWC_nyim , MRI_float ) ;
06492       flar = mri_data_pointer( flim ) ;
06493       scl  = 0.0 ;
06494       for( ii=0 ; ii < nvox ; ii++ ) flar[ii] = 0.0 ;
06495    }
06496 
06497 /*** find first "good" image and initialize DFILT, if needed ***/
06498 
06499    if( DFILT_code == DFILT_TIME ){
06500       int good ;
06501       int ii , jj , nx , ny , joff ;
06502       MRI_IMAGE * xim , * yim , * tim , * bim , * flim ;
06503       float     * xar , * yar , * tar ;
06504       float  hnx , hny , fac ;
06505 
06506       for( kim=0 ; kim < npoints ; kim++ ){
06507          good = fabs(id[kim]) < 33333.0 ;            /* check ideal and orts for OK */
06508          for( ii=0 ; ii < RWC_numort ; ii++ )
06509             good = good && ( fabs(RWC_ort[ii]->ts[kim]) < 33333.0 ) ;
06510          if( good ) break ;
06511       }
06512       if( kim == npoints ){
06513          fprintf(stderr,"*** NO good images in FIM time series!? ***\a\n") ;
06514          exit(-1) ;
06515       }
06516 
06517       flim     = mri_to_float( allim[kim] ) ;  /* first good image */
06518       flim->dx = flim->dy = 1.0 ;
06519       nx       = flim->nx ;  hnx = 0.5 * nx ;
06520       ny       = flim->ny ;  hny = 0.5 * ny ;
06521       fac      = 1.0 / MAX(hnx,hny) ;
06522 
06523       bim = mri_filt_fft( flim , DFILT_SIGMA , 0 , 0 , FILT_FFT_WRAPAROUND ) ;  /* smooth */
06524       xim = mri_filt_fft( flim , DFILT_SIGMA , 1 , 0 , FILT_FFT_WRAPAROUND ) ;  /* and d/dx */
06525       yim = mri_filt_fft( flim , DFILT_SIGMA , 0 , 1 , FILT_FFT_WRAPAROUND ) ;  /* and d/dy */
06526 
06527       tim = mri_new( nx , ny , MRI_float ) ;    /* x * d/dy - y * d/dx */
06528       tar = mri_data_pointer( tim ) ;           /* which is d/d(theta) */
06529       xar = mri_data_pointer( xim ) ;
06530       yar = mri_data_pointer( yim ) ;
06531       for( jj=0 ; jj < ny ; jj++ ){
06532          joff = jj * nx ;
06533          for( ii=0 ; ii < nx ; ii++ ){
06534             tar[ii+joff] = fac * (  (ii-hnx) * yar[ii+joff]
06535                                   - (jj-hny) * xar[ii+joff] ) ;
06536          }
06537       }
06538 
06539       INIT_IMARR ( DFILT_rim ) ;
06540       ADDTO_IMARR( DFILT_rim , bim ) ;  /* will NOT be an extra ref */
06541       ADDTO_IMARR( DFILT_rim , xim ) ;
06542       ADDTO_IMARR( DFILT_rim , yim ) ;
06543       ADDTO_IMARR( DFILT_rim , tim ) ;
06544 
06545       mri_free( flim ) ;
06546    }
06547 
06548 /*** put images thru the fim wringer ***/
06549 
06550    for( kim=0 ; kim < npoints ; kim++ ){
06551 
06552 #ifdef OV_DEBUG1
06553    fprintf(stderr,"  at kim=%d, reference=%11.4g\n",kim,id[kim]) ;
06554 #endif
06555 
06556       good = fabs(id[kim]) < 33333.0 ;            /* check ideal and orts for OK */
06557       for( ii=0 ; ii < RWC_numort ; ii++ )
06558          good = good && ( fabs(RWC_ort[ii]->ts[kim]) < 33333.0 ) ;
06559 
06560       /** load the current_refs even if not good **/
06561 
06562       dkim = kim / ((double) npoints) ;
06563       pval = 1.0 ;
06564       for( ii=0 ; ii <= RWC_polort ; ii++ ){
06565          current_refs[ii] = pval ;
06566          pval            *= dkim ;
06567       }
06568 
06569       for( ii=0 ; ii < RWC_numort ; ii++ )
06570          current_refs[ii+RWC_polort+1] = RWC_ort[ii]->ts[kim] ;
06571 
06572       if( DFILT_code == DFILT_TIME ){  /* fit current image to ref images */
06573          MRI_IMAGE * blim ;
06574          float * fit ;
06575          int ii , ibase ;
06576          float val ;
06577 
06578          blim = mri_filt_fft( allim[kim] , DFILT_SIGMA , 0 , 0 , FILT_FFT_WRAPAROUND ) ;
06579          fit  = mri_lsqfit( blim , DFILT_rim , blim ) ;
06580          mri_free( blim ) ;
06581 
06582          ibase = RWC_numort + RWC_polort + 1 ;
06583 
06584          for( ii=0 ; ii < DFILT_NREF ; ii++ ){  /* load big fits as refs, except fit[0] */
06585             val = fit[ii+1] ;
06586             current_refs[ibase+ii] = (fabs(val) > DFILT_THRESH) ? val : 0.0 ;
06587          }
06588          free(fit) ;
06589       }
06590 
06591       current_refs[nref-1] = id[kim] ;       /* load ideal as last ref */
06592 
06593       /** load LSQ_ref **/
06594 
06595       for( ii=0 ; ii < nref ; ii++ ){
06596          dkim = current_refs[ii] ;
06597          LSQ_ref[ii]->ts[kim] = (fabs(dkim) < 33333.0) ? dkim : 0.0 ;
06598       }
06599 
06600       /** process if all refs are good **/
06601 
06602       if( good ){
06603          nowim = SAR(kim) ;
06604          update_references( current_refs , RWC_refs ) ;
06605          update_voxel_corr( nowim , RWC_refs , RWC_voxcor ) ;
06606 
06607          if( make_thrim ){
06608             for( ii=0 ; ii < nvox ; ii++ ) flar[ii] += abs(nowim[ii]) ;
06609             scl++ ;  /* one more image */
06610          }
06611       }  /* end if(good) */
06612    } /* end for kim */
06613 
06614    DESTROY_IMARR( DFILT_rim ) ;
06615 
06616    /*** setup threshold on image intensity ***/
06617 
06618    if( make_thrim ){
06619       scl   = 1.0 / scl ;
06620       thrim = mri_to_short( scl , flim ) ;           /* average of abs */
06621       thrar = mri_data_pointer( thrim ) ;
06622       imthr = (short) ( 0.05 * mri_max( thrim ) ) ;  /* 5% threshold */
06623       mri_free( flim ) ;                             /* old junk */
06624    }
06625 
06626 #ifdef FLAG_PIX
06627    fprintf(stderr,"imthr = %d  thrar[flag] = %d\n",imthr,thrar[FLAG_PIX]);
06628 #endif
06629 
06630    /*** compute and threshold on correlation coefficient ***/
06631 
06632    get_pcor_thresh_coef( RWC_refs , RWC_voxcor ,
06633                          0.001 , 0.001 , pc , alp , &thr ) ;
06634 
06635    /*** compute least squares fit coefficients in each voxel ***/
06636 
06637    DESTROY_IMARR( LSQ_fitim ) ;
06638    INIT_IMARR( LSQ_fitim ) ;
06639    for( ii=0 ; ii < nref ; ii++ ){
06640       flim = mri_new( RWC_nxim , RWC_nyim , MRI_float ) ;
06641       ADDTO_IMARR(LSQ_fitim,flim) ;
06642       LSQ_fit[ii] = MRI_FLOAT_PTR(flim) ;
06643    }
06644    get_lsqfit( RWC_refs , RWC_voxcor , LSQ_fit ) ;
06645 
06646 #ifdef FLAG_PIX
06647    fprintf(stderr,"pc[flag] = %f  alp[flag] = %f\n",pc[FLAG_PIX],alp[FLAG_PIX]) ;
06648 #endif
06649 
06650 #ifdef OV_DEBUG1
06651    THR_DUMP(thr,"for overfim") ;
06652 #endif
06653 
06654    if( RWC_imover != NULL ){  /* toss old overlay, if any */
06655       free(RWC_imover) ;
06656       RWC_imover = NULL ;
06657    }
06658 
06659 /*** threshold results on voxel data and fim results ***/
06660 
06661    alp_max = 0.0 ;
06662    for( ii=0 ; ii < nvox ; ii++ ){
06663       if( fabs(pc[ii]) >= RWC_pcthresh ){
06664          alp_max = (alp[ii]>0) ? MAX(alp_max, alp[ii])
06665                                : MAX(alp_max,-alp[ii]) ;
06666       }
06667    }
06668 
06669 #ifdef FLAG_PIX
06670    fprintf(stderr,"alp_max = %f\n",alp_max) ;
06671 #endif
06672 
06673    if( alp_max > 0.0 ){
06674 
06675       RWC_imover = RWC_create_overlay( RWC_nxim , RWC_nyim ) ;
06676 
06677       for( ii=0 ; ii < RWC_fim_colors ; ii++ ){
06678          alp_thr[ii] = RWC_fim_thresh[ii] * alp_max ;
06679       }
06680 
06681    /*** loop over all voxels ***/
06682 
06683       for( ii=0 ; ii < nvox ; ii++ ){
06684 
06685          if( thrar[ii] >= imthr && fabs(pc[ii]) >= RWC_pcthresh ){
06686 
06687             if( alp[ii] >= alp_thr[0] ){  /* positive over threshold */
06688 
06689                for( jj=1 ; jj < RWC_fim_colors ; jj++ )  /* find place */
06690                   if( alp[ii] < alp_thr[jj] ) break ;
06691 
06692                RWC_imover[ii] = RWC_fim_colors_pos[jj-1] ;
06693 
06694             }
06695 
06696             else if( alp[ii] <= -alp_thr[0] ){  /* negative over threshold */
06697 
06698                for( jj=1 ; jj < RWC_fim_colors ; jj++ )  /* find place */
06699                   if( alp[ii] > -alp_thr[jj] ) break ;
06700 
06701                RWC_imover[ii] = RWC_fim_colors_neg[jj-1] ;
06702 
06703             }
06704          } /* end if nowim && pc */
06705      } /* end for ii (voxel loop) */
06706 
06707 #ifdef FLAG_PIX
06708    fprintf(stderr,"imover[flag] = %d]\n",RWC_imover[FLAG_PIX]) ;
06709 #endif
06710 
06711      pc[1]  = 1.0     ; pc[2]  = -1.0 ;
06712      alp[1] = alp_max ; alp[2] = -alp_max ;
06713 
06714      RWC_overhide = 0 ;
06715 
06716      if( imflag ){  /* display results */
06717 
06718         ii = Im_Nr ;
06719 
06720         mri_add_name( "correlation_image" , RWC_pcim ) ;
06721         add_extra_image( RWC_pcim ) ;
06722 
06723         mri_add_name( "fim_image" , RWC_alpim ) ;
06724         add_extra_image( RWC_alpim ) ;
06725 
06726         Im_Nr = ii ;
06727         Put_image( Im_Nr ) ;
06728      }
06729 
06730    } /* end if alp_max */
06731 
06732    free_voxel_corr( RWC_voxcor ) ; free_references( RWC_refs ) ;
06733 
06734    return ;
06735 }
06736 
06737 /****************************************************************************/
06738 
06739 int FIM_action(ikey)
06740   int ikey ;
06741 {
06742    int i ;
06743 #ifdef USE_MCW
06744    static int mcw_count = 0 ;
06745 #endif
06746 
06747    for( i=FIM_first_key ; i <= FIM_last_key ; i++ ){
06748       if( FIM_pressed ) XUnmapWindow(theDisp,  key[i].wid);  /* second press */
06749       else              XMapWindow  (theDisp,  key[i].wid);  /* first press */
06750    }
06751 
06752    if( FIM_pressed ){                  /* second press */
06753       FIM_pressed = 0 ;
06754       xtkeys[kFIM].st = key_kFIM_FIM ;
06755       DrawKey(kFIM) ;                  /* restore key label */
06756 
06757       if( RWC_do_overfim && FIM_modified ){
06758 #ifdef USE_MCW
06759          mcw_count++ ; Put_image(-1) ;  /* show the logo */
06760 #endif
06761          InvertKey(kFIM) ;
06762          XFlush(theDisp) ;
06763          RWC_setup_fims( 1 ) ;  /* 1 => display results */
06764          InvertKey(kFIM) ;
06765       }
06766 
06767       Put_image( Im_Nr ) ;
06768       DrawTopWindow() ;
06769       redraw_graph() ;
06770 
06771    } else {                            /* first press */
06772 
06773      FIM_pressed  = 1;
06774      FIM_modified = 0 ;
06775      xtkeys[kFIM].st = key_kFIM_GO ;
06776      DrawKey(kFIM) ;                  /* set key label to "GO" */
06777    }
06778 
06779 }
06780 
06781 /****************************************************************************/
06782 
06783 int FIM_selection(ikey)
06784   int ikey ;
06785 {
06786    int x , y , ifim = ikey - FIM_first_key , ref_modified = 0 ;
06787    float fval ;
06788    char *cpt ;
06789    char stst[64] ;
06790    time_series *newts ;
06791 
06792    if ( txtW_ON || ikey < FIM_first_key || ikey > FIM_last_key ) {
06793       XBell(theDisp, 100); return 0;
06794    }
06795 
06796    if( FIM_selection_name[ifim] != NULL ){  /* if dialog box has a label */
06797       txtW_ON = 1;
06798 
06799       if( ifim != 1 ){
06800          strcpy(stst,FIM_selection_name[ifim]) ;
06801       } else {
06802               if( rot_direct == -1 ) strcpy(stst,"Reference ") ;
06803          else if( rot_direct ==  0 ) strcpy(stst,"Ort ") ;
06804          else                        strcpy(stst,"Useless ") ;
06805          strcat(stst,FIM_selection_name[ifim]) ;
06806       }
06807 
06808       x = 50 + GL_DLX;
06809       y = xtkeys[FIM_first_key].y ;
06810 
06811       strp[0] = ASC_NUL ;
06812       take_file_name(theDisp, GWindow , CMap, txtGC, mfinfo, x, y, strp, 41,
06813                      stst , 0 );
06814       txtW_ON = 0 ;
06815       if( strlen(strp) <= 0 ) return 0;
06816    }
06817 
06818    switch( ikey ){
06819 
06820       /*** set threshold ***/
06821 
06822       case kFI1:
06823          fval = strtod( strp , &cpt ) ;
06824          if( *cpt != ASC_NUL || fval < 0.0 || fval > 1.0 ){
06825             fprintf(stderr,
06826                     "\n*** Illegal correlation threshold %s!\n" , strp ) ;
06827             XBell(theDisp, 100); return 0;
06828          } else {
06829             RWC_pcthresh = fval ;
06830          }
06831       break ;  /* end of ikey=kFI1 */
06832 
06833      /*** set reference time series ***/
06834 
06835       case kFI2:
06836 
06837          /*** turn FIM off ***/
06838 
06839          if( strcmp(strp,"!nofim") == 0 ){
06840 
06841             RWC_do_overfim = 0 ;
06842             if( RWC_imover != NULL ) { free(RWC_imover) ; RWC_imover = NULL ; }
06843             if( RWC_ideal  != NULL ){
06844                RWC_free_time_series( RWC_ideal ) ;
06845                RWC_ideal = NULL ;
06846             }
06847 
06848          } else {
06849 
06850             newts = RWC_read_time_series( strp ) ;
06851             if( newts == NULL || newts->len < npoints ){
06852                fprintf(stderr,
06853                        "\n*** Illegal vector file %s!\n" , strp ) ;
06854                XBell(theDisp, 100); return 0;
06855             }
06856 
06857             if( rot_direct == -1 ){  /* left button */
06858                if( RWC_ideal != NULL ) RWC_free_time_series( RWC_ideal ) ;
06859                RWC_ideal      = newts ;
06860                RWC_do_overfim = 1 ;
06861 
06862             } else if( rot_direct == 0 ){ /* middle button */
06863                if( RWC_numort >= MAX_NUMORT ){ XBell(theDisp, 100); return 0; }
06864                RWC_ort[RWC_numort++] = newts ;
06865 
06866             } else { XBell(theDisp, 100); return 0; }
06867 
06868          }
06869          ref_modified      = 1 ;
06870          kFI3_refsum_count = -1 ;
06871       break ;  /* end of ikey=kFI2 */
06872 
06873       case kFI3:
06874          if( rot_direct == 1 ){  /* right button => change key */
06875 
06876             if( (rot_state & (ShiftMask | ControlMask)) == 0 ){
06877                kFI3_status = (kFI3_status+1) % (kFI3_NUM) ;            /* forward */
06878             } else {
06879                kFI3_status = (kFI3_status-1+kFI3_NUM) % (kFI3_NUM) ;   /* backward */
06880             }
06881             xtkeys[kFI3].st = key_kFI3[kFI3_status] ;
06882             DrawKey(kFI3) ;
06883             return 0;
06884          }  /* end of handling right button press */
06885 
06886          /*** perform actions based on status of key ***/
06887 
06888          switch( kFI3_status ){
06889 
06890             case -1:{
06891                int ii ;
06892 
06893                fprintf(stderr,"\a\n") ;
06894                fprintf(stderr,"*** Button 3 cycles between options  ***\n");
06895                fprintf(stderr,"*** [Shift+Button 3 cycles backwards ***\n");
06896                fprintf(stderr,"*** Buttons 1 and 2 choose options:  ***\n");
06897                fprintf(stderr,"***   for -+ options, Button 1 is -  ***\n");
06898                fprintf(stderr,"***                   Button 2 is +  ***\n");
06899                fprintf(stderr,"*** Keys available:\n") ;
06900 
06901                for( ii=0 ; ii < kFI3_NUM ; ii++ )
06902                   fprintf(stderr,"    %s %s\n" ,
06903                           key_kFI3[ii] , key_kFI3_help[ii] ) ;
06904 
06905             }
06906             /* fall through to default on purpose */
06907 
06908             default:{
06909                XBell(theDisp,100) ; return 0;
06910             }
06911 
06912          /*** use current pixel ***/
06913 
06914             case 0:
06915             case 1:{
06916                char * fake_name ;
06917                float * id ;
06918                int ii , addit ;
06919 
06920                fake_name = (char *) malloc( 24 ) ;
06921                if( fake_name == NULL ){
06922                   XBell(theDisp,100) ; return 0;
06923                }
06924 
06925                addit = (kFI3_status == 1) && ( RWC_ideal != NULL )
06926                                           && ( RWC_do_overfim )    ;
06927 
06928                if( !addit ){
06929                   RWC_free_time_series( RWC_ideal ) ;
06930                   RWC_ideal = RWC_blank_time_series( npoints ) ;
06931                }
06932 
06933                id = RWC_ideal->ts ;
06934 
06935                if( addit && kFI3_refsum_count < 0 ){
06936                   for( ii=0 ; ii < npoints ; ii++ )
06937                      if( fabs(id[ii]) < 33333.0 ) id[ii] *= 0.01 ;
06938 
06939                   kFI3_refsum_count = 1 ;
06940                }
06941 
06942                if( addit ){
06943                   for( ii=0 ; ii < npoints ; ii++ )
06944                                           id[ii] += 0.01*val[xc][yc][ii];
06945                   kFI3_refsum_count++ ;
06946                } else {
06947                   for( ii=0 ; ii < npoints ; ii++ )
06948                                           id[ii]  = 0.01*val[xc][yc][ii];
06949                   kFI3_refsum_count = 1 ;
06950                }
06951 
06952                if( addit ){
06953                   sprintf( fake_name , "%d:+PIX%d:%d" , kFI3_refsum_count,xpoint,ypoint ) ;
06954                } else {
06955                   sprintf( fake_name , "PIX%d:%d" , xpoint,ypoint ) ;
06956                }
06957                if( RWC_ideal->fname != NULL ) free( RWC_ideal->fname ) ;
06958                RWC_ideal->fname = fake_name ;
06959 
06960                RWC_do_overfim = 1 ;
06961                ref_modified   = 1 ;
06962             }
06963             break ;  /* end of status=0 or 1 */
06964 
06965             /*** median filter ***/
06966 
06967             case 2:{
06968                char * fake_name ;
06969                int flen ;
06970 
06971                if( RWC_ideal == NULL || !RWC_do_overfim ){
06972                   XBell(theDisp,100) ; return 0;
06973                }
06974 
06975                RWC_medfilt_time_series( RWC_ideal ) ;
06976 
06977                flen = 4 ;
06978                if( RWC_ideal->fname != NULL ) flen += strlen(RWC_ideal->fname) ;
06979 
06980                fake_name = (char *) malloc( flen ) ;
06981                if( fake_name != NULL ){
06982                   strcpy(fake_name,RWC_ideal->fname) ;
06983                   strcat(fake_name,"!m") ;
06984                   if( RWC_ideal->fname != NULL ) free( RWC_ideal->fname ) ;
06985                   RWC_ideal->fname = fake_name ;
06986                }
06987 
06988                ref_modified = 1 ;
06989             }
06990             break ;  /* end of status=2 */
06991 
06992             /*** modify threshold ***/
06993 
06994             case 3:{
06995 
06996                if( RWC_ideal == NULL || !RWC_do_overfim ){
06997                   XBell(theDisp,100) ; return 0;
06998                }
06999 
07000                if( rot_direct   == -1  ) RWC_pcthresh -= 0.05 ;
07001                if( rot_direct   ==  0  ) RWC_pcthresh += 0.05 ;
07002                if( RWC_pcthresh >= 1.0 ) RWC_pcthresh  = 0.99999 ;
07003                if( RWC_pcthresh <  0.0 ) RWC_pcthresh  = 0.0 ;
07004             }
07005             break ;  /* end of status=3 */
07006 
07007             /*** nofim ***/
07008 
07009             case 4:{
07010                RWC_do_overfim = 0 ;
07011                if( RWC_imover != NULL ) {free(RWC_imover); RWC_imover = NULL;}
07012                if( RWC_ideal != NULL ){
07013                   RWC_free_time_series( RWC_ideal ) ;
07014                   RWC_ideal = NULL ;
07015                }
07016                ref_modified = 1 ;
07017             }
07018             break ;  /* end of status=4 */
07019 
07020             /*** number of ref plots to show ***/
07021 
07022             case 5:{
07023                int kold = kFI3_show_ref ;
07024 
07025                if( !RWC_do_overfim || RWC_ideal == NULL ){
07026                   XBell(theDisp,100) ; return 0;
07027                }
07028                if( rot_direct == -1 && kFI3_show_ref > 0 ) kFI3_show_ref -- ;
07029                if( rot_direct ==  0 && kFI3_show_ref < 2 ) kFI3_show_ref ++ ;
07030 
07031                if( kold == kFI3_show_ref ){ XBell(theDisp,100) ; return 0; }
07032 
07033                ref_modified = 1 ;   /* force redraw */
07034             }
07035             break ;  /* end of status=5 */
07036 
07037             /*** write current reference to a file ***/
07038 
07039             case 6:{
07040                float idmax , idmin , val , yscal , yoff ;
07041                float *id ;
07042                int ii , ival ;
07043                FILE * fp ;
07044 
07045                if( !RWC_do_overfim || RWC_ideal == NULL ){ XBell(theDisp,100) ; return 0; }
07046 
07047                /*** get file name ***/
07048 
07049                txtW_ON = 1;
07050                x       = 50 + GL_DLX;
07051                y       = xtkeys[FIM_first_key].y ;
07052                strp[0] = ASC_NUL ;
07053                take_file_name(theDisp, GWindow , CMap, txtGC, mfinfo, x, y,
07054                               strp, 41, "Filename for Reference Function:", 1 );
07055                txtW_ON = 0 ;
07056                if( strlen(strp) <= 0 ) return 0;
07057 
07058                /*** find scale factor for plot ***/
07059 
07060                if( kFI3_refsum_count > 0 ){
07061                   yscal = 100.0 / kFI3_refsum_count ;
07062                   yoff  = 0.0 ;
07063                } else {
07064                   yscal = 1.0 ;
07065                   yoff  = 0.0 ;
07066                }
07067                id = RWC_ideal->ts ;
07068 
07069 /*** this code is for rescaling the plot to range 0..10000 ***/
07070 #if 0
07071                idmax = -99999.0 ;
07072                idmin =  99999.0 ;
07073 
07074                for( ii=0 ; ii < npoints ; ii++ ){
07075                  val = id[ii] ;
07076                  if( fabs(val) < 33333.0 ){
07077                     idmax = MAX(idmax,val) ;
07078                     idmin = MIN(idmin,val) ;
07079                  }
07080                }
07081                if( idmax >= 33333.0 || idmax <= -33333.0 || idmax <= idmin )
07082                  return 0;
07083 
07084                yscal = 10000.0 / (idmax-idmin) ;
07085                yoff  = idmin ;
07086 #endif
07087                /*** write plot ***/
07088 
07089                fp = fopen( strp , "w" ) ;
07090                if( fp == NULL ){
07091                   fprintf(stderr,"\n*** cannot open file %s\n",strp) ;
07092                   XBell(theDisp,100) ; return 0;
07093                }
07094 
07095                for( ii=0 ; ii < npoints ; ii++ ){
07096                   val  = id[ii] ;
07097                   ival = (fabs(val) < 33333.0) ? (int) (yscal*(val-yoff))
07098                                                : 99999 ;
07099                   fprintf(fp,"%5d\n",ival) ;
07100                }
07101                fclose(fp) ;
07102                fprintf(stderr,"*** wrote plot file %s\n",strp) ;
07103 
07104                return 0;  /* no need to change status, so exit now */
07105             }
07106             break ;  /* end of status=6 */
07107 
07108             /*** increment # of polynomial orts ***/
07109 
07110             case 7:{
07111                int kold = RWC_polort ;
07112 
07113                if( rot_direct == -1 ){
07114                   if( RWC_polort >= 0 ) RWC_polort -- ;
07115                } else if( rot_direct == 0 ){
07116                   if( RWC_polort < MAX_POLORT ) RWC_polort ++ ;
07117                }
07118                if( kold == RWC_polort ){ XBell(theDisp,100) ; return 0; }
07119             }
07120             break ;  /* end of status=7 */
07121 
07122             /*** make current ref file an ort also ***/
07123 
07124             case 8:{
07125                int ii ;
07126 
07127                if( RWC_ideal == NULL || RWC_numort == MAX_NUMORT ){
07128                   XBell(theDisp,100) ; return 0;
07129                }
07130 
07131                RWC_ort[RWC_numort++] = RWC_ideal ;  /* put into ort array */
07132 
07133                /* now, turn fim off, since don't have a ref anymore */
07134 
07135                ref_modified   = 1 ;
07136                RWC_do_overfim = 0 ;
07137                RWC_ideal      = NULL ;
07138                if( RWC_imover != NULL ) {free(RWC_imover); RWC_imover = NULL;}
07139 
07140                /* switch to ref=plot status; current status is now useless */
07141 
07142                kFI3_status     = 0 ;
07143                xtkeys[kFI3].st = key_kFI3[kFI3_status] ;
07144                DrawKey(kFI3) ;
07145             }
07146             break ; /* end of status=8 */
07147 
07148             /*** clear all orts ***/
07149 
07150             case 9:{
07151                int ii ;
07152                if( RWC_numort == 0 ){ XBell(theDisp,100) ; return 0; }
07153                for( ii=0 ; ii < RWC_numort ; ii++ ){
07154                   RWC_free_time_series( RWC_ort[ii] ) ;
07155                   RWC_ort[ii] = NULL ;
07156                }
07157                RWC_numort = 0 ;
07158             }
07159             break ; /* end of status=9 */
07160 
07161 #if 0
07162             /*** modify DFILT_code ***/
07163 
07164             case 10:{
07165                int old_code = DFILT_code ;
07166 
07167                if( RWC_ideal == NULL || !RWC_do_overfim ){
07168                   XBell(theDisp,100) ; return 0;
07169                }
07170 
07171                if( rot_direct   == -1  ) DFILT_code = DFILT_NONE ;
07172                if( rot_direct   ==  0  ) DFILT_code = DFILT_TIME ;
07173 
07174                if( old_code == DFILT_code ){ XBell(theDisp,100) ; return 0; }
07175             }
07176             break ;  /* end of status=10 */
07177 #endif
07178 
07179             /*** modify LSQ_code ***/
07180 
07181             case 10:{
07182                int old_code = LSQ_code , old_imed = LSQ_imedit[LSQ_code] ;
07183 
07184                if( RWC_ideal == NULL || !RWC_do_overfim || LSQ_fitim == NULL ){
07185                   XBell(theDisp,100) ; return 0;
07186                }
07187 
07188                if( rot_direct   == -1      ) LSQ_code-- ;
07189                if( rot_direct   ==  0      ) LSQ_code++ ;
07190                if( LSQ_code < LSQ_NONE     ) LSQ_code = LSQ_LASTCODE ;
07191                if( LSQ_code > LSQ_LASTCODE ) LSQ_code = LSQ_NONE ;
07192 
07193                DrawTopWindow() ; redraw_graph() ;
07194                old_im = -1 ;
07195                if( old_imed != LSQ_imedit[LSQ_code] && Im_Nr < npoints ) Put_image( Im_Nr ) ;
07196 
07197                return 0;
07198             }
07199             break ;  /* end of status=10 */
07200 
07201          }  /* end of kFI3_status switch */
07202       break ; /* end of ikey=kFI3 */
07203 
07204    }  /* end of ikey switch */
07205 
07206    /*** if we get to here, the user changed something,
07207         so mark the FIM calculations to be redone, and do some graphics ***/
07208 
07209    InvertKey(kFIM) ;  /* flash the FIM key */
07210    DrawTopWindow() ;  /* update the labels */
07211    InvertKey(kFIM) ;
07212 
07213    if( ref_modified ){
07214       redraw_graph() ;
07215       FIM_edit_time_series( RWC_ideal ) ;
07216    }
07217 
07218    FIM_modified = 1 ;
07219    return 0;
07220 }
07221 
07222 /****************************************************************************/
07223 
07224 int FIM_edit_time_series( vec )
07225   time_series * vec ;
07226 {
07227    int i , itop ;
07228    if( vec == NULL ) return 0;
07229 
07230    /*** blast out first locations, if requested ***/
07231 
07232    itop = MIN( Im_frst-1 , (vec->len)-1 ) ;
07233    for (i=0; i < itop ; i++) vec->ts[i] = 99999.99 ;
07234 
07235    return 0;
07236 }
07237 
07238 /*--------------------------------------------------------------------------*/
07239 
07240 /*** delete the current image, if possible ***/
07241 
07242 int kill_curr_im()
07243 {
07244    int kk ;
07245 
07246    if( Im_Nr < npoints ){ XBell(theDisp,100) ; return 0; }
07247 
07248    mri_free( allim[Im_Nr] ) ;
07249    for( kk=Im_Nr+1 ; kk < N_im ; kk++ ) allim[kk-1] = allim[kk] ;
07250 
07251    N_im-- ;                           /* one less image in the pile */
07252    old_im = -1 ;                      /* mark saved image as invalid */
07253    Im_Nr  = MIN( Im_Nr , N_im-1 ) ;   /* leave Im_Nr same, if possible */
07254 
07255    Put_image(Im_Nr);  /* redisplay */
07256    DrawSubWindow();
07257    DrawTopWindow();
07258    XFlush(theDisp);
07259 
07260    return 0;
07261 }
07262 
07263 /*--------------------------------------------------------------------------*/
07264 
07265 /*** add an extra image onto the end of allim ***/
07266 
07267 void add_extra_image(newim)
07268      MRI_IMAGE *newim;
07269 {
07270    if( N_im >= dim_allim ){
07271       dim_allim += INC_ALLIM ;
07272       allim = AFREALL( allim, MRI_IMAGE*, sizeof(MRI_IMAGE *) * dim_allim ); 
07273       if( allim == NULL ){
07274          fprintf(stderr,"\n*** cannot allocate space for new image!\a\n") ;
07275          exit(-1) ;
07276       }
07277    }
07278 
07279    allim[N_im] = mri_to_short( 0.0 , newim ) ;
07280    mri_add_name( newim->name , allim[N_im] ) ;
07281    N_im++ ;
07282 
07283    Im_Nr = N_im - 1 ;
07284 
07285    Put_image(Im_Nr);
07286    DrawSubWindow();
07287    DrawTopWindow();
07288 
07289    return ;
07290 }
07291 
07292 /*----------------------------------------------------------------------*/
07293    int read_new_im()
07294 {
07295    MRI_IMAGE * im ;
07296    int x , y ;
07297 
07298    if ( txtW_ON ) {
07299       XBell(theDisp, 100); return(2);
07300    }
07301    txtW_ON = 1;
07302 
07303    x = 50 + GL_DLX;
07304    y = 50 + GT_DLY;
07305 
07306    strp[0] = ASC_NUL ;
07307    take_file_name(theDisp, GWindow , CMap, txtGC, mfinfo, x, y, strp, 41,
07308                   "Enter input image name:" , 0 );
07309    txtW_ON = 0 ;
07310 
07311    if( strp[0] == '\0' ) return(1) ;
07312 
07313    im = mri_read_nsize( strp ) ;
07314 
07315    /* we have already decided on swapping     27 Aug 2004 [rickr] */
07316 
07317    if ( RCR_swap && im->kind == MRI_short ) {
07318      swap_2(MRI_SHORT_PTR(im), im->nx*im->ny*2);
07319    }
07320    else if ( RCR_swap && im->kind == MRI_float ) {
07321      swap_4(MRI_FLOAT_PTR(im), im->nx*im->ny*4);
07322    }
07323 
07324    if( im == NULL ) return(3) ;
07325 
07326    if( (im->nx != im->ny) ||
07327        ( (im->nx != EPX1) && (im->nx != EPX2) &&
07328          (im->nx != EPX3) && (im->nx != EPX4) ) ){
07329 
07330       fprintf(stderr,"\n*** input file %s has illegal dimensions!\n",strp) ;
07331       mri_free( im ) ;
07332       return(4) ;
07333    }
07334 
07335    add_extra_image( im ) ;
07336    mri_free( im ) ;
07337 
07338    return(0);
07339 }
07340 
07341 /**-------------------------------------------------------------------------**/
07342 
07343 /*** initialize the FIM colors:
07344         from the command line options (in FIM_opt_* variables), OR
07345         from the X11 defaults database (in the fim_* variables), OR
07346         from the default tables (in overfim.h)
07347 ***/
07348 
07349 void RWC_init_fim_colors()
07350 {
07351    char * xdef ;
07352    char stst[32] ;
07353    int ncol = DEFAULT_FIM_COLORS ;  /* defined in overfim.h */
07354    int ii , thr_good ;
07355    XColor test_color ;
07356    float xx ;
07357 
07358 /*
07359 #define COLOR_DEBUG
07360 */
07361 
07362 #ifdef COLOR_DEBUG
07363 #  define MESG(str) fprintf(stderr,"read string %s; %s\n",xdef,str)
07364 #else
07365 #  define MESG(str)
07366 #endif
07367 
07368    if( FIM_opt_colors > 0 ){
07369       ncol = FIM_opt_colors ;
07370    } else {
07371       xdef = XGetDefault(theDisp,Xdef_Name,"fim_colors") ;
07372       if( xdef != NULL ){
07373          ii = strtol( xdef , NULL , 10 ) ;
07374          if( ii > 0 && ii <= MAX_FIM_COLORS ){
07375             ncol = ii ;
07376             MESG("for ncol") ;
07377          } else {
07378             fprintf(stderr,
07379                     "\n*** illegal fim_colors in X11 database: %s\n",xdef) ;
07380          }
07381       }
07382    }
07383    RWC_fim_colors = ncol ;
07384 
07385    thr_good = 0 ;
07386 
07387    /* read from X defaults or from FIM_opt_* variables */
07388 
07389    for( ii=1 ; ii <= ncol ; ii++ ){
07390 
07391       sprintf( stst , "fim_pos_%d" , ii ) ;
07392       if( FIM_opt_colors > 0 ){
07393          xdef = FIM_opt_pos[ii-1] ;
07394       } else {
07395          xdef = XGetDefault(theDisp,Xdef_Name,stst) ;
07396       }
07397       if( xdef != NULL ){
07398          MESG("for pos color") ;
07399          if( check_color(xdef) ) FIM_poscol[ii-1] = xdef ;
07400          else
07401             fprintf(stderr,"\n*** illegal FIM color %s replaced by %s\n",
07402                     xdef , FIM_poscol[ii-1] ) ;
07403       }
07404 
07405       sprintf( stst , "fim_neg_%d" , ii ) ;
07406       if( FIM_opt_colors > 0 ){
07407          xdef = FIM_opt_neg[ii-1] ;
07408       } else {
07409          xdef = XGetDefault(theDisp,Xdef_Name,stst) ;
07410       }
07411       if( xdef != NULL ){
07412          MESG("for neg color") ;
07413          if( check_color(xdef) ) FIM_negcol[ii-1] = xdef ;
07414          else
07415             fprintf(stderr,"\n*** illegal FIM color %s replaced by %s\n",
07416                     xdef , FIM_negcol[ii-1] ) ;
07417       }
07418 
07419       if( FIM_opt_colors > 0 ){
07420          RWC_fim_thresh[ncol-ii] = FIM_opt_thr[ii-1] ;
07421          thr_good ++ ;
07422       } else {
07423          sprintf( stst , "fim_thr_%d" , ii ) ;
07424          xdef = XGetDefault(theDisp,Xdef_Name,stst) ;
07425          if( xdef != NULL ){
07426             MESG("for thresh") ;
07427             xx = strtod( xdef , NULL ) ;
07428             if( xx > 0.0 && xx < 1.0 ){
07429                RWC_fim_thresh[ncol-ii] = xx ;
07430                thr_good ++ ;
07431             } else {
07432                fprintf(stderr,"\n*** illegal FIM threshold %s being replaced\n",
07433                        xdef ) ;
07434             }
07435          }
07436       }  /* end if FIM_opt_colors */
07437 
07438    }  /* end for ii */
07439 
07440    /*** check if thresholds are all good ***/
07441 
07442    if( thr_good > 0 && thr_good < ncol ){
07443       fprintf(stderr,"\n*** input thresholds being replaced!\n") ;
07444    }
07445 
07446    if( thr_good < ncol ){
07447       float dth = 0.95 / ncol ;
07448       for( ii=0 ; ii < ncol ; ii++ ) RWC_fim_thresh[ii] = 0.05 + ii*dth ;
07449    }
07450 
07451    if( thr_good > 0 && thr_good < ncol ){
07452       for( ii=0 ; ii < ncol ; ii++ )
07453          fprintf(stderr,"%5.2f ",RWC_fim_thresh[ii]);
07454    }
07455 
07456    /*** now, actually put color indices into place ***/
07457 
07458    for( ii=0 ; ii < ncol ; ii++ ){
07459       int rr,gg,bb ;
07460 
07461       XParseColor(theDisp,CMap,FIM_poscol[ncol-ii-1],&test_color) ;
07462       rr = test_color.red ;
07463       gg = test_color.green ;
07464       bb = test_color.blue ;
07465 
07466 #ifdef COLOR_DEBUG
07467       fprintf(stderr,"FIM %d: pos color = %d %d %d\n" , ii,rr,gg,bb ) ;
07468 #endif
07469 
07470       add_extra_color( rr,gg,bb , NUM_STD_COLORS + ii + 1) ;
07471       RWC_fim_colors_pos[ii] =  -(NUM_STD_COLORS + ii + 1) ;
07472 
07473       XParseColor(theDisp,CMap,FIM_negcol[ncol-ii-1],&test_color) ;
07474       rr = test_color.red ;
07475       gg = test_color.green ;
07476       bb = test_color.blue ;
07477 
07478 #ifdef COLOR_DEBUG
07479       fprintf(stderr,"      : neg color = %d %d %d\n" , rr,gg,bb ) ;
07480       fprintf(stderr,"      : thresh    = %f\n"       , RWC_fim_thresh[ii] ) ;
07481 #endif
07482 
07483       add_extra_color( rr,gg,bb , NUM_STD_COLORS + ncol + ii + 1) ;
07484       RWC_fim_colors_neg[ii] =  -(NUM_STD_COLORS + ncol + ii + 1) ;
07485    }
07486    return ;
07487 }
07488 
07489 /*-------------------------------------------------------------------------*/
07490 
07491 /*** add a color with the given r,g,b values to the extra_colors table
07492      (see routine STD_colors)
07493 ***/
07494 
07495 void add_extra_color(r, g, b, ind)
07496      int r;
07497      int g;
07498      int b;
07499      int ind;
07500 {
07501    XColor any_col;
07502    int    ic ;
07503    char *cH;
07504    byte  *a8;
07505    short *a16;
07506 
07507    ic = ind - NUM_STD_COLORS ;
07508    if( ic < 1 || ic > MAX_EXTRA_COLORS ){
07509       fprintf(stderr,"\n*** illegal call to add_extra_color()!\a\n");
07510       exit(-1) ;
07511    }
07512 
07513    any_col.red   = r ; any_col.green = g ; any_col.blue = b ;
07514    any_col.flags = DoRed | DoGreen | DoBlue;
07515 
07516    if ( AJ_PseudoColor ) {
07517 #ifdef RWCOX_LINUX
07518       if( !XAllocColor(theDisp, CMap, &any_col) ){
07519          fprintf(stderr,"cannot XAllocColor in add_extra_color(). RWC\n") ;
07520          return ;
07521    }
07522 #else
07523       if( !XAllocColor(theDisp, CMap, &any_col) )
07524          FatalError ("XAllocColor problem in add_extra_color(). RWC");
07525 #endif  /* RWCOX_LINUX */
07526 
07527       extra_color_x11[ic-1] = any_col.pixel ;
07528    }
07529    else {
07530       switch( bperpix ) {
07531          case 32:
07532             cH = (char *) &AJ_RGB[ind + NCOLORS - 1];
07533          case 24:
07534             a8 = (byte *) AJ_RGB;
07535             cH = a8 + (ind + NCOLORS - 1) * 3;
07536          break;
07537          case 16:
07538             a16 = (short *) AJ_RGB;
07539             cH = (char *) &a16[ind + NCOLORS - 1];
07540          break;
07541          case 8:
07542             a8 = (byte *) AJ_RGB;
07543             cH = (char *) &a8[ind + NCOLORS - 1];
07544          break;
07545       }
07546 
07547       AJ_rgb[0].r = (r >> 8) & 0xff;
07548       AJ_rgb[0].g = (g >> 8) & 0xff;
07549       AJ_rgb[0].b = (b >> 8) & 0xff;
07550       Make_RGB_lookup(AJ_rgb, cH, 1);
07551    }
07552 }
07553 
07554 /* ----------------------------------------------------------------------- */
07555 
07556 /*** check that a character string is a valid color name ***/
07557 
07558 int check_color( cname )
07559   char * cname ;
07560 {
07561    XColor test_color ;
07562 
07563    return XParseColor(theDisp,CMap,cname,&test_color) ;
07564 }
07565 
07566 /* --------------- */
07567    int dec_indx(n)
07568    int n;
07569 /* --------------- */
07570 {
07571    int m;
07572 
07573    m = 0;
07574    while (n) {
07575       n /= 10;
07576       m++;
07577    }
07578    return (m);
07579 }
07580 
07581 /* -------------------- */
07582    int Get_X_Y(mx, my)
07583    int *mx, *my;
07584 /* -------------------- */
07585 {
07586    Window       rW, cW;
07587    u_int        key;
07588    int          x, y, rx, ry;
07589 
07590    if ( XQueryPointer(theDisp, theWindow, &rW, &cW,
07591                                 &rx, &ry, &x, &y, &key) ) {
07592       if ( (x < eWIDE) && (y < eHIGH) ) {
07593          *mx = Mltx[x]/x_mag;
07594          *my = Mlty[y]/x_mag;
07595          return(1);
07596       }
07597       else
07598          return(0);
07599    }
07600    else
07601       return(0);
07602 }
07603 
07604 /* ----------------------- */
07605    int swap_2(arR, nr)
07606    char *arR;
07607    int nr;
07608 /* ----------------------- */
07609 {
07610    int i;
07611    char ctmp;
07612 
07613    for (i=0; i < nr; i+=2){
07614      ctmp     = arR[i+1];
07615      arR[i+1] = arR[i];
07616      arR[i]   = ctmp;
07617    }
07618 }
07619 
07620 /* ----------------------- */
07621    int swap_4(arR, nr)
07622    char *arR;
07623    int nr;
07624 /* ----------------------- */
07625 {
07626    int i;
07627    char ctmp2, ctmp3;
07628 
07629    for (i=0; i < nr; i+=4){
07630      ctmp3    = arR[i+3];
07631      ctmp2    = arR[i+2];
07632      arR[i+2] = arR[i+1];
07633      arR[i+3] = arR[i];
07634      arR[i]   = ctmp3;
07635      arR[i+1] = ctmp2;
07636    }
07637 }
07638 
07639 /* ----------------------------------------- */
07640    int
07641    AJ_StoreColors(Disp, cmap, mc, nc, color)
07642    Display   *Disp;
07643    Colormap  cmap;
07644    XColor    *mc;
07645    int       nc, color;
07646 /* ----------------------------------------- */
07647 {
07648    int i;
07649    if ( color ) {                    /* correction for inverse order AAJ */
07650       for (i=0; i < nc; i++) {
07651          AJ_rgb[nc-i-1].r = mc[i].red >> 8;
07652          AJ_rgb[nc-i-1].g = mc[i].green >> 8;
07653          AJ_rgb[nc-i-1].b = mc[i].blue >> 8;
07654       }
07655    }
07656    else {
07657       for (i=0; i < nc; i++) {
07658          AJ_rgb[i].r = mc[i].red >> 8;
07659          AJ_rgb[i].g = mc[i].green >> 8;
07660          AJ_rgb[i].b = mc[i].blue >> 8;
07661       }
07662    }
07663    Make_RGB_lookup(AJ_rgb, AJ_RGB, nc);
07664    if ( expImage != NULL )  Put_image(Im_Nr);
07665 }
07666 
07667 /* --------------------------------- create machine packed RGB values */
07668    int
07669    Make_RGB_lookup(in, out, nc)
07670    AJ_rgb_str *in;
07671    char *out;
07672    int nc;
07673 /* --------------------------------- */
07674 {
07675    unsigned long r, g, b, rmask, gmask, bmask;
07676    int           rshift, gshift, bshift, i, *xcol;
07677    byte          *ip;
07678 
07679    rmask = theVisual->red_mask;   rshift = 7 - highbit(rmask);
07680    gmask = theVisual->green_mask; gshift = 7 - highbit(gmask);
07681    bmask = theVisual->blue_mask;  bshift = 7 - highbit(bmask);
07682 
07683    xcol = (int *) malloc(sizeof(int) * nc);
07684    for (i=0; i < nc; i++) {
07685       r = in[i].r;
07686       g = in[i].g;
07687       b = in[i].b;
07688       r = (rshift<0) ? (r<<(-rshift)) : (r>>rshift); r = r & rmask;
07689       g = (gshift<0) ? (g<<(-gshift)) : (g>>gshift); g = g & gmask;
07690       b = (bshift<0) ? (b<<(-bshift)) : (b>>bshift); b = b & bmask;
07691       xcol[i] = r | g | b;
07692    }
07693 
07694    ip = (byte *) out;
07695    switch( bperpix ) {
07696       case 32:
07697         if (border == MSBFirst)
07698            for( i=0 ; i < nc ; i++ ){
07699               *ip++ = (xcol[i]>>24) & 0xff ;
07700               *ip++ = (xcol[i]>>16) & 0xff ;
07701               *ip++ = (xcol[i]>>8)  & 0xff ;
07702               *ip++ =  xcol[i]      & 0xff ;
07703             }
07704         else
07705            for( i=0 ; i < nc ; i++ ){
07706               *ip++ =  xcol[i]      & 0xff ;
07707               *ip++ = (xcol[i]>>8)  & 0xff ;
07708               *ip++ = (xcol[i]>>16) & 0xff ;
07709               *ip++ = (xcol[i]>>24) & 0xff ;
07710             }
07711       break ;
07712 
07713       case 24:
07714         if (border == MSBFirst)
07715            for( i=0 ; i < nc ; i++ ){
07716              *ip++ = (xcol[i]>>16) & 0xff ;
07717              *ip++ = (xcol[i]>>8)  & 0xff ;
07718              *ip++ =  xcol[i]      & 0xff ;
07719            }
07720         else
07721            for( i=0 ; i < nc ; i++ ){
07722              *ip++ =  xcol[i]      & 0xff ;
07723              *ip++ = (xcol[i]>>8)  & 0xff ;
07724              *ip++ = (xcol[i]>>16) & 0xff ;
07725            }
07726       break ;
07727 
07728       case 16:
07729         if (border == MSBFirst)
07730            for( i=0 ; i < nc ; i++ ){
07731              *ip++ = (xcol[i]>>8)  & 0xff ;
07732              *ip++ =  xcol[i]      & 0xff ;
07733            }
07734         else
07735            for( i=0 ; i < nc ; i++ ){
07736              *ip++ =  xcol[i]      & 0xff ;
07737              *ip++ = (xcol[i]>>8)  & 0xff ;
07738            }
07739       break ;
07740 
07741       case 8:
07742            for( i=0 ; i < nc ; i++ )
07743               *ip++ = xcol[i] & 0xff ;
07744       break ;
07745    }
07746 }
07747 
07748 /* ---------------------------------- */
07749    int
07750    AJ_make_STDcol(mc, nc)
07751    struct S_16_c  *mc;
07752    int    nc;
07753 /* ---------------------------------- */
07754 {
07755    int i;
07756    char *cH;
07757    byte  *a8;
07758    short *a16;
07759  
07760    switch( bperpix ) {
07761       case 32:
07762          cH = (char *) &AJ_RGB[NCOLORS];
07763       break;
07764       case 24:
07765          a8 = (byte *) AJ_RGB;
07766          cH = a8 + NCOLORS * 3;
07767       break;
07768       case 16:
07769          a16 = (short *) AJ_RGB;
07770          cH = (char *) &a16[NCOLORS];
07771       break;
07772       case 8:
07773          a8 = (byte *) AJ_RGB;
07774          cH = (char *) &a8[NCOLORS];
07775       break;
07776    }
07777   
07778    for (i=0; i < nc; i++) {
07779       AJ_rgb[i].r = mc[i].red >> 8;
07780       AJ_rgb[i].g = mc[i].green >> 8;
07781       AJ_rgb[i].b = mc[i].blue >> 8;
07782    }
07783    Make_RGB_lookup(AJ_rgb, cH, nc);
07784 }
07785 
07786 /* ------------- */
07787    int
07788    AJ_init_RGB()
07789 /* ------------- */
07790 {
07791    int i;
07792    XImage *tstImage;
07793    tstImage = XCreateImage(theDisp, theVisual, Planes, ZPixmap,
07794                            0, NULL, 16, 16, 32, 0);
07795    if ( tstImage == NULL ) return 1;
07796    bperpix = tstImage->bits_per_pixel;
07797    border  = tstImage->byte_order;
07798    XDestroyImage(tstImage);
07799   /* AJ our order for RGB */
07800    for (i=0; i < (NCOLORS); i++) pixels[i] = i;
07801    for (i=0; i < (NUM_STD_COLORS + MAX_EXTRA_COLORS); i++)
07802       STD_indx[i] = NCOLORS + i;
07803 
07804    return 0;
07805 }
07806 
07807 /*------------------------------------------------------------------------
07808   Returns position of highest set bit in 'ul' as an integer (0-31),
07809   or returns -1 if no bit is set.
07810 --------------------------------------------------------------------------*/
07811 /* ------------------------- */
07812    static int
07813    highbit(unsigned long ul)
07814 /* ------------------------- */
07815 {
07816   int i;  unsigned long hb;
07817 
07818   hb = 0x80;  hb = hb << 24;   /* hb = 0x80000000UL */
07819   for (i=31; ((ul & hb) == 0) && i>=0;  i--, ul<<=1);
07820   return i;
07821 }
 

Powered by Plone

This site conforms to the following standards: