File: uves_mdark_impl.c

package info (click to toggle)
cpl-plugin-uves 6.1.3+dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 23,128 kB
  • sloc: ansic: 171,056; sh: 4,359; python: 3,002; makefile: 1,322
file content (1116 lines) | stat: -rw-r--r-- 38,642 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
/*                                                                              *
 *   This file is part of the ESO UVES Pipeline                                 *
 *   Copyright (C) 2004,2005 European Southern Observatory                      *
 *                                                                              *
 *   This library is free software; you can redistribute it and/or modify       *
 *   it under the terms of the GNU General Public License as published by       *
 *   the Free Software Foundation; either version 2 of the License, or          *
 *   (at your option) any later version.                                        *
 *                                                                              *
 *   This program is distributed in the hope that it will be useful,            *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 *   GNU General Public License for more details.                               *
 *                                                                              *
 *   You should have received a copy of the GNU General Public License          *
 *   along with this program; if not, write to the Free Software                *
 *   Foundation, 51 Franklin St, Fifth Floor, Boston MA 02110-1301 USA          *
 */
 
/*
 * $Author: amodigli $
 * $Date: 2011-01-03 08:39:09 $
 * $Revision: 1.53 $
 * $Name: not supported by cvs2svn $
 *
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

/*----------------------------------------------------------------------------*/
/**
 * @defgroup uves_mdark  Recipe: Master Dark
 *
 * This recipe calculates the master dark frame.
 * See man-page for details.
 */
/*----------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------
                                Includes
 -----------------------------------------------------------------------------*/
#include <uves_mdark_impl.h>

#include <uves_parameters.h>
#include <uves_utils.h>
#include <uves.h>
#include <uves_dfs.h>
#include <uves_pfits.h>
#include <uves_qclog.h>
#include <uves_recipe.h>
#include <uves_utils_wrappers.h>
#include <uves_error.h>
#include <uves_globals.h>

#include <cpl.h>
#include <float.h>
#include <string.h>
/*-----------------------------------------------------------------------------
                            Functions prototypes
 -----------------------------------------------------------------------------*/
/*
static int
uves_qcdark_define_parameters_body(cpl_parameterlist *parameters, 
				   const char *recipe_id);
*/
static int
uves_mdark_define_parameters(cpl_parameterlist *parameters);

static void uves_mdark_region_qc(cpl_image* img, 
                                 const cpl_parameterlist* p,
                                 const cpl_imagelist* raw_images,
				 const char* recipe_id,
                                 cpl_table* qclog);
static cpl_image *
uves_mdark_process_chip(const cpl_imagelist *raw_images, 
			uves_propertylist **raw_headers,
			const cpl_image *master_bias,
			uves_propertylist *mdark_header, 
			const cpl_parameterlist *parameters,
			const char* recipe_id,
                        cpl_table* qclog, const int do_qc);


/*-----------------------------------------------------------------------------
                            Recipe standard code
 -----------------------------------------------------------------------------*/
#define cpl_plugin_get_info uves_mdark_get_info
UVES_RECIPE_DEFINE(
    UVES_MDARK_ID, UVES_MDARK_DOM, 
    /* Warning: if more parameters are added to this recipe, they 
       need to be propagated to uves_cal_mkmaster! */
    uves_mdark_define_parameters,
    "Jonas M. Larsen", "cpl@eso.org",
    "Creates the master dark frame",
    "This recipe creates a master dark frame by taking the median of all\n"
    "input frames which should have identical exposure times. Symbolically,\n"
    "   masterdark = median( dark_i ) - masterbias\n"
    "\n"
    "The input dark frames must have same tag and size and must be either\n"
    "(P)DARK_BLUE or (P)DARK_RED. Also, a master bias (MASTER_BIAS_xxxx) must\n"
    "be provided for each chip (xxxx = BLUE, REDL, REDU).\n"
    "\n"
    "On blue input the recipe computes one master dark frame; on red input the\n"
    "recipe produces a master dark frame for each chip (MASTER_(P)DARK_xxxx).\n");

/**@{*/
/*-----------------------------------------------------------------------------
                            Functions code
 -----------------------------------------------------------------------------*/



/*----------------------------------------------------------------------------*/
/**
  @brief    Find basic parameters to control QC   
  @param    parameters        the parameterlist to fill
  @return   0 if everything is ok
 */
/*----------------------------------------------------------------------------*/
static cpl_error_code
uves_extract_basic_parameters_for_qc(const cpl_parameterlist* p,
                                     const char* recipe_id,
                                     int * pr_num_x, 
                                     int* pr_num_y, 
                                     int* pr_box_sx, 
                                     int* pr_box_sy)
{

  char name[MAX_NAME_SIZE];
  char pname[MAX_NAME_SIZE];

  sprintf(name,"reg.num_x");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  uves_msg("pname=%s",pname);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,pr_num_x), 
	"Could not read parameter");

  sprintf(name,"reg.num_y");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,pr_num_y), 
	 "Could not read parameter");

  sprintf(name,"reg.box_sx");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,pr_box_sx),
	 "Could not read parameter");

  sprintf(name,"reg.box_sy");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,pr_box_sy),
	 "Could not read parameter");

  cleanup:
  return cpl_error_get_code();

}






/*----------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options    
  @param    parameters        the parameterlist to fill
  @return   0 if everything is ok
 */
/*----------------------------------------------------------------------------*/
static int
uves_mdark_define_parameters(cpl_parameterlist *parameters)
{
  if (uves_master_stack_define_parameters(parameters,
                                           make_str(UVES_MDARK_ID))
        != CPL_ERROR_NONE)
        {
            return -1;
        }

    return uves_qcdark_define_parameters_body(parameters, 
                         make_str(UVES_MDARK_ID));
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options    
  @param    parameters   the parameterlist to fill
  @param    recipe_id    name of calling recipe
  @return   0 if everything is ok
 */
/*----------------------------------------------------------------------------*/
int
uves_qcdark_define_parameters_body(cpl_parameterlist *parameters, 
                  const char *recipe_id)
{
    /*****************
     *    General    *
     *****************/
    if (uves_define_global_parameters(parameters) != CPL_ERROR_NONE)
    {
        return -1;
    }

    if (uves_master_stack_define_parameters(parameters,recipe_id) 
        != CPL_ERROR_NONE)
        {
            return -1;
        }

    
    /****************************
     *  Spline back.sub.        *
     ****************************/
    
    if (uves_propagate_parameters_step(UVES_QCDARK_ID, parameters, 
                       recipe_id, NULL) != 0)
    {
        return -1;
    }

    return (cpl_error_get_code() != CPL_ERROR_NONE);
}



/*----------------------------------------------------------------------------*/
/**
   @brief    Define recipe parameters used for master dark generation
   @param   parameters recipe input parameters
   @return   The parameters for this step

   The parameters defined set region where perform QC
   See source code or 'esorex --man-page' for a description of each parameter.
*/
/*----------------------------------------------------------------------------*/
cpl_error_code 
uves_mdark_define_qc_parameters(cpl_parameterlist* parameters)
{
  


    

    {
   
      const char* name = "reg.num_x";
      char* full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID, name);
      cpl_parameter *p = NULL;
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "Number of regions along the X axis "
                               "(where mean/med/rms are computed). ",
			       UVES_QCDARK_ID,
			       4,0,INT_MAX);

      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name );
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);



      name = "reg.num_y";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "Number of regions along the Y axis"
                               "(where mean/med/rms are computed). ",
			       UVES_QCDARK_ID,
			       4,0,INT_MAX);

      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);



      name = "reg.box_sx";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "Region X size [pix]",
			       UVES_QCDARK_ID,
			       100,0,INT_MAX);
      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);


      name = "reg.box_sy";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "Region Y size [pix]",
			       UVES_QCDARK_ID,
			       100,0,INT_MAX);
      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);

      name = "reg.border_x";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "X distance between the left hand side "
                               "of the detector and the left hand side "
                               "of the region [pix]",
			       UVES_QCDARK_ID,
			       100,0,INT_MAX);
      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);


      name = "reg.border_y";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "X distance between the left hand side "
                               "of the detector and the left hand side "
                               "of the region [pix]",
			       UVES_QCDARK_ID,
			       100,0,INT_MAX);
      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);



      name = "reg.when";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_enum(p, full_name,
			       CPL_TYPE_INT,
			       "When QC analysis is performed. "
                               "0: on each raw frame or "
                               "1: on the master frame",
			       UVES_QCDARK_ID,
			      0,2,0,1);
      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);


    }
    
    if (cpl_error_get_code() != CPL_ERROR_NONE)
    {
        cpl_msg_error(__func__, "Creation of mdark parameters failed: '%s'", 
              cpl_error_get_where());
        cpl_parameterlist_delete(parameters);
    }
    return cpl_error_get_code();
}


/*----------------------------------------------------------------------------*/
/**
   @brief    Define recipe parameters used for master dark generation
   @return   The parameters for this step

   The parameters defined set region where perform QC
   See source code or 'esorex --man-page' for a description of each parameter.
*/
/*----------------------------------------------------------------------------*/
cpl_parameterlist *
uves_qcdark_define_parameters(void)
{
  
    cpl_parameterlist *parameters = NULL;
    
    parameters = cpl_parameterlist_new();

    check(uves_mdark_define_qc_parameters(parameters),
          "Error defining mdark qc parameters");


  cleanup:  
    if (cpl_error_get_code() != CPL_ERROR_NONE)
    {
        cpl_msg_error(__func__, "Creation of mdark parameters failed: '%s'", 
              cpl_error_get_where());
        cpl_parameterlist_delete(parameters);
        return NULL;
    } else {
       return parameters;
    }
}





/*----------------------------------------------------------------------------*/
/**
  @brief    Process a single chip
  @param    raw_images  The input images
  @param    raw_headers An array containing the input image headers. The ordering
                        must be the same as the ordering of images in the input image list
  @param    master_bias The master bias image for this chip, or NULL
  @param    mdark_header The product header. This is updated to contain the exposure time.
  @param    parameters  the parameters list
  @return   The master dark image
 
  This function
  - subtracts from each input image the provided @em master bias (only if provided),
  - computes the master dark image by taking the pixel-by-pixel median of all input frames,

  masterdark = median( (dark_i - masterbias) )

  Note that the master dark frame is not normalized to 1 sec exposure time.

 */
/*----------------------------------------------------------------------------*/
static cpl_image *
uves_mdark_process_chip(const cpl_imagelist *raw_images, 
                        uves_propertylist **raw_headers, 
                        const cpl_image *master_bias,
		        uves_propertylist *mdark_header, 
			const cpl_parameterlist *parameters,
			const char* recipe_id,
			cpl_table* qclog,const int do_qc)
{
   cpl_image *master_dark        = NULL; /* Result */
   cpl_image *current_dark       = NULL;
   cpl_imagelist *preproc_images = NULL;
   double min_exptime = 0;
   double max_exptime = 0;
   int i;
   //char name[MAX_NAME_SIZE];
   //char pname[MAX_NAME_SIZE];

   int pr_num_x=4;
   int pr_num_y=4;
   int pr_box_sx=100;
   int pr_box_sy=100;
   const char* STACK_METHOD=NULL;
   double STACK_KLOW=0;
   double STACK_KHIGH=0;
   int STACK_NITER=0;

/* check critical QC parameters to see if QC need to be computed or not */

   check_nomsg(uves_extract_basic_parameters_for_qc(parameters,recipe_id,
                                                    &pr_num_x,&pr_num_y, 
                                                    &pr_box_sx,&pr_box_sy));

/* parameters for stacking */
    check( uves_get_parameter(parameters, NULL, recipe_id, "stack_method", CPL_TYPE_STRING, &STACK_METHOD),
               "Could not read parameter");

    uves_string_toupper((char*)STACK_METHOD);

    check( uves_get_parameter(parameters, NULL, recipe_id, "klow", CPL_TYPE_DOUBLE, &STACK_KLOW),
               "Could not read parameter");
    check( uves_get_parameter(parameters, NULL, recipe_id, "khigh", CPL_TYPE_DOUBLE, &STACK_KHIGH),
               "Could not read parameter");
    check( uves_get_parameter(parameters, NULL, recipe_id, "niter", CPL_TYPE_INT, &STACK_NITER),
               "Could not read parameter");



    /* First process each input image and store the results in a 
       new image list */

    preproc_images = cpl_imagelist_new();
    for (i = 0; i < cpl_imagelist_get_size(raw_images); i++)
    {
        double exposure_time = 0.0;
        const uves_propertylist *current_header;
        
        current_dark = cpl_image_duplicate(cpl_imagelist_get_const(raw_images, i));
        current_header = raw_headers[i];
                
        /* Subtract master bias */
        if (master_bias != NULL)
        {
            uves_msg("Subtracting master bias");
            check( uves_subtract_bias(current_dark, master_bias), 
               "Error subtracting master bias");

                    if (false) {
            uves_msg_debug("Thresholding to non-negative values");
            check( cpl_image_threshold(current_dark, 
                           0, DBL_MAX,     /* Interval */
                           0, DBL_MAX),    /* New values */
               "Error thresholding image");
                    }
        }
        else
        {
            uves_msg("Skipping bias subtraction");
        }
        
         check( exposure_time = uves_pfits_get_exptime(current_header),
           "Error reading exposure time");

        if(pr_num_x != 0 && pr_num_y != 0 && pr_box_sx != 0 && pr_box_sy !=0 ) {
        if(do_qc == 0) {
	  uves_msg("Calculating QC parameters on raw dark frame %d",i);
          uves_mdark_region_qc(current_dark,parameters,raw_images,recipe_id,qclog);
	}

        }
        /* Initialize/update min/max exposure time*/
        if (i == 0 || exposure_time < min_exptime)
        {
            min_exptime = exposure_time;
        }
        if (i == 0 || exposure_time > max_exptime)
        {
            max_exptime = exposure_time;
        }

        /* Do not normalize to unit exposure time */
/*        If this is uncommented, then remember to also calculate the
        correct master dark exposure time below.
            uves_msg("Normalizing from %f s to unit exposure time", exposure_time);
        check( cpl_image_divide_scalar(current_dark, exposure_time), 
        "Error normalizing dark frame");   */        

        /* Append to imagelist */
        check( cpl_imagelist_set(preproc_images,
                     current_dark,  
                     i),            /* Position (number_of_images=>append) */
           "Could not insert image into image list");
        
        /* Don't deallocate the image. It will be deallocated when
           the image list is deallocated */
        current_dark = NULL;
    }

    /* Check exposure times */
    uves_msg("Exposure times range from %e s to %e s (%e %% variation)", 
            min_exptime,
            max_exptime,
            100 * (max_exptime - min_exptime) / min_exptime);

    if ((max_exptime - min_exptime) / min_exptime > .001)
    {
        uves_msg_warning("Exposure times differ by %e %%", 
                 100 * (max_exptime - min_exptime) / min_exptime);
    }
    
    /* Get median stack of input darks */
    if(strcmp(STACK_METHOD,"MEDIAN")==0) {
       uves_msg("Calculating stack median");
       check( master_dark = cpl_imagelist_collapse_median_create(preproc_images), 
              "Error computing median");
    } else {
       uves_msg("Calculating stack mean");
       check( master_dark = uves_ksigma_stack(preproc_images,STACK_KLOW,
                                              STACK_KHIGH,STACK_NITER),
              "Error computing master dark");

    } 
    check( uves_pfits_set_exptime(mdark_header, (max_exptime + min_exptime)/2),
       "Error setting master dark exposure time");
    //uves_pfits_set_extname(mdark_header,"Master dark");
    
  cleanup:
    uves_free_image(&current_dark);
    uves_free_imagelist(&preproc_images);
    if (cpl_error_get_code() != CPL_ERROR_NONE)
    {
        uves_free_image(&master_dark);
    }
    
    return master_dark;
}


/*----------------------------------------------------------------------------*/
/**
  @brief    Executor function
  @param    parameters  the parameters list
  @param    frames      the frames list
  @param    starttime   execution start
 */
/*----------------------------------------------------------------------------*/
static void
UVES_CONCAT2X(UVES_MDARK_ID,exe)(cpl_frameset *frames, 
                   const cpl_parameterlist *parameters,
                   const char *starttime)
{
    uves_mdark_exe_body(frames, parameters, starttime, make_str(UVES_MDARK_ID));
    return;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Get the command line options and execute the data reduction
  @param    parameters  the parameters list
  @param    frames      the frames list
  @return   CPL_ERROR_NONE if everything is ok

  After computing the master dark frame, the pixel average, standard deviation
  and median values are also computed and written in appropriate keywords in the
  output image header.

 */
/*----------------------------------------------------------------------------*/
void
uves_mdark_exe_body(cpl_frameset *frames, 
            const cpl_parameterlist *parameters,
            const char *starttime,
            const char *recipe_id)
{
    /* Function id */
    /*
     * Variables that will contain the values of the recipe parameters 
     */
    /* None */

    /* CPL objects */
    /* Input */
    cpl_imagelist *raw_images[2]       = {NULL, NULL};
    uves_propertylist  **raw_headers[2] = {NULL, NULL};    /* Two arrays of pointers */

    /* Master bias */
    cpl_image *master_bias               = NULL;
    uves_propertylist *master_bias_header = NULL;
    
    /* Output */
    cpl_table* qclog[2] = {NULL, NULL};
    cpl_image *master_dark              = NULL;
    uves_propertylist *product_header[2] = {NULL, NULL};
    
    /* Local variables */
    char *product_filename = NULL;
    const char *product_tag[2] = {NULL, NULL};
    bool blue;
    enum uves_chip chip;

    const char* pname=NULL;
   

    int pr_when=0;
    const char* PROCESS_CHIP=NULL;
    int pr_num_x=0;
    int pr_num_y=0;
    int pr_box_sx=0;
    int pr_box_sy=0;
    bool dump_qc=true;

    /* Load and check raw dark images and headers, identify arm (blue/red) */
    /* On success, 'raw_headers' will be an array with the same size as 'raw_images' */
    if (cpl_frameset_find(frames, UVES_DARK(true )) != NULL ||
    cpl_frameset_find(frames, UVES_DARK(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       false,    /* FLAMES format? */
                       UVES_DARK(true), UVES_DARK(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw dark frames");
        
        for (chip = uves_chip_get_first(blue); 
         chip != UVES_CHIP_INVALID; 
         chip = uves_chip_get_next(chip))
        {
            product_tag[uves_chip_get_index(chip)] = UVES_MASTER_DARK(chip);
        }
    }
    else if (cpl_frameset_find(frames, UVES_PDARK(true )) != NULL ||
         cpl_frameset_find(frames, UVES_PDARK(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       false,  /* FLAMES format? */
                       UVES_PDARK(true), UVES_PDARK(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw dark frames");
        
        for (chip = uves_chip_get_first(blue);
         chip != UVES_CHIP_INVALID;
         chip = uves_chip_get_next(chip))
        {
            product_tag[uves_chip_get_index(chip)] = UVES_MASTER_PDARK(chip);
        }
    }
    else
    {
        assure(false, CPL_ERROR_DATA_NOT_FOUND,
           "Missing input dark frame: %s, %s, %s or %s expected",
           UVES_DARK(true) , UVES_DARK(false),
           UVES_PDARK(true), UVES_PDARK(false));
    }


  
   check_nomsg(uves_extract_basic_parameters_for_qc(parameters,recipe_id,
                                                    &pr_num_x,&pr_num_y, 
                                                    &pr_box_sx,&pr_box_sy));

   if(pr_num_x <=0 || pr_num_y <= 0 || pr_box_sx <=0 || pr_box_sy <= 0) {
      dump_qc=false;
   }
    pname = uves_sprintf("%s.%s", UVES_QCDARK_ID, "reg.when");
    check(uves_get_parameter(parameters,NULL,recipe_id,pname,CPL_TYPE_INT,&pr_when), 
	 "Could not read parameter");
  
    check( uves_get_parameter(parameters, NULL, "uves", "process_chip", CPL_TYPE_STRING, &PROCESS_CHIP),
               "Could not read parameter");
    uves_string_toupper((char*)PROCESS_CHIP);


    /* Loop over one or two chips */
    for (chip = uves_chip_get_first(blue); 
         chip != UVES_CHIP_INVALID; 
         chip = uves_chip_get_next(chip))
        {

      if(strcmp(PROCESS_CHIP,"REDU") == 0) {
	chip = uves_chip_get_next(chip);
      }

        const char *master_bias_filename = "";
        const char *chip_name = "";
        
        int raw_index = uves_chip_get_index(chip);
        
        uves_msg("Processing %s chip",
             uves_chip_tostring_upper(chip));

        /* Get chip name of first input frame */
        check_nomsg( chip_name = uves_pfits_get_chipid(raw_headers[raw_index][0], chip));

        /* Load master bias, set pointer to NULL if not present */
        uves_free_image(&master_bias);
        uves_free_propertylist(&master_bias_header);
        if (cpl_frameset_find(frames, UVES_MASTER_BIAS(chip)) != NULL)
        {
            check( uves_load_mbias(frames, chip_name,
                       &master_bias_filename, &master_bias, 
                       &master_bias_header, chip), 
               "Error loading master bias");
            
            uves_msg_low("Using master bias in '%s'", master_bias_filename);
        }
        else
        {
            uves_msg_low("No master bias in SOF. Bias subtraction not done");
        }
        
        /* Process chip */



        uves_free_image(&master_dark);
	uves_qclog_delete(&qclog[0]);
	qclog[0] = uves_qclog_init(raw_headers[raw_index][0], chip);
        check( master_dark = uves_mdark_process_chip(raw_images[raw_index], 
						     raw_headers[raw_index], 
						     master_bias,
						     product_header[raw_index],
						     parameters,recipe_id,
                                                     qclog[0],pr_when),
	       "Error processing chip");


        /* Finished. Save */
                /* Finished. Calculate QC parameters and save */
        if(pr_when==1) {
	  uves_msg("Calculating QC parameters on master dark frame");
          uves_mdark_region_qc(master_dark,parameters,
		  	       raw_images[raw_index],recipe_id,qclog[0]);

	}

        /* Insert into frame set */
        uves_msg("Saving product");
        
        cpl_free(product_filename);
        check( product_filename = uves_masterdark_filename(chip), "Error getting filename");

  
        check( uves_frameset_insert(frames,
                    master_dark,
                    CPL_FRAME_GROUP_PRODUCT,
                    CPL_FRAME_TYPE_IMAGE,
                    CPL_FRAME_LEVEL_INTERMEDIATE,
                    product_filename,
                    product_tag[raw_index],
                    raw_headers[raw_index][0],
                    product_header[raw_index],
                    NULL,
                    parameters,
                    recipe_id,
                    PACKAGE "/" PACKAGE_VERSION,qclog,
                    starttime, dump_qc, 
                    UVES_ALL_STATS), 
           "Could not add master dark %s to frameset", product_filename);
        uves_msg("Master dark %s added to frameset", product_filename);
        uves_qclog_delete(&qclog[0]);

      if(strcmp(PROCESS_CHIP,"REDL") == 0) {
	chip = uves_chip_get_next(chip);
      }
        

    }/* For each chip */

  cleanup:
    /* Input */
    if (raw_images[0] != NULL)
    {
        int i;
        for (i = 0; i < cpl_imagelist_get_size(raw_images[0]); i++) 
        {
            if (raw_headers[0] != NULL) uves_free_propertylist(&raw_headers[0][i]);
            if (raw_headers[1] != NULL) uves_free_propertylist(&raw_headers[1][i]);
        }

        cpl_free(raw_headers[0]); raw_headers[0] = NULL;
        cpl_free(raw_headers[1]); raw_headers[1] = NULL;
    }

    uves_free_imagelist(&raw_images[0]);
    uves_free_imagelist(&raw_images[1]);

    /* Master bias */
    uves_free_image(&master_bias);
    uves_free_propertylist(&master_bias_header);

    /* Output */
    uves_qclog_delete(&qclog[0]);
    uves_free_image(&master_dark);
    uves_free_propertylist(&product_header[0]);
    uves_free_propertylist(&product_header[1]);
    cpl_free(product_filename);
    uves_free(pname);
    return;
}


static void 
uves_mdark_region_qc(cpl_image* img, 
                     const cpl_parameterlist* p,
                     const cpl_imagelist* raw_images,
                     const char* recipe_id,
                     cpl_table* qclog)
{

  int pr_num_x=4;
  int pr_num_y=4;
  int pr_box_sx=100;
  int pr_box_sy=100;
  int pr_border_x=100;
  int pr_border_y=100;


  int i=0;
  int j=0;
  int llx=0;
  int lly=0;
  int urx=0;
  int ury=0;
  int space_x=0;
  int space_y=0;
  int sx=0;
  int sy=0;
  int nraw=0;
  int raw=0;
  char name[MAX_NAME_SIZE];
  char pname[MAX_NAME_SIZE];
  char qc_key[MAX_NAME_SIZE];
  char qc_com[MAX_NAME_SIZE];
  double qc_avg=0;
  double qc_med=0;
  double qc_rms=0;
  double qc_min=0;
  double qc_max=0;
  cpl_table* qc_sto=NULL;
 
  check_nomsg(uves_extract_basic_parameters_for_qc(p,recipe_id,
                                                    &pr_num_x,&pr_num_y, 
                                                    &pr_box_sx,&pr_box_sy));

  uves_msg("pr_num_x=%d pr_num_y=%d pr_box_sx=%d pr_box_sy=%d",
          pr_num_x,pr_num_y,pr_box_sx,pr_box_sy);

  if(pr_num_x <= 0 || pr_num_y <= 0 || pr_box_sx <= 0 || pr_box_sy <= 0) {
     return; 
  }
 
  sprintf(name,"reg.border_x");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,&pr_border_x),
	 "Could not read parameter");

  sprintf(name,"reg.border_y");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,&pr_border_y),
	 "Could not read parameter");


  check_nomsg(nraw=cpl_imagelist_get_size(raw_images));
  check_nomsg(uves_qclog_add_int(qclog,
                        "PRO DATANCOM",
                        nraw,
                        "Number of frames combined",
                        "%d"));

  sx=cpl_image_get_size_x(img);
  sy=cpl_image_get_size_y(img);
  space_x=(int)((sx-2*pr_border_x)/pr_num_x);
  space_y=(int)((sy-2*pr_border_y)/pr_num_y);
  qc_sto=cpl_table_new(pr_num_x*pr_num_y);
  cpl_table_new_column(qc_sto,"MIN",CPL_TYPE_DOUBLE);
  cpl_table_new_column(qc_sto,"MAX",CPL_TYPE_DOUBLE);
  cpl_table_new_column(qc_sto,"AVG",CPL_TYPE_DOUBLE);
  cpl_table_new_column(qc_sto,"MED",CPL_TYPE_DOUBLE);
  cpl_table_new_column(qc_sto,"RMS",CPL_TYPE_DOUBLE);

  for(i=0;i<pr_num_x;i++) {
    llx=pr_border_x+i*space_x;
    urx=llx+pr_box_sx;

    llx=(llx>0) ? llx:1;
    urx=(urx<=sx) ? urx:sx;

    for(j=0;j<pr_num_y;j++) {
      lly=pr_border_y+j*space_y;
      ury=lly+pr_box_sy;

      lly=(lly>0) ? lly:1;
      ury=(ury<=sy) ? ury:sy;

      raw=i*pr_num_y+j;
      check_nomsg(qc_min=cpl_image_get_min_window(img,llx,lly,urx,ury));
      qc_max=cpl_image_get_min_window(img,llx,lly,urx,ury);
      qc_avg=cpl_image_get_mean_window(img,llx,lly,urx,ury);
      qc_med=cpl_image_get_median_window(img,llx,lly,urx,ury);
      qc_rms=cpl_image_get_stdev_window(img,llx,lly,urx,ury);
      uves_msg_debug("QC on area [%d,%d:%d,%d]. Min %g Max %g Avg %g Med %g Rms %g",
	       llx,lly,urx,ury,qc_min,qc_max,qc_avg,qc_med,qc_rms);

      sprintf(qc_key,"%s%d%d%s","QC REG",i,j," MIN");
      sprintf(qc_com,"%s%d%d","Min of region [%d,%d]",i,j);
      check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));
      check_nomsg(cpl_table_set_double(qc_sto,"MIN",raw,qc_min));

      sprintf(qc_key,"%s%d%d%s","QC REG",i,j," MAX");
      sprintf(qc_com,"%s%d%d","Max of region [%d,%d]",i,j);
      check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));
      check_nomsg(cpl_table_set_double(qc_sto,"MAX",raw,qc_max));

      sprintf(qc_key,"%s%d%d%s","QC REG",i,j," AVG");
      sprintf(qc_com,"%s%d%d","Mean of region [%d,%d]",i,j);
      check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));
      check_nomsg(cpl_table_set_double(qc_sto,"AVG",raw,qc_avg));

      sprintf(qc_key,"%s%d%d%s","QC REG",i,j," MED");
      sprintf(qc_com,"%s%d%d","Median of region [%d,%d]",i,j);
      check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));
      check_nomsg(cpl_table_set_double(qc_sto,"MED",raw,qc_med));

      sprintf(qc_key,"%s%d%d%s","QC REG",i,j," RMS");
      sprintf(qc_com,"%s%d%d","Rms of region [%d,%d]",i,j);
      check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));
      check_nomsg(cpl_table_set_double(qc_sto,"RMS",raw,qc_rms));


    }
  }


  check_nomsg(qc_min=cpl_table_get_column_min(qc_sto,"MIN"));
  check_nomsg(qc_max=cpl_table_get_column_max(qc_sto,"MIN"));
  check_nomsg(qc_avg=cpl_table_get_column_mean(qc_sto,"MIN"));
  check_nomsg(qc_med=cpl_table_get_column_median(qc_sto,"MIN"));
  check_nomsg(qc_rms=cpl_table_get_column_stdev(qc_sto,"MIN"));

  sprintf(qc_key,"%s","QC REG MIN MIN");
  sprintf(qc_com,"%s","Min of all Mins");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MIN MAX");
  sprintf(qc_com,"%s","Max of all Mins");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MIN AVG");
  sprintf(qc_com,"%s","Mean of all Mins");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MIN MED");
  sprintf(qc_com,"%s","Median of all Mins");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MIN RMS");
  sprintf(qc_com,"%s","Rms of all Mins");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));



  check_nomsg(qc_min=cpl_table_get_column_min(qc_sto,"MAX"));
  check_nomsg(qc_max=cpl_table_get_column_max(qc_sto,"MAX"));
  check_nomsg(qc_avg=cpl_table_get_column_mean(qc_sto,"MAX"));
  check_nomsg(qc_med=cpl_table_get_column_median(qc_sto,"MAX"));
  check_nomsg(qc_rms=cpl_table_get_column_stdev(qc_sto,"MAX"));

  sprintf(qc_key,"%s","QC REG MAX MIN");
  sprintf(qc_com,"%s","Min of all Maxs");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MAX MAX");
  sprintf(qc_com,"%s","Max of all Maxs");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MAX AVG");
  sprintf(qc_com,"%s","Mean of all Maxs");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MAX MED");
  sprintf(qc_com,"%s","Median of all Maxs");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MAX RMS");
  sprintf(qc_com,"%s","Rms of all Maxs");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));


  check_nomsg(qc_min=cpl_table_get_column_min(qc_sto,"AVG"));
  check_nomsg(qc_max=cpl_table_get_column_max(qc_sto,"AVG"));
  check_nomsg(qc_avg=cpl_table_get_column_mean(qc_sto,"AVG"));
  check_nomsg(qc_med=cpl_table_get_column_median(qc_sto,"AVG"));
  check_nomsg(qc_rms=cpl_table_get_column_stdev(qc_sto,"AVG"));

  sprintf(qc_key,"%s","QC REG AVG MIN");
  sprintf(qc_com,"%s","Min of all Means");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG AVG MAX");
  sprintf(qc_com,"%s","Max of all Means");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG AVG AVG");
  sprintf(qc_com,"%s","Mean of all Means");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG AVG MED");
  sprintf(qc_com,"%s","Median of all Means");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG AVG RMS");
  sprintf(qc_com,"%s","Rms of all Means");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));


  check_nomsg(qc_min=cpl_table_get_column_min(qc_sto,"MED"));
  check_nomsg(qc_max=cpl_table_get_column_max(qc_sto,"MED"));
  check_nomsg(qc_avg=cpl_table_get_column_mean(qc_sto,"MED"));
  check_nomsg(qc_med=cpl_table_get_column_median(qc_sto,"MED"));
  check_nomsg(qc_rms=cpl_table_get_column_stdev(qc_sto,"MED"));

  sprintf(qc_key,"%s","QC REG MED MIN");
  sprintf(qc_com,"%s","Min of all Medians");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MED MAX");
  sprintf(qc_com,"%s","Max of all Medians");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MED AVG");
  sprintf(qc_com,"%s","Mean of all Medians");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MED MED");
  sprintf(qc_com,"%s","Median of all Medians");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MED RMS");
  sprintf(qc_com,"%s","Rms of all Medians");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));


  check_nomsg(qc_min=cpl_table_get_column_min(qc_sto,"RMS"));
  check_nomsg(qc_max=cpl_table_get_column_max(qc_sto,"RMS"));
  check_nomsg(qc_avg=cpl_table_get_column_mean(qc_sto,"RMS"));
  check_nomsg(qc_med=cpl_table_get_column_median(qc_sto,"RMS"));
  check_nomsg(qc_rms=cpl_table_get_column_stdev(qc_sto,"RMS"));


  sprintf(qc_key,"%s","QC REG RMS MIN");
  sprintf(qc_com,"%s","Min of all Rms");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG RMS MAX");
  sprintf(qc_com,"%s","Max of all Rms");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG RMS AVG");
  sprintf(qc_com,"%s","Mean of all Rms");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG RMS MED");
  sprintf(qc_com,"%s","Median of all Rms");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG RMS RMS");
  sprintf(qc_com,"%s","Rms of all Rms");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));




 cleanup:
  uves_free_table(&qc_sto);

  return;

}


/**@}*/