
#include "configuration.h"
#include <stdio.h>
#include <unistd.h>
#include "telemetry.h"
#include <sys/wait.h>



extern float latitude;
extern int dive_num;
int deviation_fog, deviation_compass, declination_fog, declination_compass;
extern int arm_time_constant, cam_time_constant;
extern char enable_overlay_string[100], insert_overlay_string[100];

extern Vehicle vehicle;

string page_string[4];


// The total number of element information needed to create an
// I/O type element in database
const int ELEM_INFO_NUM = 21;
char backup_filename[128];

/* Constructor */
Configuration::Configuration()
{
     	
}

/* Destructor */
Configuration::~Configuration()
{

}

/*********************************************************************************************
*  bool parse_and_create_elem(IOelementContriol ioElementControl, char some_string[])
*
* This function parse a string into elements and then insert them into the
* element I/O database and then returns 'true'
*
*********************************************************************************************/
bool
parse_and_create_elem (IOElementControl& io_elem_control, char some_string[])
{

   char *ptr;
   int i = 0;
   string temp[ELEM_INFO_NUM];

      ptr = strtok(some_string, "|" );
      while (ptr)
      {
         //cout << ptr << " ";
         temp[i] = ptr;
         i++;
         ptr = strtok(NULL, "|" );
      }
      //cout <<"\n";

      // Convert all the char* type to its corrent type so that we can insert
      // them to database using function call 'make'  that takes 21 arguments


   int surfVehicle = atoi(temp[0].c_str());
   int digAnalog = atoi(temp[1].c_str());
   int element_num = atoi(temp[2].c_str());
   string element_name(temp[3]);
   string defaults(temp[4]);	
   int default_level = atoi(temp[5].c_str());	
   bool enable_channel = atoi(temp[6].c_str());
   bool	auto_calibrate_enable = atoi(temp[7].c_str());
   bool enable_graphics = atoi(temp[8].c_str());
   int digital_value = 0;
   float analog_value = 0.0;
   float analog_raw = 0.0;
   float analog_offset = atof(temp[12].c_str());
   float p_gain = atof(temp[13].c_str());
   float i_gain = atof(temp[14].c_str());
   float d_gain = atof(temp[15].c_str());
   string graphic_type(temp[16].c_str());
   int color = atoi(temp[17].c_str());
   int x = atoi(temp[18].c_str());
   int y = atoi(temp[19].c_str());
   int vga_screen = atoi(temp[20].c_str());

    if (element_num == 0) { return false;}


   // cout <<"configuration.cpp. defaults : " <<defaults<<endl;

  // create a new element
  IOElement io_element;
  io_element.make( surfVehicle,
 		digAnalog,
   		element_num,
 		element_name,
		defaults,
		default_level,
		enable_channel,
		auto_calibrate_enable,
		enable_graphics,
		digital_value,
		analog_value,
		analog_raw,
		analog_offset,
		p_gain,
		i_gain,
		d_gain,
		graphic_type,
		color,
		x,
		y,
		vga_screen );

   return io_elem_control.pushElement(io_element);

}


/*-------------------------------------------------------------------------------------
 * Note : This parsing function is different from other parsing functuion because
 	  it contains 2 different type of string needed to be parsed
 	  this string will have " " as delimeter, the string "some_string"
 	  supposedly contains the $surfVeh $digAnal $element_num and $output_string
 	  output_string looks like :
 	  1|0|3|4... --> board#|elem#|board#|elem#... if it's from surface and
 	  Graphic  ---> output from vehicle
 	
 *-------------------------------------------------------------------------------------*/


bool
parse_and_create_output (IOElementControl& io_elem_control, char some_string[])
{
   char *ptr;
   int count = 0;
   string temp[ELEM_INFO_NUM];

      ptr = strtok(some_string, " " );
      while (ptr)
      {
         //cout << ptr << " ";
         temp[count] = ptr;
         count++;
         ptr = strtok(NULL, " " );
      }
      //cout <<"\n";

      int surveh = atoi(temp[0].c_str());
      int diganal = atoi(temp[1].c_str());
      int elem_num = atoi(temp[2].c_str());
      char out_string[100];



      strcpy(out_string, temp[3].c_str());
      //cout <<"element is "<<surveh<<" "<<diganal<<" "<<elem_num<<endl;
      //cout <<"output is "<<out_string<<endl;

      io_elem_control.make_input_output(surveh, diganal, elem_num, out_string);
   //   io_elem_control.dump_output();

      return true;





}


char*
write_output(IOElementControl& ioElementControl, char some_string [])
{
   char *ptr;
   int count = 0;
   string temp[ELEM_INFO_NUM];

   string temp_out;
   static char out_string[100];

      ptr = strtok(some_string, "|" );
      while (ptr)
      {
         //cout << ptr << " ";
         temp[count] = ptr;
         count++;
         ptr = strtok(NULL, "|" );
      }
     //cout <<"\n";
	
      int surveh = atoi(temp[0].c_str());
      int diganal = atoi(temp[1].c_str());
      int elem_num = atoi(temp[2].c_str());

      temp_out = ioElementControl.display_output(surveh, diganal, elem_num);

      sprintf(out_string, "%d %d %d %s", surveh, diganal, elem_num, temp_out.c_str());

      return out_string;




}


bool
parse_and_set_button (IOElementControl& ioElementControl, char some_string [])
{
   char *ptr;
   int count = 0;
   string temp[20];

   string temp_out;

      ptr = strtok(some_string, "|" );
      while (ptr)
      {
         //cout << ptr << " ";
         temp[count] = ptr;
         count++;
         ptr = strtok(NULL, "|" );
      }
      //cout <<"\n";

      string name = temp[0];
      string type = temp[1];
      int board = atoi (temp[2].c_str());
      int elem_num = atoi (temp[3].c_str());
      int x = atoi(temp[4].c_str());
      int y = atoi(temp[5].c_str());
      string color = temp[6];
      int state = 0;
      int x2 = atoi(temp[8].c_str());
      int y2 = atoi(temp[9].c_str());


   ioElementControl.add_to_button_db(name, type, board, elem_num, x, y, color, state, 1);
   ioElementControl.add_to_button_db(name, type, board, elem_num, x2, y2, color, state, 2);


   return true;

}

bool
parse_and_set_bardetail (IOElementControl& ioElementControl, char some_string [])
{
   char *ptr;
   int count = 0;
   float temp[20];

   string temp_out;

      ptr = strtok(some_string, "|" );
      while (ptr)
      {
         //cout << ptr << " ";
         temp[count] = atof(ptr);
         count++;
         ptr = strtok(NULL, "|" );
      }
      //cout <<"\n";

      // bar string is "elem_num| max | min |ave | yrange |rrange"
      int elem_num = (int)temp[0];

      float max = temp[1];
      float min = temp[2];
      float ave = temp[3];
      float yrange = temp[4];
      float rrange = temp[5];

      //cout <<"configuration.cpp: Must have been reading the non bargraph elem num : "<<elem_num<<endl;
	
      ioElementControl.setting_bar_detail(elem_num, max, min, ave, yrange, rrange);

      return true;
}

bool parse_and_set_graphic  (string type, char some_string[])
{
   char* ptr;
   int count = 0;
   string temp[20];

      ptr = strtok(some_string, "|" );
      while (ptr)
      {
        // cout << ptr << " ";
         temp[count] = ptr;
         count++;
         ptr = strtok(NULL, "|" );
      }
      //cout <<"\n";

        int x1 = atoi(temp[0].c_str());
      	int y1 = atoi(temp[1].c_str());
      	int  x2 = atoi(temp[2].c_str());
      	int  y2 = atoi(temp[3].c_str());
      	 	
 	
 	if ( type == "compass" )
 	{
 		//------------------------ 	
                // FOG
                //------------------------
                // Screen 1
                graph.set_graphic_info ( "compass", temp[4], x1, y1, 1 );
                // Screen 2
                graph.set_graphic_info ( "compass", temp[4], x2, y2, 2 );

                //------------------------
                // Backup Compass
                //------------------------
                int x3 = atoi(temp[5].c_str());
		int y3 = atoi(temp[6].c_str());
      		int x4 = atoi(temp[7].c_str());
		int y4 = atoi(temp[8].c_str());
      	
                // Screen 1
                graph.set_graphic_info ( "compass", temp[9], x3, y3, 1 );
                // Screen 2
                graph.set_graphic_info ( "compass", temp[9], x4, y4, 2 );
                return true;                                                                                                 		
 	}

 	if ( type == "vehicle" )
 	{
                // Screen 1
                graph.set_graphic_info ( "vehicle", "veh1", x1, y1, 1 );
                // Screen 2
                graph.set_graphic_info ( "vehicle", "veh2", x2, y2, 2 );
                return true;                                                                                                 		
 	}

 	
 	if (type == "tms")
 	{
 		graph.tmsx1 = x1;
 	        graph.tmsy1 = y1;
 	        graph.tmsx2 = x2;
 	        graph.tmsy2 = y2;
 	
 		return true;
 	
 	}
 	
 	
 	return false;

}





bool
parse_and_set_light (int screen, char some_string[])
{
   char *ptr;
   int count = 0;
   int temp[50];

      ptr = strtok(some_string, "|" );
      while (ptr)
      {
         //cout << ptr << " ";
         temp[count] = atoi(ptr);
         count++;
         ptr = strtok(NULL, "|" );
      }
      //cout <<"\n";


      	int x = temp[0];
      	int y = temp[1];
      	int  x1 = temp[2];
      	int  x2 = temp[3];
      	int  x3 = temp[4];
      	int  x4 = temp[5];
      	int  x5 = temp[6];
      	int  x6 = temp[7];
      	int  x7 = temp[8];
      	int  x8 = temp[9];
      	int  x9 = temp[10];
      	int  x10 = temp[11];
      	int  y1 = temp[12];
      	int  y2 = temp[13];
      	int  y3 = temp[14];
      	int  y4 = temp[15];
      	int  y5 = temp[16];
      	int  y6 = temp[17];
      	int  y7 = temp[18];
      	int  y8 = temp[19];
      	int  y9 = temp[20];
      	int  y10 = temp[21];
      		
      	graph.set_light_db (  screen,  x,  y,
     		 x1,  x2,  x3,  x4,  x5,  x6,  x7,  x8,  x9,  x10,     		
     		 y1,  y2,  y3,  y4,  y5,  y6,  y7,  y8,  y9, y10 );
     		

     	return true;

}




bool
parse_and_set_slidebar (IOElementControl& ioElementControl, char some_string[])
{
   char *ptr;
   int count = 0;
   string temp[20];

   string temp_out;

      ptr = strtok(some_string, "|" );
      while (ptr)
      {
         //cout << ptr << " ";
         temp[count] = ptr;
         count++;
         ptr = strtok(NULL, "|" );
      }
      //cout <<"\n";

      string name = temp[0];

      int board = atoi(temp[1].c_str());
      int elem_num = atoi(temp[2].c_str());
      float value = 0.0;
      int x = atoi(temp[4].c_str());
      int y = atoi(temp[5].c_str());
      string color = temp[6];
      int x2 = atoi(temp[7].c_str());
      int y2 = atoi(temp[8].c_str());

   ioElementControl.add_to_slidebar_db(name, board, elem_num, value, x, y, color, 1);
   ioElementControl.add_to_slidebar_db(name, board, elem_num, value, x2, y2, color, 2);


	return true;
}



bool
parse_and_set_control (string type, char some_string[])
{
   char *ptr;
   int count = 0;
   string temp[60];

   char temp_str[512];
   snprintf (temp_str, 512, "%s", some_string);
    	
      ptr = strtok(some_string, "|" );
      while (ptr)
      {
         temp[count] = ptr;
         count++;
         ptr = strtok(NULL, "|" );
      }
      //cout <<"\n\n";



   if (type == "Camera")
   {
   	// the following are bottom output channels
    	vehicle.camera.sin_shoulder_channel = atoi(temp[0].c_str());
    	vehicle.camera.cos_shoulder_channel = atoi(temp[1].c_str());
    	vehicle.camera.offset_shoulder = atof(temp[2].c_str());
    	// the following are the top input channels
    	vehicle.camera.command_shoulder_channel_top = atoi(temp[3].c_str());
   	vehicle.camera.master_shoulder = atof(temp[4].c_str());
    	vehicle.camera.feedback_shoulder = atof(temp[5].c_str());
    	vehicle.camera.shoulder_servo_channel_bot = atoi(temp[6].c_str());
    	vehicle.camera.p_shoulder = atof(temp[7].c_str());
    	vehicle.camera.i_shoulder = atof(temp[8].c_str());
    	vehicle.camera.d_shoulder = atof(temp[9].c_str());

    	// the following are bottom output channels
    	vehicle.camera.sin_pan_channel = atoi(temp[10].c_str());
    	vehicle.camera.cos_pan_channel = atoi(temp[11].c_str());
    	vehicle.camera.offset_pan = atof(temp[12].c_str());
     	// the following are the top input channels
    	vehicle.camera.command_pan_channel_top = atoi(temp[13].c_str());
    	vehicle.camera.master_pan = atof(temp[14].c_str());
    	vehicle.camera.feedback_pan = atof(temp[15].c_str());
    	vehicle.camera.pan_servo_channel_bot = atoi(temp[16].c_str());
    	vehicle.camera.p_pan = atof(temp[17].c_str());
    	vehicle.camera.i_pan = atof(temp[18].c_str());
    	vehicle.camera.d_pan = atof(temp[19].c_str());

	// the following are bottom output channels
    	vehicle.camera.sin_tilt_channel = atoi(temp[20].c_str());
    	vehicle.camera.cos_tilt_channel = atoi(temp[21].c_str());
    	vehicle.camera.offset_tilt = atof(temp[22].c_str());
    	// the following are the top input channels
    	vehicle.camera.command_tilt_channel_top = atoi(temp[23].c_str());
    	vehicle.camera.master_tilt = atof(temp[24].c_str());
    	vehicle.camera.feedback_tilt = atof(temp[25].c_str());
    	vehicle.camera.tilt_servo_channel_bot = atoi(temp[26].c_str());
    	vehicle.camera.p_tilt = atof(temp[27].c_str());
    	vehicle.camera.i_tilt = atof(temp[28].c_str());
    	vehicle.camera.d_tilt = atof(temp[29].c_str());
    	
    	vehicle.camera.cam_string = string(temp_str);
    	
    	
    	return true;

    }


   if (type == "Arm")
   {
    	/* the following are bottom output channels */
    	vehicle.arm.sin_shoulder_channel = atoi(temp[0].c_str());
    	vehicle.arm.cos_shoulder_channel = atoi(temp[1].c_str());
    	vehicle.arm.offset_shoulder = atof(temp[2].c_str());
    	/* the following are the top input channels */
    	vehicle.arm.command_shoulder_channel_top = atoi(temp[3].c_str());
   	vehicle.arm.master_shoulder = atof(temp[4].c_str());
    	vehicle.arm.feedback_shoulder = atof(temp[5].c_str());
    	vehicle.arm.shoulder_servo_channel_bot = atoi(temp[6].c_str());
    	vehicle.arm.p_shoulder = atof(temp[7].c_str());
    	vehicle.arm.i_shoulder = atof(temp[8].c_str());
    	vehicle.arm.d_shoulder = atof(temp[9].c_str());

    	/* the following are bottom output channels */
    	vehicle.arm.sin_swing_channel = atoi(temp[10].c_str());
    	vehicle.arm.cos_swing_channel = atoi(temp[11].c_str());
    	vehicle.arm.offset_swing = atof(temp[12].c_str());
     	/* the following are the top input channels */
    	vehicle.arm.command_swing_channel_top = atoi(temp[13].c_str());
    	vehicle.arm.master_swing = atof(temp[14].c_str());
    	vehicle.arm.feedback_swing = atof(temp[15].c_str());
    	vehicle.arm.swing_servo_channel_bot = atoi(temp[16].c_str());
    	vehicle.arm.p_swing = atof(temp[17].c_str());
    	vehicle.arm.i_swing = atof(temp[18].c_str());
    	vehicle.arm.d_swing = atof(temp[19].c_str());

	/* the following are bottom output channels */
    	vehicle.arm.sin_elbow_channel = atoi(temp[20].c_str());
    	vehicle.arm.cos_elbow_channel = atoi(temp[21].c_str());
    	vehicle.arm.offset_elbow = atof(temp[22].c_str());
    	/* the following are the top input channels */
    	vehicle.arm.command_elbow_channel_top = atoi(temp[23].c_str());
    	vehicle.arm.master_elbow = atof(temp[24].c_str());
    	vehicle.arm.feedback_elbow = atof(temp[25].c_str());
    	vehicle.arm.elbow_servo_channel_bot = atoi(temp[26].c_str());
    	vehicle.arm.p_elbow = atof(temp[27].c_str());
    	vehicle.arm.i_elbow = atof(temp[28].c_str());
    	vehicle.arm.d_elbow = atof(temp[29].c_str());
    	
    	/* the following are bottom output channels */
    	vehicle.arm.sin_pitch_channel = atoi(temp[30].c_str());
    	vehicle.arm.cos_pitch_channel = atoi(temp[31].c_str());
    	vehicle.arm.offset_pitch = atof(temp[32].c_str());
    	/* the following are the top input channels */
    	vehicle.arm.command_pitch_channel_top = atoi(temp[33].c_str());
    	vehicle.arm.master_pitch = atof(temp[34].c_str());
    	vehicle.arm.feedback_pitch = atof(temp[35].c_str());
    	vehicle.arm.pitch_servo_channel_bot = atoi(temp[36].c_str());
    	vehicle.arm.p_pitch = atof(temp[37].c_str());
    	vehicle.arm.i_pitch = atof(temp[38].c_str());
    	vehicle.arm.d_pitch = atof(temp[39].c_str());

    	/* the following are bottom output channels */
    	vehicle.arm.sin_yaw_channel = atoi(temp[40].c_str());
    	vehicle.arm.cos_yaw_channel = atoi(temp[41].c_str());
    	vehicle.arm.offset_yaw = atof(temp[42].c_str());
    	/* the following are the top input channels */
    	vehicle.arm.command_yaw_channel_top = atoi(temp[43].c_str());
    	vehicle.arm.master_yaw = atof(temp[44].c_str());
    	vehicle.arm.feedback_yaw = atof(temp[45].c_str());
    	vehicle.arm.yaw_servo_channel_bot = atoi(temp[46].c_str());
    	vehicle.arm.p_yaw = atof(temp[47].c_str());
    	vehicle.arm.i_yaw = atof(temp[48].c_str());
    	vehicle.arm.d_yaw = atof(temp[49].c_str());

        vehicle.arm.arm_string = string(temp_str);
    	
    	return true;

    }


   if (type == "Auto")
     {
          vehicle.autopilot.foreaft_ch = atoi(temp[0].c_str());
          vehicle.autopilot.turns_ch = atoi(temp[1].c_str());

     	/* digital input */
          vehicle.autopilot.autoHead_ch = atoi(temp[2].c_str());
          vehicle.autopilot.autoDepth_ch = atoi(temp[3].c_str());
          vehicle.autopilot.autoAltitude_ch = atoi(temp[4].c_str());
          vehicle.autopilot.autoCruise_ch = atoi(temp[5].c_str());
          vehicle.autopilot.depthJogUp_ch = atoi(temp[6].c_str());
          vehicle.autopilot.depthJogDown_ch = atoi(temp[7].c_str());

      	/**** the following are coming from the bottom ***/
           vehicle.autopilot.headingSource = atoi(temp[8].c_str());	// 0 for gyro, 1 for compass
           vehicle.autopilot.depthTransducer = atoi(temp[9].c_str());	// digital channel???
           vehicle.autopilot.AltitudeSource = atoi(temp[10].c_str());	// 0 for alt #1, 1 for #2
           vehicle.autopilot.dvlInput = atoi(temp[11].c_str());

      	/**** the following are the pid's ****************/
           vehicle.autopilot.p_autoHead = atof(temp[12].c_str());
           vehicle.autopilot.i_autoHead = atof(temp[13].c_str());
           vehicle.autopilot.d_autoHead = atof(temp[14].c_str());
           vehicle.autopilot.p_autoDepth = atof(temp[15].c_str());
           vehicle.autopilot.i_autoDepth = atof(temp[16].c_str());
           vehicle.autopilot.d_autoDepth = atof(temp[17].c_str());
           vehicle.autopilot.p_autoAlt = atof(temp[18].c_str());
           vehicle.autopilot.i_autoAlt = atof(temp[19].c_str());
           vehicle.autopilot.d_autoAlt = atof(temp[20].c_str());
           vehicle.autopilot.p_autoCruise = atof(temp[21].c_str());
           vehicle.autopilot.i_autoCruise = atof(temp[22].c_str());
           vehicle.autopilot.d_autoCruise = atof(temp[23].c_str());

      	/**** the following are the      vehicle output channels ****/
           vehicle.autopilot.portThruster_ch = atoi(temp[24].c_str());
           vehicle.autopilot.STBDThruster_ch = atoi(temp[25].c_str());
           vehicle.autopilot.vertThruster_ch = atoi(temp[26].c_str());
           vehicle.autopilot.latThruster_ch = atoi(temp[27].c_str());

           vehicle.autopilot.auto_pilot_string = string(temp_str);
    	

           return true;
   }

   return false;

}



bool
parse_and_set_overlay (char some_string[])
{
   char *ptr;
   int count = 0;
   string temp[10];
   char unit[16];

   ptr = strtok(some_string, "|" );
   while (ptr)
   {
         //cout << ptr << " ";
         temp[count] = ptr;
         count++;
         ptr = strtok(NULL, "|" );
   }
   //cout <<"\n";

   int type = atoi( temp[0].c_str() );
   int channel = atoi( temp[1].c_str() );
   int line =  atoi( temp[2].c_str() );
   int column =  atoi( temp[3].c_str() );
   int color =  atoi( temp[4].c_str() );
   strncpy(unit, temp[5].c_str() , 16);


   // channel can NOT be 0, it is greater than 0 if valid channel, and -1 if invalid
   if ( channel == 0 ) return false;

   // Save the information to the overlay database
   int exist = graph.add_overlay_db(type, channel, line, column, color, unit);
		
   return true;
}



bool
parse_and_set_teleos (IOElementControl& ioElementControl,char some_string[])
{

	//printf(some_string);

        sscanf (some_string, "%4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %d",
        	vehicle.teleos.kf1_foreaft,
   		vehicle.teleos.kf1_turns,
   		vehicle.teleos.kf1_lateral,
   		vehicle.teleos.kf1_vertical,
   		vehicle.teleos.kf2_foreaft,
   		vehicle.teleos.kf2_turns,
   		vehicle.teleos.kf2_lateral,
   		vehicle.teleos.kf2_vertical,
   		vehicle.teleos.db_foreaft,
   		vehicle.teleos.db_turns,
   		vehicle.teleos.db_lateral,
   		vehicle.teleos.db_vertical,
   		vehicle.teleos.st_foreaft,
   		vehicle.teleos.st_turns,
   		vehicle.teleos.st_lateral,
   		vehicle.teleos.st_vertical,
   		vehicle.teleos.curve_mode );
   

snprintf (vehicle.teleos.teleos_string, 1024, "%s", some_string);

		
	ioElementControl.initializeLookup();
	return true;
	

}


bool
parse_and_set_logging (char some_string[])
{

	int type, channel;
	char name[256];
	
        char *ptr;
   	int count = 0;
   	string temp[10];

      	ptr = strtok(some_string, "|" );
      	while (ptr)
      	{
        	temp[count] = ptr;
         	count++;
         	ptr = strtok(NULL, "|" );
      	}
      	
      	type = atoi(temp[3].c_str());
      	channel = atoi(temp[4].c_str());
      	snprintf(name, 256, temp[5].c_str());
      	
	// the filename and time for logging has actually been set before we
        // reach this parsing point
        	
        telstring.add_log_item(name, type, channel, log_filename.c_str(), log_time, log_interval) ;
		
   	return true;

}


/****************************************************************************************
* READING FROM A FILE
*
****************************************************************************************/

int
Configuration::reading(IOElementControl& ioElementControl, string name)
{
   static char some_string[512];

    ifstream infile;
    infile.open(name.c_str(), ios::in);

    if ( !infile.is_open() )
    {
    	cout <<"ERROR : Can not open file for reading : "<< name << endl;
    	return -1;
    }

    //-----------------LIGHT-----------------------


    if(infile)
    {
    	// get the first screen light info
      	infile.getline(some_string, 512);  		// LIGHT info screen 1
      	parse_and_set_light (1, some_string);
   	
      	// get the second screen light info
      	infile.getline(some_string, 512);                 	// LIGHT info screen 2
      	parse_and_set_light (2, some_string);
      	
      	infile.getline(some_string, 512);                 	// LIGHT info screen 2      	
      	string temp(some_string);
      	graph.output_light_string = temp;
      	      	
    }
      	

    //-----------------COMPASS-----------------------

    if(infile)
    {
    	// get the first string ---> slidebar
      	infile.getline(some_string, 512);	// COMPASS
      	infile.getline(some_string, 512);	// COMPASS  info
      	
     	//cout <<"configuration.cpp: compass string read : "<<some_string<<endl;
        parse_and_set_graphic ("compass", some_string);      		


    }

    //-----------------VEHICLE-----------------------


    if(infile)
    {
      	infile.getline(some_string, 512);	// VEHICLE
      	infile.getline(some_string, 512);         // VEHICLE info

   //	cout <<"configuration.cpp: vehicle string read : "<<some_string<<endl;
        	parse_and_set_graphic ( "vehicle" , some_string);

    }

    //-----------------BUTTON-----------------------

    if(infile)
    {
      	infile.getline(some_string, 512);	// BUTTON
      	infile.getline(some_string, 512);	// BUTTON  info
    }

    while (strcmp(some_string, "SLIDEBAR") != 0 && infile)
    {
     	// parse and set values for button
     	//cout <<"configuration.cpp: button string read : "<<some_string<<endl;
        parse_and_set_button (ioElementControl, some_string);
        		
        infile.getline(some_string, 512);         	
    }

    //-----------------SLIDEBAR-----------------------
     if(infile)
    {
    	// get the first string ---> slidebar
      	infile.getline(some_string, 512);
    }

    while (strcmp(some_string, "IO_ELEMENT") != 0 && infile)
    {
     	// parse and set values for slidebar
     //	cout <<"configuration.cpp: slide string read : "<<some_string<<endl;
        parse_and_set_slidebar (ioElementControl, some_string);
        		
        infile.getline(some_string, 512);         	
    }
   	
    //-----------------IO ELEMENT-----------------------

    if (infile)
    {
    	infile.getline(some_string, 512);
    	
    }

    while (strcmp(some_string, "BARGRAPH") != 0 && strcmp(some_string, "NEXT") != 0 && infile)
    {
    	
        // get the first line -> IO Element information
       // infile.getline(some_string, 512);

        /* *************************************************************
        * Let's parse the string into its elements and then CREATE
        * a new element in database using this function below
        ****************************************************************/
        if (parse_and_create_elem(ioElementControl, some_string) == false)
        {
        	return -1;
        }


        // get the next line which are the output for this particular io element
        infile.getline(some_string, 512);
        // while next line is NOT equal to "NEXT" of is NOT end of file
        while (strcmp(some_string, "NEXT") != 0 && strcmp(some_string, "BARGRAPH") != 0 && infile)
        {
        	if (strcmp(some_string, "\0") != 0)	// there is at least one output
        	{	        		
        		if(parse_and_create_output(ioElementControl, some_string) == false)
                  		return -1;
                }

         	// get the next output till it finds "NEXT"
         	infile.getline(some_string, 512);
         	
         	
        }

        infile.getline(some_string, 512);
       //cout<<"What is string here3 : "<<some_string<<endl;


    // end IO_ELEMENT while loop
    }


     	
      //----------------- BARGRAPH -----------------------

    // while the next string is not equalt to "AUTO PILOT" and it's not end  of file
    while (strcmp(some_string, "AUTO PILOT") != 0 && infile)
    {
    	
     	// parse and set values for slidebar
     //	cout <<"configuration.cpp: bargraph string read : "<<some_string<<endl;
        	parse_and_set_bardetail (ioElementControl, some_string);
        	infile.getline(some_string, 512);
        	       	
    }
   	

    //----------------------- AUTO PILOT --------------------
    // Read the values of the auto pilot string
    if (infile)
    {

        //memset(some_string, 0, 512);
    	infile.getline(some_string, 512); 	
	parse_and_set_control("Auto", some_string);
	//cout <<"configuration.cpp: Auto string read : "<<some_string<<endl;
	
    }

    //---------------------- ARM ----------------------------
    // Read the string "ARM"
    if (infile)
    	infile.getline(some_string, 512); 	
    // Read the values of arm string
    if (infile)
    {
      	//memset(some_string, 0, 512);
    	infile.getline(some_string, 512); 		
	parse_and_set_control("Arm", some_string);
	
    }
    	
    //----------------------- CAMERA --------------------------
    // Read the string "CAMERA"
    if (infile)
    	infile.getline(some_string, 512); 	
    // Read the values of camera string
    if (infile)
    {
      	//memset(some_string, 0, 512);
    	infile.getline(some_string, 512); 	
	parse_and_set_control("Camera", some_string);
	
    }


   //----------------------- TMS --------------------------
   // Read the string "TMS"
    if (infile)
    	infile.getline(some_string, 512);

    // Read the values of tms string
    if (infile)
    {
      	//memset(some_string, 0, 512);
    	infile.getline(some_string, 512); 	
	parse_and_set_graphic("tms", some_string);
	
    }


   //----------------------- OVERLAY -------------------------

   // Read the string "OVERLAY"    	
    if (infile)
    	infile.getline(some_string, 512);

    while (strcmp(some_string, "TELEOS") != 0 && infile)
    {
	// get the overlay item
      	infile.getline(some_string, 512);  	
      	//cout <<"configuration.cpp: overlay item "<<some_string<<endl;

      	parse_and_set_overlay(some_string);
      	
    }
      	
    //----------------------- TELEOS -------------------------

    if (infile)
    {

        //memset(some_string, 0, 512);
    	infile.getline(some_string, 512); 	
	parse_and_set_teleos(ioElementControl, some_string);
	//cout <<"configuration.cpp: Teleos string read : "<<some_string<<endl;
	
    }      	

    	
   //----------------------- DISK_LOGGING -------------------------

    if (infile) 	// this is the DISK_LOGGING string
    {
    	infile.getline(some_string, 512); 	
    	//cout <<some_string<<endl;	
    }

    if (infile) 	// this is the filename
    {
    	infile.getline(some_string, 512);
	log_filename = string(some_string);
        //cout <<"configuration.cpp: logging filename : "<<temp<<endl;		
    }

    if (infile) 	// this is the length of time to log
    {
    	infile.getline(some_string, 512);
    	log_time = atoi(some_string); 	
    	//cout <<some_string<<endl;	
    }

    //while (strcmp(some_string, "RPM_INTERVAL") != 0 && infile)
    if (infile) 	// this is the sampling interval
    {
    	infile.getline(some_string, 512);
    	log_interval = atoi(some_string); 	
    	//cout <<some_string<<endl;	
    }


    // now we want to get all the items
    while (strcmp(some_string, "ANNOTATE") != 0 && infile)
          {
          infile.getline(some_string, 512);  	
          parse_and_set_logging(some_string);
      	//cout <<some_string<<endl;
      	}
    if(infile)
    {
	// get the annotate items item
    for (int i = 0; i < 4; i++)
    {
    	if (infile)
    	{
    		infile.getline(some_string, 512);
    		int string_length = strlen(some_string);
    		int j;
      		for(j=0; j < string_length; j++) if(some_string[j] == '~') some_string[j] = '\n';
                //cout <<"configuration.cpp: Annotate info "<<i<<some_string<<endl;
    	        page_string[i] = string(some_string);
    	}
    }

      	
    }

    // ------------------- ANNOTATE --------------------	
    


    // Kenny added the following - NOV. 18, 2002	
    //------- DiveNum + rpm_interval + latitude ----------
    //while (strcmp(some_string, "DIVE_NUMBER") != 0 && infile)
    if (infile)
    {
	infile.getline(some_string, 512); 	
	infile.getline(some_string, 512); 	
	dive_num = atoi(some_string);
	//cout <<"configuration.cpp: DiveNum : "<<some_string<<endl;
	
    }      	

    if (infile)
    {
    	infile.getline(some_string, 512); 	
	infile.getline(some_string, 512); 	
	vehicle.rpm_interval = atoi(some_string);
	//cout <<"configuration.cpp: rpm_interval : "<<some_string<<endl;
	
    }      	

    if (infile)
    {
    	infile.getline(some_string, 512); 
	infile.getline(some_string, 512); 	
	latitude = atof(some_string);
	//cout <<"configuration.cpp: latitude : "<<some_string<<endl;
	
    }      	

    // Dave added the following Mar 10 2003
    // Fog and Compass deviation and declination

     if (infile)
    {
    	infile.getline(some_string, 512);
	infile.getline(some_string, 512); 	
	deviation_fog = atoi(some_string);
	//cout <<"configuration.cpp: FOG deviation : "<<some_string<<endl;
	
    }      	

     if (infile)
    {
    	infile.getline(some_string, 512);
	infile.getline(some_string, 512); 	
	deviation_compass = atoi(some_string);
	//cout <<"configuration.cpp: Compass Deviation : "<<some_string<<endl;
	
    }      	

     if (infile)
    {
    	infile.getline(some_string, 512);
	infile.getline(some_string, 512); 	
	declination_fog = atoi(some_string);
	//cout <<"configuration.cpp: FOG Declination : "<<some_string<<endl;
	
    }      	

     if (infile)
    {
    	infile.getline(some_string, 512);
	infile.getline(some_string, 512); 	
	declination_compass = atoi(some_string);
	//cout <<"configuration.cpp: Compass Declination : "<<some_string<<endl;
	
    }
          	
     if (infile)
    {
    	infile.getline(some_string, 512);
	infile.getline(some_string, 512); 	
	arm_time_constant = atoi(some_string);
	//cout <<"configuration.cpp: Arm Time Constant : "<<some_string<<endl;
	
    }
         	
     if (infile)
    {
    	infile.getline(some_string, 512);
	infile.getline(some_string, 512); 	
	cam_time_constant = atoi(some_string);
	//cout <<"configuration.cpp: Cam Time Constant : "<<some_string<<endl;
    }
     if (infile)
    {
    	infile.getline(some_string, 512);
    	infile.getline(some_string, 512);
    	snprintf(enable_overlay_string, 100, "%s", some_string);
    }         	
     if (infile)
    {
    	infile.getline(some_string, 512);
    	infile.getline(some_string, 512);
    	snprintf(insert_overlay_string, 100, "%s", some_string);
    }         	
     	     	




    //----------------------------- end of reading -----------------------------

    infile.close();		/* close the file */

    return 0;

}








/****************************************************************************************
*  WRITING TO A FILE
*
*****************************************************************************************/

int
Configuration::writing(IOElementControl& ioElementControl, string name)
{
    char some_string[512];
    int top_dig_size = ioElementControl.retDigSize();
    int top_ana_size = ioElementControl.retAnaSize();
    int sub_dig_size = ioElementControl.retSubDigSize();
    int sub_ana_size = ioElementControl.retSubAnaSize();
    int anaout_size = ioElementControl.retAnaOutSize();


    FILE *filename;
    if( (filename = fopen (name.c_str(), "r+")) != NULL)
    {        	
     	//fclose(filename);
     	int length = strlen(name.c_str());
     	snprintf (backup_filename,length-3, name.c_str());
     	
     	strncat(backup_filename ,"_bak.cfg", 128);
     	
     	
     	
     	pid_t pid;
     	
     	// child process
     	if (( pid = fork() ) == 0) {
     	
     		int val = execl("/bin/cp", "-f", name.c_str(), backup_filename, NULL);
     		cout <<"configuration.cpp: Creating backup file : "<<backup_filename <<" "<<val<<endl;
    	
    		}
    		
    		if (waitpid (pid, NULL, 0) < 0)
    		{
    		 	cerr <<"Error in terminating child process \n";    		
    		}

    		//cout <<"Successfully terminating child process \n";
        	fclose(filename);
     	
    }


     // wait for 1 second just to make sure child process is done with the file
	sleep(1);
	
	
	ofstream outfile;               		/* for outputing to file */
	outfile.open(name.c_str(), ios::out); 	/* open the file */

	if ( !outfile.is_open() )
	{
		cout <<"ERROR : Can not open file for writing : "<< name << endl;
    		return -1;
	}


    //cout <<"configuration.cpp : Opening / Creating file : "<<name.c_str()<<endl;


    /********************************************* ELSE ******************************************/
    	
    	//---------------- Light -------------------
    	// screen 1
    	graph.get_light_string(1, some_string) ;
    	outfile << some_string <<"\n";
    	// screen 2
    	graph.get_light_string(2, some_string  );
    	outfile << some_string <<"\n";
    	
    	// finally, save the output for light
    	outfile << graph.output_light_string <<"\n";
    	
    	//---------------- Compass -------------------
    	
    	outfile <<"COMPASS \n";
    	// screen 1 and 2
    	graph.get_compass_string(some_string);
    	outfile << some_string <<"\n";
    	
    	//---------------- Vehicle -------------------
    	
    	outfile <<"VEHICLE \n";
    	// screen 1 and 2
    	graph.get_vehicle_string(some_string) ;
    	outfile << some_string <<"\n";
    	
    	
    	
    	//---------------- Button -------------------
    	
    	outfile << "BUTTON" << "\n";
    		
    	for (ioElementControl.but_ptr = ioElementControl.first_but; ioElementControl.but_ptr != NULL; ioElementControl.but_ptr = ioElementControl.but_ptr->next)
    	{
    		// get " name|type|board|elem_num|x|y|state "
    		if (ioElementControl.ret_button_db_string(some_string, ioElementControl.but_ptr) == true)
       		{
    	    		outfile << some_string <<"\n";
    	    	} 	
    	}
    	
    	
    	//------------- Slidebar -----------------------
    	
    	outfile << "SLIDEBAR" << "\n";
    	
    	for (ioElementControl.slide_ptr = ioElementControl.first_slide; ioElementControl.slide_ptr != NULL; ioElementControl.slide_ptr = ioElementControl.slide_ptr->next)
    	{
    		// get " name|board|elem_num|x|y|value "
    	    	if (ioElementControl.ret_slide_db_string(some_string, ioElementControl.slide_ptr) == true)
       		{
    	    		outfile << some_string <<"\n";
    	    	}
    	}
    	
    	outfile << "IO_ELEMENT" << "\n";
    	
    	
    	
        //---------- IO ELEMENT + OUTPUT -----------------

       // Writing the "Digital In" elements into a file
       for ( int i = 0 ; i < top_dig_size ; i++)
       {
       		if (ioElementControl.retDigitalObjString(some_string, i) == true)
       		{
        		outfile << some_string << "\n";
        		outfile << write_output(ioElementControl, some_string) << "\n";
        	}
        	
        	outfile <<"NEXT"<< "\n";      	
        	
       }                  // end for loop

       // Writing the "Analog In" elements into a file
       for ( int i = 0 ; i < top_ana_size ; i++)
       {
       		if (ioElementControl.retAnalogObjString(some_string, i) == true)
       		{
        		outfile << some_string << "\n";
        		outfile << write_output(ioElementControl, some_string) << "\n";        	
             	}
             	
             	outfile <<"NEXT"<<"\n";
       }

       // Writing the "Sub Digital In" elements into a file
       for ( int i = 0 ; i < sub_dig_size ; i++)
       {
       		if (ioElementControl.retSubDigitalObjString(some_string, i) == true)
       		{
        		outfile << some_string << "\n";
        		outfile << write_output(ioElementControl, some_string) << "\n";
             		}
             	
             	outfile <<"NEXT"<<"\n";

       }                  // end for loop


       // Writing the "Analog In" elements into a file
       for ( int i = 0 ; i < sub_ana_size ; i++)
       {
       		if (ioElementControl.retSubAnalogObjString(some_string, i) == true)
       		{
        		outfile << some_string << "\n";
        		outfile << write_output(ioElementControl, some_string) << "\n";
             	}
             	
             	 outfile <<"NEXT"<<"\n";
       } 	



       // Writing the "Analog Out" elements into a file
       for ( int i = 0 ; i < anaout_size ; i++)
       {
       		if (ioElementControl.retTopAnalogOutObjString(some_string, i) == true)
       		{
        		outfile << some_string << "\n";
        		
        		outfile << write_output(ioElementControl, some_string) << "\n";
             	}
             	
             	 outfile <<"NEXT"<<"\n";
       }


      outfile << "BARGRAPH" << "\n";
      for(int i = 0; i < ioElementControl.retSubAnaSize(); i++) {

      	int elem_num = ioElementControl.ret_subana_elem_num(i);
      	//cout<<"configuration.cpp: elem_num : "<<elem_num<<endl;
      	if (elem_num != -1)
      	{
		ioElementControl.getting_bar_detail (elem_num, some_string );
              	outfile <<some_string<<"\n";
  	}
      }

      outfile <<"AUTO PILOT" << "\n";
      outfile <<vehicle.autopilot.auto_pilot_string<<"\n";

      outfile <<"ARM" << "\n";
      outfile <<vehicle.arm.arm_string<<"\n";

      outfile <<"CAMERA" << "\n";
      outfile <<vehicle.camera.cam_string<<"\n";

      outfile <<"TMS" << "\n";
      char temp[50];
      snprintf(temp, 50, "%d|%d|%d|%d", graph.tmsx1, graph.tmsy1, graph.tmsx2, graph.tmsy2);
      outfile <<temp<<"\n";


      outfile <<"OVERLAY" << "\n";      	
      for (int i = 0; i < graph.ov_count; i++)
      {
      	outfile <<graph.get_overlay_info(i)<<"\n";
      }

      outfile <<"TELEOS" << "\n";      	
      outfile <<vehicle.teleos.teleos_string<<"\n";

      outfile <<"DISK_LOGGING" << "\n";      	
      outfile <<log_filename<<"\n";
      outfile <<log_time<<"\n";
      outfile <<log_interval<<"\n";
      
      for (int i = 0; i < telstring.log_count; i++)
      {
      		outfile <<telstring.get_log_info(i)<<"\n";
      		//cout <<"configuration.cpp: get_log_info : "<<telstring.get_log_info(i)<<endl;
 	
      }

      outfile <<"ANNOTATE" <<"\n";
 

     
	for (int i = 0; i < 4; i++)
      {
      	char temp_string[200];
      	// note that here we dont have to append new line again
      	// because the page_string[] has already contain new line character
       	strcpy(temp_string, page_string[i].c_str());
       	
       	int string_length_page = strlen(temp_string);
      	int j;

      	for(j=0; j < string_length_page; j++) if(temp_string[j] == '\n') temp_string[j] = '~';
      	outfile <<temp_string<<endl;
      }

      // Kenny added these - NOV. 18 2002
      outfile <<"DIVE_NUMBER" << "\n";      	
      outfile <<dive_num<<"\n";
      outfile <<"RPM_INTERVAL" << "\n";      	
      outfile <<vehicle.rpm_interval<<"\n";
      outfile <<"LATITUDE" << "\n";      	
      outfile <<latitude<<"\n";

      //Dave added these - Mar 10 2003
      outfile <<"FOG_DEVIATION" << "\n";      	
      outfile <<deviation_fog<<"\n";
      outfile <<"COMPASS_DEVIATION" << "\n";      	
      outfile <<deviation_compass<<"\n";
      outfile <<"FOG_DECLINATION" << "\n";      	
      outfile <<declination_fog<<"\n";
      outfile <<"COMPASS_DECLINATION" << "\n";      	
      outfile <<declination_compass<<"\n";
      outfile <<"ARM_TIME_CONSTANT" << "\n";      	
      outfile <<arm_time_constant<<"\n";
      outfile <<"CAM_TIME_CONSTANT" << "\n";      	
      outfile <<cam_time_constant<<"\n";
      outfile <<"ENABLE_OVERLAY_STRING" << "\n";      	
      outfile <<enable_overlay_string<<"\n";
      outfile <<"INSERT_OVERLAY_STRING" << "\n";      	
      outfile <<insert_overlay_string<<"\n";

    cout <<"configuration.cpp : Done Saving : "<<name.c_str()<<endl;

    outfile.close();		/* close the file */
    sync();

    return 0;


}




