Esempio n. 1
0
int main(int nargs, char ** args) 
{

  sortOutPidFile("Tuffd") ; 
  setupSignals(); 

  do 
  {
    currentState = PROG_STATE_RUN;  

    while(currentState == PROG_STATE_RUN)
    {
      sleep(1); 
    }
  } while(currentState == PROG_STATE_INIT); 



  cleanup(); 
  return 0; 

}
Esempio n. 2
0
int main(int argc, char *argv[])
{
    //Temporary variables
  int retVal=0,pri=0,ind=0;
  
  /* Config file thingies */
  //  int status=0;
  //  char* eString ;
  sprintf(currentOpenportDir,"%s",OPENPORT_OUTPUT_DIR);
   
    char *progName=basename(argv[0]);

    //
    retVal=sortOutPidFile(progName);
    if(retVal<0)
      return -1;

  
    /* Set signal handlers */
    signal(SIGUSR1, sigUsr1Handler);
    signal(SIGUSR2, sigUsr2Handler);
    signal(SIGTERM, handleBadSigs);
    signal(SIGINT, handleBadSigs);
    signal(SIGSEGV, handleBadSigs);
    signal(SIGRTMIN, refreshLinksHandler);


    /* Setup log */
    setlogmask(LOG_UPTO(LOG_INFO));
    openlog (progName, LOG_PID, ANITA_LOG_FACILITY) ;


    syslog(LOG_INFO,"Starting Openportd\n");

   /* Load Config */
    kvpReset () ;
    //    status = configLoad (GLOBAL_CONF_FILE,"global") ;
    //    eString = configErrorString (status) ;

    //Fill event dir names
    for(pri=0;pri<NUM_PRIORITIES;pri++) {
      retVal=snprintf(eventTelemDirs[pri],sizeof(eventTelemDirs[pri]),"%s/%s%d",BASE_EVENT_TELEM_DIR,EVENT_PRI_PREFIX,pri);
      if(retVal<0) {
	syslog(LOG_ERR,"Error using snprintf -- %s",strerror(errno));
      }
      retVal=snprintf(eventTelemLinkDirs[pri],sizeof(eventTelemLinkDirs[pri]),"%s/link",eventTelemDirs[pri]);
      if(retVal<0) {
	syslog(LOG_ERR,"Error using snprintf -- %s",strerror(errno));
      }
      makeDirectories(eventTelemLinkDirs[pri]);
    }    
    makeDirectories(OPENPORT_OUTPUT_DIR);
    makeDirectories(OPENPORT_STAGE_DIR);
    makeDirectories(OPENPORTD_CMD_ECHO_TELEM_LINK_DIR);


    for(ind=0;ind<NUM_HK_TELEM_DIRS;ind++) {
      makeDirectories(telemLinkDirs[ind]);
    }


    retVal=readConfig();
    
    char currentHeader[FILENAME_MAX];
    static int numLinks[NUM_PRIORITIES]={0};
    static int numHkLinks[NUM_HK_TELEM_DIRS]={0};
    int totalEventLinks=0;
    int totalHkLinks=0;
    int totalEventsSent=0;
    time_t currentTime=0;
    time_t lastRefresh=0;

    int hkInd=0;
    char *tempString=0;
    int numSent=0;
    
    
    //Setup inotify watches
    for(pri=0;pri<NUM_PRIORITIES;pri++) {
      //Setup inotify watches
      if(wdEvents[pri]==0) {
       wdEvents[pri]=setupLinkWatchDir(eventTelemLinkDirs[pri]);
       if(wdEvents[pri]<=0) {
	 fprintf(stderr,"Unable to watch %s\n",eventTelemLinkDirs[pri]);
	 syslog(LOG_ERR,"Unable to watch %s\n",eventTelemLinkDirs[pri]);
	 handleBadSigs(0);
       }
       numLinks[pri]=getNumLinks(wdEvents[pri]);
      }
    }
        
    for(hkInd=0;hkInd<NUM_HK_TELEM_DIRS;hkInd++) {
      if(wdHks[hkInd]==0) {	
	wdHks[hkInd]=setupLinkWatchDir(telemLinkDirs[hkInd]);
	if(wdHks[hkInd]<=0) {
	  fprintf(stderr,"Unable to watch %s\n",telemLinkDirs[hkInd]);
	  syslog(LOG_ERR,"Unable to watch %s\n",telemLinkDirs[hkInd]);
	  //	handleBadSigs(0);
	}
	numHkLinks[hkInd]=getNumLinks(wdHks[hkInd]);
      }      
    }
    time(&lastRefresh);

    int hkCount=0;
    
    printf("Before while loop\n");
    startCopyScript();

    do {
	if(printToScreen) printf("Initalizing Openportd\n");
	currentState=PROG_STATE_RUN;
	while(currentState==PROG_STATE_RUN) {
	  printf("Inside while loop\n");
	  if(!sendData) {
	    sleep(1);
	    continue;
	  }
	  
	  //The idea is that we only write an output file if there is space for it
	  int numWaitingToTransfer=countFilesInDir(currentOpenportDir);
	  if(numWaitingToTransfer>2) {
	    fprintf(stderr,"There are %d files waiting to transer, will sleep now\n",numWaitingToTransfer);
	    
	    sleep(1);
	    continue;
	  }
	  
	  
	  if(totalEventsSent%10==0) {
	    printf("Data sent\nEvents:\t");
	    for(pri=0;pri<NUM_PRIORITIES;pri++)
	      printf("%d ",numEventsSent[pri]);
	    printf("\nHk:\t");
	    for(hkInd=0;hkInd<NUM_HK_TELEM_DIRS;hkInd++) 
	      printf("%d ",numHksSent[hkInd]);
	    printf("\n");
	  }
	  
	  //Check to see if we need to refresh the links
	  time(&currentTime);
	  if(currentTime>lastRefresh+REFRESH_LINKS_EVERY || needToRefreshLinks) {
	    refreshLinkDirs();
	    lastRefresh=currentTime;
	    needToRefreshLinks=0;
	  }
	  
	  //Update the link lists
	  //or some time has passed
	  if(totalEventLinks==0)
	    retVal=checkLinkDirs(1,0);
	  else
	    retVal=checkLinkDirs(0,1);
	  
	  totalEventLinks=0;
	  for(pri=0;pri<NUM_PRIORITIES;pri++) {
	    numLinks[pri]=getNumLinks(wdEvents[pri]);
	    totalEventLinks+=numLinks[pri];
	  }
	  
	  totalHkLinks=0;
	  for(hkInd=0;hkInd<NUM_HK_TELEM_DIRS;hkInd++) {
	    numHkLinks[hkInd]=getNumLinks(wdHks[hkInd]);
	    totalHkLinks+=numHkLinks[hkInd];
	  }
	  if(!retVal && totalHkLinks==0 && totalEventLinks==0) {
	    //No data
	    needToRefreshLinks=1;
	    usleep(1000);
	    continue;
	  }
	  printf("%d %d %d\n",totalEventLinks,totalHkLinks,retVal);
	  
	  if(totalEventLinks) {
	    //Which priority are we sending
	    currentPri=priorityOrder[orderIndex];	
	    int doneEvent=0;
	    while(!doneEvent && totalEventLinks>0) {
	    while(numLinks[currentPri]==0) {
	      orderIndex++;
	      if(orderIndex>=numOrders) orderIndex=0;
	      currentPri=priorityOrder[orderIndex];	
	    }
	    printf("Trying priority %d -- numLinks %d\n",currentPri,numLinks[currentPri]);
	    if(numLinks[currentPri]) {
	      //Got an event	    
	      tempString=getLastLink(wdEvents[currentPri]);
	      retVal=snprintf(currentHeader,sizeof(currentHeader),"%s/%s",eventTelemLinkDirs[currentPri],tempString);
	      if(retVal<0) {
		syslog(LOG_ERR,"Error using snprintf -- %s",strerror(errno));
	      }
	      //	    syslog(LOG_INFO,"Trying %s\n",currentHeader);
	      doneEvent=readAndSendEventRamdisk(currentHeader); //Also deletes
	      if(doneEvent) {
		numEventsSent[currentPri]++;
		totalEventsSent++;
	      }
	      numLinks[currentPri]--;
	      totalEventLinks--;
	    }
	    }
	    
	  if(currentTime>lastRefresh+REFRESH_LINKS_EVERY || 
	     needToRefreshLinks) {
	    refreshLinkDirs();
	    lastRefresh=currentTime;
	    needToRefreshLinks=0;
	    
	    totalHkLinks=0;
	    for(hkInd=0;hkInd<NUM_HK_TELEM_DIRS;hkInd++) {
	      numHkLinks[hkInd]=getNumLinks(wdHks[hkInd]);
	      totalHkLinks+=numHkLinks[hkInd];
	    }	    
	  }
	    

	  //Now try to send some stuff I like
	  numSent=0;
	  if(numHkLinks[OPENPORT_TELEM_HEADER])
	    readHkAndOpenport(wdHks[OPENPORT_TELEM_HEADER],
			   headersPerEvent,HEADER_TELEM_DIR,
			   HEADER_TELEM_LINK_DIR,sizeof(AnitaEventHeader_t),&numSent);
	  numHksSent[OPENPORT_TELEM_HEADER]+=numSent;
	  
	  numSent=0;
	  if(numHkLinks[OPENPORT_TELEM_CMD_ECHO])
	    readHkAndOpenport(wdHks[OPENPORT_TELEM_CMD_ECHO],echoesPerEvent,
			   OPENPORTD_CMD_ECHO_TELEM_DIR,
			   OPENPORTD_CMD_ECHO_TELEM_LINK_DIR,
			   sizeof(CommandEcho_t),&numSent);
	  numHksSent[OPENPORT_TELEM_CMD_ECHO]+=numSent;
	  
	  numSent=0;
	  if(numHkLinks[OPENPORT_TELEM_HK])
	    readHkAndOpenport(wdHks[OPENPORT_TELEM_HK],hkPerEvent,HK_TELEM_DIR,
			   HK_TELEM_LINK_DIR,sizeof(HkDataStruct_t),&numSent);
	  
	  numSent=0;
	  if(numHkLinks[OPENPORT_TELEM_ADU5A_PAT])
	    readHkAndOpenport(wdHks[OPENPORT_TELEM_ADU5A_PAT],1,
			   ADU5A_PAT_TELEM_DIR,
			   ADU5A_PAT_TELEM_LINK_DIR,
			   sizeof(GpsAdu5PatStruct_t),&numSent);
	  numHksSent[OPENPORT_TELEM_ADU5A_PAT]+=numSent;
	  
	  numSent=0;
	  if(numHkLinks[OPENPORT_TELEM_MONITOR])
	    readHkAndOpenport(wdHks[OPENPORT_TELEM_MONITOR],monitorPerEvent,
			   MONITOR_TELEM_DIR,MONITOR_TELEM_LINK_DIR,
			   sizeof(MonitorStruct_t),&numSent); 
	  numHksSent[OPENPORT_TELEM_MONITOR]+=numSent;
	  
	
	  //	else if(totalEventLinks==0) {
	//	  usleep(1000);
	//	}
	  
	  orderIndex++;
	  if(orderIndex>=numOrders) orderIndex=0;
	}
    
	
	//Now we try and send some data
	//I'm going to try and modify this but for now
	if(hkCount%eventBandwidth==0)
	  sendSomeHk(10000);
	hkCount++;
	}
    } while (currentState == PROG_STATE_INIT);
    stopCopyScript();
    unlink(OPENPORTD_PID_FILE);
    return 0;
}
Esempio n. 3
0
int main (int argc, char *argv[])
{
    int retVal=0;
    int relaysChanged=0;
    int firstTime=1;
    int lastRelayWriteSec=0;
       
    // Config file thingies 
    int status=0;
    char* eString;
    char *globalConfFile="anitaSoft.config";
    // Log stuff 
    char *progName=basename(argv[0]);
    

    int millisecs=0;
    struct timespec milliWait;
    milliWait.tv_sec=0;


    int lastCal=0;
    time_t rawTime;

    // Setup log 
    setlogmask(LOG_UPTO(LOG_INFO));
    openlog (progName, LOG_PID, ANITA_LOG_FACILITY) ;

    // Set signal handlers 
    signal(SIGUSR1, sigUsr1Handler);
    signal(SIGUSR2, sigUsr2Handler);
    signal(SIGTERM, handleBadSigs);
    signal(SIGINT, handleBadSigs);
    signal(SIGSEGV, handleBadSigs);

    //Dont' wait for children
    signal(SIGCLD, SIG_IGN);     

    //Sort out PID File
    retVal=sortOutPidFile(progName);
    if(retVal!=0) {
      return retVal;
    }


    // Load Config 
    kvpReset () ;
    status = configLoad (globalConfFile,"global") ;


    // Get Calibd output dirs
    if (status == CONFIG_E_OK) {
	hkDiskBitMask=kvpGetInt("hkDiskBitMask",1);

	disableUsb=kvpGetInt("disableUsb",1);
	if(disableUsb)
	    hkDiskBitMask&=~USB_DISK_MASK;
	//	disableNeobrick=kvpGetInt("disableNeobrick",1);
	//	if(disableNeobrick)
	//	    hkDiskBitMask&=~NEOBRICK_DISK_MASK;
	disableHelium2=kvpGetInt("disableHelium2",1);
	if(disableHelium2)
	    hkDiskBitMask&=~HELIUM2_DISK_MASK;
	disableHelium1=kvpGetInt("disableHelium1",1);
	if(disableHelium1)
	    hkDiskBitMask&=~HELIUM1_DISK_MASK;
    }
    else {
	eString=configErrorString (status) ;
	syslog(LOG_ERR,"Error reading %s: %s\n",globalConfFile,eString);
    }

    makeDirectories(CALIBD_STATUS_LINK_DIR);
    makeDirectories(HK_TELEM_DIR);
    makeDirectories(HK_TELEM_LINK_DIR);

    prepWriterStructs();

    //Need to set digital carrier num
    retVal=readConfigFile();
    //Setup acromag
    acromagSetup();
    ip470Setup();

    //Set code values
    autoZeroStruct.code=IP320_AVZ;
    rawDataStruct.code=IP320_RAW;
    calDataStruct.code=IP320_CAL;



    do {
	if(printToScreen) printf("Initializing Calibd\n");
	retVal=readConfigFile();
	relaysChanged=1;
	currentState=PROG_STATE_RUN;
//RJN for Hkd
        ip320Setup();
	millisecs=0;
	lastRelayWriteSec=0;
	while(currentState==PROG_STATE_RUN) {	  
	  time(&rawTime);
	  
	  //Set Relays to correct state
	  if(relaysChanged || firstTime) retVal=setRelays();
	  
	  if(relaysChanged || (rawTime-lastRelayWriteSec)>=relayWritePeriod) {

	    if(printToScreen) {
	      printf("Amplite1 (%d)  Amplite2 (%d)  BZAmpa1 (%d)  BZAmpa2 (%d)  NTUAmpa (%d)\tSB (%d) SSD_5V (%d) SSD_12V (%d) SSD_Shutdown (%d)\n",stateAmplite1,stateAmplite2,stateBZAmpa1,stateBZAmpa2,stateNTUAmpa,stateSB,stateNTUSSD5V,stateNTUSSD12V,stateNTUSSDShutdown);
	    }
	    writeStatus();
	    relaysChanged=0;
	    lastRelayWriteSec=rawTime;
	  }
	    

	  if(firstTime) firstTime=0;
	  
	  

	  
	  if((millisecs % readoutPeriod)==0) {
	    
	    time(&rawTime);		
	    
	    //		printf("Mag Ret: %d\n",retVal);
	    if((rawTime-lastCal)>calibrationPeriod) {
	      ip320Calibrate();
	      outputData(IP320_CAL);
	      outputData(IP320_AVZ);
	      lastCal=rawTime;
	    }
	    ip320Read(0);
	    outputData(IP320_RAW);
	    
	    millisecs=1;
	  }
	    //Just for safety we'll reset the sleep time
	  milliWait.tv_nsec=1000000;
	  nanosleep(&milliWait,NULL);
	  millisecs++;	   	 

	} //End of run loop
    } while(currentState==PROG_STATE_INIT);
    closeHkFilesAndTidy(&hkRawWriter);
    closeHkFilesAndTidy(&hkCalWriter);
    closeHkFilesAndTidy(&calibWriter);
    unlink(CALIBD_PID_FILE);
    syslog(LOG_INFO,"Calibd Terminating");
    return 0;
    
 }
Esempio n. 4
0
 int main(int argc, char *argv[])
 {
   int pri,retVal,firstTime=1,ind=0;
   time_t lastRefresh=0;
   time_t lastUpdate=0;
   time_t currentTime=0;
   char *tempString=0;
   char *progName=basename(argv[0]);

//   last_send.tv_sec = 0; 
//   last_send.tv_nsec = 0; 

   //Sort out PID File
   retVal=sortOutPidFile(progName);
   if(retVal!=0) {
     return retVal;
   }


   //Directory listing tools
   //    char currentTouchname[FILENAME_MAX];
   char currentHeader[FILENAME_MAX];
   int numLinks[NUM_PRIORITIES]={0};
   int totalEventLinks=0;
   int wdEvents[NUM_PRIORITIES]={0};
   //   int sillyEvNum[NUM_PRIORITIES]={0};


   /* Set signal handlers */
   signal(SIGUSR1, sigUsr1Handler);
   signal(SIGUSR2, sigUsr2Handler);
   signal(SIGTERM, handleBadSigs);
   signal(SIGINT,handleBadSigs);
   signal(SIGSEGV,handleBadSigs);


   /* Setup log */
   setlogmask(LOG_UPTO(LOG_INFO));
   openlog (progName, LOG_PID, ANITA_LOG_FACILITY) ;

   // Load Config 
   retVal=readConfig();
   if(!laptopDebug) {
     retVal=initDevice();
     if(retVal!=0) {
       return 1;
     }
   }
   else {
     retVal=0;
     printf("Running in debug mode not actually trying to talk to device\n");
     makeDirectories(fakeOutputDir);
   }

   makeDirectories(PRIORITIZERD_EVENT_LINK_DIR);

   
    for(ind=0;ind<NUM_HK_TELEM_DIRS;ind++) {
      makeDirectories(telemLinkDirs[ind]);
    }


   //Fill event dir names
   for(pri=0;pri<NUM_PRIORITIES;pri++) {
     sprintf(eventTelemDirs[pri],"%s/%s%d",BASE_EVENT_TELEM_DIR,
	     EVENT_PRI_PREFIX,pri);
     sprintf(eventTelemLinkDirs[pri],"%s/link",eventTelemDirs[pri]);
     makeDirectories(eventTelemLinkDirs[pri]);


     if(sendData) {
	 //And setup inotify watches
	 if(wdEvents[pri]==0) {
	     wdEvents[pri]=setupLinkWatchDir(eventTelemLinkDirs[pri]);
	     if(wdEvents[pri]<=0) {
		 fprintf(stderr,"Unable to watch %s\n",eventTelemLinkDirs[pri]);
		 syslog(LOG_ERR,"Unable to watch %s\n",eventTelemLinkDirs[pri]);
		 handleBadSigs(0);
	     }
	     numLinks[pri]=getNumLinks(wdEvents[pri]);
	 }
     }
   }
   time(&lastRefresh);

   pthread_t thread; 
   retVal = pthread_create(&thread, 0, watchdogThread,0); 
   if (retVal) 
   {
     syslog(LOG_ERR, "LOSd:  create watchdog thread returned %d\n", retVal); 
   }

   do {
     if(verbosity) printf("Initializing LOSd\n");
     int lastSendData=sendData;
     retVal=readConfig();
     if(lastSendData!=sendData) {
	 break; //Lets restart LOSd
     }
     if(firstTime) {
       sendWakeUpBuffer();
       firstTime=0;
     }
     int hkCount=0;    	
     currentState=PROG_STATE_RUN;
     while(currentState==PROG_STATE_RUN) {
       //This is just if LOSd has been turned off when we're out of range
       if(!sendData) {
	 sleep(1);
	 continue;
       }
       
       //Check to see if we need to refresh the links
       time(&currentTime);
       if(currentTime>lastRefresh+REFRESH_LINKS_EVERY) {

	   refreshLinkDirs();
	   lastRefresh=currentTime;
       }

       //Work which priority we're doing
       currentPri=priorityOrder[orderIndex];

       //Will actually change this to almost work in the future
       if(hkCount%5==0) fillBufferWithHk();
       hkCount++;

       //Check the link dirs
       if(currentTime>lastUpdate+10 || totalEventLinks<1) {
	 if(totalEventLinks<1) 
	   checkLinkDirs(1,0);
	 else
	   checkLinkDirs(0,1); //Maybe I don't need to do this every time
	 lastUpdate=currentTime;
       }

       totalEventLinks=0;
       for(pri=0;pri<NUM_PRIORITIES;pri++) {
	 numLinks[pri]=getNumLinks(wdEvents[pri]);
	 totalEventLinks+=numLinks[pri];
       }

       if(printToScreen && verbosity>1) {
	 printf("Got %d links in %s\n",numLinks[currentPri],
		eventTelemLinkDirs[currentPri]);
       }
       //       sillyEvNum[currentPri]=0;

       if(numLinks[currentPri]>0) {
	 //Got an event

	 tempString=getLastLink(wdEvents[currentPri]);	
	 sprintf(currentHeader,"%s/%s",eventTelemLinkDirs[currentPri],
		 tempString);
	 if(printToScreen && verbosity)
	   printf("Starting %s\n",currentHeader);
	 readAndSendEventRamdisk(currentHeader); //Also deletes
	 numLinks[currentPri]--;
	 totalEventLinks--;	       
       }

       //Again I need to improve the bandwidth sharing between data and hk
       fillBufferWithHk();
//       if(totalEventLinks<1) usleep(100);
       //	    printf("totalEventLinks %d\n",totalEventLinks);
       orderIndex++;
       if(orderIndex>=numOrders) orderIndex=0;
     }
   } while(currentState==PROG_STATE_INIT);
   unlink(LOSD_PID_FILE);
   syslog(LOG_INFO,"LOSd terminating");
   //    fprintf(stderr, "Bye bye\n");
   return 0;
 } 
Esempio n. 5
0
int main (int argc, char *argv[])
{
    int retVal,pri;

    /* Log stuff */
    char *progName=basename(argv[0]);
    	    
    retVal=sortOutPidFile(progName);
    if(retVal<0)
	return -1;

    /* Setup log */
    setlogmask(LOG_UPTO(LOG_INFO));
    openlog (progName, LOG_PID, ANITA_LOG_FACILITY) ;

    /* Set signal handlers */
    signal(SIGUSR1, sigUsr1Handler);
    signal(SIGUSR2, sigUsr2Handler);
    signal(SIGINT,handleBadSigs);
    signal(SIGTERM,handleBadSigs);
    signal(SIGSEGV,handleBadSigs);


    //Dont' wait for children
    signal(SIGCLD, SIG_IGN); 
    
    retVal=0;
    for(pri=0;pri<NUM_PRIORITIES;pri++) {
	sprintf(eventTelemLinkDirs[pri],"%s/%s%d/link",BASE_EVENT_TELEM_DIR,
		EVENT_PRI_PREFIX,pri);
	sprintf(eventTelemDirs[pri],"%s/%s%d",BASE_EVENT_TELEM_DIR,
		EVENT_PRI_PREFIX,pri);

	makeDirectories(eventTelemLinkDirs[pri]);
	
	sprintf(priorityPurgeDirs[pri],"%s/pri%d",BASE_PRIORITY_PURGE_DIR,
		pri);
	makeDirectories(priorityPurgeDirs[pri]);
    }
    
    retVal=readConfigFile();
    if(retVal<0) {
	syslog(LOG_ERR,"Problem reading Playbackd.config");
	printf("Problem reading Playbackd.config\n");
	exit(1);
    }
  

    //Main Loop
    do {
	printf("Initalizing Playbackd\n");
	retVal=readConfigFile();
	if(retVal<0) {
	    syslog(LOG_ERR,"Problem reading Playbackd.config");
	    printf("Problem reading Playbackd.config\n");
	    exit(1);
	}
	currentState=PROG_STATE_RUN;
	while(currentState==PROG_STATE_RUN) {
	    if(sendData) startPlayback();
	    retVal=checkForRequests();
	    if(!retVal)
	      printf("sleep\n");sleep(10);
	}
    } while(currentState==PROG_STATE_INIT);    
    unlink(PLAYBACKD_PID_FILE);
    return 0;
}
Esempio n. 6
0
int main(int argc, char *argv[]){

  {
    int runInd=0;
    for(runInd=0; runInd<NUM_RUNS; runInd++){
      lastEvents[runInd] = firstEvents[runInd]+5000 < lastEvents[runInd] ? firstEvents[runInd]+5000 : lastEvents[runInd];
    }
  }

  /* { */
  /*   int runInd=0; */
  /*   for(runInd=0; runInd<NUM_RUNS; runInd++){ */
  /*     lastEvents[runInd] = firstEvents[runInd]+10000; */
  /*   } */
  /* } */


  int retVal; //,count;
  /* Directory reading things */
  int wd=0;
  /* char *tempString; */
  int numEventLinks;
    
  /* Log stuff */
  char *progName=basename(argv[0]);

  retVal=sortOutPidFile(progName);
  if(retVal<0)
    return retVal;

#ifdef WRITE_DEBUG_FILE
  FILE *debugFile = fopen("/tmp/priDebugFile.txt","w");
  if(!debugFile) {
    fprintf(stderr,"Couldn't open debug file\n");
    exit(0);
  }
#endif

  /* Set signal handlers */
  signal(SIGUSR1, sigUsr1Handler);
  signal(SIGUSR2, sigUsr2Handler);
  signal(SIGTERM, handleBadSigs);
  signal(SIGINT, handleBadSigs);
  signal(SIGSEGV, handleBadSigs);

  //Dont' wait for children
  //RJN hack will have to fix this somehow
  signal(SIGCLD, SIG_IGN); 


  /* Setup log */
  setlogmask(LOG_UPTO(LOG_INFO));
  openlog (progName, LOG_PID, ANITA_LOG_FACILITY) ;

  makeDirectories(HEADER_TELEM_LINK_DIR);
  makeDirectories(HEADER_TELEM_DIR);
  makeDirectories(EVENTD_EVENT_LINK_DIR);
  makeDirectories(PRIORITIZERD_EVENT_LINK_DIR);
  makeDirectories(ACQD_EVENT_LINK_DIR);

  makeDirectories(GPU_TELEM_DIR);
  makeDirectories(GPU_TELEM_LINK_DIR);

  retVal=0;
  /* Main event getting loop. */

  if(wd==0) {
    //First time need to prep the watcher directory
    wd=setupLinkWatchDir(EVENTD_EVENT_LINK_DIR);
    if(wd<=0) {
      fprintf(stderr,"Unable to watch %s\n",EVENTD_EVENT_LINK_DIR);
      syslog(LOG_ERR,"Unable to watch %s\n",EVENTD_EVENT_LINK_DIR);
      exit(0);
    }
    numEventLinks=getNumLinks(wd);
  }

  /* 
     This function  mallocs at some global pointers
     so needs to be outside any kind of loop.
  */
  prepareGpuThings();
  prepareTimingCalibThings();
  /* Reset average */
  int phi=0;
  for(phi=0; phi<NUM_PHI_SECTORS; phi++){
    memset(&payloadPowSpec[phi], 0, sizeof(GpuPhiSectorPowerSpectrumStruct_t));
  }
  
  prepWriterStructs();

  do {
    if(printToScreen) printf("Initalizing fakePrioritizerd\n");
    retVal=readConfig();
    if(retVal<0) {
      syslog(LOG_ERR,"Problem reading Prioritizerd.config");
      printf("Problem reading Prioritizerd.config\n");
      exit(1);
    }
    currentState=PROG_STATE_RUN;

    /* This one is the main while loop */
    int runInd=0;
    for(runInd=0; runInd<NUM_RUNS; runInd++) {
      int run = runs[runInd];
      if(run!=selectedRun) continue;

      const char* baseDir = "/home/anita/anitaStorage/antarctica14/raw";
      int eventFileNum=0;
      int firstFile = 100*(firstEvents[runInd]/100) + 100;
      int lastFile = 100*(lastEvents[runInd]/100) - 100;
      for(eventFileNum=firstFile; eventFileNum<=lastFile; eventFileNum+=100){
	//    while(currentState==PROG_STATE_RUN) {

	//	usleep(1);
	retVal=checkLinkDirs(1,0);
	if(retVal || numEventLinks) numEventLinks=getNumLinks(wd);

	if(numEventLinks>=panicQueueLength) {
	  syslog(LOG_INFO,"Prioritizerd is getting behind (%d events in inbox), will have some prioritity 7 events",numEventLinks);
	}

	/* if(!numEventLinks){ */
	/* 	usleep(1000); */
	/* 	continue; */
	/* } */

	/* Read data into program memory */
	int eventDir1 = eventFileNum/1000000;
	eventDir1 *= 1000000;
	int eventDir2 = eventFileNum/10000;
	eventDir2 *= 10000;
      
	char dir[FILENAME_MAX];
	sprintf(dir, "%s/run%d/event/ev%d/ev%d", baseDir, run, eventDir1, eventDir2);

	char fileName1[FILENAME_MAX];
	sprintf(fileName1, "%s/psev_%d.dat.gz", dir, eventFileNum);
	char fileName2[FILENAME_MAX];	
	sprintf(fileName2, "%s/hd_%d.dat.gz", dir, eventFileNum);

	printf("%s\n", fileName1);
	readIn100Events(fileName1, pedSubBody, fileName2, theHeader);
	/* readInTextFile(pedSubBody, theHeader); */


	int eventsReadIn = 0;
	while(eventsReadIn<100 && currentState==PROG_STATE_RUN){

	  /* numEventLinks=getNumLinks(wd); */
	  /* tempString=getFirstLink(wd); */
	  /* if(numEventLinks==0) break; */
	  /* if(tempString==NULL) continue; */
	  /* //	printf("tempString = %s\n", tempString); */
	  /* //	printf("%s\n",eventLinkList[eventsReadIn]->d_name);  */
	  /* sscanf(tempString,"hd_%d.dat",&doingEvent); */
	  /* if(lastEventNumber>0 && doingEvent!=lastEventNumber+1) { */
	  /*   syslog(LOG_INFO,"Non-sequential event numbers %d and %d\n", lastEventNumber, doingEvent); */
	  /* } */
	  /* lastEventNumber=doingEvent; */

	  /* sprintf(linkFilename, "%s/%s", EVENTD_EVENT_LINK_DIR, tempString); */
	  /* sprintf(hdFilename, "%s/hd_%d.dat", EVENTD_EVENT_DIR, doingEvent); */

	  /* //RJN 4th June 2008 */
	  /* //Switch to Acqd writing psev files */
	  /* sprintf(bodyFilename[eventsReadIn],"%s/psev_%d.dat", ACQD_EVENT_DIR, doingEvent); */

	  /* retVal=fillHeader(&theHeader[eventsReadIn],hdFilename);	 */

	  if(numEventLinks < panicQueueLength){
	    /* Then we add to GPU queue... */
	    /* retVal=fillPedSubbedBody(&pedSubBody,bodyFilename[eventsReadIn]); */
	    double* finalVolts[ACTIVE_SURFS*CHANNELS_PER_SURF];
	    /* printf("fakePrioritizer reads event %d with priority %d\n",theHeader[eventsReadIn].eventNumber,  theHeader[eventsReadIn].priority&0xf); */
	    doTimingCalibration(eventsReadIn, &theHeader[eventsReadIn], pedSubBody[eventsReadIn], finalVolts);
	    addEventToGpuQueue(eventsReadIn, finalVolts, theHeader[eventsReadIn]);
	    int chanInd=0;
	    for(chanInd=0; chanInd<ACTIVE_SURFS*CHANNELS_PER_SURF; chanInd++){
	      free(finalVolts[chanInd]);
	    }
	    eventsReadIn++;
	  }
	  else{/* Panic! Write all header files to archived directory with priority 7! */
	    panicWriteAllLinks(wd, 7, panicQueueLength, priorityPPS1, priorityPPS2);
	  }
	}
	/* exit(-1); */

	printf("eventsReadIn = %d, max is %d.\n", eventsReadIn, NUM_EVENTS);

	/* Now use GPU to determine priority, send in arrays of length eventsReadIn... */
	if(eventsReadIn>0){
	  mainGpuLoop(eventsReadIn, theHeader, payloadPowSpec, writePowSpecPeriodSeconds);
	}

	if(payloadPowSpec[0].unixTimeLastEvent - payloadPowSpec[0].unixTimeFirstEvent >= writePowSpecPeriodSeconds
	   || currentState!=PROG_STATE_RUN){
	  int phi=0;
	  for(phi=0; phi<NUM_PHI_SECTORS; phi++){
	    printf("Trying to write and link for phi sector %d...\n", phi);
	    writeFileAndLink(&payloadPowSpec[phi], phi);
	  }
	  if(currentState==PROG_STATE_RUN){
	    /* Reset average */
	    for(phi=0; phi<NUM_PHI_SECTORS; phi++){
	      memset(&payloadPowSpec[phi], 0, sizeof(GpuPhiSectorPowerSpectrumStruct_t));
	    }
	  }
	}

	int count = 0;
	for(count=0;count<eventsReadIn;count++) {

	  // handle queue forcing of PPS here
	  int pri=theHeader[count].priority&0xf;
	  if((theHeader[count].turfio.trigType&0x2) && (priorityPPS1>=0 && priorityPPS1<=9))
	    pri=priorityPPS1;
	  if((theHeader[count].turfio.trigType&0x4) && (priorityPPS2>=0 && priorityPPS2<=9))
	    pri=priorityPPS2;
	  if(pri<0 || pri>9) pri=9;
	  theHeader[count].priority=(16*theHeader[count].priority)+pri;

	  /* printf("eventNumber = %u, priority = %d\n", theHeader[count].eventNumber, theHeader[count].priority&0xf); */

	  //Now Fill Generic Header and calculate checksum
	  /* fillGenericHeader(&theHeader[count],theHeader[count].gHdr.code,sizeof(AnitaEventHeader_t)); */

	  /* //Rename body and write header for Archived */
	  /* sprintf(archiveBodyFilename,"%s/psev_%u.dat",PRIORITIZERD_EVENT_DIR, */
	  /* 	theHeader[count].eventNumber); */
	  /* if(rename(bodyFilename[count],archiveBodyFilename)==-1) */
	  /*   { */
	  /*     syslog(LOG_ERR,"Error moving file %s -- %s",archiveBodyFilename, */
	  /* 	   strerror(errno)); */
	  /*   } */

	  /* sprintf(archiveHdFilename,"%s/hd_%u.dat",PRIORITIZERD_EVENT_DIR, */
	  /* 	theHeader[count].eventNumber); */
	  /* writeStruct(&theHeader[count],archiveHdFilename,sizeof(AnitaEventHeader_t)); */

	  /* makeLink(archiveHdFilename,PRIORITIZERD_EVENT_LINK_DIR); */
    
	  /* //Write Header and make Link for telemetry */
	  /* sprintf(telemHdFilename,"%s/hd_%d.dat",HEADER_TELEM_DIR, */
	  /* 	theHeader[count].eventNumber); */
	  /* retVal=writeStruct(&theHeader[count],telemHdFilename,sizeof(AnitaEventHeader_t)); */
	  /* makeLink(telemHdFilename,HEADER_TELEM_LINK_DIR); */

	  /* /\* Delete input *\/ */
	  /* sprintf(linkFilename,"%s/hd_%d.dat",EVENTD_EVENT_LINK_DIR, */
	  /* 	theHeader[count].eventNumber); */
	  /* sprintf(hdFilename,"%s/hd_%d.dat",EVENTD_EVENT_DIR, */
	  /* 	theHeader[count].eventNumber); */
	  /* removeFile(linkFilename); */
	  /* removeFile(hdFilename); */

	}
      }
    }
  } while(currentState==PROG_STATE_INIT && 0); 
  unlink(PRIORITIZERD_PID_FILE);


  closeHkFilesAndTidy(&gpuWriter);

  tidyUpGpuThings();
  tidyUpTimingCalibThings();
 /* Close the file which contains the high level output information */

  printf("fakePrioritizerd exiting. Reached end of main\n.");
  return 0;
}