File: uves_redchain_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 (1032 lines) | stat: -rw-r--r-- 42,939 bytes parent folder | download | duplicates (3)
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
/*                                                                              *
 *   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: 2010-09-24 09:32:07 $
 *
 */

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


/*----------------------------------------------------------------------------*/
/**
 * @defgroup uves_redchain  Recipe: Reduction Chain
 *
 * This recipe executes a reduction chain. See man-page for details.
 */
/*----------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------
                                Includes
 -----------------------------------------------------------------------------*/

#include <uves.h>

#include <uves_parameters.h>
#include <uves_utils.h>
#include <uves_utils_wrappers.h>
#include <uves_dfs.h>
#include <uves_recipe.h>
#include <uves_error.h>
#include <uves_msg.h>

/* Library */
#include <cpl.h>
#include <string.h>
/*-----------------------------------------------------------------------------
                            Local constants
 -----------------------------------------------------------------------------*/
static const bool flames = false;  /* This recipe is only for UVES */

/*-----------------------------------------------------------------------------
                            Functions prototypes
 -----------------------------------------------------------------------------*/
static bool frame_is_needed(bool blue, const cpl_frame *f);
static cpl_error_code execute_recipe(const char *recipe_id, 
                                     cpl_frameset *frames, const cpl_parameterlist *parameters,
                                     const char *products[], int n_products, bool reclassify);
static bool is_missing(const cpl_frameset *frames, const char *frame1, const char *frame2);
static void remove_input_frame(cpl_frameset *frames, const char *tag);

static int uves_redchain_define_parameters(cpl_parameterlist *parameters);

/*-----------------------------------------------------------------------------
                            Recipe standard code
 -----------------------------------------------------------------------------*/
#define cpl_plugin_get_info uves_redchain_get_info
UVES_RECIPE_DEFINE(
    UVES_REDCHAIN_ID, UVES_REDCHAIN_DOM, uves_redchain_define_parameters,
    "Jonas M. Larsen", "cpl@eso.org",
    "Runs the full UVES reduction chain",
    "This recipe does a complete science reduction. It runs all necessary\n"
    "calibration recipes depending on the availability of raw/processed\n"
    "calibration frames.\n"
    "Input frames are all UVES raw and reference frames:\n"
    "formatchecks, ARC_LAMP_FORM_xxxx, xxxx=BLUE or RED,\n"
    "order definition frames, ORDER_FLAT_xxx,\n"
    "biases, BIAS_xxx,\n"
    "darks, DARK_xxx,\n"
    "flats, FLAT_xxx,\n"
    "arc lamps, ARC_LAMP_xxx,\n"
    "standard stars, STANDARD_xxx\n"
    "a wavelength catalogue table,LINE_REFER_TABLE, \n"
    "and optionally a wavelength table of bright lines,LINE_INTMON_TABLE, \n"
    "used only for computing Quality Control parameters.\n"
    "a reference standard star flux table, FLUX_STD_TABLE, \n"
    "a table describing the atmospheric extintion,EXTCOEFF_TABLE.\n"
    "optionally, science frames, SCIENCE_xxx, or UVES_SCI_POINT_xxx, \n"
    "or UVES_SCI_EXTND_xxx, or UVES_SCI_SLICER_xxx.\n"
    "For further details on the data reduction and the input frame types\n"
    "refer to the man page of the individual recipes.\n");

/**@{*/

/*-----------------------------------------------------------------------------
                              Functions code
 -----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options    
  @param    parameters        the parameterlist to fill
  @return   0 if everything is ok
 */
/*----------------------------------------------------------------------------*/
static int
uves_redchain_define_parameters(cpl_parameterlist *parameters)
{
    const char *recipe_id = make_str(UVES_REDCHAIN_ID);
    const char *subcontext = NULL;
   
    uves_par_new_value("scired",
                       CPL_TYPE_BOOL,
                       "Whether or not to do science reduction. "
                       "If false, only master calibration frames "
                       "are created. If false, either zero or all "
                       "necessary calibration frames must be provided "
                       "for each arm",
                       true);

    /*****************
     *    General    *
     *****************/
    if (uves_define_global_parameters(parameters) != CPL_ERROR_NONE)
        {
            return -1;
        }

    /******************
     *   Master bias  *
     ******************/
    if (uves_propagate_parameters(
            make_str(UVES_MBIAS_ID), parameters, make_str(UVES_REDCHAIN_ID), NULL) != 0)
        {
            return -1;
        }


    /******************
     *   Master dark  *
     ******************/
    if (uves_propagate_parameters(
            make_str(UVES_MDARK_ID), parameters, make_str(UVES_REDCHAIN_ID), NULL) != 0)
        {
            return -1;
        }

    /******************
     * Physical model *
     ******************/
    if (uves_propagate_parameters(
            make_str(UVES_PHYSMOD_ID), parameters, make_str(UVES_REDCHAIN_ID), NULL) != 0)
        {
            return -1;
        }

    /******************
     * Order position *
     ******************/
    if (uves_propagate_parameters(
            make_str(UVES_ORDERPOS_ID), parameters, make_str(UVES_REDCHAIN_ID), NULL) != 0)
        {
            return -1;
        }

    /******************
     *   Master flat  *
     ******************/
    if (uves_propagate_parameters(
            make_str(UVES_MFLAT_ID), parameters, make_str(UVES_REDCHAIN_ID), NULL) != 0)
        {
            return -1;
        }

    
    /******************
     *   Wave.cal.    *
     ******************/
    if (uves_propagate_parameters(
            make_str(UVES_WAVECAL_ID), parameters, make_str(UVES_REDCHAIN_ID), NULL) != 0)
        {
            return -1;
        }

    /******************
     *    Response    *
     ******************/
/*
    if (uves_propagate_parameters(
             make_str(UVES_RESPONSE_ID), parameters, make_str(UVES_REDCHAIN_ID), NULL) != 0)
    {
             return -1;
    }
*/

    uves_define_background_for_response_chain_parameters(parameters);
    uves_define_extract_for_response_chain_parameters(parameters);
    uves_define_reduce_for_response_chain_parameters(parameters);
    uves_define_rebin_for_response_chain_parameters(parameters);
    uves_define_efficiency_for_response_chain_parameters(parameters);
  


    /******************
     *    Scired      *
     ******************/
    if (uves_propagate_parameters(
            make_str(UVES_SCIRED_ID), parameters, make_str(UVES_REDCHAIN_ID), NULL) != 0)
        {
            return -1;
        }

    return (cpl_error_get_code() != CPL_ERROR_NONE);
}

/*----------------------------------------------------------------------------*/
/**
  @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


 */
/*----------------------------------------------------------------------------*/
static void
UVES_CONCAT2X(UVES_REDCHAIN_ID,exe)(cpl_frameset *frames,
                      const cpl_parameterlist *parameters, 
                      const char *starttime)
{
    cpl_frameset *blue_frames = NULL;
    cpl_frameset *red_frames = NULL;
    cpl_frameset *common_frames = NULL;
 

    bool blue;
    bool do_science;

    bool run_mbias[2];     /* index 0 (==false): red  arm */
    bool run_mdark[2];     /* index 1 (==true ): blue arm  */
    bool run_mflat[2];
    bool run_physmod[2];
    bool run_orderpos[2];
    bool run_wavecal[2];
    bool run_response[2];
    bool run_scired[2];
    bool nraw_arm[2];      /* Do we have frames used exclusively
                              for this arm? */
    const char* PROCESS_CHIP=NULL;

    /* Exceptionally, this parameter is not used because this
       recipe does not create any products on its own. Suppress
       warning about unused variable */
    starttime = starttime;

    check( uves_get_parameter(parameters, NULL, make_str(UVES_REDCHAIN_ID), "scired", 
                              CPL_TYPE_BOOL, &do_science), "Could not read parameter");

    /* Check for at least one science frame */
    assure(!do_science ||
           cpl_frameset_find(frames, UVES_SCIENCE(true ))    != NULL ||
           cpl_frameset_find(frames, UVES_SCIENCE(false))    != NULL ||
           cpl_frameset_find(frames, UVES_SCI_EXTND(true ))  != NULL ||
           cpl_frameset_find(frames, UVES_SCI_EXTND(false))  != NULL ||
           cpl_frameset_find(frames, UVES_SCI_POINT(true ))  != NULL ||
           cpl_frameset_find(frames, UVES_SCI_POINT(false))  != NULL ||
           cpl_frameset_find(frames, UVES_SCI_SLICER(true )) != NULL ||
           cpl_frameset_find(frames, UVES_SCI_SLICER(false)) != NULL,
           CPL_ERROR_DATA_NOT_FOUND, "No %s, %s, %s, %s, %s, %s, %s or %s in frame set", 
           UVES_SCIENCE(true),
           UVES_SCIENCE(false),
           UVES_SCI_EXTND(true),
           UVES_SCI_EXTND(false),
           UVES_SCI_POINT(true),
           UVES_SCI_POINT(false),
           UVES_SCI_SLICER(true),
           UVES_SCI_SLICER(false));
        
    blue_frames = cpl_frameset_new();
    red_frames = cpl_frameset_new();
    common_frames = cpl_frameset_new();

    check( uves_get_parameter(parameters, NULL, "uves", "process_chip", CPL_TYPE_STRING, &PROCESS_CHIP),
               "Could not read parameter");
    uves_string_toupper((char*)PROCESS_CHIP);

    /* Split in blue/red frames */
    {
        cpl_frame *f = NULL;
        int i=0;
        int nfrm=0;
        nfrm=cpl_frameset_get_size(frames);
        for (i=0;i<nfrm;i++)
            {

                f=cpl_frameset_get_frame(frames,i);
                if (frame_is_needed(true, f))    /* Used in blue arm? */
                    {
                        uves_msg_debug("Found blue frame: '%s'", cpl_frame_get_tag(f));
                        check( cpl_frameset_insert(blue_frames, cpl_frame_duplicate(f)),
                               "Error extracting frame '%s' from frame set",
                               cpl_frame_get_tag(f));
                    }
                if (frame_is_needed(false, f))  /* Used in red arm? */
                    {
                        uves_msg_debug("Found red frame: '%s'", cpl_frame_get_tag(f));
                        check( cpl_frameset_insert(red_frames, cpl_frame_duplicate(f)),
                               "Error extracting frame '%s' from frame set",
                               cpl_frame_get_tag(f));
                    }

                if (frame_is_needed(true, f) && 
                    frame_is_needed(false, f))  /* Used in both arms? */
                    {
                        uves_msg_debug("Found common frame: '%s'", cpl_frame_get_tag(f));
                        check( cpl_frameset_insert(common_frames, cpl_frame_duplicate(f)),
                               "Error extracting frame '%s' from frame set",
                               cpl_frame_get_tag(f));
                    }

            }
        /* Remove all frames from input frame set */
        cpl_frame *frm = NULL;
        for (i=0;i<nfrm;i++) {
            check_nomsg(frm=cpl_frameset_get_frame(frames,0));
            check_nomsg(cpl_frameset_erase_frame(frames, frm));
        }


    }

    /* Algorithm:
       (with purpose of failing early if we have to fail.)

       1) Find out which recipes to run
       2) Check for necessary input frames
       3) Execute
    */

    blue = true;
    do {
        enum uves_chip chip1 = (blue) ? UVES_CHIP_BLUE : UVES_CHIP_REDL;
        enum uves_chip chip2 = (blue) ? UVES_CHIP_BLUE : UVES_CHIP_REDU;
        
        cpl_frameset *fms = (blue) ? blue_frames : red_frames;

        nraw_arm[blue] = 
            cpl_frameset_get_size(fms) > 
            cpl_frameset_get_size(common_frames);
        
        uves_msg_debug("nraw_arm=%d (%s arm)", nraw_arm[blue], blue ? "blue" : "red");
        
        run_scired[blue] = do_science &&
            !(is_missing(fms, UVES_SCIENCE(blue), NULL) &&
              is_missing(fms, UVES_SCI_EXTND(blue), NULL) &&
              is_missing(fms, UVES_SCI_POINT(blue), NULL) &&
              is_missing(fms, UVES_SCI_SLICER(blue), NULL));
        
        /* If calibrations must be produced for this arm */
        if (run_scired[blue]
            ||
            (!do_science && nraw_arm[blue])) {
            
            /* Require master bias */
            run_mbias[blue] = is_missing(fms, 
                                         UVES_MASTER_BIAS(chip1),
                                         UVES_MASTER_BIAS(chip2)
                );
            
            /* Run master dark, only if raw frames are available */ 
            run_mdark[blue] = 
                is_missing(fms,
                           UVES_MASTER_DARK(chip1),
                           UVES_MASTER_DARK(chip2)) 
                &&
                is_missing(fms,
                           UVES_MASTER_PDARK(chip1),
                           UVES_MASTER_PDARK(chip2))
                &&(
                    !is_missing(fms, UVES_DARK(blue), NULL) ||
                    !is_missing(fms, UVES_PDARK(blue), NULL));
            
            /* Run orderpos if either order table is missing, 
               or raw frame available */
            run_orderpos[blue] = is_missing(fms,
                                            UVES_ORDER_TABLE(flames, chip1),
                                            UVES_ORDER_TABLE(flames, chip2)
                ) ||
                !is_missing(fms, UVES_ORDER_FLAT(flames, blue), NULL);
            
            /* Run master flat recipe if master flat frame is missing */
            run_mflat[blue] = 
                is_missing(fms,
                           UVES_MASTER_FLAT(chip1),
                           UVES_MASTER_FLAT(chip2))
                &&
                is_missing(fms,
                           UVES_MASTER_DFLAT(chip1),
                           UVES_MASTER_DFLAT(chip2))
                &&
                is_missing(fms,
                           UVES_MASTER_IFLAT(chip1),
                           UVES_MASTER_IFLAT(chip2))
                &&
                is_missing(fms,
                           UVES_MASTER_SCREEN_FLAT(chip1),
                           UVES_MASTER_SCREEN_FLAT(chip2))
                &&
                is_missing(fms,
                           UVES_REF_TFLAT(chip1),
                           UVES_REF_TFLAT(chip2));
            
            
            /* Line tables are used as both input and output
               for wavecal recipe. A provided line table is 
               interpreted as an input table if an arc lamp 
               frame is also available, otherwise as output.
               Line tables produce by the physmod recipe are
               input tables. The logic is
               
               if !linetable
                 physmod=yes
                 wavecal=yes
               if linetable
                 physmod=no
                 if !arclamp
                   wavecal=no   // line table is final
                 if arclamp
                   wavecal=yes  // line table is guess
            */
            
            /* Run physical model if there's no
               line table */
            run_physmod[blue] = is_missing(fms,
                                           UVES_LINE_TABLE(flames, chip1),
                                           UVES_LINE_TABLE(flames, chip2))
                &&
        is_missing(fms,
               UVES_GUESS_LINE_TABLE(flames, chip1),
               UVES_GUESS_LINE_TABLE(flames, chip2))
                &&
                (
                    is_missing(fms,
                               UVES_LINE_TABLE_MIDAS(chip1, 1), 
                               UVES_LINE_TABLE_MIDAS(chip2, 1)) ||
                    is_missing(fms,
                               UVES_LINE_TABLE_MIDAS(chip1, 2),
                               UVES_LINE_TABLE_MIDAS(chip2, 2)) ||
                    is_missing(fms,
                               UVES_LINE_TABLE_MIDAS(chip1, 3),
                               UVES_LINE_TABLE_MIDAS(chip2, 3))
                    );
                    
            /* Run wavecal if no line table,
               or if there's an arc lamp frame
            */
            run_wavecal[blue] = 
                run_physmod[blue]
                ||
        (
            is_missing(fms,
                   UVES_LINE_TABLE(flames, chip1),
                   UVES_LINE_TABLE(flames, chip2))
            &&
            (
            is_missing(fms,
                   UVES_LINE_TABLE_MIDAS(chip1, 1), 
                   UVES_LINE_TABLE_MIDAS(chip2, 1)) ||
            is_missing(fms,
                   UVES_LINE_TABLE_MIDAS(chip1, 2),
                   UVES_LINE_TABLE_MIDAS(chip2, 2)) ||
            is_missing(fms,
                   UVES_LINE_TABLE_MIDAS(chip1, 3),
                   UVES_LINE_TABLE_MIDAS(chip2, 3))
            )
            )
        ||
        (
            !is_missing(fms,
                                UVES_ARC_LAMP(flames, blue), NULL) ||
                    !is_missing(fms,
                                UVES_ECH_ARC_LAMP(blue), NULL)
                    );
        
            /* Run response only if there's a standard star.
               Otherwise no response correction is done */
            run_response[blue] = !is_missing(fms,
                                             UVES_STD_STAR(blue), NULL);
                    
                    
            uves_msg("Reduction strategy for %s arm:", (blue) ? "BLUE" : "RED");
            uves_msg("Run %-13s: %s", make_str(UVES_MBIAS_ID)   , (run_mbias[blue]   ) ? "Yes" : "No");
            uves_msg("Run %-13s: %s", make_str(UVES_MDARK_ID)   , (run_mdark[blue]   ) ? "Yes" : "No");
            uves_msg("Run %-13s: %s", make_str(UVES_PHYSMOD_ID) , (run_physmod[blue] ) ? "Yes" : "No");
            uves_msg("Run %-13s: %s", make_str(UVES_ORDERPOS_ID), (run_orderpos[blue]) ? "Yes" : "No");
            uves_msg("Run %-13s: %s", make_str(UVES_MFLAT_ID)   , (run_mflat[blue]   ) ? "Yes" : "No");
            uves_msg("Run %-13s: %s", make_str(UVES_WAVECAL_ID) , (run_wavecal[blue] ) ? "Yes" : "No");
            uves_msg("Run %-13s: %s", make_str(UVES_RESPONSE_ID), (run_response[blue]) ? "Yes" : "No");
            uves_msg("Run %-13s: %s", make_str(UVES_SCIRED_ID)  , (run_scired[blue]  ) ? "Yes" : "No");
    
        }  /* if reduce this arm */
        else {
            uves_msg("Skipping %s arm", 
                     (blue) ? "BLUE" : "RED");

            run_mbias[blue] = false;
            run_mdark[blue] = false;
            run_mflat[blue] = false;
            run_physmod[blue] = false;
            run_orderpos[blue] = false;
            run_wavecal[blue] = false;
            run_response[blue] = false;
        }
            
        blue = !blue;
    }
    while (!blue);

    /* As a service to the user, assure that required
       raw frames and catalogue calibration frames
       exist *before* doing the reduction */
    
    blue = true;
    do
        {
            cpl_frameset *fms = (blue) ? blue_frames : red_frames;

            assure( !run_mbias[blue] || !is_missing(fms, UVES_BIAS(blue), NULL), 
                    CPL_ERROR_DATA_NOT_FOUND,
                    "One or more '%s' frames needed for recipe '%s'",
                    UVES_BIAS(blue), make_str(UVES_MBIAS_ID));
            
            assure( !run_mdark[blue] || 
                    !is_missing(fms, UVES_DARK(blue), NULL) ||
                    !is_missing(fms, UVES_PDARK(blue), NULL),
                    CPL_ERROR_DATA_NOT_FOUND, 
                    "One or more '%s' or '%s' frames needed for recipe '%s'",
                    UVES_DARK(blue), UVES_PDARK(blue), make_str(UVES_MDARK_ID));
            
            assure( !run_physmod[blue] || !is_missing(fms, UVES_FORMATCHECK(flames, blue), NULL),
                    CPL_ERROR_DATA_NOT_FOUND, "Frame '%s' needed for recipe '%s'",
                    UVES_FORMATCHECK(flames, blue), make_str(UVES_PHYSMOD_ID));
            
            assure( !run_orderpos[blue] || !is_missing(fms, UVES_ORDER_FLAT(flames, blue), NULL),
                    CPL_ERROR_DATA_NOT_FOUND, "Frame '%s' needed for recipe '%s'",
                    UVES_ORDER_FLAT(flames, blue), make_str(UVES_ORDERPOS_ID));
            
            assure( !run_mflat[blue] || 
                    !is_missing(fms, UVES_FLAT(blue), NULL) ||
                    !is_missing(fms, UVES_IFLAT(blue), NULL) ||
                    !is_missing(fms, UVES_SCREEN_FLAT(blue), NULL) ||
                    !is_missing(fms, UVES_DFLAT(blue), NULL) ||
                    !is_missing(fms, UVES_TFLAT(blue), NULL),
                    CPL_ERROR_DATA_NOT_FOUND, 
                    "One or more '%s', '%s', '%s', '%s' or '%s' frames needed for recipe '%s'",
                    UVES_FLAT(blue), 
                    UVES_IFLAT(blue), 
                    UVES_SCREEN_FLAT(blue), 
                    UVES_DFLAT(blue), 
                    UVES_TFLAT(blue), 
                    make_str(UVES_MFLAT_ID));
            
            assure( !run_wavecal[blue] || (
                        !is_missing(fms, UVES_ARC_LAMP(flames, blue), NULL) ||
                        !is_missing(fms, UVES_ECH_ARC_LAMP(blue), NULL)),
                    CPL_ERROR_DATA_NOT_FOUND, "Frame '%s' or '%s' needed for recipe '%s'",
                    UVES_ARC_LAMP(flames, blue), UVES_ECH_ARC_LAMP(blue), make_str(UVES_WAVECAL_ID));
            assure( !run_wavecal[blue] || !is_missing(fms, UVES_LINE_REFER_TABLE, NULL),
                    CPL_ERROR_DATA_NOT_FOUND, "Frame '%s' needed for recipe '%s'",
                    UVES_LINE_REFER_TABLE, make_str(UVES_WAVECAL_ID));
            
            assure( !run_response[blue] || !is_missing(fms, UVES_STD_STAR(blue), NULL), 
                    CPL_ERROR_DATA_NOT_FOUND, "Frame '%s' needed for recipe '%s'",
                    UVES_STD_STAR(blue), make_str(UVES_RESPONSE_ID));
            assure( !run_response[blue] || !is_missing(fms, UVES_FLUX_STD_TABLE, NULL), 
                    CPL_ERROR_DATA_NOT_FOUND, "Frame '%s' needed for recipe '%s'",
                    UVES_FLUX_STD_TABLE, make_str(UVES_RESPONSE_ID));
            assure( !run_response[blue] || !is_missing(fms, UVES_EXTCOEFF_TABLE, NULL), 
                    CPL_ERROR_DATA_NOT_FOUND, "Frame '%s' needed for recipe '%s'",
                    UVES_EXTCOEFF_TABLE, make_str(UVES_RESPONSE_ID));
            
            blue = !blue;
        }
    while (!blue);
   
    /* We now know which recipes to run and
     * that required input frames exist. Execute
     * chain; re-classify PRODUCT->CALIB under way
     */
    
    blue = true;
    do
        {
            enum uves_chip chip1 = (blue) ? UVES_CHIP_BLUE : UVES_CHIP_REDL;
            enum uves_chip chip2 = (blue) ? UVES_CHIP_BLUE : UVES_CHIP_REDU;

            cpl_frameset *fms = (blue) ? blue_frames : red_frames;

            if (run_mbias[blue])
                {
                    const char *products[2];
                    
                    int nprod = sizeof(products) / sizeof (char *);
                    
                    products[0] = UVES_MASTER_BIAS(chip1);
                    products[1] = UVES_MASTER_BIAS(chip2);
                    
                    if (blue) nprod /= 2;
                    
                    check( execute_recipe(make_str(UVES_MBIAS_ID), fms, parameters, products, nprod, true),
                           "Recipe execution failed");
                }
            
            check( remove_input_frame(fms, UVES_BIAS(blue)), "Error removing input frames");
            
            if (run_mdark[blue])
                {
                    const char *products[4];
                    
                    int nprod = sizeof(products) / sizeof (char *);
                    
                    products[0] = UVES_MASTER_DARK(chip1);
                    products[1] = UVES_MASTER_PDARK(chip1);
                    products[2] = UVES_MASTER_DARK(chip2);
                    products[3] = UVES_MASTER_PDARK(chip2);
                    
                    if (blue) nprod /= 2;

                    check( execute_recipe(
                               make_str(UVES_MDARK_ID), fms, parameters, products, nprod, true), 
                           "Recipe execution failed");
                }
            
            check( remove_input_frame(fms, UVES_DARK(blue)), "Error removing input frames");
            check( remove_input_frame(fms, UVES_PDARK(blue)), "Error removing input frames");
            
            if (run_physmod[blue])
                {
                    const char *products[4];
                    int nprod = sizeof(products) / sizeof (char *);
                    
                    products[0] = UVES_GUESS_LINE_TABLE (flames, chip1);
                    products[1] = UVES_GUESS_ORDER_TABLE(flames, chip1);
                    products[2] = UVES_GUESS_LINE_TABLE (flames, chip2);
                    products[3] = UVES_GUESS_ORDER_TABLE(flames, chip2);
                    
                    if (blue) nprod /= 2;
                    
                    check( execute_recipe(
                               make_str(UVES_PHYSMOD_ID), 
                               fms, parameters, products, nprod, true), 
                           "Recipe execution failed");
                }
            
            check( remove_input_frame(fms, UVES_FORMATCHECK(flames, blue)), 
                   "Error removing input frames");
            
            if (run_orderpos[blue])
                {
                    const char *products[2];
                    int nprod = sizeof(products) / sizeof (char *);
                    
                    products[0] = UVES_ORDER_TABLE(flames, chip1);
                    products[1] = UVES_ORDER_TABLE(flames, chip2);
                    
                    if (blue) nprod /= 2;
                            
                    check( execute_recipe(
                               make_str(UVES_ORDERPOS_ID), 
                               fms, parameters, products, nprod, true), 
                           "Recipe execution failed");
                }

            check( remove_input_frame(fms, UVES_ORDER_FLAT(flames, blue)),
                   "Error removing input frames");
                    
            if (run_mflat[blue])
                {
                    const char *products[10];
                            
                    int nprod = sizeof(products) / sizeof (char *);

                    products[0] = UVES_MASTER_FLAT(chip1);
                    products[1] = UVES_MASTER_DFLAT(chip1);
                    products[2] = UVES_MASTER_IFLAT(chip1);
                    products[3] = UVES_MASTER_TFLAT(chip1);
                    products[4] = UVES_MASTER_SCREEN_FLAT(chip1);
                    products[5] = UVES_MASTER_FLAT(chip2);
                    products[6] = UVES_MASTER_DFLAT(chip2);
                    products[7] = UVES_MASTER_IFLAT(chip2);
                    products[8] = UVES_MASTER_TFLAT(chip2);
                    products[9] = UVES_MASTER_SCREEN_FLAT(chip2);
                            
                    if (blue) nprod /= 2;
                            
                    check( execute_recipe(make_str(UVES_MFLAT_ID), 
                                          fms, parameters, products, nprod, true), 
                           "Recipe execution failed");
                }
                    
            check( remove_input_frame(fms, UVES_FLAT(blue)), "Error removing input frames");
            check( remove_input_frame(fms, UVES_IFLAT(blue)), "Error removing input frames");
            check( remove_input_frame(fms, UVES_DFLAT(blue)), "Error removing input frames");
            check( remove_input_frame(fms, UVES_TFLAT(blue)), "Error removing input frames");
            check( remove_input_frame(fms, UVES_SCREEN_FLAT(blue)), "Error removing input frames");
                    
            if (run_wavecal[blue])
                {
                    const char *products[2];
                            
                    int nprod = sizeof(products) / sizeof (char *);

                    products[0] = UVES_LINE_TABLE(flames, chip1);
                    products[1] = UVES_LINE_TABLE(flames, chip2);
                            
                    if (blue) nprod /= 2;
                    
                    check( execute_recipe(make_str(UVES_WAVECAL_ID), 
                                          fms, parameters, products, nprod, true), 
                           "Recipe execution failed");
                }

            check( remove_input_frame(fms, UVES_ARC_LAMP(flames, blue)), 
           "Error removing input frames");
            check( remove_input_frame(fms, UVES_ECH_ARC_LAMP(blue)), 
           "Error removing input frames");
            check( remove_input_frame(fms, UVES_LINE_REFER_TABLE), 
           "Error removing input frames");
                    
            if (run_response[blue])
                {
                    const char *products[2];
                            
                    int nprod = sizeof(products) / sizeof (char *);

                    products[0] = UVES_INSTR_RESPONSE(chip1);
                    products[1] = UVES_INSTR_RESPONSE(chip2);
                            
                    if (blue) nprod /= 2;
                            
                     check( execute_recipe(make_str(UVES_RESPONSE_ID), 
                                          fms, parameters, products, nprod, true),
                           "Recipe execution failed");
                }

            check( remove_input_frame(fms, UVES_STD_STAR(blue)), "Error removing input frames");
            check( remove_input_frame(fms, UVES_FLUX_STD_TABLE), "Error removing input frames");

            if (run_scired[blue])
                {
                    const char *products[2];
                            
                    int nprod = sizeof(products) / sizeof (char *);

                    products[0] = blue ? "RED_SCIENCE_BLUE" : "RED_SCIENCE_REDL";
                    products[1] = blue ? "RED_SCIENCE_BLUE" : "RED_SCIENCE_REDU";
                            
                    if (blue) nprod /= 2;

                    check( execute_recipe(make_str(UVES_SCIRED_ID), 
                                          fms, parameters, products, nprod, false),
                           "Recipe execution failed");
                }
                    
            check( remove_input_frame(fms, UVES_SCIENCE(blue))   , "Error removing input frames");
            check( remove_input_frame(fms, UVES_SCI_EXTND(blue)) , "Error removing input frames");
            check( remove_input_frame(fms, UVES_SCI_POINT(blue)) , "Error removing input frames");
            check( remove_input_frame(fms, UVES_SCI_SLICER(blue)), "Error removing input frames");
                    
            /* Insert all product frames into recipe frame set */
            {
                cpl_frame *f = NULL;
                int i=0;
                int nfrm=0;
                nfrm=cpl_frameset_get_size(fms);
                for (i=0;i<nfrm;i++)
                    {
                     f=cpl_frameset_get_frame(fms,i);
                        if (cpl_frame_get_group(f) == CPL_FRAME_GROUP_PRODUCT)
                            {
                                check( cpl_frameset_insert(frames, cpl_frame_duplicate(f)),
                                       "Error inserting product '%s' into frame set",
                                       cpl_frame_get_tag(f));
                            }
                    }
            }
            
            blue = !blue;
        }
    while(!blue);     /* For each arm */
    
  cleanup:
    uves_free_frameset(&blue_frames);
    uves_free_frameset(&red_frames);
    uves_free_frameset(&common_frames);

    return;
}

/* Returns true, iff frame is used for blue/red arm
   (note that some frames like UVES_FLUX_STD_TABLE are
   used for both arms) */
static bool
frame_is_needed(bool blue, const cpl_frame *f)
{
    const char *tag = cpl_frame_get_tag(f);
    
    bool result = (strcmp(tag, UVES_ORDER_FLAT (flames, blue)) == 0 ||
                   strcmp(tag, UVES_BIAS       (blue)) == 0 ||
                   strcmp(tag, UVES_DARK       (blue)) == 0 ||
                   strcmp(tag, UVES_PDARK      (blue)) == 0 ||
                   strcmp(tag, UVES_FLAT       (blue)) == 0 ||
                   strcmp(tag, UVES_IFLAT      (blue)) == 0 ||
                   strcmp(tag, UVES_DFLAT      (blue)) == 0 ||
                   strcmp(tag, UVES_TFLAT      (blue)) == 0 ||
                   strcmp(tag, UVES_SCREEN_FLAT(blue)) == 0 ||
                   strcmp(tag, UVES_STD_STAR   (blue)) == 0 ||
                   strcmp(tag, UVES_FORMATCHECK(flames, blue)) == 0 ||
                   strcmp(tag, UVES_STD_STAR   (blue)) == 0 ||
                   strcmp(tag, UVES_SCIENCE    (blue)) == 0 ||
                   strcmp(tag, UVES_SCI_EXTND  (blue)) == 0 ||
                   strcmp(tag, UVES_SCI_POINT  (blue)) == 0 ||
                   strcmp(tag, UVES_SCI_SLICER (blue)) == 0 ||
                   strcmp(tag, UVES_ARC_LAMP   (flames, blue)) == 0 ||
                   strcmp(tag, UVES_ECH_ARC_LAMP(blue)) == 0);
    
    enum uves_chip chip;
    
    /* Loop through all blue or red chips  (1 or 2) */
    for (chip = uves_chip_get_first(blue); 
         chip != UVES_CHIP_INVALID; 
         chip = uves_chip_get_next(chip))
        {
            result = result || (strcmp(tag, UVES_DRS_SETUP(flames, chip)) == 0 ||
                                strcmp(tag, UVES_ORDER_TABLE(flames, chip)) == 0 ||
                                strcmp(tag, UVES_GUESS_ORDER_TABLE(flames, chip)) == 0 ||
                                strcmp(tag, UVES_MASTER_BIAS(chip)) == 0 ||
                                strcmp(tag, UVES_MASTER_DARK(chip)) == 0 ||
                                strcmp(tag, UVES_MASTER_PDARK(chip)) == 0 ||
                                strcmp(tag, UVES_MASTER_FLAT(chip)) == 0 ||
                                strcmp(tag, UVES_MASTER_DFLAT(chip)) == 0 ||
                                strcmp(tag, UVES_MASTER_IFLAT(chip)) == 0 ||
                                strcmp(tag, UVES_MASTER_TFLAT(chip)) == 0 ||
                                strcmp(tag, UVES_REF_TFLAT(chip)) == 0 ||
                                strcmp(tag, UVES_MASTER_SCREEN_FLAT(chip)) == 0 ||
                                strcmp(tag, UVES_LINE_TABLE (flames, chip)) == 0 ||
                                strcmp(tag, UVES_GUESS_LINE_TABLE(flames, chip)) == 0 ||
                                strcmp(tag, UVES_LINE_TABLE_MIDAS(chip, 1)) == 0 ||
                                strcmp(tag, UVES_LINE_TABLE_MIDAS(chip, 2)) == 0 ||
                                strcmp(tag, UVES_LINE_TABLE_MIDAS(chip, 3)) == 0 ||
                                strcmp(tag, UVES_LINE_REFER_TABLE ) == 0 ||
                                strcmp(tag, UVES_FLUX_STD_TABLE   ) == 0 ||
                                strcmp(tag, UVES_EXTCOEFF_TABLE   ) == 0);
        }
    return result;
}

/* Execute a recipe and re-classify its products as calibration frames */
static cpl_error_code
execute_recipe(const char *recipe_id, 
               cpl_frameset *frames, const cpl_parameterlist *parameters,
               const char *products[],
               int n_products,
               bool reclassify)              /* Re-classify products? */
{
  int i;
  cpl_frame *f = NULL;

  /* Remove (from frame set) any product
     frames already present */
  for (i = 0; i < n_products; i++)
      {
          if ((f = cpl_frameset_find(frames, products[i])) != NULL)
              {
                  if (cpl_frame_get_group(f) == CPL_FRAME_GROUP_PRODUCT)
                      {
                          cpl_msg_warning(__func__, "Ignoring %s frame in '%s'. "
                                          "A new %s frame will now be calculated",
                                          products[i], cpl_frame_get_filename(f),
                                          products[i]);
                          
                          cpl_frameset_erase_frame(frames, f);
                      }
              }
      }
  
  /* Execute */
  check( uves_invoke_recipe(recipe_id, parameters, frames, make_str(UVES_REDCHAIN_ID), NULL),
         "Recipe '%s' failed", recipe_id);
            
  check(cpl_dfs_update_product_header(frames),"Error updating pipe products' header");
  if (reclassify)
      {
          /* Now re-classify PRODUCT->CALIB to be used in the remaining
             reduction chain. Before doing that, we have to remove any
             calibration frame with same tag as a product (such as line tables),
             in order not to confuse the re-classified products with the
             previous calibration frames */
          
          for (i = 0; i < n_products; i++)
              {
                  if ((f = cpl_frameset_find(frames, products[i])) != NULL &&
                      cpl_frame_get_group(f) != CPL_FRAME_GROUP_PRODUCT)
                      {
                          uves_msg("Removing %s frame in '%s' from frameset. "
                                   "It is not tagged as a product",
                                   products[i], cpl_frame_get_filename(f));
                          
                          cpl_frameset_erase_frame(frames, f);
                      }
              }
          
          /*
           * Re-classify products
           */
          for (i = 0; i < n_products; i++)
              {
                  cpl_frame *found = NULL;
                  int j=0;
                  int nfrm=cpl_frameset_get_size(frames);
                  for (j=0;j<nfrm;j++)
                      {
                          f=cpl_frameset_get_frame(frames,j);
                          if (cpl_frame_get_group(f) == CPL_FRAME_GROUP_PRODUCT)
                              {
                                  if (strcmp(cpl_frame_get_tag(f), products[i]) == 0)
                                      {
                                          found = f;
                                      }
                              }
                      }
                  
                  if (found != NULL)
                      {
                          /* Re-classify the product as calibration frames */
                          uves_msg("Re-classifying %s product in '%s' PRODUCT->CALIB",
                                   products[i], cpl_frame_get_filename(found));
                          
                          cpl_frame_set_group(found, CPL_FRAME_GROUP_CALIB);
                      }
              }
          
          /*
           * Remove other products that 
           * are not used later  (e.g. BKG_FLAT_xxxx)
           */

          int k=0;
          int nfrm=cpl_frameset_get_size(frames);
          int nerased=0;
          for (k=0;k<nfrm-nerased;k++)
              {
                  f=cpl_frameset_get_frame(frames,k);

                  if (cpl_frame_get_group(f) == CPL_FRAME_GROUP_PRODUCT)
                      {
                          /* Remove this product */
                          uves_msg("Removing product %s in '%s' from frameset. "
                                   "Not needed later",
                                   cpl_frame_get_tag(f), cpl_frame_get_filename(f));
                          
                          cpl_frameset_erase_frame(frames, f);
                          nerased++;

                      }
              }  

      } /* if re-classify... */  

  cleanup:
  return cpl_error_get_code();
}
  

/* Retruns true if either frame 1 or frame 2 is not in the
   provided frame set 

   fixme: reverse the logic of this function, i.e. rename to 'contains'
*/
static bool
is_missing(const cpl_frameset *frames, const char *frame1, const char *frame2)
{
    bool result = false;
    if (cpl_frameset_find_const(frames, frame1) == NULL)
        {
            uves_msg("checking for %s... no", frame1);
            result = true;
        }
    else
        {
            uves_msg("checking for %s... yes", frame1);
        }
    
    if (frame2 != NULL && strcmp(frame1, frame2) != 0)
        {
            if (cpl_frameset_find_const(frames, frame2) == NULL)
                {
                    uves_msg("checking for %s... no", frame2);
                    result = true;
                }
            else
                {
                    uves_msg("checking for %s... yes", frame2);
                }
        }
    
  return result;
}


/* Remove input frames (e.g. bias frames) along the way */
static void
remove_input_frame(cpl_frameset *frames, const char *tag)
{
    int removed = cpl_frameset_erase(frames, tag);

    if (removed > 0)
        {
            uves_msg("Removing %d %s frame(s) from frame set", removed, tag);
        }

    return;
}
/**@}*/