int __bea_callspec__ Disasm (PDISASM pMyDisasm) {

    if (InitVariables(pMyDisasm)) {
        (void) AnalyzeOpcode(pMyDisasm);
        if (!GV.OutOfBlock) {
            FixArgSizeForMemoryOperand(pMyDisasm);
            FixREXPrefixes(pMyDisasm);
            FillSegmentsRegisters(pMyDisasm);
            CompleteInstructionFields(pMyDisasm);
            #ifndef BEA_LIGHT_DISASSEMBLY
                if (GV.SYNTAX_ == ATSyntax) {
                    BuildCompleteInstructionATSyntax(pMyDisasm);
                }
                else {
                    BuildCompleteInstruction(pMyDisasm);
                }
            #endif
            if (GV.ERROR_OPCODE) {
                return -1;
            }
            else {
                return (int) (GV.EIP_-(*pMyDisasm).EIP);
            }
        }
        else {
            return 0;
        }
    }
    else {
        return -1;
    }
}
/**
 * @brief DialogCutSplinePath create dialog.
 * @param data container with data
 * @param parent parent widget
 */
DialogCutSplinePath::DialogCutSplinePath(const VContainer *data, const quint32 &toolId, QWidget *parent)
    :DialogTool(data, toolId, parent), ui(new Ui::DialogCutSplinePath), formula(QString()),
      splinePathId(NULL_ID), formulaBaseHeight(0), path(nullptr)
{
    ui->setupUi(this);
    InitVariables(ui);
    InitFormulaUI(ui);
    ui->lineEditNamePoint->setText(qApp->getCurrentDocument()->GenerateLabel(LabelType::NewLabel));
    labelEditNamePoint = ui->labelEditNamePoint;
    this->formulaBaseHeight = ui->plainTextEditFormula->height();
    ui->plainTextEditFormula->installEventFilter(this);

    InitOkCancelApply(ui);
    flagFormula = false;
    CheckState();

    FillComboBoxSplinesPath(ui->comboBoxSplinePath);

    connect(ui->toolButtonPutHere, &QPushButton::clicked, this, &DialogCutSplinePath::PutHere);
    connect(ui->listWidget, &QListWidget::itemDoubleClicked, this, &DialogCutSplinePath::PutVal);
    connect(ui->toolButtonEqual, &QPushButton::clicked, this, &DialogCutSplinePath::EvalFormula);
    connect(ui->lineEditNamePoint, &QLineEdit::textChanged, this, &DialogCutSplinePath::NamePointChanged);
    connect(ui->plainTextEditFormula, &QPlainTextEdit::textChanged, this, &DialogCutSplinePath::FormulaChanged);
    connect(ui->pushButtonGrowLength, &QPushButton::clicked, this, &DialogCutSplinePath::DeployFormulaTextEdit);

    path = new VisToolCutSplinePath(data);
}
Example #3
0
/**
 * @brief DialogEndLine create dialog
 * @param data container with data
 * @param parent parent widget
 */
DialogEndLine::DialogEndLine(const VContainer *data, QWidget *parent)
    :DialogTool(data, parent), ui(new Ui::DialogEndLine), pointName(QString()), typeLine(QString()), formula(QString()),
      angle(0), basePointId(0), formulaBaseHeight(0)
{
    ui->setupUi(this);
    InitVariables(ui);
    InitFormulaUI(ui);
    labelEditNamePoint = ui->labelEditNamePoint;
    this->formulaBaseHeight = ui->plainTextEditFormula->height();

    InitOkCancelApply(ui);
    flagFormula = false;
    flagName = false;
    CheckState();

    FillComboBoxPoints(ui->comboBoxBasePoint);
    FillComboBoxTypeLine(ui->comboBoxLineType);

    InitArrow(ui);

    connect(ui->toolButtonPutHere, &QPushButton::clicked, this, &DialogEndLine::PutHere);
    connect(ui->listWidget, &QListWidget::itemDoubleClicked, this, &DialogEndLine::PutVal);
    connect(ui->toolButtonEqual, &QPushButton::clicked, this, &DialogEndLine::EvalFormula);
    connect(ui->lineEditNamePoint, &QLineEdit::textChanged, this, &DialogEndLine::NamePointChanged);
    connect(ui->plainTextEditFormula, &QPlainTextEdit::textChanged, this, &DialogEndLine::FormulaTextChanged);
    connect(ui->pushButtonGrowLength, &QPushButton::clicked, this, &DialogEndLine::DeployFormulaTextEdit);
}
Example #4
0
int32_t ResetSimpleLink() {
	int32_t i32Mode = -1, i32RetVal = -1;
	uint8_t ui8Val = 1;

	i32Mode = sl_Start(0, 0, 0);

	i32RetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION,
			SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0);
	if (i32RetVal != 0) {
		return -1;
	}

	i32RetVal = sl_WlanProfileDel(0xFF);
	if (i32RetVal != 0) {
		return -1;
	}

	if (ROLE_STA != i32Mode) {
		if (ROLE_AP == i32Mode) {
			while (!STATUS_GET(g_sSLCon.Status, STATUS_BIT_IP_ACQUIRED)) {

			}
		}

		sl_WlanSetMode(ROLE_STA);
		sl_Stop(0);

		g_sSLCon.Status = 0;

		i32RetVal = sl_Start(0, 0, 0);

		if (ROLE_STA != i32RetVal) {
			return -1;
		}
	}

	i32RetVal = sl_WlanDisconnect();
	if (i32RetVal == 0) {
		while (STATUS_GET(g_sSLCon.Status, STATUS_BIT_CONNECTED)) {

		}
	}

	sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE, 1, 1, &ui8Val);
	sl_WlanPolicySet(SL_POLICY_SCAN, SL_SCAN_POLICY(0), NULL, NULL);

	ui8Val = 0;
	sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID,
	WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (unsigned char *) &ui8Val);

	sl_WlanPolicySet(SL_POLICY_PM, SL_NORMAL_POLICY, NULL, 0);
	sl_NetAppMDNSUnRegisterService(0, 0);
	sl_Stop(0);

	InitVariables();

	return 0;
}
/* ====================================================================
 *
 * ==================================================================== */
int __bea_callspec__ Disasm (PDISASM pMyDisasm)
{
    InitVariables(pMyDisasm);
    AnalyzeOpcode(pMyDisasm);
    if (GV.ERROR_OPCODE) {
        return -1;
    }
    if (!GV.OutOfBlock) {
        //CompleteInstructionFields(pMyDisasm);
        return (int) (GV.EIP_-(*pMyDisasm).EIP);
    }
    // if all 15 bytes is used, it should be opcode error. not out of block
    if ((*pMyDisasm).SecurityBlock == 0 || (*pMyDisasm).SecurityBlock >= MAX_INSTR_LENGTH)
        return -1;
    return 0;
}
Example #6
0
void Camera3::Init(const Vector3& pos, const Vector3& target, const Vector3& up)
{
	this->position = defaultPosition = pos;
	this->target = defaultTarget = target;
	Vector3 view = (target - position).Normalized();
	Vector3 right = view.Cross(up);

	cameraRotate.SetZero();

	right.y = 0;
	right.Normalize();
	this->up = defaultUp = right.Cross(view).Normalized();

	InitVariables();

	//Initialise the camera movement flags
	for(int i = 0; i< 255; i++)
	{
		myKeys[i] = false;
	}
}
Example #7
0
/****************************************************************************
 Function
     InitJSRcommand

 Parameters
     uint8_t : the priorty of this service

 Returns
     bool, false if error in initialization, true otherwise

 Description
     Saves away the priority, and does any 
     other required initialization for this service
 Notes

 Author
     J. Edward Carryer, 01/16/12, 10:00
****************************************************************************/
bool InitJSRcommand ( uint8_t Priority )
{
   ES_Event ThisEvent;

   MyPriority = Priority;
  
   // post the initial transition event
   DDRS |= BIT7HI; // To control SS line manually
   RED_DARK_ADDRESS &= ~RED_DARK_PIN; // Set pin as input
   RED_DARK_PORT &= ~RED_DARK_PIN; //Set button low
   InitSPI();
   readFrom = 4;// Looking for the 4th command from JSR
   InitVariables();
   QueryCommand =  STATUS_QUERY;
   ES_Timer_InitTimer(JSRtimer, 3); // Start JSRtimer for 2ms.
 
   ThisEvent.EventType = ES_INIT;
   if (ES_PostToService( MyPriority, ThisEvent) == true)
      return true;
   else
      return false;
}
Example #8
0
int main(int argc, char **argv)
{
  unsigned long valuemask;		/* mask for create windows */
  XSetWindowAttributes attributes;	/* attributes for create windows */
  void InternUsefulAtoms(void);
  void InitVariables(void);
  int  i, len;
  extern int x_fd;
  char *display_string;
  char message[255];
  Bool single = False;
  Bool option_error = FALSE;
  MenuRoot *mr;

  g_argv = argv;
  g_argc = argc;

  OpenConsole();
  DBUG("main", "Entered, about to parse args");

  for (i = 1; i < argc; i++) {
    if (strncasecmp(argv[i], "-debug", 6) == 0) {
      debugging = True;
    } else if (strncasecmp(argv[i], "-s", 2) == 0) {
      single = True;
    } else if (strncasecmp(argv[i], "-d", 2) == 0) {
      if (++i >= argc)
	usage();
      display_name = argv[i];
    } else if (strncasecmp(argv[i], "-f", 2) == 0) {
      if (++i >= argc)
	usage();
      config_command = (char *) malloc(6 + strlen(argv[i]));
      strcpy(config_command, "Read ");
      strcat(config_command, argv[i]);
      free_config_command = True;
    } else if (strncasecmp(argv[i], "-cmd", 4) == 0) {
      if (++i >= argc)
	usage();
      config_command = argv[i];
    } else if (strncasecmp(argv[i], "-file", 5) == 0) {
      if (++i >= argc)
	usage();
      output_file = argv[i];
    } else if (strncasecmp(argv[i], "-h", 2) == 0) {
      usage();
      exit(0);
    } else if (strncasecmp(argv[i], "-blackout", 9) == 0) {
      Blackout = True;
    } else if (strncasecmp(argv[i], "-version", 8) == 0) {
      fvwm_msg(INFO, "main", "Fvwm95 Version %s compiled on %s at %s\n",
	       VERSION, __DATE__, __TIME__);
    } else {
      fvwm_msg(ERR, "main", "Unknown option: `%s'\n", argv[i]);
      option_error = TRUE;
    }
  }

  DBUG("main", "Done parsing args");

  if (option_error) {
    usage();
  }

  DBUG("main", "Installing signal handlers");

  newhandler(SIGINT);
  newhandler(SIGHUP);
  newhandler(SIGQUIT);
  newhandler(SIGTERM);
  signal(SIGUSR1, Restart);
  signal(SIGPIPE, DeadPipe);

  ReapChildren();

  if (!(dpy = XOpenDisplay(display_name))) {
    fvwm_msg(ERR, "main", "can't open display %s",
	     XDisplayName(display_name));
    exit(1);
  }
  Scr.screen = DefaultScreen(dpy);
  Scr.NumberOfScreens = ScreenCount(dpy);

  master_pid = getpid();

  if (!single) {
    int myscreen = 0;
    char *cp;

    strcpy(message, XDisplayString(dpy));

    XCloseDisplay(dpy);

    for (i = 1; i < Scr.NumberOfScreens; i++) {
      if (fork() == 0) {
	myscreen = i;
	break;
      }
    }
    /*
     * Truncate the string 'whatever:n.n' to 'whatever:n',
     * and then append the screen number.
     */
    cp = strchr(message, ':');
    if (cp != NULL) {
      cp = strchr(cp, '.');
      if (cp != NULL)
	*cp = '\0';		/* truncate at display part */
    }
    sprintf(message + strlen(message), ".%d", myscreen);
    dpy = XOpenDisplay(message);
    Scr.screen = myscreen;
    Scr.NumberOfScreens = ScreenCount(dpy);
  }

  x_fd = XConnectionNumber(dpy);
  fd_width = GetFdWidth();

  if (fcntl(x_fd, F_SETFD, 1) == -1) {
    fvwm_msg(ERR, "main", "close-on-exec failed");
    exit(1);
  }

  /*  Add a DISPLAY entry to the environment, in case we were started
   *  with fvwm -display term:0.0
   */
  len = strlen(XDisplayString(dpy));
  display_string = safemalloc(len + 10);
  sprintf(display_string, "DISPLAY=%s", XDisplayString(dpy));
  putenv(display_string);

  /* Add a HOSTDISPLAY environment variable, which is the same as
   * DISPLAY, unless display = :0.0 or unix:0.0, in which case the full
   * host name will be used for ease in networking . */

  /* Note: Can't free the rdisplay_string after putenv, because it
   * becomes part of the environment! */

  if (strncmp(display_string, "DISPLAY=:", 9) == 0) {
    char client[MAXHOSTNAME], *rdisplay_string;

    mygethostname(client, MAXHOSTNAME);
    rdisplay_string = safemalloc(len + 14 + strlen(client));
    sprintf(rdisplay_string, "HOSTDISPLAY=%s:%s", client,
	    &display_string[9]);
    putenv(rdisplay_string);
  } else if (strncmp(display_string, "DISPLAY=unix:", 13) == 0) {
    char client[MAXHOSTNAME], *rdisplay_string;

    mygethostname(client, MAXHOSTNAME);
    rdisplay_string = safemalloc(len + 14 + strlen(client));
    sprintf(rdisplay_string, "HOSTDISPLAY=%s:%s", client,
	    &display_string[13]);
    putenv(rdisplay_string);
  } else {
    char *rdisplay_string;

    rdisplay_string = safemalloc(len + 14);
    sprintf(rdisplay_string, "HOSTDISPLAY=%s", XDisplayString(dpy));
    putenv(rdisplay_string);
  }

  Scr.Root = RootWindow(dpy, Scr.screen);
  if (Scr.Root == None) {
    fvwm_msg(ERR, "main", "Screen %d is not a valid screen",
	     (char *) Scr.screen);
    exit(1);
  }

#ifdef SHAPE
  ShapesSupported =
      XShapeQueryExtension(dpy, &ShapeEventBase, &ShapeErrorBase);
#endif	/* SHAPE */

  InternUsefulAtoms();

  /* Make sure property priority colors is empty */
  XChangeProperty(dpy, Scr.Root, _XA_MIT_PRIORITY_COLORS,
		  XA_CARDINAL, 32, PropModeReplace, NULL, 0);

  XSetErrorHandler((XErrorHandler) CatchRedirectError);
  XSetIOErrorHandler((XIOErrorHandler) CatchFatal);

  XSelectInput(dpy, Scr.Root,
	       LeaveWindowMask | EnterWindowMask | PropertyChangeMask |
	       SubstructureRedirectMask | KeyPressMask |
	       SubstructureNotifyMask |
	       ButtonPressMask | ButtonReleaseMask);

  XSync(dpy, 0);

  XSetErrorHandler((XErrorHandler) FvwmErrorHandler);

  BlackoutScreen();

  CreateCursors();
  InitVariables();
  InitEventHandlerJumpTable();
  initModules();

  InitPictureCMap(dpy, Scr.Root);	/* for the pixmap cache... */

  Scr.gray_bitmap =
      XCreateBitmapFromData(dpy, Scr.Root, g_bits, g_width, g_height);

  DBUG("main", "Setting up rc file defaults...");
  SetRCDefaults();

  DBUG("main", "Running config_command...");
  ExecuteFunction(config_command, NULL, &Event, C_ROOT, -1);
  DBUG("main", "Done running config_command");

/*
  CaptureAllWindows();
  MakeMenus();
*/

#if 0	/* this seems to cause problems for FvwmCpp/M4 startup actually */
  /* if not a direct 'Read', we'll capture all windows here, in case cmd
     fails we'll still have defaults */
  if (strncasecmp(config_command, "Read", 4) != 0 &&
      strncasecmp(config_command, "PipeRead", 8) != 0) {
    /* so if cmd (FvwmM4/Cpp most likely) fails, we can still have
       borders & stuff... */
    StartupStuff();
  }
#endif	/* 0 */

  if (free_config_command) {
    free(config_command);
  }

  if (Scr.d_depth < 2) {
    Scr.gray_pixmap =
	XCreatePixmapFromBitmapData(dpy, Scr.Root, g_bits, g_width,
				    g_height, Scr.WinColors.fore,
				    Scr.WinColors.back, Scr.d_depth);
    Scr.light_gray_pixmap =
	XCreatePixmapFromBitmapData(dpy, Scr.Root, l_g_bits, l_g_width,
				    l_g_height, Scr.WinColors.fore,
				    Scr.WinColors.back, Scr.d_depth);
  }

  /* create a window which will accept the keyboard focus when no other 
     windows have it */
  attributes.event_mask = KeyPressMask | FocusChangeMask;
  attributes.override_redirect = True;
  Scr.NoFocusWin = XCreateWindow(dpy, Scr.Root, -10, -10, 10, 10, 0, 0,
				 InputOnly, CopyFromParent,
				 CWEventMask | CWOverrideRedirect,
				 &attributes);
  XMapWindow(dpy, Scr.NoFocusWin);

  SetMWM_INFO(Scr.NoFocusWin);

  XSetInputFocus(dpy, Scr.NoFocusWin, RevertToParent, CurrentTime);

  XSync(dpy, 0);
  if (debugging)
    XSynchronize(dpy, 1);

  Scr.SizeStringWidth = XTextWidth(Scr.StdFont.font,
				   " +8888 x +8888 ", 15);
  attributes.border_pixel = Scr.WinColors.fore;
  attributes.background_pixel = Scr.WinColors.back;
  attributes.bit_gravity = NorthWestGravity;
  attributes.save_under = True;
  valuemask = (CWBorderPixel | CWBackPixel | CWBitGravity | CWSaveUnder);

  /* create the window for coordinates */
  Scr.SizeWindow = XCreateWindow(dpy, Scr.Root,
				 Scr.MyDisplayWidth / 2 -
				 (Scr.SizeStringWidth +
				  SIZE_HINDENT * 2) / 2,
				 Scr.MyDisplayHeight / 2 -
				 (Scr.StdFont.height +
				  SIZE_VINDENT * 2) / 2,
				 (unsigned int) (Scr.SizeStringWidth +
						 SIZE_HINDENT * 2),
				 (unsigned int) (Scr.StdFont.height +
						 SIZE_VINDENT * 2),
				 (unsigned int) 0, 0,
				 (unsigned int) CopyFromParent,
				 (Visual *) CopyFromParent,
				 valuemask, &attributes);

#ifndef NON_VIRTUAL
  initPanFrames();
#endif

  XGrabServer(dpy);

#ifndef NON_VIRTUAL
  checkPanFrames();
#endif
  XUngrabServer(dpy);
  UnBlackoutScreen();
  DBUG("main", "Entering HandleEvents loop...");
  HandleEvents();
  DBUG("main", "Back from HandleEvents loop?  Exiting...");

  return 0;
}
Example #9
0
/****************************************************************************
 Function
    RunJSRcommand

 Parameters
   ES_Event : the event to process

 Returns
   ES_Event, ES_NO_EVENT if no error ES_ERROR otherwise

 Description
   Code for receiving and parsing message received through SPI bus from JSR

 Notes
   
 Author
   A. Han,            02/20/14, 17:30
   J. Edward Carryer, 01/15/12, 15:23
****************************************************************************/
ES_Event RunJSRcommand( ES_Event ThisEvent )
{
   static unsigned char dummy;
   ES_Event ReturnEvent;
   ReturnEvent.EventType = ES_NO_EVENT; // assume no errors
  
  
   if (RED_DARK_PORT&RED_DARK_PIN == RED_DARK_PIN) //Hi
   {
      RELOAD_STATUS = RED_RELOAD_STATUS;  //RED KNIGHT
      DontChangeKnightFlag = true;
   }
   else if (DontChangeKnightFlag == false)
   {
      RELOAD_STATUS = DARK_RELOAD_STATUS; //DARK KNIGHT
   }	
  
   switch (ThisEvent.EventType)
   {
      case QUERY4STATUS:
         readFrom = 4;// Looking for the 4th command from JSR
         InitVariables();
         QueryCommand =  STATUS_QUERY;
         break;
    
      case QUERY4SCORE :
         readFrom = 3;// Looking for the 3rd and 4th command from JSR
         InitVariables();
         QueryCommand =  SCORE_QUERY;
         break;
        
      case ES_TIMEOUT :  // re-start timer & announce
         if ((SPISR & _S12_SPTEF) == _S12_SPTEF)  //if query can be sent
    		{
    			i++;
    			if (i==1)
    			{ 
    			   PTS &= BIT7LO;  // Set SS line low to recieve 4 bytes
    			   SPIDR = QueryCommand; //Send Status Query
    			} else
    			{
    			  	SPIDR = 0x00;
    			}
    		} 
         break;
    
      case FLAGSET:
         if ((SPISR & _S12_SPIF) == _S12_SPIF) //If Data can be received
        	{
            ByteInfo = SPIDR;
        		dummy = (BIT0HI|BIT1HI|BIT2HI)&(ByteInfo) ;  //Reading Bit 0,1,2
        		 
            if (i<readFrom)
            {
               dummy = SPIDR;
        		}
        		else if (i == readFrom)
        		{
               HeadStatus = ByteInfo & HEAD_STATUS;
               ReloadStatus = ByteInfo & RELOAD_STATUS;
               command1 = dummy;//SPIDR;
               if (command1 != LastCommand1)
               {
                  ES_Event ThisEvent;
                  LastCommand1 = command1;
                  
                  ThisEvent.EventType = NEW_COMMAND_RECEIVED;
                  ThisEvent.EventParam = command1;
                  PostBot(ThisEvent);
               }
            }
            else if (i > readFrom)
            {
               command2 = dummy;//SPIDR;
               if (command2 != LastCommand2)
               {
                  ES_Event ThisEvent;
                  LastCommand2 = command2;
                  
                  ThisEvent.EventType = NEW_COMMAND_RECEIVED;
                  ThisEvent.EventParam = command2;
                  PostBot(ThisEvent);
               }
            }
        		 
            if(ES_Timer_InitTimer(JSRtimer, 3)==ES_Timer_OK)// Start JSRtimer 3ms
        		if (i==4)
            {  
               // Set SS line high after receiving 4 bytes
               i=0;
               PTS |= BIT7HI;
            }
         }
         break;
   }
   return ReturnEvent;
}
Example #10
0
//=========================================================================
//----- (00000148) --------------------------------------------------------
__myevic__ void Main()
{
	InitDevices();

	InitVariables();

	// Enable chip temp sensor sampling by ADC
	if ( ISRX300 )
	{
		SYS->IVSCTL |= SYS_IVSCTL_VTEMPEN_Msk;
	}

	InitHardware();

	myprintf( "\n\nJoyetech APROM\n" );
	myprintf( "CPU @ %dHz(PLL@ %dHz)\n", SystemCoreClock, PllClock );

	SetBatteryModel();

	gFlags.sample_vbat = 1;
	ReadBatteryVoltage();

	gFlags.sample_btemp = 1;
	ReadBoardTemp();

	InitDisplay();
	MainView();
	SplashTimer = 3;

	CustomStartup();

	if ( !PD3 )
	{
		DrawScreen();
		while ( !PD3 )
			;
	}

	while ( 1 )
	{
		while ( gFlags.playing_fb )
		{
			// Flappy Bird game loop
			fbCallTimeouts();
			if ( gFlags.tick_100hz )
			{
				// 100Hz
				gFlags.tick_100hz = 0;
				ResetWatchDog();
				TimedItems();
				SleepIfIdle();
				GetUserInput();
				if ( !PE0 )
					SleepTimer = 3000;
			}
			if ( gFlags.tick_10hz )
			{
				// 10Hz
				gFlags.tick_10hz = 0;
				DataFlashUpdateTick();
			}
		}

		if ( gFlags.firing )
		{
			ReadAtoCurrent();
		}

		if ( gFlags.tick_5khz )
		{
			// 5000Hz
			gFlags.tick_5khz = 0;

			if ( gFlags.firing )
			{
				RegulateBuckBoost();
			}
		}

		if ( gFlags.tick_1khz )
		{
			// 1000Hz
			gFlags.tick_1khz = 0;

			if ( gFlags.firing )
			{
				ReadAtomizer();

				if ( ISMODETC(dfMode) )
				{
					if ( gFlags.check_mode )
					{
						CheckMode();
					}
					TweakTargetVoltsTC();
				}
				else if ( ISMODEVW(dfMode) )
				{
					TweakTargetVoltsVW();
				}
			}

			if ( dfStatus.vcom )
			{
				VCOM_Poll();
			}
		}

		if ( gFlags.tick_100hz )
		{
			// 100Hz
			gFlags.tick_100hz = 0;

			ResetWatchDog();

			if ( gFlags.read_battery )
			{
				gFlags.read_battery = 0;
			}

			TimedItems();
			SleepIfIdle();
			ReadBatteryVoltage();
			ReadBoardTemp();

			if ( gFlags.firing && BoardTemp >= 70 )
			{
				Overtemp();
			}

			if ( ISVTCDUAL )
			{
				BatteryChargeDual();
			}
			else if ( ISCUBOID || ISCUBO200 || ISRX200S || ISRX23 || ISRX300 )
			{
				BatteryCharge();
			}

			if (( gFlags.anim3d ) && ( Screen == 1 ) && ( !EditModeTimer ))
			{
				anim3d( 0 );
			}

			if ( Screen == 60 )
			{
				AnimateScreenSaver();
			}

			if ( gFlags.firing )
			{
				if ( gFlags.read_bir && ( FireDuration > 10 ) )
				{
					ReadInternalResistance();
				}

				if ( PreheatTimer && !--PreheatTimer )
				{
					uint16_t pwr;

					if ( dfMode == 6 )
					{
						pwr = dfSavedCfgPwr[ConfigIndex];
					}
					else
					{
						pwr = dfPower;
					}

					if ( pwr > BatteryMaxPwr )
					{
						gFlags.limit_power = 1;
						PowerScale = 100 * BatteryMaxPwr / pwr;
					}
					else
					{
						gFlags.limit_power = 0;
						PowerScale = 100;
					}
				}
			}

			if ( KeyTicks >= 5 )
			{
				KeyRepeat();
			}

			GetUserInput();
		}

		if ( gFlags.tick_10hz )
		{
			// 10Hz
			gFlags.tick_10hz = 0;

			DataFlashUpdateTick();
			LEDTimerTick();

			if ( gFlags.firing )
			{
				++FireDuration;

				if ( gFlags.monitoring )
				{
					Monitor();
				}
			}

			if ( ShowWeakBatFlag )
				--ShowWeakBatFlag;

			if ( ShowProfNum )
				--ShowProfNum;

			if ( !( gFlags.firing && ISMODETC(dfMode) ) )
			{
				DrawScreen();
			}

			if ( KeyTicks < 5 )
			{
				KeyRepeat();
			}
		}

		if ( gFlags.tick_5hz )
		{
			// 5Hz
			gFlags.tick_5hz = 0;

			if ( !gFlags.rtcinit && NumBatteries )
			{
				InitRTC();
			}

			if ( gFlags.firing )
			{
				if ( TargetVolts == 0 )
				{
					ProbeAtomizer();
				}
			}
			else
			{
				if
				(	!dfStatus.off
					&& Event == 0
					&& ( AtoProbeCount < 12 )
					&& ( Screen == 0 || Screen == 1 || Screen == 5 ) )
				{
					ProbeAtomizer();
				}
			}

			if ( IsClockOnScreen() )
			{
				static uint8_t u8Seconds = 61;
				S_RTC_TIME_DATA_T rtd;

				GetRTC( &rtd );

				if ( (uint8_t)rtd.u32Second != u8Seconds )
				{
					u8Seconds = (uint8_t)rtd.u32Second;
					gFlags.refresh_display = 1;
				}
			}
		}

		if ( gFlags.tick_2hz )
		{
			// 2Hz
			gFlags.tick_2hz = 0;

			gFlags.osc_1hz ^= 1;

			if ( gFlags.firing )
			{
				if ( ISMODETC(dfMode) )
				{
					DrawScreen();
				}
			}
			else
			{
				if
				(	!dfStatus.off
					&& Event == 0
					&& ( AtoProbeCount >= 12 )
					&& ( Screen == 0 || Screen == 1 || Screen == 5 ) )
				{
					ProbeAtomizer();
				}

				if ( gFlags.monitoring )
				{
					Monitor();
				}
			}
		}

		if ( gFlags.tick_1hz )
		{
			// 1Hz
			gFlags.tick_1hz = 0;

			if ( SplashTimer )
			{
				--SplashTimer;
				
				if ( !SplashTimer )
				{
					MainView();
				}
			}

			if ( !gFlags.firing && !dfStatus.off && !EditModeTimer )
			{
				if ( HideLogo )
				{
					if ( Screen == 1 )
					{
						--HideLogo;

						if ( !HideLogo )
						{
							gFlags.refresh_display = 1;
						}
					}
				}
			}
		}

		EventHandler();

	}
}
Example #11
0
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: Entry point for the application.  Since we use a simple dialog for 
//       user interaction we don't need to pump messages.
//-----------------------------------------------------------------------------
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE, LPSTR, int )
{
    HRESULT hr;
    HWND    hWnd;
    BOOL    bDone;
    DWORD   dwResult;
    MSG     msg;

    // Initialize global varibles
    if ( FAILED( hr = InitVariables() ) )
    {
        MessageBox( NULL, _T("Error Initializing Variables"), 
                    _T("Scrawl"),  MB_ICONERROR | MB_OK );
        return TRUE;
    }

    // Display the main dialog box.
    hWnd = RegisterWindowClass( hInstance );
    if( NULL == hWnd )
    {
        MessageBox( NULL, _T("Error Creating Window"), 
                    _T("Scrawl"), MB_ICONERROR | MB_OK );
        return TRUE;
    }

    // Start message pump. Since we use notification handles, we need to use
    // MsgWaitForMultipleObjects() to wait for the event or a message, 
    // whichever comes first.

    bDone = FALSE;
    while( !bDone ) 
    {
        dwResult = MsgWaitForMultipleObjects( 1, &g_hMouseEvent, 
                                              FALSE, INFINITE, QS_ALLINPUT );

        switch( dwResult ) 
        {
            // WAIT_OBJECT_0 + 0 means that g_hevtMouse was signalled 
            case WAIT_OBJECT_0 + 0:
                OnMouseInput( hWnd );
                break;

            // WAIT_OBJECT_0 + 1 means that we have messages to process 
            case WAIT_OBJECT_0 + 1:
                while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) 
                {
                    if( msg.message == WM_QUIT ) 
                    {
                        // Stop loop if it's a quit message
                        bDone = TRUE;
                    } 
                    else 
                    {
                        TranslateMessage( &msg );
                        DispatchMessage( &msg );
                    }
                }
                break;
        }
    }

    // Clean up
    FreeDirectInput();

    // Delete bitmaps
    if( g_hDC ) 
    {
        if( g_hbmpDeselect ) 
            SelectObject( g_hDC, g_hbmpDeselect );

        DeleteDC( g_hDC );
    }

    if( g_hBitmap ) 
        DeleteObject( g_hBitmap );

    return TRUE;
}
Example #12
0
void ControlServer(void *pvParameters) {

	char ServerBuffer[CONFIG_SERVER_BUFFER];
	char MsgBuffer[100];
	char *pMsgBuffer;

	SlSockAddrIn_t sAddr;
	SlSockAddrIn_t sLocalAddr;
	int32_t i32SockID;
	int32_t i32NewSockID;
	int32_t i32DataSize;
	int32_t i32NonBlocking = 1;
	SlSocklen_t i32AddrSize;
	int32_t retval;

	pMsgBuffer = &MsgBuffer[0];

	InitVariables();
	retval = ResetSimpleLink();
	if (retval < 0)
		while (1)
			;

	WlanConnect();

	sprintf(MsgBuffer, "Connectado a rede: %s\n\r"
			"IP: %d.%d.%d.%d\n\r"
			"Gateway: %d.%d.%d.%d\n\r", SL_IPV4_BYTE(g_sSLCon.DeviceIP, 3),
			SL_IPV4_BYTE(g_sSLCon.DeviceIP, 2),
			SL_IPV4_BYTE(g_sSLCon.DeviceIP, 1),
			SL_IPV4_BYTE(g_sSLCon.DeviceIP, 0),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 3),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 2),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 1),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 0));

	osi_MsgQWrite(&g_sUartQuee, &pMsgBuffer, OSI_NO_WAIT);

	sLocalAddr.sin_family = SL_AF_INET;
	sLocalAddr.sin_port = sl_Htons((unsigned short) g_sSLCon.PortNumber);
	sLocalAddr.sin_addr.s_addr = 0;

	i32SockID = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, 0);
	sl_Bind(i32SockID, (SlSockAddr_t *) &sLocalAddr, sizeof(SlSockAddrIn_t));
	sl_Listen(i32SockID, 0);
	sl_SetSockOpt(i32SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &i32NonBlocking,
			sizeof(i32NonBlocking));

	while (1) {
		i32NewSockID = SL_EAGAIN;

		while (i32NewSockID < 0) {
			i32NewSockID = sl_Accept(i32SockID, (struct SlSockAddr_t *) &sAddr,
					(SlSocklen_t*) &i32AddrSize);
			if (i32NewSockID == SL_EAGAIN) {
				osi_Sleep(100);
			} else if (i32NewSockID < 0) {
				while (1) {
				}
			}
		}

		i32DataSize = sl_Recv(i32NewSockID, ServerBuffer, CONFIG_SERVER_BUFFER,
				0);

		if (strcmp(ServerBuffer, "Led On") == 0) {
			Led_Green(LED_ON);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		} else if (strcmp(ServerBuffer, "Led Off") == 0) {
			Led_Green(LED_OFF);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		} else if (strcmp(ServerBuffer, "Lamp On") == 0) {
			MAP_GPIOPinWrite(GPIOA0_BASE, GPIO_PIN_6, GPIO_PIN_6);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		} else if (strcmp(ServerBuffer, "Lamp Off") == 0) {
			MAP_GPIOPinWrite(GPIOA0_BASE, GPIO_PIN_6, 0);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		}

		sl_Send(i32NewSockID, ServerBuffer, i32DataSize, 0);
		sl_Close(i32NewSockID);
	}

}
Example #13
0
DWORD WINAPI CT_FindCertificates(void* lpvoid)
{
    CT_created_log=false;
    CT_isdebugging=true;
    patched_magic_jump=false;
    fdProcessInfo=0;
    magic_value_addr=0;
    encrypted_cert_real=0;
    encrypted_cert_real_size=0;
    cert_func_count=0;

    if(CT_cert_data)
    {
        if(CT_cert_data->projectid)
            free2(CT_cert_data->projectid);
        if(CT_cert_data->customer_service)
            free2(CT_cert_data->customer_service);
        if(CT_cert_data->website)
            free2(CT_cert_data->website);
        if(CT_cert_data->unknown_string)
            free2(CT_cert_data->unknown_string);
        if(CT_cert_data->stolen_keys)
            free2(CT_cert_data->stolen_keys);
        if(CT_cert_data->intercepted_libs)
            free2(CT_cert_data->intercepted_libs);
        if(CT_cert_data->raw_data)
            free2(CT_cert_data->raw_data);
        if(CT_cert_data->encrypted_data)
            free2(CT_cert_data->encrypted_data);
        free2(CT_cert_data);
    }
    CT_cert_data=(CERT_DATA*)malloc2(sizeof(CERT_DATA));
    memset(CT_cert_data, 0, sizeof(CERT_DATA));
    InitVariables(program_dir, (CT_DATA*)CT_cert_data, StopDebug, 1, GetParent(CT_shared));
    FILE_STATUS_INFO inFileStatus= {0};
    CT_time1=GetTickCount();
    IsPE32FileValidEx(CT_szFileName, UE_DEPTH_SURFACE, &inFileStatus);
    if(inFileStatus.FileIs64Bit)
    {
        MessageBoxA(CT_shared, "64-bit files are not (yet) supported!", "Error!", MB_ICONERROR);
        return 0;
    }
    HANDLE hFile, fileMap;
    ULONG_PTR va;
    DWORD bytes_read=0;
    StaticFileLoad(CT_szFileName, UE_ACCESS_READ, false, &hFile, &bytes_read, &fileMap, &va);
    if(!IsArmadilloProtected(va))
    {
        InitVariables(program_dir, 0, StopDebug, 0, 0);
        CT_isdebugging=false;
        MessageBoxA(CT_shared, "Not armadillo protected...", "Error!", MB_ICONERROR);
        return 0;
    }
    StaticFileClose(hFile);
    fdFileIsDll=inFileStatus.FileIsDLL;
    if(!fdFileIsDll)
        fdProcessInfo=(LPPROCESS_INFORMATION)InitDebugEx(CT_szFileName, 0, 0, (void*)CT_cbEntry);
    else
        fdProcessInfo=(LPPROCESS_INFORMATION)InitDLLDebug(CT_szFileName, false, 0, 0, (void*)CT_cbEntry);
    if(fdProcessInfo)
    {
        EnableWindow(GetDlgItem(CT_shared, IDC_BTN_START), 0);
        DebugLoop();
        InitVariables(program_dir, 0, StopDebug, 0, 0);
        CT_ParseCerts();
    }
    else
        MessageBoxA(CT_shared, "Something went wrong during initialization...", "Error!", MB_ICONERROR);
    InitVariables(program_dir, 0, StopDebug, 0, 0);
    CT_isdebugging=false;
    return 0;
}
Example #14
0
int32_t main()
{

/***************************************************************************
*       ClkInit()
****************************************************************************/
	ClkInit();

/***************************************************************************
*       GPIOInit();
****************************************************************************/
//	DrvGPIO_InitFunction(E_FUNC_GPIO);
	outpw(&SYS->P0_MFP, 0);
	outpw(&SYS->P1_MFP, 0);
	outpw(&SYS->P2_MFP, 0);
	outpw(&SYS->P3_MFP, 0);
	outpw(&SYS->P4_MFP, 0);

	_GPIO_SET_PIN_MODE(MODEM_ON_PORT, MODEM_ON_PIN, GPIO_PMD_OUTPUT);
	ModuleOn(TRUE);

	_GPIO_SET_PIN_MODE(MODEM_POWER_PORT, MODEM_POWER_PIN, GPIO_PMD_OUTPUT);
	ModulePowerOn(FALSE);

	_GPIO_SET_PIN_MODE(LOCK_POWER_PORT, LOCK_POWER_PIN, GPIO_PMD_OUTPUT);
	LockPower(FALSE);

	_GPIO_SET_PIN_MODE(KEY_HELP_PORT, KEY_HELP_PIN, GPIO_PMD_QUASI);
	_GPIO_SET_PIN_MODE(KEY_BAT_PORT, KEY_BAT_PIN, GPIO_PMD_QUASI);

	_GPIO_SET_PIN_MODE(SLEEP_PORT, SLEEP_PIN, GPIO_PMD_OUTPUT);
	ModemSleep(FALSE);

	_GPIO_SET_PIN_MODE(LED_PORT, LED_PIN, GPIO_PMD_OUTPUT);
	
	LedDark();
	
	_GPIO_SET_PIN_MODE(INT_PORT, INT_PIN, GPIO_PMD_INPUT);

/***************************************************************************
*       TimerInit();
****************************************************************************/
	SysTick_Config(SYS_TICK);
//	SYS_LockReg();

/***************************************************************************
*       UartInit();
****************************************************************************/
	UartInit();
//	debug(VERSION);
//	DrvSYS_GetPLLClockFreq();

/***************************************************************************
*       WatchdogInit();
****************************************************************************/	
	WatchdogInit();

//	udpTest();
	NvInit();



 	WhatToDo();
	AdcInit();
	
	
	
	WaitLockPower();

  LockPower(!custermParam.param.lockState);


	InitMsgDebug();	
	
	if( Communication(10) == FALSE )
		SoftReset();

	if( isCheckingBattery )
	{
		delay_50ms(40);
		MeasurePower(4);
	}
	else
	{
		MeasurePower(2);
	}
					
	Flag_ModuleOn = TRUE;
	//Flag_ModuleOn = TRUE;
	ModemVolumeInit();

	///--------------------24.11.2015----------------------------------------------
	////////////////////////////////////////////////////////////////////////////////////////
while(PressHelp()&&(tmp_my<200)&&(PressBatter())){
	tmp_my++;
		
	delay_50ms(1);
if (tmp_my>=150) {
	  LedLight(144);
	    if (custermParam.param.lockState) {
														LockPower(TRUE);
														custermParam.param.lockState = FALSE;
												    WriteToNv( &custermParam ); //- save to eeprom
  													PlayVoice("\"unitUnlock.wav\",2\r");
														delay_ms(2000);
			                      LockPower(FALSE);
			
			} else {
	                          //  debug("ins");
															while(PressBatter()){};
														 tmp_my=0;
												while (tmp_my<25){               
																											tmp_my++;
																											delay_ms(150);
																											if (PressBatter()){counterPress++;
																																				while(!PressBatter()){};
																																					}
																										  if (counterPress>2){ 
																																					PlayVoice("\"unitLock.wav\",2\r");
																																					delay_ms(2000);
																																					custermParam.param.lockState = TRUE;
																																					WriteToNv( &custermParam ); //- save to eeprom
																																		      tmp_my=0;
																																					delay_ms(2000);
																																					LockPower(DISABLE);

																																				}
																											}
													LedBlink();
										} 
					///////				
			tmp_my=0;
			}

}

while(custermParam.param.lockState){}
 
///////////////////////////////////////////////////////////////////////////////////////////////													
#ifdef DELAY_TEST
	DelayTest();
#endif
	PowerOn();
	
	

	
	if(state==STATE_POWERING_DOWN || Flag_Power_Down)
	{
		Flag_Power_Down = FALSE;
		EnterPowerDown();
		while( TimerWait )
			FeedWatchdog();
		PowerDown();
		//不会返回
	}
	
	InitVariables();
	  
	if(state == STATE_NULL)
	{
		state = STATE_1ST_CALL;
		TimerWait = 100;	// 5 s
	}
	
	TimerTestMode = 6000;
	//debug("ent main loop");
	while(1)
	{  
			
		///--------------------
				if (!TimerTestMode && state==STATE_TEST)
										{ 
										PlayMusic(MUSIC_PD);
										EnterPowerDown();
										}
		
		///--------------------
		
		if( Flag_Incomming )
		{
	#if 1
			TimerWait = 200;
			Flag_Incomming = FALSE;
			TimerStandby = custermParam.param.delay;
			//if(state != STATE_ACTIVE)
			{
				ModemSleep(FALSE);
				state = STATE_INCOMMING;
			}
	#else
			Flag_Incomming = FALSE;
			if(state != STATE_INCOMMING)
			{
				state = STATE_INCOMMING;
				ModemSleep(FALSE);
				EnterAnswer();
			}
	#endif
		}
		
		if(TimerWait == 0)
		{
			switch(state)
			{
									
			case STATE_POWERING_DOWN:
				PowerDown();
				break;

			case STATE_1ST_CALL:
				RegisterWait();
				break;

			case STATE_REGISTER_OK:	
				GetCpsiInfo();
				if( Flag_ObtainCpsi==TRUE)
				{
					state = STATE_GSM_STEADY;
					if( Flag_SimExist )
					{
						//delay_50ms(200);
						SockOpen();
						TimerWait = 400;
					}
					else
					{
						TimerWait = 60;
					}
				}
				else
				{
					TimerWait = 70;
				}
				break;

			case STATE_GSM_STEADY:	
				if( gPhoneNumOk==PHONE_NUM_READY || Flag_SimExist==FALSE)
					EnterCall();
				else
					TimerWait = 40;
				break;
				
			case STATE_CALL_PROMPT:
				Call();
				break;

			case STATE_ALERT:
				EnterCallFail();
				break;
			
			case STATE_NEXT_CALL:
				Redial();
				break;				

			case STATE_BATT_DISPLAY:
				EnterPowerDown();
				break;

			case STATE_INCOMMING:
				TimerStandby = custermParam.param.delay;
				EnterStandby();
				break;
			}
		}

		if( TimerSock==0 && Flag_SimExist
			&& ( (state>=STATE_GSM_STEADY && state<STATE_STANDBY) || progress>=TEST_GPS ) )
		{
			switch(sockState)
			{
			//case SOCKSTATE_NULL:
			case SOCKSTATE_CONFIG:				
			case SOCKSTATE_OPENNING:
				SockOpen();	// 打开失败,从新打开
				break;

			case SOCKSTATE_OPENED:
				SendAtWaitRsq(50, 1, FALSE, "AT+CIPOPEN=0,\"UDP\",,,%s\r\n", custermParam.param.local_port);
				TimerSock = 80;
				break;
	#if 0
			case SOCKSTATE_CONNECTING:
				SockConnect();	// 连接失败,从新连接
				break;
	#endif
			case SOCKSTATE_CONNECT_OK:		
				if( witchApn == 1)
					ClientInit();
				break;

			default:
				break;
			}
		}

		KeyHandle();

		SecondHandle();
		//SignalCheck();
		BatterCheck();
		PowerDownHandle();
		MsgHandle();
											
		if( Flag_SimExist )
		{
			UdpHandle();
			SmsHandle();
			PowerDownHandle();
		}
		
		FeedWatchdog();
	}
}	
Example #15
0
int main(int argc, char *argv[]) {
  
  int   i, OutputNumber = 0, d;
  int   ni, ntot;
  char  ParameterFile[MAXLINELENGTH];
  if (argc == 1) PrintUsage (argv[0]);
  strcpy (ParameterFile, "");
  for (i = 1; i < argc; i+=d) {
    d=1;
    if (*(argv[i]) == '+') {
      if (strspn (argv[i], \
		  "+S#D") \
	  != strlen (argv[i]))
	PrintUsage (argv[0]);
      if (strchr (argv[i], '#')) {
	d=2;
	ArrayNb = atoi(argv[i+1]);
	EarlyOutputRename = YES;
	if (ArrayNb <= 0) {
	  masterprint ("Incorrect Array number after +# flag\n");
	  PrintUsage (argv[0]);
	}
      }
      if (strchr (argv[i], 'D')) {
	d=2;
	strcpy (DeviceFile, argv[i+1]);
	DeviceFileSpecified = YES;
      }
      if (strchr (argv[i], 'S')) {
	d=2;
	StretchNumber = atoi(argv[i+1]);
	StretchOldOutput = YES;
      }
    }
    if (*(argv[i]) == '-') {
      if (strspn (argv[i], \
		  "-tofCmkspSVBD0#") \
	  != strlen (argv[i]))
	PrintUsage (argv[0]);
      if (strchr (argv[i], 't'))
	TimeInfo = YES;
      if (strchr (argv[i], 'f'))
	ForwardOneStep = YES;
      if (strchr (argv[i], '0'))
	OnlyInit = YES;
      if (strchr (argv[i], 'C')) {
	EverythingOnCPU = YES;
#ifdef GPU
	mastererr ("WARNING: Forcing execution of all functions on CPU\n");
#else
	mastererr ("WARNING: Flag -C meaningless for a CPU built\n");
#endif
      }
      if (strchr (argv[i], 'm')) {
	Merge = YES;
      }
      if (strchr (argv[i], 'k')) {
	Merge = NO;
      }
      if (strchr (argv[i], 'o')) {
	RedefineOptions = YES;
	ParseRedefinedOptions (argv[i+1]) ;
	d=2;
      }
      if (strchr (argv[i], 's')) {
	Restart = YES;
	d=2;
	NbRestart = atoi(argv[i+1]);
	if ((NbRestart < 0)) {
	  masterprint ("Incorrect restart number\n");
	  PrintUsage (argv[0]);
	}
      }
      if (strchr (argv[i], '#')) {
	d=2;
	ArrayNb = atoi(argv[i+1]);
	if (ArrayNb <= 0) {
	  masterprint ("Incorrect Array number after -# flag\n");
	  PrintUsage (argv[0]);
	}
      }
      if (strchr (argv[i], 'p')) {
	PostRestart = YES;
      }
      if (strchr (argv[i], 'S')) {
	Restart_Full = YES;
	d=2;
	NbRestart = atoi(argv[i+1]);
	if ((NbRestart < 0)) {
	  masterprint ("Incorrect restart number\n");
	  PrintUsage (argv[0]);
	}
      }
      if (strchr (argv[i], 'V')) {
	Dat2vtk = YES;
	Restart_Full = YES;
	d=2;
	NbRestart = atoi(argv[i+1]);
	if ((NbRestart < 0)) {
	  masterprint ("Incorrect output number\n");
	  PrintUsage (argv[0]);	  
	}
      }
      if (strchr (argv[i], 'B')) {
	Vtk2dat = YES;
	Restart_Full = YES;
	d=2;
	NbRestart = atoi(argv[i+1]);
	if ((NbRestart < 0)) {
	  masterprint ("Incorrect output number\n");
	  PrintUsage (argv[0]);	  
	}
      }
      if (strchr (argv[i], 'D')) {
	d=2;
	DeviceManualSelection = atoi(argv[i+1]);
      }
    }
    else strcpy (ParameterFile, argv[i]);
  }

#ifdef WRITEGHOSTS
  if (Merge == YES) {
	mastererr ("Cannot merge outputs when dumping ghost values.\n");
	mastererr ("'make nofulldebug' could fix this problem.\n");
	mastererr ("Using the -k flag could be another solution.\n");
	prs_exit (1);
  }
#endif
  
  if (ParameterFile[0] == 0) PrintUsage (argv[0]);

#ifdef MPICUDA
  EarlyDeviceSelection();
#endif
  MPI_Init (&argc, &argv);
  MPI_Comm_rank (MPI_COMM_WORLD, &CPU_Rank);
  MPI_Comm_size (MPI_COMM_WORLD, &CPU_Number);
  CPU_Master = (CPU_Rank == 0 ? 1 : 0);
  

#ifndef MPICUDA
  SelectDevice(CPU_Rank);
#endif
  InitVariables ();
  MPI_Barrier(MPI_COMM_WORLD);
  ReadDefaultOut ();
  ReadVarFile (ParameterFile);
  if (strcmp (PLANETCONFIG, "NONE") != 0)
    ThereArePlanets = YES;


  if (ORBITALRADIUS > 1.0e-30){
    YMIN *= ORBITALRADIUS;
    YMAX *= ORBITALRADIUS;
    DT   *= sqrt(ORBITALRADIUS*ORBITALRADIUS*ORBITALRADIUS);
  }


  SubsDef (OUTPUTDIR, DefaultOut);

  /* This must be placed ***BEFORE*** reading the input files in case of a restart */
  if ((ArrayNb) && (EarlyOutputRename == YES)) {
    i = strlen(OUTPUTDIR);
    if (OUTPUTDIR[i-1] == '/') OUTPUTDIR[i-1] = 0;//Remove trailing slash if any
    sprintf (OUTPUTDIR, "%s%06d/", OUTPUTDIR, ArrayNb); //Append numerical suffix
    /* There is no need to perform the wildcard (@) substitution. This has already been done */
    printf ("\n\n***\n\nNew Output Directory is %s\n\n***\n\n", OUTPUTDIR);
    MakeDir(OUTPUTDIR); /*Create the output directory*/
  }


  MakeDir(OUTPUTDIR); /*Create the output directory*/

#if !defined(X)
  NX = 1;
#endif
#if !defined(Y)
  NY = 1;
#endif
#if !defined(Z)
  NZ = 1;
#endif

  SelectWriteMethod();

#if !defined(Y) && !defined(Z)
  if (CPU_Rank==1){
    prs_error ("You cannot split a 1D mesh in x. Sequential runs only!");
  }
  if (CPU_Number > 1) {
    MPI_Finalize();
    prs_exit(EXIT_FAILURE);
  }
#endif
    
  ListVariables ("variables.par"); //Writes all variables defined in set up
  ListVariablesIDL ("IDL.var");
  ChangeArch(); /*Changes the name of the main functions
		  ChangeArch adds _cpu or _gpu if GPU is activated.*/
  split(&Gridd); /*Split mesh over PEs*/
  InitSpace();
  WriteDim();
  InitSurfaces();
  LightGlobalDev(); /* Copy light arrays to the device global memory */
  CreateFields(); // Allocate all fields.

  Sys = InitPlanetarySystem(PLANETCONFIG);
  ListPlanets();
  if(Corotating)
    OMEGAFRAME = GetPsysInfo(FREQUENCY);
  OMEGAFRAME0 = OMEGAFRAME;
  /* We need to keep track of initial azimuthal velocity to correct
the target velocity in Stockholm's damping prescription. We copy the
value above *after* rescaling, and after any initial correction to
OMEGAFRAME (which is used afterwards to build the initial Vx field. */

  
  if(Restart == YES || Restart_Full == YES) {
    CondInit (); //Needed even for restarts: some setups have custom
		 //definitions (eg potential for setup MRI) or custom
		 //scaling laws (eg. setup planetesimalsRT).
    begin_i = RestartSimulation(NbRestart);
    if (ThereArePlanets) {
      PhysicalTime  = GetfromPlanetFile (NbRestart, 9, 0);
      OMEGAFRAME  = GetfromPlanetFile (NbRestart, 10, 0);
      RestartPlanetarySystem (NbRestart, Sys);
    }
  }
  else {
    if (ThereArePlanets)
      EmptyPlanetSystemFiles ();
    CondInit(); // Initialize set up
    // Note: CondInit () must be called only ONCE (otherwise some
    // custom scaling laws may be applied several times).
  }

  if (StretchOldOutput == YES) {
    StretchOutput (StretchNumber);
  }

  FARGO_SAFE(comm(ENERGY)); //Very important for isothermal cases!

  /* This must be placed ***after*** reading the input files in case of a restart */
  if ((ArrayNb) && (EarlyOutputRename == NO)) {
    i = strlen(OUTPUTDIR);
    if (OUTPUTDIR[i-1] == '/') OUTPUTDIR[i-1] = 0;//Remove trailing slash if any
    sprintf (OUTPUTDIR, "%s%06d/", OUTPUTDIR, ArrayNb); //Append numerical suffix
    /* There is no need to perform the wildcard (@) substitution. This has already been done */
    printf ("\n\n***\n\nNew Output Directory is %s\n\n***\n\n", OUTPUTDIR);
    MakeDir(OUTPUTDIR); /*Create the output directory*/
    ListVariables ("variables.par"); //Writes all variables defined in set up
    ListVariablesIDL ("IDL.var");
    InitSpace();
    WriteDim ();
  }
  
  DumpToFargo3drc(argc, argv);

  FillGhosts(PrimitiveVariables()); 
#ifdef STOCKHOLM 
  FARGO_SAFE(init_stockholm());
#ifdef STOCKHOLMACC
  FARGO_SAFE(ComputeVymed(Vy));
  FARGO_SAFE(ComputeRhomed(Density));
  
  Write2D(Density0_avg, "density0_2d_avg.dat", OUTPUTDIR, GHOSTINC);
  Write2D(Vy0_avg, "vy0_2d_avg.dat", OUTPUTDIR, GHOSTINC);
#endif
#endif

#ifdef GHOSTSX
  masterprint ("\n\nNew version with ghost zones in X activated\n");
#else
  masterprint ("Standard version with no ghost zones in X\n");
#endif
#ifdef TIMER
    clock_t begin_timer_time, end_timer_time;
    real timer_time_elapsed;
#endif
  ntot = NTOTINIT;
  for (ni = 0; ni<NITER; ni++) { // Iteration loop
      ntot = (ni == 0) ? NTOTINIT : NTOT; 
      masterprint ("Start of %d iteration\n", ni);
      masterprint ("Evolving waves for %d DT (DT = %lg)\n", ntot,DT);
      for (i = begin_i; i<=ntot; i++) { // MAIN LOOP
    #ifdef TIMER
        if (i==begin_i) {
            begin_timer_time = clock();
        }
    #endif
        if (NINTERM * (TimeStep = (i / NINTERM)) == i) {

            TimeStepIter = ni;

    #if defined(MHD) && defined(DEBUG)
          FARGO_SAFE(ComputeDivergence(Bx, By, Bz));
    #endif
          if (ThereArePlanets)
        WritePlanetSystemFile(TimeStep, NO);
          
    #ifndef NOOUTPUTS
          WriteOutputsAndDisplay(ALL);


          if(CPU_Master) printf("OUTPUTS %d at date t = %f OK\n", TimeStep, PhysicalTime);
    #endif

          if (TimeInfo == YES)
        GiveTimeInfo (TimeStep);
        }

        if (NSNAP != 0) {
          if (NSNAP * (TimeStep = (i / NSNAP)) == i) {
        WriteOutputsAndDisplay(SPECIFIC);
          }
        }
        
        AlgoGas(FALSE);
        MonitorGlobal (MONITOR2D      | MONITORY | MONITORY_RAW|	\
               MONITORSCALAR  | MONITORZ | MONITORZ_RAW);
        
        if (ThereArePlanets) {
          WriteTorqueAndWork(TimeStep, 0);
          WritePlanetSystemFile(TimeStep, YES);
          SolveOrbits (Sys);
        }
    #ifdef TIMER
        if (i==begin_i) {
            end_timer_time = clock();
            timer_time_elapsed =( (double)(end_timer_time-begin_timer_time))/CLOCKS_PER_SEC;
            masterprint("time for time_step was %g s\n",timer_time_elapsed);
        }
    #endif

      }
      masterprint ("End of %d iteration\n", ni);
      AlgoGas(TRUE);
      masterprint ("Computing steady state\n");
      compute_steady_state();
      add_avgs();
      output_steady_state(ni);
      clear_averages();
  }

  MPI_Finalize();  
  printf("End of simulation!\n");
  return 0;  
}