File: uves_reduce_mflat.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 (1092 lines) | stat: -rw-r--r-- 40,927 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
/*                                                                              *
 *   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  02111-1307  USA       *
 *                                                                              */

/*
 * $Author: amodigli $
 * $Date: 2013-08-08 13:36:46 $
 * $Revision: 1.53 $
 */

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

/*----------------------------------------------------------------------------*/
/**
 * @defgroup uves_reduce_mflat    Master flat reduction
 *
 */
/*----------------------------------------------------------------------------*/
/**@{*/



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

#include <uves.h>
#include <uves_backsub.h>
#include <uves_chip.h>
#include <uves_dfs.h>
#include <uves_pfits.h>
#include <uves_parameters.h>
#include <uves_utils.h>
#include <uves_utils_wrappers.h>
#include <uves_qclog.h>
#include <uves_error.h>
#include <uves_msg.h>

#include <cpl.h>
#include <float.h>
#include <string.h>
/*-----------------------------------------------------------------------------
                            Functions prototypes
 -----------------------------------------------------------------------------*/

static void uves_mflat_qclog(const cpl_imagelist* raw_images,
                     cpl_table* qclog);

static cpl_error_code uves_msflats(cpl_frameset * set, const cpl_parameterlist *parameters,
                   const char *recipe_id,
                   const char *starttime);
static void uves_mflat_one(cpl_frameset *frames,
               const cpl_parameterlist *parameters, 
               bool flames,
               const char *recipe_id,
               const char *starttime,
               const char* prefix);

static cpl_error_code
uves_mflat_at_ypos(cpl_frameset* set,
           const cpl_parameterlist* parameters,
           const char *recipe_id,
           const char *starttime,
                   const cpl_frameset* raw,
                   const cpl_frameset* cdb,
                   const int ref_x1enc,
                   const int ref_x2enc,
           const int set_no);

static void uves_reduce_mflat(cpl_frameset *frames, const cpl_parameterlist *parameters,
                  bool flames,
                  const char *recipe_id, 
                  const char *starttime,
                  const char *prefix);

/*-----------------------------------------------------------------------------
                            Implementation
 -----------------------------------------------------------------------------*/
const char * const uves_mflat_desc =
"This recipe creates a master flat frame by 1) subtracting the master bias\n"
"frame from each flat field frame, 2) dividing each flat field frame by the\n"
" exposure time for that frame, 3) taking the median of all bias subtracted,\n"
" normalized raw\n flat frames, 4) optionally subtracting the master dark \n"
"frame, and 5) subtracting\n the background to get the bias subtracted, \n"
"optionally dark subtracted, normalized, background subtracted master \n"
"flat-field frame. Symbolically,\n"
" masterflat = median( (flat_i - masterbias)/exptime_i ) - masterdark/exptime\n"
"            - background.\n"
"\n"
"The input flat field frames must have same tag which must match\n"
"(I|D|S|T|SCREEN|)FLAT_(BLUE|RED), for example TFLAT_BLUE or FLAT_RED. Also, a\n"
"master bias (MASTER_BIAS_xxxx) and ordertable (ORDER_TABLE_xxxx) must be\n"
"provided for each chip (xxxx = BLUE, REDL, REDU). A master dark frame\n"
"(MASTER_(P)DARK_xxxx) may optionally be provided. On blue input the recipe\n"
"computes one master flat field frame; on red input the recipe produces a\n"
"master flat field frame for each chip (MASTER_FLAT_xxxx, MASTER_IFLAT_xxxx,\n"
"MASTER_DFLAT_xxxx, MASTER_TFLAT_xxxx or MASTER_SCREEN_FLAT_xxxx).";

/*----------------------------------------------------------------------------*/
/**
  @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_mflat_define_parameters_body(cpl_parameterlist *parameters, 
                  const char *recipe_id)
{

   cpl_parameter* p=NULL;
   /*****************
    *    General    *
    *****************/
   if (uves_define_global_parameters(parameters) != CPL_ERROR_NONE)
   {
      return -1;
   }
   if (uves_corr_traps_define_parameters(parameters,recipe_id) 
       != CPL_ERROR_NONE)
   {
      return -1;
   }

    /**************************************
     *  Master stack generation           *
     **************************************/
    if (uves_master_flat_define_parameters(parameters,recipe_id) 
        != CPL_ERROR_NONE)
    {
            return -1;
    }

    if(strcmp(recipe_id,"flames_cal_mkmaster") ==0) {
       check_nomsg(p=cpl_parameterlist_find(parameters,"flames_cal_mkmaster.norm_method"));
       cpl_parameter_set_string(p,"exptime");
    }
  cleanup:
/*
    if (uves_master_stack_define_parameters(parameters,recipe_id) 
        != CPL_ERROR_NONE)
        {
            return -1;
        }
*/
    
    /****************************
     *  Spline back.sub.        *
     ****************************/
    
    if (uves_propagate_parameters_step(UVES_BACKSUB_ID, parameters, 
                       recipe_id, NULL) != 0)
    {
        return -1;
    }



    return (cpl_error_get_code() != CPL_ERROR_NONE);
}

/*----------------------------------------------------------------------------*/
/**
   @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_flat_header  This header is updated with the normalized exposure time
   @param    master_bias         The master bias image for this chip, or NULL
   @param    master_dark         If non-null this master dark frame is subtracted
   @param    mdark_header        The header of the master dark frame (used only if 
                                 @em master_dark is non-null).
   @param    ordertable          The order table for this chip. Used for background
                                 subtraction.
   @param    order_locations     Polynomial defining the order locations. Used for
                                 background subtraction.
   @param    flames              FLAMES reduction? In this case the background image
                                 is not computed/subtracted
   @param    parameters          The recipe parameter list
   @param    chip                CCD chip
   @param    recipe_id           name of calling recipe
   @param    debug_mode               Save intermediate results to disk?
   @param    background          (output) The background image which was subtracted

   @return   The master flat image
 
   This function
   - subtracts from each input image the provided @em master bias,
   - rescales each input image to unit exposure time by dividing by the exposure
   time read from the image header.
   - computes the master flat image by taking the pixel-by-pixel median of all input frames,
   - optionally subtracts the normalized master dark frame, and
   - subtracts the background (see @c uves_backsub_spline()) .

   masterflat = median( (flat_i - masterbias)/exptime_i ) - masterdark/exptime_mdark - background

   Dark subtraction is optional and is done only if the parameter @em master_dark is non-NULL.
*/
/*----------------------------------------------------------------------------*/
static cpl_image *
uves_mflat_process_chip(const cpl_imagelist *raw_images, 
                        uves_propertylist **raw_headers, 
                        uves_propertylist *master_flat_header,
                        const cpl_image *master_bias,
                        const cpl_image *master_dark, 
                        const uves_propertylist *mdark_header, 
                        const cpl_table *ordertable, 
                        const polynomial *order_locations,
                        bool flames,
                        const cpl_parameterlist *parameters,
                        enum uves_chip chip,
                        const char *recipe_id,
                        bool debug_mode,
                        cpl_image **background)

{
    cpl_image *master_flat        = NULL; /* Result */
    cpl_image *master_flat_tmp        = NULL; /* Result */

    cpl_image *current_flat       = NULL;
   
    int i;
    const char* FLAT_METHOD=NULL;
    cpl_vector* exptimes=NULL;
    cpl_vector* gain_vals=NULL;
    double mdark_exposure=0;
    cpl_image* mdark_scaled=NULL;
    double fnoise=0;
    double gain=0;
    cpl_imagelist *raw_images_local=NULL;

    /* First process each input image and store the results in a new image list */
   /* Get recipe parameters */
  check( uves_get_parameter(parameters, NULL, recipe_id, "norm_method", 
             CPL_TYPE_STRING, &FLAT_METHOD),
               "Could not read parameter");
    uves_string_toupper((char*)FLAT_METHOD);
    
    raw_images_local=(cpl_imagelist*) raw_images;
    exptimes=cpl_vector_new(cpl_imagelist_get_size(raw_images));
    gain_vals=cpl_vector_new(cpl_imagelist_get_size(raw_images));
    /* to remove compiler warnings */
    for (i = 0; i < cpl_imagelist_get_size(raw_images); i++)
    {
        double exposure_time = 0.0;

        const uves_propertylist *current_header = NULL;

        current_flat   = 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_flat, master_bias), 
               "Error subtracting master bias");
        }
        else
        {
            uves_msg("Skipping bias subtraction");
        }
        
        /* Normalize to unit exposure time:  */
        check( exposure_time = uves_pfits_get_exptime(current_header),
           "Error reading exposure time");
        check( gain = uves_pfits_get_gain(current_header,chip), 
           "Error reading gain value");
        
        uves_msg("Normalizing flat from %f s to unit exposure time", exposure_time);
        check( cpl_image_divide_scalar(current_flat, exposure_time),
           "Error normalizing flat field");
        check( uves_pfits_set_exptime(master_flat_header, 1.0),
           "Error writing master frame exposure time");
        cpl_vector_set(exptimes,i,exposure_time);
        cpl_vector_set(gain_vals,i,gain);

        /* Append to imagelist */
        check( cpl_imagelist_set(raw_images_local,     /* Image list */
                     current_flat,       /* Image to insert */
                     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_flat = NULL;
    }

    /* subtract master dark if present */
    if (master_dark != NULL)
    {
        uves_msg("Subtracting master dark scaled to unit exposure time");
        check_nomsg( mdark_exposure = uves_pfits_get_exptime(mdark_header));

        mdark_scaled=cpl_image_duplicate(master_dark);
        cpl_image_divide_scalar(mdark_scaled,mdark_exposure); 
        check( cpl_imagelist_subtract_image(raw_images_local,mdark_scaled), 
           "Error subtracting master dark");
        uves_free_image(&mdark_scaled);
    }
    else
    {
        uves_msg("Skipping dark subtraction");
    }

    
    /* Take median of all input flats */
    if(strcmp(FLAT_METHOD,"EXPTIME")==0) {
       uves_msg("Calculating stack median");
       check(master_flat=cpl_imagelist_collapse_median_create(raw_images_local), 
              "Error computing median");
    } else {
       uves_msg("Calculating stack normalized master");
       check( master_flat_tmp = uves_flat_create_normalized_master(raw_images_local,
								   ordertable,
								   order_locations,gain_vals,&fnoise),
              "Error computing master flat with normalization");

      check( master_flat = uves_flat_create_normalized_master2(raw_images_local,
                                                               ordertable,
                                                              order_locations,
                                                               master_flat_tmp),
              "Error computing master flat with normalization");
      uves_free_image(&master_flat_tmp);
      uves_propertylist_append_c_double(master_flat_header,UVES_FNOISE,fnoise,
                                          "Master flat RMS on frame");

    }
    /*clean mem and reset local pointers to null */
    raw_images_local=NULL;
    uves_free_vector(&exptimes);
    uves_free_vector(&gain_vals);

    if (debug_mode && !flames)
    {
        check( uves_save_image_local("Pre-background subtracted master flat", "pre",
                                     master_flat, chip, -1, -1, master_flat_header, true), 
           "Error saving image");
    }
    
    /* Subtract background from master flat */
    if (!flames)
    {
        uves_msg("Subtracting background");
        
        check( uves_backsub_spline(master_flat, 
                       /* Info about chip (wavelength, ...) is 
                      stored in any raw header,
                      so just pass the first one   */
                       raw_headers[0],                
                       ordertable, order_locations, 
                       parameters, recipe_id,
                       chip,
                       true,     /* Use flat-field parameters? */
                       background),
           "Error subtracting background from master flat");
    }
    else
    {
        uves_msg("Skipping background subtraction");
    }
    //uves_pfits_set_extname(master_flat_header,"Master flat");
  cleanup:


    uves_free_image(&current_flat);
    if (cpl_error_get_code() != CPL_ERROR_NONE)
    {
        uves_free_image(&master_flat);
    }
    
    return master_flat;
}

/*----------------------------------------------------------------------------*/
/**
   @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 flat frame, the pixel average, standard deviation
   and median values are also computed and written in appropriate keywords in the
   output image header.

*/
/*----------------------------------------------------------------------------*/
void
uves_mflat_exe_body(cpl_frameset *frames, 
                    const cpl_parameterlist *parameters,
                    const char *starttime,
                    const char *recipe_id)
{
    /* Do FLAMES reduction if SFLAT frame is given */
    if (cpl_frameset_find(frames, UVES_SFLAT(false)) != NULL) {
  
        check(uves_msflats(frames, parameters, recipe_id, starttime),
              "find same sflats failed");
    }
    else {
        bool flames = false;
        check(uves_mflat_one(frames, parameters, flames, recipe_id, 
                             starttime, ""),
              "Master flat one failed");
    }
    
 cleanup:
    return;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Computes coherent master sflats 
  @param    set     The input frameset
  @return   CPL_ERROR_NONE iff ok
 */
/*----------------------------------------------------------------------------*/
static cpl_error_code
uves_msflats(cpl_frameset * set, const cpl_parameterlist *parameters,
         const char *recipe_id,
         const char *starttime)
{
  /* Pseudocode:
     extract raw frames from set
     extract cdb frames from set
     identifies how many different Y position we have 
     for each Y pos:
         extract from the raw_set the raw frames corresponding to each Y pos 
         merge in a new wrk_set the cdb_set 
         computes the corresponding master flat 
         put the products in the final set 
     endfor 
  */
  cpl_frameset* raw=NULL;
  cpl_frameset* cdb=NULL;
  cpl_frameset* pro=NULL;
  int status=0;
  int x1enc=0;
  int x2enc=0;

  cpl_table* encoder_tbl=NULL;
  int nset=0;
  int i=0;

  //Extracts SFLAT raw frames 
  check(raw=uves_frameset_extract(set,UVES_SFLAT(false)),
				  "Extract %s frames failed",
				  UVES_SFLAT(false));

  check(uves_extract_frames_group_type(set,&cdb,CPL_FRAME_GROUP_CALIB),
    "Extract cdb frames failed");
  check(uves_sflats_get_encoder_steps(raw,&encoder_tbl,&nset),
    "Get encoder steps failed");
  uves_msg("Check Slit Flat Field Y nominal positions within each set");
  for(i=0;i<nset;i++) {

         uves_msg("Slit Flat field set %d: x1enc = %d x2enc = %d",
              i+1,
              cpl_table_get_int(encoder_tbl,"x1enc",i,&status),
              cpl_table_get_int(encoder_tbl,"x2enc",i,&status));

  }

  for(i=0;i<nset;i++) {
    x1enc=cpl_table_get_int(encoder_tbl,"x1enc",i,&status);
    x2enc=cpl_table_get_int(encoder_tbl,"x2enc",i,&status);

    uves_msg("Processing set %d", i+1);
   
    check(uves_mflat_at_ypos(set,parameters,recipe_id,starttime,raw,cdb,x1enc,x2enc,i+1),
      "Master flat one failed");
  }

  cleanup:
  uves_free_table(&encoder_tbl);
  uves_free_frameset(&raw);
  uves_free_frameset(&cdb);
  uves_free_frameset(&pro);

    return cpl_error_get_code();
}


/*----------------------------------------------------------------------------*/
/**
  @brief    Computes coherent master sflats 
  @param    set     The input frameset
  @return   CPL_ERROR_NONE iff ok
 */
/*----------------------------------------------------------------------------*/
static cpl_error_code
uves_mflat_at_ypos(cpl_frameset* set,
           const cpl_parameterlist* parameters,
           const char *recipe_id,
           const char *starttime,
                   const cpl_frameset* raw,
                   const cpl_frameset* cdb,
                   const int ref_x1enc,
                   const int ref_x2enc,
                   const int set_no)
{

    const cpl_frame* frm_tmp=NULL;
  char* file=NULL;
  uves_propertylist* plist=NULL;
  cpl_size i=0;
  const int threshold = 5;
  cpl_frame* frm_dup=NULL;
  cpl_frameset* tmp=NULL;
  cpl_frameset* pro=NULL;
  int x1enc=0;
  int x2enc=0;
  char prefix[255];
  bool flames = true;

  check_nomsg(tmp=cpl_frameset_new());
   for(i=0;i<cpl_frameset_get_size(raw);i++)
    {
    check_nomsg(frm_tmp=cpl_frameset_get_frame_const(raw,i));
    check_nomsg(file=cpl_strdup(cpl_frame_get_filename(frm_tmp)));
    check_nomsg(plist=uves_propertylist_load(file,0));
    check_nomsg(x1enc=uves_pfits_get_slit3_x1encoder(plist));
    check_nomsg(x2enc=uves_pfits_get_slit3_x2encoder(plist));
    
    if( (fabs(x1enc - ref_x1enc) <= threshold) &&
        (fabs(x2enc - ref_x2enc) <= threshold) ) {
      uves_msg_debug("file=%s x1enc=%d x2enc=%d",file,x1enc,x2enc);
      check(frm_dup = cpl_frame_duplicate(frm_tmp),"duplicate");
      check(cpl_frameset_insert(tmp,frm_dup),"insert");
    }
    cpl_free(file);
    uves_free_propertylist(&plist);
    }
   check_nomsg(uves_frameset_merge(tmp,cdb));
   sprintf(prefix,"%s%d%s","set",set_no,"_");
   check(uves_mflat_one(tmp,parameters, flames, recipe_id, starttime,prefix),"Master flat one failed");
   check_nomsg(uves_extract_frames_group_type(tmp,&pro,CPL_FRAME_GROUP_PRODUCT));
   check_nomsg(uves_frameset_merge(set,pro));

 cleanup:
   uves_free_frameset(&tmp);
   uves_free_frameset(&pro);
   uves_free_propertylist(&plist);
  
    return cpl_error_get_code();
}
/*----------------------------------------------------------------------------*/
/**
   @brief    Get the command line options and execute the data reduction
   @param    frames      the frames list
   @param    parameters  the parameters list
   @parma    flames      FLAMES mode?
   @return   CPL_ERROR_NONE if everything is ok

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

*/
/*----------------------------------------------------------------------------*/
static void
uves_mflat_one(cpl_frameset *frames,
           const cpl_parameterlist *parameters, 
           bool flames,
           const char *recipe_id,
           const char *starttime,
               const char* prefix)
{
    /* Do flat-fielding */
    check_nomsg( uves_reduce_mflat(frames, parameters, 
                   flames, recipe_id,
                   starttime, prefix) );

  cleanup:
    return;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Get the command line options and execute the data reduction
  @param    frames      the frames list
  @param    parameters  the parameters list
  @param    flames      Called by FLAMES recipe?
  @param    recipe_id   the recipe name (will be written to FITS headers)
  @param    starttime   time when calling recipe started
  @param    prefix      tag prefix as x in 'xFLAT'
  @return   CPL_ERROR_NONE if everything is ok
 */
/*----------------------------------------------------------------------------*/
static void
uves_reduce_mflat(cpl_frameset *frames, const cpl_parameterlist *parameters,
          bool flames,
          const char *recipe_id, 
          const char *starttime,
          const char *prefix)
{
    bool debug_mode;

    /* Input */
    cpl_imagelist       *raw_images[2] = {NULL, NULL}; /* An image list for both chips */
    uves_propertylist  **raw_headers[2] = {NULL, NULL}; /* Two arrays of pointers */

    /* Master bias */
    cpl_image *master_bias               = NULL;
    uves_propertylist *master_bias_header = NULL;

    /* Master dark */
    cpl_image *master_dark               = NULL;
    uves_propertylist *master_dark_header = NULL;

    /* Order table */
    cpl_table        *ordertable            = NULL;
    uves_propertylist *ordertable_header     = NULL;
    polynomial       *order_locations       = NULL;
    cpl_table        *traces                = NULL;
    
    /* Reference master flat */
    cpl_image        *ref_flat              = NULL;
    uves_propertylist *ref_flat_header       = NULL;

    /* Output */
    cpl_table *qclog[]                  = {NULL, NULL};
    cpl_image *master_flat              = NULL;
    cpl_image *background               = NULL;
    uves_propertylist *product_header[]  = {NULL, NULL};
    cpl_image *ratio                    = NULL;
    
    /* Local variables */
    char *product_filename = NULL;
    char pro_filename[255];
    const char *product_tag[2] = {NULL, NULL};
    bool blue;
    enum uves_chip chip;
    const char* PROCESS_CHIP=NULL;




    const char *ordertable_filename = "";
    const char *master_bias_filename = "";
    const char *master_dark_filename = "";
    const char *chip_name = "";
    int raw_index = 0;
    const char *ref_flat_filename;

    /* Read recipe parameters */
    {
    /* General */
    check( uves_get_parameter(parameters, NULL, "uves", "debug", CPL_TYPE_BOOL  , &debug_mode ), 
           "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);

    /* Load and check raw flat images and headers, identify arm (blue/red) */
    /* On success, 'raw_headers' will be an array with the same size as 'raw_images' */
    /* Set product tags to match input tag */

    if (cpl_frameset_find(frames, UVES_FLAT(true )) != NULL ||
    cpl_frameset_find(frames, UVES_FLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_FLAT(true), UVES_FLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat 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_FLAT(chip);
        }
    }
    else if (cpl_frameset_find(frames, UVES_DFLAT(true )) != NULL ||
         cpl_frameset_find(frames, UVES_DFLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_DFLAT(true), UVES_DFLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat 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_DFLAT(chip);
        }
    }
    else if  (cpl_frameset_find(frames, UVES_IFLAT(true )) != NULL ||
          cpl_frameset_find(frames, UVES_IFLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_IFLAT(true), UVES_IFLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat 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_IFLAT(chip);
        }
    }
    else if  (cpl_frameset_find(frames, UVES_TFLAT(true )) != NULL ||
          cpl_frameset_find(frames, UVES_TFLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_TFLAT(true), UVES_TFLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat 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_TFLAT(chip);
        }
    }
    else if  (cpl_frameset_find(frames, UVES_SCREEN_FLAT(true )) != NULL ||
          cpl_frameset_find(frames, UVES_SCREEN_FLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_SCREEN_FLAT(true), UVES_SCREEN_FLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat 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_SCREEN_FLAT(chip);
        }
    }
    else if  (cpl_frameset_find(frames, UVES_SFLAT(true )) != NULL ||
          cpl_frameset_find(frames, UVES_SFLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_SFLAT(true), UVES_SFLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat 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_SFLAT(chip);
        }
    }
    else 
    {
        assure(false, CPL_ERROR_DATA_NOT_FOUND,
           "Missing input flat frame: "
           "%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s or %s expected",
           UVES_FLAT(true) , UVES_FLAT(false),
           UVES_DFLAT(true), UVES_DFLAT(false),
           UVES_IFLAT(true), UVES_IFLAT(false),
           UVES_TFLAT(true), UVES_TFLAT(false),
           UVES_SCREEN_FLAT(true), UVES_SCREEN_FLAT(false),
           UVES_SFLAT(true), UVES_SFLAT(false));
    }

    /* 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);
      }
        
        raw_index = uves_chip_get_index(chip);
        
        uves_msg("Processing %s chip", uves_chip_tostring_upper(chip));

        /* 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)
        {
            uves_free_image(&master_bias);
            uves_free_propertylist(&master_bias_header);
            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");
        }
    
        /* Load master dark, set pointer to NULL if not present */
        uves_free_image(&master_dark);
        uves_free_propertylist(&master_dark_header);
        if (cpl_frameset_find(frames, UVES_MASTER_DARK(chip))  != NULL ||
        cpl_frameset_find(frames, UVES_MASTER_PDARK(chip)) != NULL)
        {
            uves_free_image(&master_dark);
            uves_free_propertylist(&master_dark_header);
            check( uves_load_mdark(frames, chip_name,
                       &master_dark_filename, &master_dark,
                       &master_dark_header, chip), 
               "Error loading master dark");
            
            uves_msg_low("Using master dark in '%s'", master_dark_filename);
        }
        else
        {
            uves_msg_low("No master dark in SOF. Dark subtraction not done");
        }
    
        /* Load the order table for this chip */
        if (flames)
        /* FLAMES does not do background subtraction (here)
           and therefore does not need an ordertable */
        {
            if (cpl_frameset_find(frames, UVES_ORDER_TABLE(flames, chip)) != NULL)
            {
                uves_msg_warning("Order table (%s) is not used in FLAMES reduction",
                         UVES_ORDER_TABLE(flames, chip));
            }
        }
        else
        {
            uves_free_table       (&ordertable);
            uves_free_propertylist(&ordertable_header);
            uves_polynomial_delete(&order_locations);
            uves_free_table       (&traces);
            
            check( uves_load_ordertable(frames,
                        flames,
                        chip_name,
                        &ordertable_filename, 
                                                &ordertable,
                        &ordertable_header, 
                                                NULL,
                                                &order_locations,
                        &traces, NULL, NULL,
                                       NULL, NULL, /* fibre_pos,fibre_mask */
                        chip,
                        false),
               "Could not load order table");
            uves_msg("Using order table in '%s'", ordertable_filename);
        }

        /* Compute QC parameters and save */
        uves_msg("Computing QC parameters");
            uves_qclog_delete(&qclog[0]);
            qclog[0] = uves_qclog_init(raw_headers[raw_index][0], chip);

            check(uves_mflat_qclog(raw_images[raw_index],
                   qclog[0]),"error computing qclog");
    

       
        /* Process chip */
        uves_free_image(&master_flat);
        uves_free_image(&background);
        check( master_flat = uves_mflat_process_chip(
               raw_images[raw_index], raw_headers[raw_index],
               product_header[raw_index],
               master_bias,
               master_dark, master_dark_header,
               ordertable, order_locations,
               flames,
               parameters,
               chip,
               recipe_id,
               debug_mode,
               &background),
           "Error processing chip");

         /* Finished. Save */ 
        uves_msg("Saving products");
    
        cpl_free(product_filename);
        check( product_filename = uves_masterflat_filename(chip), 
               "Error getting filename");
        strcpy(pro_filename,prefix);
        strcat(pro_filename,product_filename);
        check( uves_frameset_insert(
                   frames,
                   master_flat,
                   CPL_FRAME_GROUP_PRODUCT,
                   CPL_FRAME_TYPE_IMAGE,
                   CPL_FRAME_LEVEL_INTERMEDIATE,
                   pro_filename,
                   product_tag[raw_index],
                   raw_headers[raw_index][0],
                   product_header[raw_index],
                   NULL,
                   parameters,
                   recipe_id,
                   PACKAGE "/" PACKAGE_VERSION, qclog,
                   starttime, true, UVES_ALL_STATS),
               "Could not add master flat %s %s to frameset", 
               product_filename, product_tag[raw_index]);
        uves_msg("Master flat %s %s added to frameset", 
                 pro_filename, product_tag[raw_index]);

        /* Save background image */
        if (!flames)
        {
            cpl_free(product_filename);
            check( product_filename = uves_masterflat_bkg_filename(chip), 
               "Error getting filename");
            strcpy(pro_filename,prefix);
            strcat(pro_filename,product_filename);
            //uves_pfits_set_extname(product_header[raw_index],"Inter-order background");
            check( uves_frameset_insert(frames,
                        background,
                        CPL_FRAME_GROUP_PRODUCT,
                        CPL_FRAME_TYPE_IMAGE,
                        CPL_FRAME_LEVEL_INTERMEDIATE,
                        pro_filename,
                        UVES_BKG_FLAT(chip),
                        raw_headers[raw_index][0],
                        product_header[raw_index],
                        NULL,
                        parameters,
                        recipe_id,
                        PACKAGE "/" PACKAGE_VERSION, NULL,
                        starttime, false, 
                        CPL_STATS_MIN | CPL_STATS_MAX),
               "Could not add background image '%s' to frameset", 
               product_filename);
            uves_msg("Master flat background '%s' added to frameset", 
                 product_filename);
                }

        /* Compute and save ratio MASTER_TFLAT / REF_TFLAT */
        if (strcmp(recipe_id, make_str(UVES_TFLAT_ID)) == 0)
        {

            uves_free_image(&ref_flat);
            uves_free_propertylist(&ref_flat_header);

            check( uves_load_ref_flat(frames, chip_name, &ref_flat_filename, 
                          &ref_flat, &ref_flat_header, 
                          chip),
               "Error loading reference flat field");
            
            uves_msg("Using reference flat field in '%s'", ref_flat_filename);

            check( ratio = cpl_image_divide_create(master_flat, ref_flat),
               "Error computing ratio of master and reference flat");

            cpl_free(product_filename);
            check( product_filename = uves_flat_ratio_filename(chip), 
               "Error getting filename");
            
            check( uves_frameset_insert(frames,
                        ratio,
                        CPL_FRAME_GROUP_PRODUCT,
                        CPL_FRAME_TYPE_IMAGE,
                        CPL_FRAME_LEVEL_INTERMEDIATE,
                        product_filename,
                        UVES_RATIO_TFLAT(chip),
                        raw_headers[raw_index][0],
                        product_header[raw_index],
                        NULL,
                        parameters,
                        recipe_id,
                        PACKAGE "/" PACKAGE_VERSION,
                        qclog,
                        starttime, false, 
                        UVES_ALL_STATS),
               "Could not add ratio image '%s' to frameset", product_filename);

            uves_msg("Master flat ratio '%s' added to frameset", product_filename);
        }


      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);

    /* Master dark */
    uves_free_image(&master_dark);
    uves_free_propertylist(&master_dark_header);

    /* Order table */
    uves_free_table(&ordertable);
    uves_free_propertylist(&ordertable_header);
    uves_polynomial_delete(&order_locations);
    uves_free_table(&traces);

    /* Reference master flat */
    uves_free_image(&ref_flat);
    uves_free_propertylist(&ref_flat_header);
    
    /* Output */
    uves_qclog_delete(&qclog[0]);
    uves_free_image(&master_flat);
    uves_free_image(&background);
    uves_free_image(&ratio);
    uves_free_propertylist(&product_header[0]);
    uves_free_propertylist(&product_header[1]);
    cpl_free(product_filename);
    
    return;
}


/*----------------------------------------------------------------------------*/
/**
   @brief    Process a single chip
   @param    raw_images    the input images
   @param    qclog         QC parameters are written here
*/
/*----------------------------------------------------------------------------*/

static void
uves_mflat_qclog(const cpl_imagelist* raw_images,
         cpl_table* qclog)
{
  int nraw=0;

  check_nomsg(uves_qclog_add_string(qclog,
                        "QC TEST1 ID",
                        "Test-on-Master-Flat",
                        "Name of QC test",
                        "%s"));
  check_nomsg(nraw=cpl_imagelist_get_size(raw_images));

  check_nomsg(uves_qclog_add_int(qclog,
                        "PRO DATANCOM",
                        nraw,
                        "Number of frames combined",
                        "%d"));
 cleanup:
  return;
}
/**@}*/