/* BasyouhuC200005.c
 * =================
 * - for Japanese Special Discretionary Time in May-Aug,2000 ver. 1.00
 * - for conjugate study with SyowaS/Halley/Sanae/TigerTas,
 *				SyowaE/Kerguelen, IcelandE/Finland radars
 *
 *	--- based on BasyouhuC200002.c ver.1.03
 *	--- based on Sessai's revised version of Rob's normal_scan
 *		for Radops2000v4.01 which can be used also on Radops v4.10A
 *
 *	intt=3
 *	!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 *	if you cannot, please change it using '-it' option!!!!!!!!!!!
 *				e.g. '-it 4' for intt=4.  !!!!!!!!!!!
 *	!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 *
 *	(rsep=45km,frang=180km,mpinc=2400 as usual)
 *	No GPS Synchronization (wb_min=0,wb_sec=0)
 *	Special Basyouhu Scan for high speed global scan
 *	and 3 high time resolution special camping beams
 *	for high time resolution cusp observation
 *	(defined in "for loop" code in this program and in "BasyouhuC200005.h")
 *
 *	#define CP_ID 5249
 *
 *	!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 *	Please Specify your 2 most appropriate FREQUENCIES
 *	or by giving "-df" "-nf" option to me
 *		-df is a freq to be used for day time
 *		-nf is a freq to be used for night time
 *	!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 *
 *	If you want to reduce the amount of smr files, you can specify
 *	'-smrsep smrsepsec' option.  'smrsepsec' is minimum separation
 *	in seconds bewteen the last recording time and the next recording time
 *	for each smr beam.  (The default value is just 0(L)(second).)
 *
 *	If you don't wanna change your default summary beams
 *	which are defined in /radops/usr/include/default.h
 *	(SMR_BEAM_A and SMR_BEAM_B),
 *	you can specify -nosmrch command line option
 *	(If you want to record only 1 smr beam,
 *	 make sure your SMR_BEAM_B is -1(not between 0 and 15))
 *
 *	Even if you specify -nosmrch option,
 *	you can also use -smrsep option to reduce your smr records...
 *
 *					...This is Not the "Nasu"...
 *
 *							by Sessai@NIPR
 */

/*
 $Log: BasyouhuC200005.c,v $
 Revision 1.00  2000/04/18 00:00:00  sessai
 initial version based on BasyouhuC200003 ver1.03

 */

/*
 $Log: BasyouhuC200002.c,v $
 Revision 1.03  2000/02/28 00:00:00  sessai
 now -smrsep option works even if -nosmrch is specified

 Revision 1.02  2000/02/28 00:00:00  sessai
 Add nosmrch option not to change smr beams
 (note: if nosmrch specified, smrsep option will not work)

 Revision 1.01  2000/02/14 00:00:00  sessai
 Add smrsep option to reduce smr records
 And fix a bug in usage message

 Revision 1.00  2000/01/21 00:00:00  sessai
 initial version based on BasyouhuP200002 ver1.00

 */

/*
 $Log: BasyouhuP200002.c,v $
 Revision 1.00  1999/12/21 00:00:00  sessai
 initial version based on BasyouhuP200001 ver1.01

 */

/*
 $Log: BasyouhuP200001.c,v $
 Revision 1.01  1999/12/14 12:00:00  sessai
 Added more TIGER support.

 Revision 1.00  1999/12/06 00:00:00  sessai
 initial version based on BasyouhuC9908 ver1.00

 */

/*
 $Log: BasyouhuC9908.c,v $
 Revision 1.00  1999/07/06 00:00:00  sessai
 initial version based on BasyouhuC9905 ver1.01

 */

/*
 $Log: BasyouhuC9905.c,v $
 Revision 1.01  1999/04/26 00:00:00  sessai
 change special beam selection in BasyouhuC9905.h

 Revision 1.00  1999/04/01 00:00:00  sessai
 initial version based on BasyouhuC9903 ver1.01

 */

/*
 $Log: BasyouhuC9903.c,v $
 Revision 1.01  1999/02/25 00:00:00  sessai
 bug fix about Leicester freq_band part

 Revision 1.00  1999/02/01 00:00:00  sessai
 initial version based on BasyouhuP9901 ver3.00

 */

/*
 $Log: BasyouhuP9901.c,v $
 Revision 3.00  1999/01/08 00:00:00  sessai
 introduce MODEMAX in BasyouhuP9901.h
 now this can be used both for Jan. and Feb., 1999 ST

 Revision 2.00  1998/12/16 00:00:00  sessai
 actually no change in BasyouhuP9901.c
 only BasyouhuP9901.h has been modified
 due to modification of sounding modes

 Revision 1.00  1998/12/08 00:00:00  sessai
 initial version

 */

/* ---- Sessai's normal_scan history record ---- */
/* Sessai revised Dec. 1,1997 - fixed missing usr_resS1
 * Sessai version Nov. 1,1997 -many fixes to Rob's v.2.10
 */

/* ---- Rob's normal_scan rcs record ---- */
/*
 $Log: normal_scan.c,v $
 Revision 2.10  1997/06/10 20:24:57  root
 Removed redundant header entry.
 ............

 */

#ifdef __USAGE
%C [-df day_start_freq/band] [-df day_start_freq/band]
           [-dt day_start_hr] [-nt night_start_hr] [-smrsep smrsepsec]
           [-xcf xcount] [-it intt] [-v verbose(0-9)] [-nosmrch] [option file]

*** This is ver.1.00 ***

Please specify the 2 best frequencies to get as much echo as possible!!!!!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Specify them by '-df' & '-nf' options

        -df   day_start_freq/band     one    freq/band for  day  time
        -nf night_start_freq/band     one    freq/band for night time

If you want to change day/night boundary, you can specify them by
'-dt' and '-nt' options as in normal_scan.

If you want to change "intt" to avoid this RCP or your hardware crashing,
you can use '-it' option to overide it.

mode and submode will be selected AUTOMATICALLY by this RCP
by reading current time on this PC.

If you specify verbose level >=2, then you can get records on time/beam/scan
values in your errlog file (which will be useful for testing...).

If you want to reduce the amount of smr files, you can specify
'-smrsep smrsepsec' option.  'smrsepsec' is minimum separation in seconds
bewteen the last recording time and the next recording time
for each smr beam.  (The default value is just 0(L)(second).)

If you don't wanna change default summary beams, specify -nosmrch option.
(If you specify it, sd_summary will record only SMR_BEAM_A and SMR_BEAM_B
 which are defined in your /radops/usr/include/default.h.
 If you want to record only 1 smr beam, make sure that
 SMR_BEAM_B is -1(not between 0 and 15) in your default.h file.)
(Even if you specify -nosmrch option,
 you can also use -smrsep option to reduce your smr records...

Many thanks for your collaboration...
#endif

#define SIM_FILE "/radops/demo.dat"

//#define CP_ID 5247
#define CP_ID 5249

#include <stdlib.h>
#include <stdio.h>
#include <string.h>	// added by Sessai
#include <signal.h>
#include <time.h>

/* Headers for the control library
 * ===============================
 */

#include "message.h"
#include "radops.h"
#include "fitdata.h"

#include "task_write.h"
#include "user_int.h"
#include "get_status.h"
#include "log_error.h"
#include "sample.h"
#include "read_raw.h"

/* Header for the support library
 * ===============================
 */

#include "support.h"
#include "sync.h"
#include "summary_control.h"
#include "option.h"

/* the normal_scan headers */

#include "radar_id.h"
#include "default.h"

#define DEFAULT_INTT 3
#define DEFAULT_RSEP 45
#define DEFAULT_FRANG 180
#define DEFAULT_MPINC 2400
#define DEFAULT_FREQ_RANGE 300
#define DEFAULT_FREQ_STEP 5
#define DEFAULT_SP_SCAN -32768
#define DEFAULT_WB_MIN 0

/* registered names of the tasks to receive data */

#include "task_names.h"	//#include "task_names0.h"

char prg_name[32]; /* this is the program name displayed by display */
char cmd_line[256];
char errbuf[256];

//short int v=0;
short int v=1;

#include "option2.h"
#include "sync2.h"

#ifdef NIPR
 #include "ntp.h"
int nntp=0;
#endif
//#include "set_summary.h"
#include "forbid_freq_check.h"
#include "show.h"

// for Basyouhu Special (May,2000)
#include "BasyouhuC200005.h"		// newly revised one!

/* The main program */

int f=0;
int frame_counter=0;

short int start_freq,end_freq,freq_range=DEFAULT_FREQ_RANGE;

short int start_beam,end_beam,skip_beam;
short int spbmc=-1;
short int spbmc2;
short int spbmnum;

short int day_start_hr=DAY_START;
short int night_start_hr=NIGHT_START;
#if !defined(LEICESTER) && !defined(TIGER)
short int day_start_freq=DAY_FREQ;
short int night_start_freq=NIGHT_FREQ;
#endif
short int day_frang=DAY_FRANG;
short int night_frang=NIGHT_FRANG;
short int day_mpinc=DAY_MPINC;
short int night_mpinc=NIGHT_MPINC;
short int day_night_flag;
short int count=0,xcount=XCF;

#if defined(LEICESTER) || defined(TIGER)
 short int day_start_band=DAY_BAND;
 short int night_start_band=NIGHT_BAND;
 #include "freq_band.h"
#endif

// moved from main(), Julian, OK?   <------- Julian, Look and check here!!
#ifdef PULSE_CODE
 #include "pulse_code.h"
#endif

FILE *sim_file=NULL;

short int wb_min=DEFAULT_WB_MIN,wb_sec=0;
//short int wb_st_hr=0;wb_st_min=0,wb_st_sec=0;

short int mode=0;	// shuold be set between 1 and MODEMAX
short int smode=0;	// shuold be set between 1 and SUBMODEMAX
short int force_mode=0;
short int force_smode=0;
short int last_mode=-1;
short int last_smode=-1;

#if defined(LEICESTER) || defined(TIGER)
 short int df1=DAY_BAND;
 short int df2=DAY_BAND;
 short int nf1=NIGHT_BAND;
 short int nf2=NIGHT_BAND;
 short int df=DAY_BAND;
 short int nf=NIGHT_BAND;
#else
short int df1=DAY_FREQ;
short int df2=DAY_FREQ;
short int nf1=NIGHT_FREQ;
short int nf2=NIGHT_FREQ;
short int df=DAY_FREQ;
short int nf=NIGHT_FREQ;
#endif
short int stf[2][2]={1,2,3,4};	//stf[day_night_flag][0/1]={df1,df2,nf1,nf2};
short int fnc=0;
short int fsc=0;

#ifdef DEBUG
short int dum1;
long int dum2;
#endif

time_t smrsep=0L;
time_t smlast[16]={0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L};
time_t nowc;
struct timespec rtc;

short int nosmrch=0;
// moved from main()
long int tmpA,tmpB,tmpP;

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

  int exit_poll=0;
  int argnum=0;

// Julian, I moved these below up to global part above! OK?
//  I need this for making a function "onebeam()" below......
//#ifdef PULSE_CODE
// #include "pulse_code.h"
//#endif

struct option opt[] = {
    {"dt", 's', 0, &day_start_hr},
    {"nt", 's', 0, &night_start_hr},
//#ifdef LEICESTER
//    {"df", 's', 0, &day_start_band},
//    {"nf", 's', 0, &night_start_band},
//#else
//    {"df", 's', 0, &day_start_freq},
//    {"nf", 's', 0, &night_start_freq},
//#endif
//  {"df1", 's', 0, &df1},
//  {"df2", 's', 0, &df2},
//  {"nf1", 's', 0, &nf1},
//  {"nf2", 's', 0, &nf2},
    {"df", 's', 0, &df},
    {"nf", 's', 0, &nf},

//  {"dr", 's', 0, &day_frang},
//  {"nr", 's', 0, &night_frang},
//  {"fr", 's', 0, &frang},
    {"xcf",'s', 0, &xcount},
//  {"dm", 's', 0, &day_mpinc},
//  {"nm", 's', 0, &night_mpinc},
//  {"mp", 's', 0, &mpinc},
//  {"mpinc", 's', 0, &mpinc},
//  {"sb", 's', 0, &start_beam},
//  {"eb", 's', 0, &end_beam},
    {"it", 's', 0, &intt},
    {"intt", 's', 0, &intt},
    {"rs", 's', 0, &rsep},
    {"rsep", 's', 0, &rsep},
//  {"nwb", NULL, 0, NULL},
//  {"wb", 's', 0, &wb_min},
//  {"wbs", 's', 0, &wb_sec},
    {"v", 's', 0, &v},
#ifdef NIPR
    {"nntp", NULL, 0, &nntp},	// Sessai to specify ignoring NTP.tbl!!!
#endif
//  {"mode", 's', 0, &mode},	// should be given like 1,2,...,MODEMAX
//  {"submode", 's', 0, &smode}, // should be given like 1,2,...,SUBMODEMAX
    {"force_mode", 's', 0, &force_mode},
    {"force_submode", 's', 0, &force_smode},
    {"smrsep", 'l', 0, &smrsep},
//  {"nosmrch", NULL, 0, &nosmrch},
    {"nosmrch", NULL, 0, NULL},
    0};

//FILE *sim_file=NULL;
  FILE *opt_file=NULL;
//int status,c;
  int bmc;		// beam number counter
  int bm_scan_sign=1;	// +1 when start_beam<=end_beam, otherwise -1
//int first_beam=1;
//long int tmpA,tmpB,tmpP;
 
  /* define the pulse sequence and the lag table */

  short int ptab[7] = {0,9,12,20,22,26,27};
  short int lags[2][18] ={
    {0,26,20,9,22,22,20,20,12,0,12,9,0,9,12,12,9,9},
    {0,27,22,12,26,27,26,27,20,9,22,20,12,22,26,27,26,27}};

  /* set up the default parameters */

  #ifdef DISCRETIONARY
    cp =-CP_ID;
  #else
    cp=CP_ID;
  #endif

  intt = DEFAULT_INTT;
//rsep = DEFAULT_RSEP;
  rsep = SPRSEP;

//freq_range=DEFAULT_FREQ_RANGE;

//mpinc = day_mpinc;
//frang = day_frang;
  mpinc = DEFAULT_MPINC;
  frang = DEFAULT_FRANG;
  nrang = NRANG;
  max_atten = MAX_ATTEN;
  prot_atten= PROT_ATTEN;
  rxnarrow=RXNARROW;
  rxwide=RXWIDE;
  rsep_switch=RSEP_SWITCH;

//strcpy(combf,"$Id: normal_scan.c,v 2.10 1997/06/10 20:24:57 root Exp root $");
//strcpy(combf,"$Id: Nasumiso.c,v 1.00 1997/12/24 00:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: Basyouhu.c,v 1.00 1998/01/17 00:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: BasyouhuP9901.c,v 3.00 1999/01/08 00:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: BasyouhuC9903.c,v 1.01 1999/02/25 00:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: BasyouhuC9905.c,v 1.01 1999/04/26 00:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: BasyouhuC9908.c,v 1.01 1999/07/06 00:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: BasyouhuP200001.c,v 1.00 1999/12/06 00:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: BasyouhuP200001.c,v 1.01 1999/12/14 12:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: BasyouhuP200002.c,v 1.00 1999/12/21 00:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: BasyouhuC200002.c,v 1.00 2000/01/21 00:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: BasyouhuC200002.c,v 1.01 2000/02/14 00:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: BasyouhuC200002.c,v 1.02 2000/03/28 00:00:00 sessai Exp sessai $");
//strcpy(combf,"$Id: BasyouhuC200002.c,v 1.03 2000/03/29 00:00:00 sessai Exp sessai $");
  strcpy(combf,"$Id: BasyouhuC200005.c,v 1.01 2000/04/18 00:00:00 sessai Exp sessai $");

// added by Sessai on Dec. 1, 1997
#ifdef BACKWARDS
  usr_resS1 = -1;  /* backwards scan */
#else
  usr_resS1 = 1;   /* forward scan */
#endif

// I moved these from down below..., Julian, OK?
#if defined(LEICESTER) || defined(TIGER)
  init_freq_bands();
//init_proxy();
#else
  start_freq=day_start_freq;
#endif

 report("================================");
 report("Control Program started.");
	sprintf(errbuf,"%d %s %c",SD_RADAR_ID,SD_RADAR_NAME,SD_RADAR_CODE);
	report(errbuf);

   /* set the program name on the display */

// strcpy(prg_name,"normal_scan");
   set_prg_name(argv[0]);

   /* build the command line string */

  set_cmd_line(argc,argv);

	strcpy(errbuf,combf);
	report(errbuf);

  /* decode the command line parameters */

  //argnum=process_option(argc,argv,opt,NULL);
  argnum=process_option2(argc,argv,opt,NULL);
  if (argnum<argc)  {
    if((opt_file=fopen(argv[argnum],"r"))!=NULL) {
        //process_file(opt_file,opt,NULL);
        process_file2(opt_file,opt,NULL);
        fclose(opt_file);
    } else {
	sprintf(errbuf,"Cannot open option file %s!!!!",argv[argnum]);
	report(errbuf);
	// exit(1);
    }
  }

	if(optset("nosmrch",opt)){
		nosmrch=1;
	}
//	if(optset("mode",opt)){
//	    if((mode>MODEMAX)||(mode<=0)){
//		sprintf(errbuf,"mode %d specified...",mode);
//		report(errbuf);
//		report("mode MUST be among 1,2,...,MODEMAX !!!");
//		report("Abnormal Exit!!!...");
//		exit(1);
//	    }
//		sprintf(errbuf,"mode %d specified by -mode option...",mode);
//		report(errbuf);
//		mode=mode-1;
//	} else {
//		report("mode option not specified!!!...");
//		report("You MUST Specify mode option by -mode option!!!...");
//		report("Abnormal Exit!!!...");
//		exit(1);
//	}

	if(optset("force_mode",opt)){
		if(force_mode>MODEMAX)force_mode=MODEMAX;
		if(force_mode<=0)force_mode=1;
			sprintf(errbuf,"mode %d by -force_mode option...",
				force_mode);
			report(errbuf);
		mode=force_mode-1;
	} else {
		//mode=0;
			sprintf(errbuf,"mode option not specified...");
			report(errbuf);
			sprintf(errbuf,"automatical set_mode applied!");
			report(errbuf);
			sprintf(errbuf,"spdadte[MODEMAX]=");
			{ int i; char tmpchr[33];
			    for(i=0;i<MODEMAX;i++){
				strcat(errbuf,ltoa((long)spdate[i],tmpchr,10));
				if(i<MODEMAX-1)strcat(errbuf,",");
			    }
			}
			report(errbuf);
		read_clock(&yr,&mon,&day,&hr,&min,&sec,&msec,&usec);
			sprintf(errbuf,"it is now %d/%02d/%02d %02d:%02d:%02d",
				yr,mon,day,hr,min,sec);
			report(errbuf);
		//set_mode(yr,mon,day,hr,min,sec);
		set_mode1(yr,mon,day);
			sprintf(errbuf,"set_mode1 set mode to %d",mode);
			report(errbuf);
	}

	if(optset("force_submode",opt)){
		if(force_smode>SUBMODEMAX)force_smode=SUBMODEMAX;
		if(force_smode<=0)force_smode=1;
			sprintf(errbuf,"submode %d by -force_smode option...",
				force_smode);
			report(errbuf);
		smode=force_smode-1;
	} else {
		//smode=0;
			sprintf(errbuf,"smode option not specified...");
			report(errbuf);
			sprintf(errbuf,"automatical set_mode2 applied!");
			report(errbuf);
			sprintf(errbuf,"sptgate[SUBMODEMAX]=");
			{ int i; char tmpchr[33];
			    for(i=0;i<SUBMODEMAX-1;i++){
				strcat(errbuf,itoa(sptgate[mode][i],tmpchr,10));
				if(i<SUBMODEMAX-2)strcat(errbuf,",");
			    }
			}
			report(errbuf);
		read_clock(&yr,&mon,&day,&hr,&min,&sec,&msec,&usec);
			sprintf(errbuf,"it is now %d/%02d/%02d %02d:%02d:%02d",
				yr,mon,day,hr,min,sec);
			report(errbuf);
		//set_mode(yr,mon,day,hr,min,sec);
		set_mode2(hr,min,sec);
			sprintf(errbuf,"set_mode2 set smode to %d",smode);
			report(errbuf);
	}

		start_beam=spstbm[mode][smode];
		end_beam  =spedbm[mode][smode];
		sprintf(errbuf,"mode %d selected...",mode);
		sprintf(errbuf,"submode %d selected...",smode);
		report(errbuf);
	    if((optset("it",opt))||(optset("intt",opt))){
		sprintf(errbuf,"intt = %d selected by mode...",spintt[mode][smode]);
		report(errbuf);
		sprintf(errbuf,"BUT intt = %d specified by intt option!!",intt);
		report(errbuf);
		report("spintt is OVERRIDED!!!...");
		sprintf(errbuf,"intt = %d selected!!!!!!!!",intt);
		report(errbuf);
	    } else {
		intt=spintt[mode][smode];
		sprintf(errbuf,"intt = %d selected by mode...",intt);
		report(errbuf);
	    }
	    if(sponly[mode][smode]){
		report("SpecialBeam(s) Only Mode is selected by mode!!!...");
	    } else {
		report("Basyouhu Special Scan Mode is selected by mode!!!...");
		sprintf(errbuf,"start_beam %d selected by mode...",start_beam);
		report(errbuf);
		sprintf(errbuf,"  end_beam %d selected by mode...",  end_beam);
		report(errbuf);
	    }
		spbmnum=0;
		while((spbm[mode][smode][0][spbmnum]!=-1)&&(spbmnum<SPBMNUM))spbmnum++;
		sprintf(errbuf,"%d spec_beam(s)(",spbmnum);
		{ int i; char tmpchr[33];
		    for(i=0;i<spbmnum;i++){
			strcat(errbuf,itoa(spbm[mode][smode][0][i],tmpchr,10));
			if(i<spbmnum-1)strcat(errbuf,",");
		    }
		}
			strcat(errbuf,") specified by mode...");
			report(errbuf);
		strcpy(errbuf,"smr_beams =");
		if(nosmrch==0){ int i; char tmpchr[33];
		    for(i=0;i<16;i++){
			if(spsmbm[mode][smode]&(0x0001<<i)){
				strcat(errbuf," ");
				strcat(errbuf,itoa(i,tmpchr,10));
			}
		    }
		}else{
				strcat(errbuf," default...");
		}
				strcat(errbuf,".");
			report(errbuf);
		sprintf(errbuf,"smrsep=%ld sec",smrsep);
			report(errbuf);
#if defined(LEICESTER) || defined(TIGER)
		sprintf(errbuf,"DAY_BAND=%d\n",DAY_BAND);
			report(errbuf);
		sprintf(errbuf,"NIGHT_BAND=%d\n",NIGHT_BAND);
			report(errbuf);
#else
		sprintf(errbuf,"DAY_FREQ=%d\n",DAY_FREQ);
			report(errbuf);
		sprintf(errbuf,"NIGHT_FREQ=%d\n",NIGHT_FREQ);
			report(errbuf);
#endif
		////////
		df1=df;
		df2=df;
		nf1=nf;
		nf2=nf;
		////////
		sprintf(errbuf,"df1/df2=%d, %d\n",df1,df2);
			report(errbuf);
		sprintf(errbuf,"nf1/nf2=%d, %d\n",nf1,nf2);
			report(errbuf);
		stf[0][0]=df1;
		stf[0][1]=df2;
		stf[1][0]=nf1;
		stf[1][1]=nf2;

#ifdef NIPR
	if(optset("nntp",opt)){
		//nntp=1;
		report("No NTP mode specified...");
	}
#endif
#if 0
	if((optset("fr",opt))||(optset("frang",opt))){
		day_frang=frang;
		night_frang=frang;
		sprintf(errbuf,"fixed frang %d specified...",frang);
		report(errbuf);
	}
	if((optset("mp",opt))||(optset("mpinc",opt))){
		day_mpinc=mpinc;
		night_mpinc=mpinc;
		sprintf(errbuf,"fixed mpinc %d specified...",mpinc);
		report(errbuf);
	}
#endif

   txpl = (rsep*20)/3;
#ifdef PULSE_CODE
   txpl = 500;
#endif


   report("Registering control Program.");
   register_program(SCHEDULE_NAME,OUR_NAME);
   if(scheduled()) report("Started by scheduler.");
   else            report("Started manually!");

  /* setup communication with the other tasks */
  
  report("Starting drivers.");
  start_up(DRIVER_NAME,RADOPS_DIO_NAME,ERRLOG_NAME);

  /* set the pulse and lag tables in the parameter block */

  report("Setting pulse table.");
  set_pulse(&raw_dt_buf,ptab,7);
  set_lag_table(&raw_dt_buf,lags,18); 

  /* close any raw or fit data files that may still be open */

  report("Closing any existing files.");
  read_clock(&yr,&mon,&day,&hr,&min,&sec,&msec,&usec);
  task_close(RAWWRITE,yr,mon,day,hr,min,sec);
  task_close(FITACF,yr,mon,day,hr,min,sec);
  task_close(ECHO_DATA,yr,mon,day,hr,min,sec);

  /* open new raw and fit data files */

  report("Opening first set of data files.");
  task_open(RAWWRITE,cmd_line,yr,mon,day,hr,min,sec);
  task_open(FITACF,cmd_line,yr,mon,day,hr,min,sec);
  task_open(ECHO_DATA,cmd_line,yr,mon,day,hr,min,sec);

#if defined(LEICESTER) || defined(TIGER)
//init_freq_bands();	<-- Julian, I moved this also to above, OK?
  init_proxy();
#else
//start_freq=day_start_freq;
#endif

#ifdef NIPR
  /* read our NTP table... by Sessai */
	//if(ntp_read(ERRLOG_NAME)==-1) exit(1);
	if(nntp==0){
		if(ntp_read(ERRLOG_NAME)==-1) exit(1);
	} else report("ignore NTP table...");
#endif

  /* show and check our restrict.freq table... by Sessai */
	//if(v>=1){
	show_forbid_freq(ERRLOG_NAME);
	//check_forbid_freq(ERRLOG_NAME,freq_range,
	//	day_start_freq,night_start_freq);
	//}

  /* setup default summary beams added by Sessai */

	//set_default_summary(ERRLOG_NAME,SUMMARY_NAME);
	get_summary(SUMMARY_NAME,&tmpA,&tmpB,&tmpP);
	sprintf(errbuf,"sd_summary b%ld,%ld,p%ld so far",tmpA,tmpB,tmpP);
	report(errbuf);
	if(nosmrch==0)
	put_summary(SUMMARY_NAME,spbm[mode][smode][0][0],SP_SMR_B,SP_SMR_P);
#if 1
	else {
	    //if(scheduled()==0){
		put_summary(SUMMARY_NAME,SMR_BEAM_A,SMR_BEAM_B,SMR_PWR);
	    //}
	}
		get_summary(SUMMARY_NAME,&tmpA,&tmpB,&tmpP);
		sprintf(errbuf,"sd_summary b%ld,%ld,p%ld now",tmpA,tmpB,tmpP);
		report(errbuf);
#endif

#ifdef DEBUG
  report("Opening Simulated data file.");
  sim_file=fopen(SIM_FILE,"r");
#endif

//#ifdef REPORT

   sprintf(errbuf,"day/night start hour %d/%d",day_start_hr,night_start_hr);
   report(errbuf);
#if defined(LEICESTER) || defined(TIGER)
   sprintf(errbuf,"day/night start band %d/%d",day_start_band,night_start_band);
   report(errbuf);
#else
   sprintf(errbuf,"day/night start freq %d/%d",day_start_freq,night_start_freq);
   report(errbuf);
#endif
   sprintf(errbuf,"day/night frang %d/%d",day_frang,night_frang);
   report(errbuf);
   sprintf(errbuf,"day/night mpinc %d/%d",day_mpinc,night_mpinc);
   report(errbuf);

   sprintf(errbuf,"intt %d, rsep %d, nrang %d",intt,rsep,nrang);
   report(errbuf);
   sprintf(errbuf,"wb_min %d, wb_sec %d",wb_min,wb_sec);
   report(errbuf);
   sprintf(errbuf,"start_beam %d, end_beam %d",start_beam,end_beam);
   report(errbuf);

//#endif

  report("Entering main loop...");
  do {

    int bi,bj;

    read_clock(&yr,&mon,&day,&hr,&min,&sec,&msec,&usec);

	if(v>=1)fprintf(stderr,"%d/%02d/%02d %02d:%02d:%02d.%03d%03d...",
			yr,mon,day,hr,min,sec,msec,usec);

    /* check if we need to open new files */

    if (test_hour(2) !=0) {
      report("Opening new set of data files.");
      task_close(RAWWRITE,yr,mon,day,hr,min,sec);
      task_close(FITACF,yr,mon,day,hr,min,sec);
      task_close(ECHO_DATA,yr,mon,day,hr,min,sec);
      task_open(RAWWRITE,cmd_line,yr,mon,day,hr,min,sec);
      task_open(FITACF,cmd_line,yr,mon,day,hr,min,sec);
      task_open(ECHO_DATA,cmd_line,yr,mon,day,hr,min,sec);
    }

#ifdef NIPR
    /* NTP_check... by Sessai */
	//if( ntp_check(hr,min,sec,msec) ) continue;
	////else if(v>=1) fprintf(stderr,"go...\n");
	if(nntp==0){
		if( ntp_check(hr,min,sec,msec) ) continue;
	}
#endif
	if(v>=1) fprintf(stderr,"go...\n");

    /* check to see if we need to update the day and night params */
 
    day_night_flag=day_or_night(day_start_hr,night_start_hr);
    if (day_night_flag == NIGHT_FLAG) {
#if defined(LEICESTER) || defined(TIGER)
      start_freq=lsfreq[night_start_band];
      freq_range=lfreq_range[night_start_band];
#else
      start_freq=night_start_freq;
#endif
      frang = night_frang;
      mpinc = night_mpinc;
    } else {
#if defined(LEICESTER) || defined(TIGER)
      start_freq=lsfreq[day_start_band];
      freq_range=lfreq_range[day_start_band];
#else
      start_freq=day_start_freq;
#endif
      frang = day_frang;
      mpinc = day_mpinc;
    }

    //set_mode(yr,mon,day,hr,min,sec);
    if(optset("force_mode",opt)==0)
	set_mode1(yr,mon,day);
    if(optset("force_submode",opt)==0)
	set_mode2(hr,min,sec);
    if((optset("it",opt))==0&&(optset("intt",opt)==0))
	intt=spintt[mode][smode];
    start_beam=spstbm[mode][smode];
    end_beam  =spedbm[mode][smode];

    /* record beam numbers if not usual */
    if ((start_beam != START_BEAM) || (end_beam != END_BEAM)) {
      usr_resS2=start_beam;
      usr_resS3=end_beam;
    }

    /* test whether we should perform xcf */

    if (xcount > 0) {
      ++count;
      if(count == xcount) {
        xcf = 1;
        count = 0;
      } else xcf= 0;
    } else xcf = 0;

//  skip_beam=calc_skip2(wb_min,wb_sec);

    if(sponly[mode][smode]){
		scan=1;
	// for(bi...) loop is just a dummy to avoid vlptm from crashing...
	for(bi=0;bi<SPBMMAX;bi++){
		spbmc++;
		if(spbmc==spbmnum)spbmc=0;
		//if(spbm[mode][smode][0][spbmc]==-1)spbmc=0;
		bmc=spbm[mode][smode][0][spbmc];
		//if((bmc<0)||(bmc>=16))continue;
		if((exit_poll=onebeam(bmc))!=0) break;
		scan=DEFAULT_SP_SCAN;
	}
    } else {
     bm_scan_sign=((start_beam>end_beam) ? -1 : 1);
     //if( (start_beam+bm_scan_sign*skip_beam-end_beam)*bm_scan_sign >0 )
		skip_beam=0;
	spbmc2=0;
	fnc=(fnc+1)%2;
     for(bi=0;bi<2;bi++){
      for(bj=0+bi;bj<4;bj+=2){
       for(bmc=start_beam+bm_scan_sign*bj;
		(end_beam-bmc)*bm_scan_sign>=0;bmc+=bm_scan_sign*4) {

	if(bmc==start_beam)
		scan=1;
	else {
		scan=0;
		if(one_of_spec(bmc))continue;
	}
#if defined(LEICESTER) || defined(TIGER)
		start_freq=lsfreq[stf[day_night_flag][fnc]];
		freq_range=lfreq_range[stf[day_night_flag][fnc]];
#else
		start_freq=stf[day_night_flag][fnc];
#endif
	if((exit_poll=onebeam(bmc))!=0) break;

	spbmc++;
	//if((spbmc==spbmnum)||(spbm[mode][smode][0][spbmc]==-1))spbmc=0;
	if((spbmc==spbmnum)||(spbm[mode][smode][0][spbmc]==-1)){
		fsc=(fsc+1)%2;
		spbmc=0;
	}
	if((spbm[mode][smode][0][spbmc]<0)||(spbm[mode][smode][0][spbmc]>=16))continue;
		if(spbmc2==spbm[mode][smode][1][spbmc])scan=0;
		else				scan=DEFAULT_SP_SCAN;
	spbmc2++;
#if defined(LEICESTER) || defined(TIGER)
		start_freq=lsfreq[stf[day_night_flag][fsc]];
		freq_range=lfreq_range[stf[day_night_flag][fsc]];
#else
		start_freq=stf[day_night_flag][fsc];
#endif
	if((exit_poll=onebeam(spbm[mode][smode][0][spbmc]))!=0) break;
       }
	if(exit_poll) break;
      }
	if(exit_poll) break;
     }
    }

    /* wait on two minute boundary */

    if (exit_poll==0) {
      read_clock(&yr,&mon,&day,&hr,&min,&sec,&msec,&usec);
	if(v>=1)fprintf(stderr,
		"%d/%02d/%02d %02d:%02d:%02d.%03d%03d...wb%d:%02d...\n",
			yr,mon,day,hr,min,sec,msec,usec,wb_min,wb_sec);
      wait_boundary2(wb_min,wb_sec);
    }

  } while (exit_poll==0);

  report("Shutdown detected.");

  /* get the last outstanding record from fitacf */

  if ((f=get_fit(FITBUFFER_NAME,&fit_dt_buf))!=frame_counter) {
     sprintf(errbuf,"Received fit data block %d",f);
     report(errbuf);
     task_write_fit(ECHO_DATA,&fit_dt_buf,1);
     frame_counter=f; /* count the number of fit data frames */
  } else report("No fit data waiting.");

  /* close files and exit */
  report("Closing data files.");
  task_close(RAWWRITE,yr,mon,day,hr,min,sec);
  task_close(FITACF,yr,mon,day,hr,min,sec);
  task_close(ECHO_DATA,yr,mon,day,hr,min,sec);

  /* back to the previous sd_summary setting... by Sessai */
	//if((nosmrch==0)||(smrsep>0L)){
		//put_summary(SUMMARY_NAME,SMR_BEAM_A,SMR_BEAM_B,SMR_PWR);
		put_summary(SUMMARY_NAME,tmpA,tmpB,tmpP);
	//}
		get_summary(SUMMARY_NAME,&tmpA,&tmpB,&tmpP);
		sprintf(errbuf,"sd_summary b%ld,%ld,p%ld now",tmpA,tmpB,tmpP);
		report(errbuf);

  report("Exiting control program.");
  report("================================");
  exit(0);
}

int one_of_spec(int bmc){
	int i,bingo;
	i=0;
	bingo=0;
	while(i<spbmnum && spbm[mode][smode][0][i]!=-1){
		if(bmc==spbm[mode][smode][0][i]){
			bingo++;
			break;
		}
		i++;
	}
	return bingo;
}

int onebeam(int bmc) {
      int status;
      static long int tmpAnow=-1L,tmpBnow=-1L;

      bmnum=bmc;

      if(v>=2){
	if(scan==0||scan==1) fprintf(stderr,"Beam%02d:",bmnum);
	else                 fprintf(stderr,"SPBM%02d:",bmnum);
      }

      end_freq=start_freq+freq_range;

      /* set the radar parameter block up */

      set_block(&raw_dt_buf);

      set_time(&raw_dt_buf);
      if(v>=2)fprintf(stderr,"%02d:%02d:%02d:",
	raw_dt_buf.PARMS.HOUR,raw_dt_buf.PARMS.MINUT,raw_dt_buf.PARMS.SEC);

////////////////////////////////////////////////////////////////////////////
//#ifdef DEBUG
      //if(v>=1){...}
      if(v>=2){
	//sprintf(errbuf,"%02d:%02d:%02d:B%d:scan%d",
	//	raw_dt_buf.PARMS.HOUR,raw_dt_buf.PARMS.MINUT,
	//	raw_dt_buf.PARMS.SEC,bmnum,scan);
	sprintf(errbuf,"%02d:%02d:%02d:B%d,F%d,scan%d",
		raw_dt_buf.PARMS.HOUR,raw_dt_buf.PARMS.MINUT,
		raw_dt_buf.PARMS.SEC,bmnum,start_freq,scan);
//#ifdef NIPR
	reportS(errbuf);	// new in control.lib!
//#else
//	report(errbuf);
//#endif
      }
//#endif
////////////////////////////////////////////////////////////////////////////

      if(v>=3)fprintf(stderr,"fclr..");
      status=fclr(&raw_dt_buf,start_freq,end_freq,DEFAULT_FREQ_STEP);
#ifdef DEBUG
	dum1=raw_dt_buf.PARMS.TFREQ;
	dum2=raw_dt_buf.PARMS.NOISE;
#endif

#if defined(LEICESTER) || defined(TIGER)
   read_uconts();
#endif

#ifdef PULSE_CODE
      if (status==0) status=pulse_code(&raw_dt_buf,nbaud,code);
#else
      if (status==0) {
	if(v>=3)fprintf(stderr,"Tx%d..",raw_dt_buf.PARMS.INTT);
	status=radar(&raw_dt_buf);
      }
#endif
      else	report("fclr failed! NoTx!.");

      if(v>=3)fprintf(stderr,"gs..");
      get_status(RADOPS_DIO_NAME,&raw_dt_buf,0);

#ifdef DEBUG
      if (sim_file !=NULL) {
        if (read_raw_data(sim_file,&raw_dt_buf) !=0) {
	   if(v>=3)fprintf(stderr,"reached end of sim. file!..");
           fclose(sim_file);
           sim_file=fopen(SIM_FILE,"r");
        }
	raw_dt_buf.PARMS.TFREQ=dum1;
	raw_dt_buf.PARMS.NOISE=dum2;
      }
#endif

 	  /* send the raw data to the other tasks */
      if(v>=3)fprintf(stderr,"twr..");
      task_write_raw(RAWWRITE,&raw_dt_buf,1);
      task_write_raw(FITACF,&raw_dt_buf,1);
      task_write_raw(ECHO_DATA,&raw_dt_buf,1);
      task_write_aux(ECHO_DATA,prg_name,strlen(prg_name)+1);

      if(v>=3)fprintf(stderr,"gf..");
      if ((f=get_fit(FITBUFFER_NAME,&fit_dt_buf))!=frame_counter) {
        if(v>=3)fprintf(stderr,"%2d(%d)..",fit_dt_buf.prms.BMNUM,f);
	  /* set summary beam again if needed */
	if(nosmrch==0){
	    if(spsmbm[mode][smode]&(0x0001<<fit_dt_buf.prms.BMNUM)){
		clock_gettime(CLOCK_REALTIME,&rtc);
		nowc = (time_t) rtc.tv_sec;
		if (nowc-smlast[(short int)fit_dt_buf.prms.BMNUM]>=smrsep){
		    smlast[(short int)fit_dt_buf.prms.BMNUM]=nowc;
		    if((fit_dt_buf.prms.BMNUM!=tmpAnow)&&(fit_dt_buf.prms.BMNUM!=tmpBnow)){
			if(v>=3)fprintf(stderr,"ps%d..",fit_dt_buf.prms.BMNUM);
			if(put_summary(SUMMARY_NAME,
				fit_dt_buf.prms.BMNUM,SP_SMR_B,SP_SMR_P)==0){
				tmpAnow=fit_dt_buf.prms.BMNUM;
				tmpBnow=SP_SMR_B;
			} else {
				if(v>=3)report("psFAILED!");
			}
		    }
		} else {
			if((tmpAnow!=-1L)||(tmpBnow!=-1L)){
				put_summary(SUMMARY_NAME,-1L,-1L,SP_SMR_P);
				tmpAnow=-1L; tmpBnow=-1L;
			}
		}
	    } else {
			if((tmpAnow!=-1L)||(tmpBnow!=-1L)){
				put_summary(SUMMARY_NAME,-1L,-1L,SP_SMR_P);
				tmpAnow=-1L; tmpBnow=-1L;
			}
	    }
	} else {
	  if(smrsep > 0L){
	    if((fit_dt_buf.prms.BMNUM==tmpA)||(fit_dt_buf.prms.BMNUM==tmpB)){
		clock_gettime(CLOCK_REALTIME,&rtc);
		nowc = (time_t) rtc.tv_sec;
		if (nowc-smlast[(short int)fit_dt_buf.prms.BMNUM]>=smrsep){
		    smlast[(short int)fit_dt_buf.prms.BMNUM]=nowc;
		    if((fit_dt_buf.prms.BMNUM!=tmpAnow)&&(fit_dt_buf.prms.BMNUM!=tmpBnow)){
			if(v>=3)fprintf(stderr,"ps%d..",fit_dt_buf.prms.BMNUM);
			if(put_summary(SUMMARY_NAME,tmpA,tmpB,SP_SMR_P)==0){
				tmpAnow=tmpA; tmpBnow=tmpB;
			} else {
				if(v>=3)report("psFAILED!");
				tmpAnow=-9L; tmpBnow=-9L;
			}
		    }
		} else {
			if((tmpAnow!=-1L)||(tmpBnow!=-1L)){
				put_summary(SUMMARY_NAME,-1L,-1L,SP_SMR_P);
				tmpAnow=-1L; tmpBnow=-1L;
			}
		}
	    }else{
			if((tmpAnow!=-1L)||(tmpBnow!=-1L)){
				put_summary(SUMMARY_NAME,-1L,-1L,SP_SMR_P);
				tmpAnow=-1L; tmpBnow=-1L;
			}
	    }
	  }
	}

 	  /* send fit data to echo_data */
         if(v>=3)fprintf(stderr,"twf..");
         task_write_fit(ECHO_DATA,&fit_dt_buf,1);
         frame_counter=f; /* count the number of fit data frames */
      } else report("No fit data waiting.");

      if(v>=3)fprintf(stderr,"EO1B\n");
      if(v>=4)show_data_list(stderr,&raw_dt_buf,&fit_dt_buf,nrang,
			start_freq,freq_range,fitOK,v-3);

      //if(v>=3)fprintf(stderr,"ui..");
#if defined(LEICESTER) || defined(TIGER)
//    exit_poll=user_int(&raw_dt_buf,...)
      status=user_int(&raw_dt_buf,
      "start_beam i end_beam i \
       day_start_band i night_start_band i \
       day_frang i night_frang i day_mpinc i \
       night_mpinc i start_freq i end_freq i",
       &start_beam,&end_beam,
       &day_start_band,&night_start_band,
       &day_frang,&night_frang,
       &day_mpinc,&night_mpinc,&start_freq,&end_freq);
#else
//    exit_poll=user_int(&raw_dt_buf,...)
      status=user_int(&raw_dt_buf,
      "start_beam i end_beam i \
       day_start_freq i night_start_freq i \
       day_frang i night_frang i day_mpinc i \
       night_mpinc i start_freq i end_freq i",
       &start_beam,&end_beam,
       &day_start_freq,&night_start_freq,
       &day_frang,&night_frang,
       &day_mpinc,&night_mpinc,&start_freq,&end_freq);
#endif

      set_vars(&raw_dt_buf);

    return status;

}

   /* build the command line string */

void set_cmd_line(int argc,char *argv[]) {
  strcpy(cmd_line,argv[0]);
  if(argc>1){
    int c;
    for (c=1;c<argc;c++) {
      strcat(cmd_line," ");
      strcat(cmd_line,argv[c]);
    }
  }
  sprintf(errbuf,"Command Line:%s",cmd_line);
  report(errbuf);
  return;
}

   /* set the program name on the display */

void set_prg_name(char *argv0) {
#if 0
   strcpy(prg_name,"normal_scan");
#else
   if(strrchr(argv0,'/')==NULL)
	strcpy(prg_name,argv0);
   else{
	static char tmpstr[64];
	strcpy(tmpstr,strrchr(argv0,'/'));
	strcpy(prg_name,&tmpstr[1]);
   }
	sprintf(errbuf,"prg_name=%s",prg_name);
	report(errbuf);
#endif
   return;
}

void set_mode(int yr,int mon,int day,int hr,int min,int sec){

//unsigned long spdate[MODEMAX]={20000203,20000208,20000213,20000224}
//short int sptgate[MODEMAX][SUBMODEMAX-1]={{12},{24},{24},{24}};

	unsigned long datenow;
	int i;

	//if(yr<100)yr+=1900;
	datenow=(unsigned long)yr*100+(unsigned long)mon*10+(unsigned long)day;

	for(i=0;i<MODEMAX;i++){
		if((i==0)&&(datenow<=spdate[i]))break;
		if((i!=0)&&(spdate[i-1]<datenow && datenow<=spdate[i]))break;
	}
	mode=i;
	last_mode=mode;

	for(i=0;i<SUBMODEMAX-1;i++){
		if((i==0)&&(hr<sptgate[mode][i]))break;
		if((i!=0)&&(sptgate[mode][i-1]<=hr && hr<sptgate[mode][i]))break;
		if((i==SUBMODEMAX-2)&&(sptgate[mode][i]<=hr)){i++;break;}
	}
	smode=i;
	last_smode=smode;

	return;
}

void set_mode1(int yr,int mon,int day){
	//unsigned long spdate[MODEMAX]={20000203,20000208,20000213,20000224};
	unsigned long datenow;
	int i;
	//if(yr<100)yr+=1900;
	datenow=(unsigned long)yr*10000+(unsigned long)mon*100+(unsigned long)day;
	for(i=0;i<MODEMAX;i++){
		if((i==0)&&(datenow<=spdate[i]))break;
		if((i!=0)&&(spdate[i-1]<datenow && datenow<=spdate[i]))break;
	}
	mode=i;
	if(mode!=last_mode){
		if(last_mode==-1)
			sprintf(errbuf,"mode initialized, mode=%d",mode);
		else	sprintf(errbuf,"mode changed from %d to %d",
							last_mode,mode);
		report(errbuf);
	}
	last_mode=mode;
	return;
}

void set_mode2(int hr,int min,int sec){
	//short int sptgate[MODEMAX][SUBMODEMAX-1]={{12},{24},{24},{24}};
	int i;
	for(i=0;i<SUBMODEMAX-1;i++){
		if((i==0)&&(hr<sptgate[mode][i]))break;
		if((i!=0)&&(sptgate[mode][i-1]<=hr && hr<sptgate[mode][i]))break;
		if((i==SUBMODEMAX-2)&&(sptgate[mode][i]<=hr)){i++;break;}
	}
	smode=i;
	if(smode!=last_smode){
		sprintf(errbuf,"mode is now %d",mode);
			report(errbuf);
		if(last_smode==-1)
			sprintf(errbuf,"smode initialized, smode=%d",smode);
		else	sprintf(errbuf,"smode changed from %d to %d",
							last_smode,smode);
			report(errbuf);
	}
	last_smode=smode;
	return;
}

void report(char *str) {
// #ifdef REPORT
  //log_error(ERRLOG_NAME,"control",str);
  log_errorS(ERRLOG_NAME,"control",str,1);
// #endif
}

void reportS(char *str) {
  //log_error2(ERRLOG_NAME,"control",str);
  log_errorS(ERRLOG_NAME,"control",str,0);
}