#include <stdlib.h>
#include <stdio.h>
#include "ast.h"

/* This program shows how to write an AST FrameSet out as ASDF YAML.
   Invoke it as follows:

   % writeasdf <yamlfile>

   where <yamlfile> is the path to a new file file to create holding the
   ASDF WCS information. The AST FrameSet will be a formed from a simple
   FITS-WCS header.

   Notes:

   - The AST library must be configured with libyaml support,
   otherwise an error will be reported (by default, AST is configured
   with libyaml support if the libyaml library can be found).

   - AST currently does not support the complete ASDF WCS schema. When
   writing an AST Object to an ASDF YAML file, the following restrictions
   on the AST object apply:

      o  Only Frames, Mappings and FrameSets can be written.
      o  Frames must be basic Frames or SkyFrames.
      o  The following SkyFrame systems are not supported: GAPPT,
         HELIOECLIPTIC, J2000 (note, "J2000" is different to "FK5 J2000"
         - "FK5 J2000" is supported), UNKNOWN.
      o  Only the following Mapping classes are supported: CmpMap, TranMap,
         UnitMap, ZoomMap, ShiftMap, WinMap, MatrixMap, PermMap, WcsMap,
         PolyMap, ChebyMap.

*/


int main(int argc, char *argv[]){

/* Local variables: */
   AstYamlChan *yamlchan;
   AstFitsChan *fitschan;
   AstFrameSet *fs;

/* Check a file name has been supplied. */
   if( argc != 2 ) {
      printf("Usage:\n   % writeasdf <yamlfile>\n" );
      exit( EXIT_FAILURE );
   }

/* Begin an AST Object context. */
   astBegin;

/* Create a FitsChan and store a simple FITS-WCS header in it (a TAN
   projection of the north celestial pole). */
   fitschan = astFitsChan( NULL, NULL, " " );
   astPutFits( fitschan, "CRPIX1  = 0", 0 );
   astPutFits( fitschan, "CRPIX2  = 0", 0 );
   astPutFits( fitschan, "CDELT1  = 0.0003", 0 );
   astPutFits( fitschan, "CDELT2  = 0.0003", 0 );
   astPutFits( fitschan, "CTYPE1  = 'RA---TAN'", 0 );
   astPutFits( fitschan, "CTYPE2  = 'DEC--TAN'", 0 );
   astPutFits( fitschan, "CRVAL1  = 0.0", 0 );
   astPutFits( fitschan, "CDELT2  = 90.0", 0 );

/* Rewind the FitsCHan by clearing its Card attribute, and then read a
   FrameSet from it. */
   astClear( fitschan, "Card" );
   fs = astRead( fitschan );

/* Create a YamlChan to write the FrameSet to the output YAML file. */
   yamlchan = astYamlChan( NULL, NULL, "SinkFile=%s", argv[1] );

/* Attempt to write the FrameSet to the YamlChan. */
   if( astWrite( yamlchan, fs ) != 1 && astOK ) {
      printf("Could not write an AST FrameSet as ASDF to file %s.", argv[1] );
      exit( EXIT_FAILURE );
   }

/* End the AST Object context. This will automatically annull all AST
   Objects created in the context. */
   astEnd;

/* Return a value indicating if an error occurred. */
   return astOK ? EXIT_SUCCESS : EXIT_FAILURE;
}