/*
 * isosort
 *
 * last modified 24 Jan 01 so I can recompile to sometimes pass glitches
 * last modified 27 Jul 00 to add SR to check flag
 * last modified 24 Mar 97
 * last modified 7 Nov 96
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN 82000

int check_flag(char* flagword, char* checkbits);

void main(int argc, char *argv[])
{
      long l,lstop;
      int i,detcount[50],detector[LEN],dirn[LEN],dumd,dums,dumx,dumy;
      double lam[LEN],flux[LEN],duml,dumf,dume;
      char filename[81],fileout[90],line[100],flagword[11],checkbits[11];
      FILE *fd1,*fdout[50];
/*
 *    command line arguments
 */
      if (argc == 2) strcpy(filename,argv[1]);
      else {
	printf("Use:  isosort input_file.\n");
	exit(1);
      }
/*
 *    initialization
 */      
      fd1=fopen(filename,"r");
      if (fd1 == NULL) {
	printf("Error.  File %s not found.\n",filename);
        exit(1);
      }
      for (i=0;i<50;i++) detcount[i] = 0;
/*      strncpy(checkbits,"0100011111",10); */ /* removes glitches */
      strncpy(checkbits,"0100011000",10);  /* lets glitches pass */

      l=0;
      while (fgets(line,80,fd1) != NULL) {
/*
 *      read char variable line and load arrays
 */
	sscanf(line,"%lf %lf %lf %s %d %d %d %d",&duml,&dumf,&dume,
               flagword,&dumd,&dums,&dumx,&dumy);
        if (check_flag(flagword,checkbits)) {
	  lam[l] = duml; 
          flux[l]=dumf; 
          detector[l]=dumd; 
          dirn[l]=dums;
	  l++;
	  if (dumd < 50) {
/*            if (dums < 0) */ detcount[dumd]++;
          } else printf("oops dumd=%d\n",dumd);
        } 
      }

      for (i=0;i<50;i++) printf("%3d ",detcount[i]);
      printf("\n");

      lstop=l;
      for (i=0;i<50;i++) for (l=0;l<lstop;l++)
/*	if (detector[l] == i && dirn[l] < 0) */
	if (detector[l] == i)
	  printf("%9.5lf %9.3lf %3d\n",lam[l],flux[l],detector[l]);
}

int check_flag(char* flagword, char* checkbits) {
/*
 *    check_flag returns a 0 
 *      if a bit set to 1 in checkbits is also 1 in flagword
 */
      int n,nstop,tripflag=1; /* tripflag = 0 is bad */
      nstop=strlen(flagword);
      for (n=0;n<nstop;n++) 
        if (checkbits[n] == '1' && flagword[n] == '1') tripflag=0;
      return tripflag;
}
