/* This file is originally from A. Vikhlinin; J. McDowell changed */ 
/* det2chip_ from int to void and added fortran wrapper to ini_pixlib_0_ */
/* which M. Markevitch removed (and used g77 compile option instead). */
/* 9.2.01 MM: in ini_pixlib_0_, instead of exit(1) after error, return 1. */
/* x.10.6: emandel added "geom" to pix_init_pixlib, for ciao 3.3+ */

#include <stdio.h>
#include <pixlib.h>

int ini_pixlib_0_(char *aim, char *fp)
{
  int n;
  int status;
  VEC3_DBLE aimpos;

  fprintf (stderr," Initializing pixlib for aimpoint %s\n and fpsys %s ... ",
	   aim,fp);
  /* ini telescope for CXC path */
  if ( pix_init_pixlib("chandra", "geom") != PIX_GOOD ) {
    fprintf (stderr," ERROR: could not initialize pixlib\n");
    return 1;
  }
  
  /* set detector to "ACIS" */
  if ( pix_set_detector ("ACIS") != PIX_GOOD ) {
    fprintf (stderr," ERROR: could not initialize pixlib for ACIS\n");
    return 1;
  }

/* Set fp sys and aim point */
  if ( pix_set_fpsys(fp) != PIX_GOOD ) {
    fprintf (stderr," ERROR: could not initialize pixlib for %s\n",fp);
    return 1;
  }
  
  if (sscanf(aim,"%lf,%lf,%lf",&aimpos[0],&aimpos[1],&aimpos[2])==3) {
    /* aimpoint is set as 3-vector */
    status = pix_set_aimpoint_by_value (aimpos);
  }
  else {
    status = pix_set_aimpoint(aim);
  }
  if (status != PIX_GOOD ) {
    fprintf (stderr," ERROR: could not initialize pixlib for aim point %s\n",
	     aim);
    return 1;
  }
  fprintf (stderr,"OK\n");
  return 0;
}
  

void det2chip_(float *detx, float *dety, float *chipx, float *chipy, int *cid)
{
  VEC2_DBLE chip, fpc;
  short chip_id;

  fpc[0]=*detx;
  fpc[1]=*dety;

  if ( pix_fpc_to_chip(fpc,&chip_id,chip) != PIX_GOOD) {
    *cid = -1;
    return;
  }
  
  *chipx = chip[0];
  *chipy = chip[1];
  *cid = chip_id;

}

int chip2det_(float *chipx, float *chipy, int *cid, float *detx, float *dety)
{
  VEC2_DBLE chip, fpc;
  short chip_id;

  chip[0]=*chipx;
  chip[1]=*chipy;
  chip_id = *cid;

  if ( pix_chip_to_fpc (chip_id, chip,fpc) != PIX_GOOD) {
    *detx = -1; *dety=-1;
    return 1;
  }
  
  *detx = fpc[0];
  *dety = fpc[1];
  return 0;

}


