/*  Hipparcos ASCII CD-ROM load and search routines Release 1.1 June 1997
    William O'Mullane 
    Astrophysics Division, ESTEC, Noordwijk, The Netherlands. 
    See the readme.pdf file for more information */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "utils.h" 
#include "tyc_main.h"  
#include "itycmain.h" 
#include "tyc_id.h" 

main (int argc,char **argv)
{
   tyc_main anentry ;
   int headPrinted=0;

   if ( argc <= 1 )
   {
	fprintf(stderr,"You must specify a key value on the command line.\n");
   }
   else
   {
	int i,decode=ASRAW,cols=0,quite=0;
	long multiRecs=0,recNo;
	FILE* dataFile;
	for (i=1; i<argc; i++ ) 
	{
	   tyc_id key;
   	   checkIfCommandLineFlag(argv,argc,&i,&cols,&decode,&quite,&multiRecs);
	   if (cols==1 && headPrinted==0 && quite==0)
	   {
	      print_tyc_main_header ();
	      headPrinted=1;
	   }
	   if ( !getIfTycId(argv[i],&key) )
	   {
	      if ( argc-3 < i)
   	      {
	         fprintf(stderr," Tycho Ids consist of 3 numbers - you must give a multiple of 3 parameters \n");
	         break;
              }
	      strAsINT(argv[i], &key.tyc1) ;
	      strAsINT(argv[i+1], &key.tyc2) ;
	      strAsINT(argv[i+2], &key.tyc3) ;
	      i=i+2;
           }
	   if ( key.tyc2.value==0 || key.tyc3.value==0)
           { /* retrive all recs with tyc1 and posibly tyc2 */
	      if (key.tyc2.value > 0)
	      {
		 key.tyc3.value=1;
		 dataFile=search_tyc_main(&key,&anentry);
	      }
	      else
	      {
	   	long rec1=find_idx_tyc_main(&key.tyc1);
		dataFile=jump_tyc_main(rec1);
		if (read_tyc_main(dataFile,&anentry) != 0)
		   break ;
	      }
	      /* Now have first one loop for the others */
	      if (dataFile)
	      {
		while (anentry.T1.tyc1.value == key.tyc1.value)
		{
		   if (cols )
		      print_tyc_main_cols (&anentry, decode); 
		   else
		      print_tyc_main (&anentry, decode); 
	  	   if (read_tyc_main(dataFile,&anentry) != 0)
		      break ;
		   if (key.tyc2.value > 0 && 
		       (key.tyc2.value != anentry.T1.tyc2.value))
		      break;
		}
	      }
	      else
	      {
		fprintf(stderr,"Could not find a match %d %d \n",key.tyc1.value, key.tyc2.value);
	      }

           } 
	   else
	   if ((dataFile=search_tyc_main (&key,&anentry)) != NULL)
	   {
		for (recNo=0; recNo<=multiRecs; recNo++)
		{
		   if (cols)
	    	   {
	    	      
	    	      print_tyc_main_cols (&anentry, decode); 
	    	   }
	    	   else
	       	      print_tyc_main (&anentry, decode); 
	    	   if (read_tyc_main(dataFile,&anentry)!=0)
			break;
		}
	   }
	   else
	   {
	        print_tyc_id_cols(&key,ASRAW);
	        printf(" not found\n");
	   }
	 
	}
   }

 
} /* End Main for idx_tyc_main_test */

