File: vmimgastrometry.c

package info (click to toggle)
cpl-plugin-vimos 2.9.15%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 18,560 kB
  • ctags: 6,341
  • sloc: ansic: 148,777; sh: 11,457; cpp: 724; makefile: 606; python: 287; perl: 10
file content (1011 lines) | stat: -rw-r--r-- 30,802 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
/* $Id: vmimgastrometry.c,v 1.6 2013-03-25 11:43:04 cgarcia Exp $
 *
 * This file is part of the VIMOS Pipeline
 * Copyright (C) 2002-2004 European Southern Observatory
 *
 * This program 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, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/*
 * $Author: cgarcia $
 * $Date: 2013-03-25 11:43:04 $
 * $Revision: 1.6 $
 * $Name: not supported by cvs2svn $
 */

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

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

#include <pilmemory.h>
#include <pilmessages.h>
#include <cpl_msg.h>
#include <pilstrutils.h>
#include <piltranslator.h>

#include "vmimage.h"
#include "vmtable.h"
#include "vmtablearray.h"
#include "vmastrometrictable.h"
#include "vmstarmatchtable.h"
#include "vmwcsutils.h"
#include "vmimgextraction.h"
#include "vmimgastrometry.h"


/**
 * @defgroup vmimgastrometry Astrometry Utilities
 *
 * The module  provides the utility functions to determine
 * the correct astrometry (CD and CO matrices) for a VIMOS image.
 */

/**@{*/

/**
 * @brief
 *   Fit a CD matrix (pointing and rotation)
 *
 * @return @c VM_TRUE or @c VM_FALSE
 * 
 * @param calTables  Set of star match tables from different quadrants.
 * @param refImage   Reference image.
 *
 * The function merges the star match tables from the input set @em set
 * into a single star match table having the origin of the coordinate
 * system a pixel (0, 0) (given by the CRPIXi keywords). The new CD
 * matrix is computed fitting pixels versus right ascension and
 * declination.
 *
 * The reference image @em refImage is used to obtain the image size
 * in pixels of the images from which the input star match tables were
 * created. It is assumed that all images have the same size.
 *
 * The headers of each star match table in the input set is updated with
 * the computed CD matrix.
 *
 * @note
 *   To work properly the pixel coordinates of the input star match tables
 *   must be corrected for temperature effects.
 */

VimosBool
VmAstroComputeCD(VimosTableArray *calTables, const VimosImage *refImage)
{

  const char *modName = "VmAstroComputeCD";

  char *comment = "";

  int j;
  int nxpix, nypix;
  
  VimosTable  *stmcTable;

  struct WorldCoor *wcs = 0L;


  /*
   * Reset the input star match tables to same world coordinate system
   * and merge them into a single new table
   */

  
  if (!(stmcTable = shiftStarMatch(tblArrayGetData(calTables)))) {
    cpl_msg_error(modName,"Merging star match tables failed!");
    return VM_FALSE;
  }
    

  /*
   * Read common world coordinate system from the merged star match table
   * and update the WCS structure with the image size in pixels from
   * the header of the reference image.
   */
  
  if (readIntDescriptor(refImage->descs, pilTrnGetKeyword("Naxis", 1),
                        &nxpix, 0L) == VM_FALSE)
      return VM_FALSE;

  if (readIntDescriptor(refImage->descs, pilTrnGetKeyword("Naxis", 2),
                        &nypix, 0L) == VM_FALSE)
      return VM_FALSE;

  writeIntDescriptor(&(stmcTable->descs), "NAXIS", 2, comment);
  writeIntDescriptor(&(stmcTable->descs), pilTrnGetKeyword("Naxis", 1),
                     nxpix, comment);
  writeIntDescriptor(&(stmcTable->descs), pilTrnGetKeyword("Naxis", 2),
                     nypix, comment);

  if (!(wcs = rdimage(stmcTable->descs)))
    return VM_FALSE;

  removeDescriptor(&(stmcTable->descs), pilTrnGetKeyword("Naxis", 1));
  removeDescriptor(&(stmcTable->descs), pilTrnGetKeyword("Naxis", 2));

  wcs->nxpix = nxpix;
  wcs->nypix = nypix;


  /*
   * Fit CD matrix on the merged table.
   */

  if (!vimosFitMatch(wcs, stmcTable, stmcTable->cols->len))
    return VM_FALSE;
    
  deleteTable(stmcTable);


  /*
   * Update star match tables with new world coordinate system (but
   * CRPIX is the original one).
   */

  for (j = 0; j < 4; j++) {
    int k = 0;
    int ki, kj;

    VimosTable *table = (VimosTable *)tblArrayGet(calTables, j);

    for (ki = 1; ki <= 2; ki++) {
      writeDoubleDescriptor(&table->descs, pilTrnGetKeyword("Crval", ki),
                             wcs->crval[ki-1], pilTrnGetComment("Crval"));
      writeStringDescriptor(&table->descs, pilTrnGetKeyword("Ctype", ki),
                            wcs->ctype[ki-1], pilTrnGetComment("Ctype"));

      for(kj = 1; kj <= 2; kj++) {
        writeDoubleDescriptor (&table->descs, pilTrnGetKeyword("CD", ki, kj),
                               wcs->cd[k], pilTrnGetComment("CD"));
        k++;
      }
    }
  }

  vimoswcsfree(wcs);

  return VM_TRUE;

}


/**
 * @brief
 *   Fit a CO matrix (scale and distortions)
 *
 * @param calImage   The image for which CO has to be computed
 * @param tolrad     Search radius.
 * @param sigClip    Threshold for sigma clipping (?)
 * @param stmcTable  Star match table.
 * @param tflag      Flag to enable/disable temperature checks
 * @param tdevmax    Tolerance in C for beam temperature
 *
 * @return @c VM_TRUE or @c VM_FALSE
 * 
 * The function reads the CD matrix from the image @em calImage,
 * or, if the a star match table was given, i.e. @em stmcTable
 * is different from @c NULL, it is taken from @em stmcTable.
 * 
 * An artificial star table with a grid of 10 times 10 points is
 * created and the CCD to sky coordinate transformation is applied
 * to them, computing right ascension and declination. The right
 * ascension and declination are used to build an astrometric table,
 * and from both tables, star table and astrometric table, a star match
 * table is created and the CO matrix is fitted. The result is an image
 * @em calImage having a CO matrix which comprises wcs and CcdToSky.
 *
 * For details on the temperature check see the documentation for
 * @b computeVirtualPixels
 *
 * @see computeVirtualPixels
 */

VimosBool
VmAstroComputeCO(VimosImage *calImage, float tolrad, float sigClip,
                 VimosTable *stmcTable, unsigned int tflag, double tdevmax)
{
  const char *modName = "VmAstroComputeCO";


  char        comment[80], filterName[80];
  int         quad;
  int         naxis1, naxis2, nrow1;
  int         count;
  int         i,j,kj;
  double      rms[4];

  double rmsTol = 1.E-2;     /* tolerance for fitting in arcseconds */

  /*
   * Star Match Parameters: in this case magnitudes are fake, so anything
   * is OK
   */

  double tolMag1 = 30 , tolMag2 = 0.1;
  int minStar = 1;

  VimosTable *astroTable;
  VimosTable *newStmcTable;
  VimosTable *new2StmcTable;

  VimosColumn *RaCol, *xWorldCol, *NumCol, *IdCol, *xpixCol, *ypixCol;
  VimosColumn *DecCol, *yWorldCol;
  VimosColumn *xvirtCol, *yvirtCol;

  struct WorldCoor *wcs = 0;


  /*
   * We get Sky To Ccd coeffs from image
   */

  readIntDescriptor(calImage->descs, pilTrnGetKeyword("Naxis",1), &naxis1,
                    comment);
  readIntDescriptor(calImage->descs, pilTrnGetKeyword("Naxis",2), &naxis2,
                    comment);

  readIntDescriptor(calImage->descs, pilTrnGetKeyword("Quadrant"), &quad,
                    comment);
  readStringDescriptor(calImage->descs, pilTrnGetKeyword("FilterName", quad),
                       filterName, comment);

  /*
   * Now select the first character of the filter name that should indicate 
   * the wavelength band: 
   */
  
  filterName[1] = '\0';


  /*
   * In case of 4 quadrants, take wcs From StarMatch. The four quadrant
   * case is recognized by passing a non-NULL pointer for stmcTable.
   */

  if (stmcTable) {

    /*
     * As it is a table, we don't have naxis k/w..., an we need them for wcs!
     * thus we take them from first image, and just add to table, temporarily
     */

    writeIntDescriptor(&(stmcTable->descs), pilTrnGetKeyword("Naxis", 1),
                       naxis1, "");
    writeIntDescriptor(&(stmcTable->descs), pilTrnGetKeyword("Naxis", 2),
                       naxis2, "");

    if (!(wcs = rdimage(stmcTable->descs))) {
      return VM_FALSE;
    } 

    removeDescriptor(&(stmcTable->descs), pilTrnGetKeyword("Naxis", 1));
    removeDescriptor(&(stmcTable->descs), pilTrnGetKeyword("Naxis", 2));
    
    /*
     * and put it into image, because ImStarMatch re-reads it from image
     */

    upheader(calImage, wcs,  rms);

  }
  else {

    /*
     * In the case of 1 Quadrant, it is the same as from image
     */

    if (!(wcs = rdimage(calImage->descs))) {
      return VM_FALSE;
    } 
  }


  /*
   * What we want in StarMatch Table now is a grid of countxcount points 
   * we don't care whatever there was before
   */

  count = 10;

  newStmcTable = resetStarMatchTable(count, naxis1, naxis2);
  if (!newStmcTable) {
    cpl_msg_error(modName,"Could not make new StarMatch Table");
    return VM_FALSE;
  }
       
  if (computeVirtualPixels(calImage->descs, newStmcTable, tflag,
                           tdevmax) == VM_FALSE) {
    cpl_msg_error(modName, "Unable to apply Sky To CCd matrix");
    return VM_FALSE;
  }

  /*
   * Finally, use columns X-Image and Y_Image from StarMatchTable, convert
   * them to wcs using Sky To Ccd and NEW CD
   */

  nrow1 = newStmcTable->cols->len;
  pixtowcs(nrow1, newStmcTable, wcs);   


  /*
   * We now have a starMatch which in reality is a sort of AstroTable
   * as it contains xpixvirtual Ypixvirtual and Ra DEC. These are the real
   * RA DEC I put it in an AstroTable structure
   */

  astroTable = resetAstroTable(count,filterName);

  if (!astroTable) {
    cpl_msg_error(modName,"Could not make new astro Table");
    return VM_FALSE;
  }

  IdCol = findColInTab(astroTable, "ID");
  RaCol = findColInTab(astroTable, "RA");
  DecCol = findColInTab(astroTable, "DEC");

  NumCol = findColInTab(newStmcTable, "NUMBER");
  xWorldCol = findColInTab(newStmcTable, "X_WORLD");
  yWorldCol = findColInTab(newStmcTable, "Y_WORLD");


  /* delete next 4 before flight */

      xvirtCol = findColInTab(astroTable, "X_IMAGE");
      yvirtCol = findColInTab(astroTable, "Y_IMAGE");
      xpixCol = findColInTab(newStmcTable, "X_IMAGE");
      ypixCol = findColInTab(newStmcTable, "Y_IMAGE");


  for (i = 0; i < nrow1; i++) {
    RaCol->colValue->dArray[i] = xWorldCol->colValue->dArray[i];
    DecCol->colValue->dArray[i] = yWorldCol->colValue->dArray[i];
    sprintf(IdCol->colValue->sArray[i], "%d", NumCol->colValue->iArray[i]);
    
    /* delete next 2 before flight */
        xvirtCol->colValue->dArray[i] = xpixCol->colValue->dArray[i];
        yvirtCol->colValue->dArray[i] = ypixCol->colValue->dArray[i];
  }


  /*
   * And now reset the X-IMAGE Y_IMAGE columns of stmcTable
   * to the original grid
   */

  xpixCol = findColInTab(newStmcTable, "X_IMAGE");
  kj=0;
  for(i=0; i<count; i++) { 
    for(j=0; j<count; j++,kj++) {
      xpixCol->colValue->dArray[kj] = (j+1)*naxis1/(count + 1);
    }
  }

  ypixCol = findColInTab(newStmcTable, "Y_IMAGE");
  kj=0;
  for(i=0; i<count; i++) { 
    for(j=0; j<count; j++,kj++) {
      ypixCol->colValue->dArray[kj] = (i+1)*naxis2/(count + 1);
    }
  }


  /*
   * Thus we have a StarMatch Table with Xpix Ypix, and an astroTable with
   * RA DEC  we should now start from Xpix Ypix 
   * and fit a CO  to RA DEC, keeping CRVAL and CRPIX fixed (last param=0)
   */

  if ((new2StmcTable = VmImBuildStarMatchTable(calImage, newStmcTable, 
                                                astroTable,
                                      minStar, tolrad, tolMag1, tolMag2,
                                      sigClip)) == NULL) {
    cpl_msg_error(modName, "Failure in making the Star Match Table");
    return VM_FALSE;
  }
         

  if (fitCO(calImage, astroTable, new2StmcTable, minStar, tolrad, tolMag1,
            tolMag2, sigClip, rmsTol) != VM_TRUE) {
    cpl_msg_error(modName, "Failure in making the Star Match Table");
    return VM_FALSE;
  }

  deleteTable(newStmcTable);
  deleteTable(new2StmcTable);
  deleteTable(astroTable);
  
  return VM_TRUE;

}


/**
 * @brief
 *   Build Astrometric Table
 *
 * @return VimosTable
 * 
 * @param count       N. of entries
 * @param filterName  Image filter
 *
 * Build up an astrometric Table (empty) of count*count rows
 * for filter FilterName (used by VmImComputeCO)
 *
 * @author B.Garilli
 */

VimosTable *resetAstroTable (int count, char *filterName) 
{

  int         totcount, i;
  char        colName[6];

  VimosColumn *currentColumn;
  VimosTable *astroTable;

  totcount = count*count;

  astroTable = newAstrometricTable(); 
  astroTable->numColumns = 7;

  /*  only number, X_image and Y_image are actually needed */  

  astroTable->cols = newStringColumn(totcount,"ID");
  astroTable->cols->len= totcount;
  currentColumn = astroTable->cols;
  for(i=0; i<totcount; i++) 
    currentColumn->colValue->sArray[i] = pil_strdup("    ");
        
  currentColumn->next = newDoubleColumn(totcount, "RA");
  currentColumn = currentColumn->next;
  for(i=0; i<totcount; i++) 
    currentColumn->colValue->dArray[i] = 0.; 
      
  currentColumn->next = newDoubleColumn(totcount, "DEC");
  currentColumn = currentColumn->next;
  for(i=0; i<totcount; i++)
    currentColumn->colValue->dArray[i] = 0.;

  sprintf(colName,"MAG_%s",filterName);
  currentColumn->next = newDoubleColumn(totcount, colName);
  currentColumn = currentColumn->next;
  for(i=0; i<totcount; i++)
    currentColumn->colValue->dArray[i] = 0.;

  currentColumn->next = newDoubleColumn(totcount, "X_IMAGE");
  currentColumn = currentColumn->next;
  for(i=0; i<totcount; i++)
    currentColumn->colValue->dArray[i] = 0.;

  currentColumn->next = newDoubleColumn(totcount, "Y_IMAGE");
  currentColumn = currentColumn->next;
  for(i=0; i<totcount; i++)
    currentColumn->colValue->dArray[i] = 0.;
  

  currentColumn->next = newIntColumn(totcount, "GOFF");
  currentColumn = currentColumn->next;
  for(i=0; i<totcount; i++)
    currentColumn->colValue->iArray[i] = 0;
      
  currentColumn->next = NULL;

  return(astroTable);

}


/**
 * @brief
 *   Build StarMatchTable Table
 *
 * @return VimosTable
 * 
 * @param count       N. of entries
 *
 * Build up an StarTable Table of count*count rows
 * Fill it up with an equally spaced grid of count*count points
 * (used by VmImComputeCO)
 *
 * @author B.Garilli
 */

VimosTable *resetStarMatchTable (int  count, int naxis1, int naxis2) 
{

  int          totcount, i, j, kj;
  VimosColumn *currentColumn;
  VimosTable  *starMatchTable;

  starMatchTable = newStarMatchTableEmpty(); 
 
  /*  only number, X_image and Y_image are actually needed */  
  totcount = count*count;

  starMatchTable->numColumns = 6;

  starMatchTable->cols = newIntColumn(totcount, "NUMBER");
  starMatchTable->cols->len = totcount;

  currentColumn = starMatchTable->cols;
  for(i=0; i<totcount; i++) 
    currentColumn->colValue->iArray[i] = i+1;
        
  currentColumn->next = newDoubleColumn(totcount, "MAG");
  currentColumn = currentColumn->next;
  for(i=0; i<totcount; i++) 
    currentColumn->colValue->dArray[i] = 0.;
      
  currentColumn->next = newDoubleColumn(totcount, "X_IMAGE");
  currentColumn = currentColumn->next;
  kj=0;
  for(i=0; i<count; i++) {
    for(j=0; j<count; j++,kj++) {
      currentColumn->colValue->dArray[kj] = (j+1)*naxis1/(count + 1);
    }
  }
      
  currentColumn->next = newDoubleColumn(totcount, "Y_IMAGE");
  currentColumn = currentColumn->next;
  kj=0;
  for(i=0; i<count; i++) { 
    for(j=0; j<count; j++,kj++) {
      currentColumn->colValue->dArray[kj] = (i+1)*naxis2/(count + 1);
    }
  }

      
  currentColumn->next = newDoubleColumn(totcount, "X_WORLD");
  currentColumn = currentColumn->next;
  for(i=0; i<totcount; i++) 
    currentColumn->colValue->dArray[i] = 0.; 
      
  currentColumn->next = newDoubleColumn(totcount, "Y_WORLD");
  currentColumn = currentColumn->next;
  for(i=0; i<totcount; i++)
    currentColumn->colValue->dArray[i] = 0.;
  currentColumn->next = NULL;

  return(starMatchTable);

}


/**
 * @brief
 *   Build StarMatchTable Table
 *
 * @return VimosTable
 * 
 * @param **starMatchTable       Array of 4 StarMatchTables (1 per quadrant)
 *
 * put together the 4 tables, different for each quadrant
 * we must change the image coordinates, and then change the CRPIX1 and 2
 * values to 0,0 
 *
 * for positive X quads (quad 1 and 4) it is:
 * new X = oldX-crpix1-0.5
 * for neg. X quads (2 and 3)
 * new X = -crpix1+oldX+0.5
 * for pos. Y quads (1 and 2)
 * new Y = oldY-crpix2-0.5
 * for neg. Y quads (3 and 4)
 * new Y = -crpix2+oldY+0.5
 *
 * @author B.Garilli
 */

VimosTable *shiftStarMatch (VimosTable **starMatchTable)
{ 
  char   modName[] = "shiftStarMatch";
  char comment[80] = "";
  char smydesc[80];

  int quad, i,j,k, nrow, nrowTot=0;
  double crpix1, crpix2, mydesc;

  VimosTable *megaStarMatchTable;
  VimosColumn *outXimaCol, *outYimaCol, *outXwldCol, *outYwldCol;
  VimosColumn *outNameCol, *outMagCol;
  VimosColumn *inXimaCol, *inYimaCol, *inXwldCol, *inYwldCol;
  VimosColumn *inNameCol, *inMagCol;


  megaStarMatchTable = newStarMatchTableEmpty(); 
 
  /* I need a number of descriptors (essentially the wcs realted ones) */

  readDoubleDescriptor(starMatchTable[0]->descs, pilTrnGetKeyword("Equinox"),
                       &mydesc, comment);
  writeDoubleDescriptor(&(megaStarMatchTable->descs),
                        pilTrnGetKeyword("Equinox"), mydesc, comment);
  readStringDescriptor(starMatchTable[0]->descs, pilTrnGetKeyword("Radecsys"),
                       smydesc, comment);
  writeStringDescriptor(&(megaStarMatchTable->descs),
                        pilTrnGetKeyword("Radecsys"), smydesc, comment);
  for (i=1; i<=2; i++) {
    readDoubleDescriptor(starMatchTable[0]->descs, pilTrnGetKeyword("Crval",i),
                         &mydesc, comment);
    writeDoubleDescriptor(&(megaStarMatchTable->descs),
                          pilTrnGetKeyword("Crval",i), mydesc, comment);
    readStringDescriptor(starMatchTable[0]->descs, pilTrnGetKeyword("Ctype",i),
                         smydesc, comment);
    writeStringDescriptor(&(megaStarMatchTable->descs),
                          pilTrnGetKeyword("Ctype",i),smydesc, comment);
    for(j=1; j<=2; j++,k++) {
      readDoubleDescriptor(starMatchTable[0]->descs, 
                           pilTrnGetKeyword("CD", i, j), &mydesc, comment);
      writeDoubleDescriptor(&(megaStarMatchTable->descs),
                            pilTrnGetKeyword("CD", i, j), mydesc, comment);
    }
  }

  for (i=0; i<4;i++) {
    nrowTot += starMatchTable[i]->cols->len;
  }

  megaStarMatchTable->numColumns = 6;
  megaStarMatchTable->cols = newIntColumn(nrowTot, "NUMBER");
  outNameCol = megaStarMatchTable->cols;
  megaStarMatchTable->cols->next = newDoubleColumn(nrowTot, "MAG");
  outMagCol = megaStarMatchTable->cols->next;
  megaStarMatchTable->cols->next->next = newDoubleColumn(nrowTot, "X_IMAGE");
  outXimaCol = megaStarMatchTable->cols->next->next;
  megaStarMatchTable->cols->next->next->next = newDoubleColumn(nrowTot,
                                                               "Y_IMAGE");
  outYimaCol = megaStarMatchTable->cols->next->next->next;
  megaStarMatchTable->cols->next->next->next->next = newDoubleColumn(nrowTot, "X_WORLD");
  outXwldCol = megaStarMatchTable->cols->next->next->next->next ;
  megaStarMatchTable->cols->next->next->next->next->next = newDoubleColumn(nrowTot, "Y_WORLD");
  outYwldCol = megaStarMatchTable->cols->next->next->next->next->next;

  k=0;
  for (i=0; i<4;i++) {
    nrow = starMatchTable[i]->cols->len; 

    readIntDescriptor(starMatchTable[i]->descs, pilTrnGetKeyword("Quadrant"),
                      &quad, comment);
    readDoubleDescriptor(starMatchTable[i]->descs, pilTrnGetKeyword("Crpix",1),
                         &crpix1, comment);
    readDoubleDescriptor(starMatchTable[i]->descs, pilTrnGetKeyword("Crpix",2),
                         &crpix2, comment);

    if(!(inXimaCol = findColInTab(starMatchTable[i], "X_IMAGE"))) {
      cpl_msg_error(modName, "Star Table: Column with X-pixel coord "
                  "not found");
      return NULL;
    }
    if(!(inYimaCol = findColInTab(starMatchTable[i], "Y_IMAGE"))) {
      cpl_msg_error(modName, "Star Table: Column with Y-pixel coord "
                  "not found");
      return NULL;
    }
    if(!(inMagCol = findColInTab(starMatchTable[i], "MAG"))) {
      cpl_msg_error(modName, "Star Table: Column with Y-pixel coord "
                  "not found");
      return NULL;
    }
    if(!(inNameCol = findColInTab(starMatchTable[i], "NUMBER"))) {
      cpl_msg_error(modName, "Star Table: Column with Y-pixel coord "
                  "not found");
      return NULL;
    }
    if(!(inXwldCol = findColInTab(starMatchTable[i], "RA"))) {
      cpl_msg_error(modName, "Star Table: Column with Y-pixel coord "
                  "not found");
      return NULL;
    }
    if(!(inYwldCol = findColInTab(starMatchTable[i], "DEC"))) {
      cpl_msg_error(modName, "Star Table: Column with Y-pixel coord "
                  "not found");
      return NULL;
    }
    
    for (j=0;j<nrow;j++) {
      if (quad == 1 || quad == 4 ) {
        outXimaCol->colValue->dArray[k] = inXimaCol->colValue->dArray[j] -
          crpix1 -0.0;
      } else {
        outXimaCol->colValue->dArray[k] = -crpix1 + 
          inXimaCol->colValue->dArray[j]+0.0;
      }
      if (quad == 1 || quad == 2 ) {
        outYimaCol->colValue->dArray[k] = inYimaCol->colValue->dArray[j] -
          crpix2 -0.0;
      } else {
        outYimaCol->colValue->dArray[k] = -crpix2 +
          inYimaCol->colValue->dArray[j]+0.0;
      }
      outXwldCol->colValue->dArray[k] = inXwldCol->colValue->dArray[j];
      outYwldCol->colValue->dArray[k] = inYwldCol->colValue->dArray[j];
      outMagCol->colValue->dArray[k] = inMagCol->colValue->dArray[j];
      outNameCol->colValue->iArray[k] = inNameCol->colValue->iArray[j];
        
      k += 1;
    }
    
    crpix1 = 0.;
    crpix2=0.;
    
    writeDoubleDescriptor(&(megaStarMatchTable->descs), 
                          pilTrnGetKeyword("Crpix",1), crpix1, comment);
    writeDoubleDescriptor(&(megaStarMatchTable->descs), 
                          pilTrnGetKeyword("Crpix",2), crpix2, comment);
    
  }

  return(megaStarMatchTable);

}


VimosBool fitCO(VimosImage *image, VimosTable *astroTable,
                VimosTable *starMatch,int minstar, double tolrad,
                double tolMag1, double tolMag2, float sigClip,double rmsTol)
{

  struct WorldCoor    * wcs = 0;     /* WCS structure */

  int      i,nastro,nstarMatch;
  int      vmncoef = 13;           /* Number of fitting coefficents */
  char     modName[] = "fitCO";

  int    * imatch = NULL;     /* index for matching stars */
  int      nmatch ;        /* Number of matches returned */
  double   chisq = 0;         /* Reduced chi-2 of plate model */
  double   rms[4] ;            /* RMS error in X and Y */



  /* Initialize the WCS structure from image descriptors  
   */
    
  for (i=0;i<=3;i++) rms[i] = 0;
  
  if  (!(wcs = rdimage(image->descs))) {       
    return VM_FALSE;
  } 
 
  /*  Find matching pairs and transformation coeff. */
   
  cpl_msg_info(modName,"Begin  to fit WCS on image");
   



  /* BG: this call to searchmatch is useless, as the input to
     fitCO is an already matched table, thus the number of matched stars
     is the length of the table */

/*    nstarMatch = starMatch->cols->len; */
/*    nastro = astroTable->cols->len; */
/*    nmatch = nstarMatch; */
/*    imatch = searchmatch(wcs, starMatch, nstarMatch, astroTable, nastro, */
/*                     &nmatch, tolrad, tolMag1, tolMag2, sigClip,minstar); */
        

  nstarMatch = starMatch->cols->len;
  nmatch = nstarMatch;

  cpl_msg_info(modName, "Fitting %d matching stars with a %d-coefficients "
             "polynomial", nmatch, vmncoef);
  
  if ((vimosFitPlate(wcs, starMatch, astroTable, nmatch, vmncoef, &chisq) == 
      VM_FALSE)) { 
    pil_free(imatch);
    return VM_FALSE;
  }
   
    
  /* Project the reference stars into pixels on image plane */
  nastro = astroTable->cols->len;
    
  wcstopix(nastro,astroTable,wcs);
   
  /* 
   * Search for matching stars. First convert search radius from
   * arcsec to pixel.
   */
    
  cpl_msg_info(modName,"Searching for matching stars");

/*    imatch = searchmatch(wcs, starMatch, nstarMatch, astroTable, nastro, */
/*                     &nmatch, tolrad, tolMag1, tolMag2, sigClip,minstar); */

  tolrad /= fabs(3600. * wcs->cdelt[0]);

  imatch = VmSearchMatches(starMatch, astroTable, tolrad, 
                            tolMag1, tolMag2, sigClip,
                            minstar, &nmatch);

  if(!imatch || nmatch < minstar) {
    cpl_msg_warning(modName, "Insufficent number of matching stars: %d found",
                  nmatch);
    pil_free(imatch);
    return VM_FALSE;
  }      
    
  /* Quality control : this is commented as now the fit is done
     only on a 10x10 grid of points: therefore the quality control
     is already done by calcres (add a check there, if wished..) */
    
    
  cpl_msg_info(modName,"Number of matching pairs is %d",nmatch);
    
  /* Project the reference stars into pixels and observed into WCS */
  /* and  compute RMS */
    
  wcstopix(nastro,astroTable,wcs);
  pixtowcs(nstarMatch,starMatch,wcs);
  calcres(starMatch, astroTable, imatch, nmatch, rms);
    
  cpl_msg_info(modName,"Computed RMS from model fit in X and Y:"
             "CCD->Sky: X_RMS error = %g (arcsec); "
             "Y_RMS error = %g (arcsec), Sky->CCD: XRMS error = %g (pixels)" 
             "Y_RMS error =%g (pixels)", rms[2],rms[3], rms[0],rms[1]);
  
  if (rms[2] > rmsTol || rms[3] > rmsTol) {
    cpl_msg_warning(modName, "CCD to Sky RMS is greater than expected: %g,%g "
                  "against %g", rms[2],rms[3],rmsTol);
  }
    
  /* update the image header */
  if(!(upheader(image, wcs, rms))) {
    cpl_msg_error(modName,"Image header cannot be be updated");
    return VM_FALSE;
  }
    
  /* Free Memory */
    
  if(wcs)     vimoswcsfree(wcs);
    
  return VM_TRUE;
}


/**
 * @brief 
 *   Compute the RMS error of the CCD <-> Sky transformation. 
 *   
 * @return VM_TRUE/VM_FALSE
 * 
 * @param wcs      wcs structure
 * @param o_star   star table
 * @param a_star   astrometric table
 * @param imatch   table of matching indexes
 * @param nmatch   number of matches
 * @param rms      pointer to the returned array
 *
 * Compute the RMS error of the CCD <-> Sky transformation.
 *
 * @author P. Montegriffo (i/o modified by P.Sartoretti)
 */

/*-----------------------------------------------------------------------------
 * Function  : calcres
 * In        : wcs structure, o_star structure, a_star structure, index table 
 *             for matching stars and number of matches
 * Out       : vector rms with mean dx,dy, x_rms, y_rms, covariance dxy
 * Purpouse  : Compute the RMS error in X and Y after that the transformation
 *             is applied; values are converted in [arcsec]
 * Note      : 
 *---------------------------------------------------------------------------*/

int calcres(VimosTable *o_star, VimosTable *a_star, int imatch[], int nmatch,
            double * rms)
{
  int    i;
  double dx, dy, dmatch, dxwld=0., dywld=0.;
  double dxsum = 0.;
  double dysum = 0.;
  double dywldsum = 0.;
  double dxwldsum = 0.;
  char   modName[] = "calcres";
  VimosColumn    *aXimaCol, *aYimaCol, *aXwldCol, *aYwldCol;
  VimosColumn    *oXimaCol, *oYimaCol, *oXwldCol, *oYwldCol;

  /****
       I have changed this function in order to estimate the RMS both of
       the direct (Sky->CCD) and the inverse transformation (CCD->Sky).
       Write all these values in rms[], and comment out what it was written
       before in rms[] (and never used). 
  ****/ 

  if(!(aXimaCol = findColInTab(a_star, "X_IMAGE"))) {
    cpl_msg_error(modName, "Astrometric Table: Column with X-pixel coord "
                "not found");
    return VM_FALSE;
  }
  if(!(aYimaCol = findColInTab(a_star, "Y_IMAGE"))) {
    cpl_msg_error(modName, "Astrometric Table: Column with Y-pixel coord "
                "not found");
    return VM_FALSE;
  }
  if(!(aXwldCol = findColInTab(a_star, "RA"))) {
    cpl_msg_error(modName, "Astrometric Table: Column with RA coord "
                "not found");
    return VM_FALSE;
  }
  if(!(aYwldCol = findColInTab(a_star, "DEC"))) {
    cpl_msg_error(modName, "Astrometric Table: Column with RA coord "
                "not found");
    return VM_FALSE;
  }
  if(!(oXimaCol = findColInTab(o_star, "X_IMAGE"))) {
    cpl_msg_error(modName, "Star Table: Column with X-pixel coord "
                "not found");
    return VM_FALSE;
  }
  if(!(oYimaCol = findColInTab(o_star, "Y_IMAGE"))) {
    cpl_msg_error(modName, "Star Table: Column with Y-pixel coord "
                "not found");
    return VM_FALSE;
  }
  if(!(oXwldCol = findColInTab(o_star, "X_WORLD"))) {
    cpl_msg_error(modName, "Star Table: Column with X-world coord "
                "not found");
    return VM_FALSE;
  }
  if(!(oYwldCol = findColInTab(o_star, "Y_WORLD"))) {
    cpl_msg_error(modName, "Star Table: Column with Y-world coord "
                "not found");
    return VM_FALSE;
  }
    
  for (i = 0; i < nmatch; i++) {
    dxwld = (aXwldCol->colValue->dArray[imatch[2*i+1]]) - 
      (oXwldCol->colValue->dArray[imatch[2*i]]);
    dywld = (aYwldCol->colValue->dArray[imatch[2*i+1]]) - 
      (oYwldCol->colValue->dArray[imatch[2*i]]); 
    dx = (aXimaCol->colValue->dArray[imatch[2*i+1]]) - 
      (oXimaCol->colValue->dArray[imatch[2*i]]);
    dy = (aYimaCol->colValue->dArray[imatch[2*i+1]]) - 
      (oYimaCol->colValue->dArray[imatch[2*i]]);

    /*
     * Next two lines added by C.Izzo, RMS computation was wrong 
     * in case coordinates are crossing the 360 degrees line.
     */

    if (fabs(fabs(dxwld) - 360.) < 0.1)
      dxwld = fabs(dxwld) - 360.;
    
    dxwld = fabs(dxwld)* 3600.;
    dywld = fabs(dywld) * 3600.;
    dx = fabs(dx);
    dy = fabs(dy);
    dxsum = dxsum + dx;
    dysum = dysum + dy;
    dxwldsum = dxwldsum + dxwld;
    dywldsum = dywldsum + dywld;
  }
  dmatch = (double) nmatch;
  *rms = dxsum / dmatch;
  *(rms+1) = dysum / dmatch;
  *(rms+2) = dxwldsum / dmatch;
  *(rms+3) = dywldsum / dmatch;
  *(rms+4) = 0.;
      
    return VM_TRUE;
}
/**@}*/