int main(int argc,char **argv)
{
  int curr_arg;
  bool bDebug;
  bool bVerbose;
  bool bHaveDateString;
  char *date_string;
  bool bGetDateFromCwd;
  bool bPosNeg;
  int retval;
  int offset;
  FILE *fptr;
  int linelen;
  int line_no;
  int number;
  int work;
  int total;
  int positive_total;
  int negative_total;

  if ((argc < 2) || (argc > 8)) {
    printf(usage);
    return 1;
  }

  bDebug = false;
  bVerbose = false;
  bHaveDateString = false;
  bGetDateFromCwd = false;
  bPosNeg = false;
  offset = 0;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-debug"))
      bDebug = true;
    else if (!strcmp(argv[curr_arg],"-verbose"))
      bVerbose = true;
    else if (!strncmp(argv[curr_arg],"-offset",7))
      sscanf(&argv[curr_arg][7],"%d",&offset);
    else if (!strncmp(argv[curr_arg],"-date",5)) {
      date_string = &argv[curr_arg][5];
      bHaveDateString = true;
    }
    else if (!strcmp(argv[curr_arg],"-get_date_from_cwd"))
      bGetDateFromCwd = true;
    else if (!strcmp(argv[curr_arg],"-pos_neg"))
      bPosNeg = true;
    else
      break;
  }

  if (argc - curr_arg != 1) {
    printf(usage);
    return 2;
  }

  if (bHaveDateString && bGetDateFromCwd) {
    printf("can't specify both -date and -get_date_from_cwd\n");
    return 3;
  }

  if (bDebug || bGetDateFromCwd)
    getcwd(save_dir,_MAX_PATH);

  if (bGetDateFromCwd) {
    retval = get_date_from_cwd(save_dir,&date_string);

    if (retval) {
      printf("get_date_from_cwd() failed: %d\n",retval);
      return 4;
    }

    bHaveDateString = true;
  }

  if ((fptr = fopen(argv[curr_arg],"r")) == NULL) {
    printf(couldnt_open,argv[curr_arg]);
    return 5;
  }

  line_no = 0;
  total = 0;

  if (bPosNeg) {
    positive_total = 0;
    negative_total = 0;
  }

  for ( ; ; ) {
    GetLine(fptr,line,&linelen,MAX_LINE_LEN);

    if (feof(fptr))
      break;

    line_no++;

    sscanf(&line[offset],"%d %d",&number,&work);
    work *= number;

    total += work;

    if (bVerbose)
      printf("%d %d %s\n",total,work,line);

    if (bPosNeg) {
      if (work < 0)
        negative_total += work;
      else
        positive_total += work;
    }
  }

  fclose(fptr);

  if (!bPosNeg) {
    if (!bDebug) {
      if (!bHaveDateString)
        printf("%d\n",total);
      else
        printf("%d\t%s\n",total,date_string);
    }
    else {
      if (!bHaveDateString)
        printf("%d %s/%s\n",total,save_dir,argv[curr_arg]);
      else
        printf("%d\t%s %s/%s\n",total,date_string,save_dir,argv[curr_arg]);
    }
  }
  else {
    if (!bDebug) {
      if (!bHaveDateString)
        printf("%d %d %d\n",total,positive_total,negative_total);
      else
        printf("%d\t%s %d %d\n",total,date_string,positive_total,negative_total);
    }
    else {
      if (!bHaveDateString) {
        printf("%d %d %d %s/%s\n",
          total,positive_total,negative_total,save_dir,argv[curr_arg]);
      }
      else {
        printf("%d\t%s %d %d %s/%s\n",
          total,date_string,positive_total,negative_total,save_dir,argv[curr_arg]);
      }
    }
  }

  return 0;
}
int main(int argc,char **argv)
{
  int m;
  int n;
  int curr_arg;
  bool bDebug;
  int player_name_ix;
  int player_name_len;
  FILE *fptr0;
  int filename_len;
  FILE *fptr;
  int line_len;
  int line_no;
  int ix;
  int file_no;

  if ((argc < 3) || (argc > 4)) {
    printf(usage);
    return 1;
  }

  bDebug = false;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-debug")) {
      bDebug = true;
      getcwd(save_dir,_MAX_PATH);
    }
    else
      break;
  }

  if (argc - curr_arg != 2) {
    printf(usage);
    return 2;
  }

  player_name_ix = curr_arg++;
  player_name_len = strlen(argv[player_name_ix]);

  if ((fptr0 = fopen(argv[curr_arg],"r")) == NULL) {
    printf(couldnt_open,argv[curr_arg]);
    return 3;
  }

  file_no = 0;

  for ( ; ; ) {
    GetLine(fptr0,filename,&filename_len,MAX_FILENAME_LEN);

    if (feof(fptr0))
      break;

    file_no++;

    if ((fptr = fopen(filename,"r")) == NULL) {
      printf(couldnt_open,filename);
      continue;
    }

    line_no = 0;

    for ( ; ; ) {
      GetLine(fptr,line,&line_len,MAX_LINE_LEN);

      if (feof(fptr))
        break;

      line_no++;

      if (Contains(true,
        line,line_len,
        argv[player_name_ix],player_name_len,
        &ix)) {

        if (!strncmp(line,dealt_to,DEALT_TO_LEN)) {
          for (n = 0; n < line_len; n++) {
            if (line[n] == '[')
              break;
          }

          if (n < line_len) {
            n++;

            for (m = n; m < line_len; m++) {
              if (line[m] == ']')
                break;
            }

            if (m < line_len) {
              line[m] = 0;

              if (!bDebug)
                printf("%s\n",&line[n]);
              else
                printf("%s %s\\%s\n",&line[n],save_dir,filename);

              continue;
            }
          }
        }
      }
    }

    fclose(fptr);
  }

  return 0;
}
Esempio n. 3
0
void PrintInstructions2()
{
	printf("\nThe Game is going to start . Press any key when you are ready.");
	GetLine();
	printf("\nTo pause,click mouse on the graph.\n");
}
Esempio n. 4
0
void PreviewSubTask()
#endif
{
#ifndef __PPC__
	struct SubTask *st;
#endif
	BOOL done = FALSE, working = FALSE, init = FALSE, stop = FALSE;
	int y;
	struct SubTaskMsg *stm;
	struct PreviewData *data;
	rsiSMALL_COLOR *line;

#ifndef __PPC__
	st = InitSubTask();
#endif
	if(st)
	{
		/*
		** after the sub task is up and running, we go into
		** a loop and process the messages from the main task.
		*/
		while(!done)
		{
			while((stm = (struct SubTaskMsg *)WARPOS_PPC_FUNC(GetMsg)(st->st_Port)))
			{
				switch(stm->stm_Command)
				{
					case STC_SHUTDOWN:
						// This is the shutdown message from KillSubTask().
						done = TRUE;
						working = FALSE;
						break;
					case STC_CLEANUP:
						working = FALSE;
						if(data->preview)
						{
#ifdef __MIXEDBINARY__
							PreviewDelete(data->preview);
#else
							delete data->preview;
#endif
							data->preview = NULL;
						}
						break;
					case STC_START:
						working = TRUE;
						stop = FALSE;
						init = FALSE;
						data = (struct PreviewData*)stm->stm_Parameter;
#ifdef __MIXEDBINARY__
						data->preview = PreviewCreate();
#else
						data->preview = new PREVIEW;
#endif
						if(!data->preview)
							done = TRUE;
						break;
					case STC_STOP:
						stop = TRUE;
						break;
					case STC_RESUME:
						stop = FALSE;
						break;
				}

				/*
				** If we received a shutdown message, we do not reply it
				** immediately. First, we need to free our resources.
				*/
				if(done)
					break;
				WARPOS_PPC_FUNC(ReplyMsg)((struct Message *)stm);
			}
			if(working && !stop)
			{
				if(!init)
				{
#ifdef __MIXEDBINARY__
					if(Init(data->preview, data->width, data->height, LINES, data->surf, data->object))
#else
					if(data->preview->Init(data->width, data->height, LINES, data->surf, data->object))
#endif
					{
						init = TRUE;
						DOMETHOD(app, MUIM_Application_PushMethod, data->msghandler, 4, MUIM_MsgHandler_PushMessage, data->renderarea, 1, MUIM_Render_ResetColors);
						DOMETHOD(app, MUIM_Application_PushMethod, data->msghandler, 6, MUIM_MsgHandler_PushMessage, data->renderarea, 3, MUIM_Set, MUIA_Render_SubTask, st);
#ifdef __MIXEDBINARY__
						DOMETHOD(app, MUIM_Application_PushMethod, data->msghandler, 6, MUIM_MsgHandler_PushMessage, data->renderarea, 3, MUIM_Set, MUIA_Render_Data, GetLine(data->preview));
#else
						DOMETHOD(app, MUIM_Application_PushMethod, data->msghandler, 6, MUIM_MsgHandler_PushMessage, data->renderarea, 3, MUIM_Set, MUIA_Render_Data, data->preview->GetLine());
#endif
						DOMETHOD(app, MUIM_Application_PushMethod, data->msghandler, 6, MUIM_MsgHandler_PushMessage, data->renderarea, 3, MUIM_Set, MUIA_Render_Lines, LINES);
						y = 0;
					}
					else
					{
						working = FALSE;
					}
				}

#ifdef __MIXEDBINARY__
				RenderLines(data->preview, y);
				line = GetLine(data->preview);
#else
				data->preview->RenderLines(y);
				line = data->preview->GetLine();
#endif
				DOMETHOD(app, MUIM_Application_PushMethod, data->msghandler, 6, MUIM_MsgHandler_PushMessage, data->renderarea, 3, MUIM_Set, MUIA_Render_Data, &line[y*data->width]);
				DOMETHOD(app, MUIM_Application_PushMethod, data->msghandler, 5, MUIM_MsgHandler_PushMessage, data->renderarea, 2, MUIM_Render_DrawUpdate, y);

				y += LINES;
				if(y >= data->height)
				{
					working = FALSE;
					if(data->caller)
					{
						DOMETHOD(app, MUIM_Application_PushMethod, data->msghandler, 4, MUIM_MsgHandler_PushMessage, data->caller, 1, MUIM_SubTask_Finished);
					}
				}
			}
			else
			{
				/* We have nothing to do, just sit quietly and wait for something to happen */
				if(!done)
				{
					WARPOS_PPC_FUNC(WaitPort)(st->st_Port);
				}
			}
		}
#ifdef __PPC__
		ExitSubTaskPPC(st, stm);
#else
		ExitSubTask(st, stm);
#endif
		if(data->preview)
		{
#ifdef __MIXEDBINARY__
			PreviewDelete(data->preview);
#else
			delete data->preview;
#endif
		}
	}
}
Esempio n. 5
0
void CVPCB_MAINFRAME::AssocieModule( wxCommandEvent& event )
{
    FOOTPRINT_ALIAS_LIST aliases;
    FOOTPRINT_ALIAS*     alias;
    COMPONENT*           component;
    wxFileName           fn;
    wxString             msg, tmp;
    char                 Line[1024];
    FILE*                file;
    size_t               ii;

    SEARCH_STACK&        search = Kiface().KifaceSearch();

    if( m_netlist.IsEmpty() )
        return;

    // Find equivalents in all available files.
    for( ii = 0; ii < m_AliasLibNames.GetCount(); ii++ )
    {
        fn = m_AliasLibNames[ii];

        if( !fn.HasExt() )
        {
            fn.SetExt( FootprintAliasFileExtension );
            // above fails if filename has more than one point
        }
        else
        {
            fn.SetExt( fn.GetExt() + wxT( "." ) + FootprintAliasFileExtension );
        }

        tmp = search.FindValidPath( fn.GetFullPath() );

        if( !tmp )
        {
            msg.Printf( _( "Footprint alias library file '%s' could not be found in the "
                           "default search paths." ),
                        GetChars( fn.GetFullName() ) );
            wxMessageBox( msg, FMT_TITLE_LIB_LOAD_ERROR, wxOK | wxICON_ERROR );
            continue;
        }

        file = wxFopen( tmp, wxT( "rt" ) );

        if( file == NULL )
        {
            msg.Printf( _( "Error opening alias library '%s'." ), GetChars( tmp ) );
            wxMessageBox( msg, FMT_TITLE_LIB_LOAD_ERROR, wxOK | wxICON_ERROR );
            continue;
        }

        while( GetLine( file, Line, NULL, sizeof(Line) ) != NULL )
        {
            char* text = Line;
            wxString value, footprint, wtext = FROM_UTF8( Line );

            value = GetQuotedText( wtext );

            if( text == NULL || ( *text == 0 ) || value.IsEmpty() )
                continue;

            footprint = GetQuotedText( wtext );

            if( footprint.IsEmpty() )
                continue;

            value.Replace( wxT( " " ), wxT( "_" ) );

            alias = new FOOTPRINT_ALIAS();
            alias->m_Name = value;
            alias->m_FootprintName = footprint;
            aliases.push_back( alias );
        }

        fclose( file );
    }

    // Display the number of footprint aliases.
    msg.Printf( _( "%d footprint aliases found." ), aliases.size() );
    SetStatusText( msg, 0 );

    m_skipComponentSelect = true;
    ii = 0;

    for( unsigned kk = 0;  kk < m_netlist.GetCount();  kk++ )
    {
        component = m_netlist.GetComponent( kk );

        bool found = false;
        m_compListBox->SetSelection( ii++, true );

        if( !component->GetFPID().empty() )
            continue;

        BOOST_FOREACH( FOOTPRINT_ALIAS& alias, aliases )
        {

            if( alias.m_Name.CmpNoCase( component->GetValue() ) != 0 )
                continue;

            // filter alias so one can use multiple aliases (for polar and
            // nonpolar caps for example)
            const FOOTPRINT_INFO *module = m_footprints.GetModuleInfo( alias.m_FootprintName );

            if( module )
            {
                size_t filtercount = component->GetFootprintFilters().GetCount();
                found = ( 0 == filtercount ); // if no entries, do not filter

                for( size_t jj = 0; jj < filtercount && !found; jj++ )
                {
                    found = module->GetFootprintName().Matches( component->GetFootprintFilters()[jj] );
                }
            }
            else
            {
                msg.Printf( _( "Component %s: footprint %s not found in any of the project "
                               "footprint libraries." ),
                            GetChars( component->GetReference() ),
                            GetChars( alias.m_FootprintName ) );
                wxMessageBox( msg, _( "CvPcb Error" ), wxOK | wxICON_ERROR, this );
            }

            if( found )
            {
                SetNewPkg( alias.m_FootprintName );
                break;
            }

        }

        // obviously the last chance: there's only one filter matching one footprint
        if( !found && 1 == component->GetFootprintFilters().GetCount() )
        {
            // we do not need to analyse wildcards: single footprint do not
            // contain them and if there are wildcards it just will not match any
            const FOOTPRINT_INFO* module = m_footprints.GetModuleInfo( component->GetFootprintFilters()[0] );

            if( module )
            {
                SetNewPkg( component->GetFootprintFilters()[0] );
            }
        }
    }

    m_skipComponentSelect = false;
}
Esempio n. 6
0
extern void ParseMicrosoft( void )
/********************************/
// read in Microsoft linker commands
{
    char        cmd[LINE_BUF_SIZE];
    char        *end;
    size_t      len;
    bool        first;
    bool        more_objs;
    bool        more_libs;


    /* Start with object files. */
    mask_spc_chr = 0x1f;    /* Replace spaces with another character. */
    more_cmdline = !!*CmdFile->current;
    first = more_cmdline;
    is_new_line = true;
    do {
        more_objs = false;  /* No more unless we discover otherwise. */
        if( first )
            len = GetLine( cmd, sizeof( cmd ), OPTION_SLOT );
        else
            len = GetLine( cmd, sizeof( cmd ), OBJECT_SLOT );

        if( !len )
            break;
        end = LastStringChar( cmd );
        if( *end == mask_spc_chr ) {
            more_objs = true;
            *end = '\0';
        }
        TokenizeLine( cmd, mask_spc_chr, DoOneObject );
        first = false;
    } while( more_objs );

    /* Check for possible error conditions. */
    if( OverlayLevel )
        Error( "unmatched left parenthesis" );
    FindObjectName();   /* This will report an error if no objects. */

    mask_spc_chr = 0;   /* Remove spaces in input. */
    /* Get executable and map file name. */
    GetNextInput( cmd, sizeof( cmd ), RUN_SLOT );
    GetNextInput( cmd, sizeof( cmd ), MAP_SLOT );

    mask_spc_chr = 0x1f;    /* Replace spaces with another character. */
    /* Get library file names. */
    if( !is_term ) {
        do {
            GetLine( cmd, sizeof( cmd ), LIBRARY_SLOT );
            more_libs = false;
            if( is_term || *cmd == '\0' )
                break;
            end = LastStringChar( cmd );
            if( *end == mask_spc_chr ) {
                more_libs = true;
                *end = '\0';
            }
            TokenizeLine( cmd, mask_spc_chr, DoOneLib );
        } while( more_libs );
    }

    mask_spc_chr = 0;   /* Remove spaces in input again. */

    /* Get def file name and process it. */
    GetNextInput( cmd, sizeof( cmd ), DEF_SLOT );
    ProcessDefFile();
}
Esempio n. 7
0
int main(int argc,char **argv)
{
  int m;
  int n;
  int p;
  int curr_arg;
  bool bDebug;
  bool bCount;
  bool bShowZero;
  int reupped_count;
  int player_name_ix;
  int player_name_len;
  FILE *fptr0;
  int filename_len;
  FILE *fptr;
  int line_len;
  int line_no;
  int dbg_line_no;
  int ix;
  int street;
  int num_street_markers;
  int starting_balance;
  int spent_this_street;
  int spent_this_hand;
  int end_ix;
  int uncalled_bet_amount;
  int collected_from_pot;
  int collected_from_pot_count;
  int ending_balance;
  int file_no;
  int dbg_file_no;
  int dbg;
  int work;
  double dwork1;
  double dwork2;
  bool bSkipping;

  if ((argc < 3) || (argc > 6)) {
    printf(usage);
    return 1;
  }

  bDebug = false;
  bCount = false;
  bShowZero = false;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-debug"))
      bDebug = true;
    else if (!strcmp(argv[curr_arg],"-count"))
      bCount = true;
    else if (!strcmp(argv[curr_arg],"-show_zero")) {
      bShowZero = true;
      bCount = true;
    }
    else
      break;
  }

  if (argc - curr_arg != 2) {
    printf(usage);
    return 2;
  }

  player_name_ix = curr_arg++;
  player_name_len = strlen(argv[player_name_ix]);

  if ((fptr0 = fopen(argv[curr_arg],"r")) == NULL) {
    printf(couldnt_open,argv[curr_arg]);
    return 3;
  }

  file_no = 0;
  dbg_file_no = -1;

  for ( ; ; ) {
    GetLine(fptr0,filename,&filename_len,MAX_FILENAME_LEN);

    if (feof(fptr0))
      break;

    strcpy(prev_filename,filename);
    file_no++;

    if (dbg_file_no == file_no)
      dbg = 1;

    if ((fptr = fopen(filename,"r")) == NULL) {
      printf(couldnt_open,filename);
      continue;
    }

    line_no = 0;
    ending_balance = -1;
    reupped_count = 0;

    for ( ; ; ) {
      GetLine(fptr,line,&line_len,MAX_LINE_LEN);

      if (feof(fptr))
        break;

      line_no++;

      if (line_no == dbg_line_no)
        dbg = 1;

      if (bDebug)
        printf("line %d %s\n",line_no,line);

      if (Contains(true,
        line,line_len,
        argv[player_name_ix],player_name_len,
        &ix)) {

        if (Contains(true,
          line,line_len,
          in_chips,IN_CHIPS_LEN,
          &ix)) {

          bSkipping = false;

          if (ending_balance == 0)
            reupped_count++;

          street = 0;
          num_street_markers = 0;
          spent_this_street = 0;
          spent_this_hand = 0;
          uncalled_bet_amount = 0;
          collected_from_pot = 0;
          collected_from_pot_count = 0;

          line[ix] = 0;

          for (ix--; (ix >= 0) && (line[ix] != '('); ix--)
            ;

          sscanf(&line[ix+1],"%d",&starting_balance);

          if (bDebug)
            printf("line %d starting_balance = %d\n",line_no,starting_balance);

          continue;
        }
        else if (bSkipping)
          continue;
        else if (Contains(true,
          line,line_len,
          posts,POSTS_LEN,
          &ix)) {
          work = get_work_amount(line,line_len);
          spent_this_street += work;

          if (bDebug) {
            printf("line %d street %d POSTS work = %d, spent_this_street = %d\n",
              line_no,street,work,spent_this_street);
          }

          continue;
        }
        else if (Contains(true,
          line,line_len,
          collected,COLLECTED_LEN,
          &ix)) {

          for (end_ix = ix + COLLECTED_LEN; end_ix < line_len; end_ix++) {
            if (line[end_ix] == ' ')
              break;
          }

          line[end_ix] = 0;
          sscanf(&line[ix + COLLECTED_LEN],"%d",&work);

          if (!collected_from_pot_count) {
            spent_this_hand += spent_this_street;
            street++;
            spent_this_street = 0;
          }

          collected_from_pot += work;
          collected_from_pot_count++;

          if (bDebug) {
            printf("line %d street %d COLLECTED work = %d, collected_from_pot = %d\n",
              line_no,street,work,collected_from_pot);
          }

          continue;
        }
        else if (!strncmp(line,uncalled_bet,UNCALLED_BET_LEN)) {
          sscanf(&line[UNCALLED_BET_LEN],"%d",&uncalled_bet_amount);
          spent_this_street -= uncalled_bet_amount;

          if (bDebug) {
            printf("line %d street %d UNCALLED uncalled_bet_amount = %d, spent_this_street = %d\n",
              line_no,street,uncalled_bet_amount,spent_this_street);
          }

          continue;
        }
        else if (Contains(true,
          line,line_len,
          folds,FOLDS_LEN,
          &ix)) {
          spent_this_hand += spent_this_street;

          if (bDebug) {
            printf("line %d street %d FOLDS spent_this_street = %d, spent_this_hand = %d\n",
              line_no,street,spent_this_street,spent_this_hand);
          }

          bSkipping = true;

          ending_balance = starting_balance - spent_this_hand + collected_from_pot;

          continue;
        }
        else if (Contains(true,
          line,line_len,
          bets,BETS_LEN,
          &ix)) {
          work = get_work_amount(line,line_len);
          spent_this_street += work;

          if (bDebug) {
            printf("line %d street %d BETS work = %d, spent_this_street = %d\n",
              line_no,street,work,spent_this_street);
          }
        }
        else if (Contains(true,
          line,line_len,
          calls,CALLS_LEN,
          &ix)) {
          work = get_work_amount(line,line_len);
          spent_this_street += work;

          if (bDebug) {
            printf("line %d street %d CALLS work = %d, spent_this_street = %d\n",
              line_no,street,work,spent_this_street);
          }
        }
        else if (Contains(true,
          line,line_len,
          raises,RAISES_LEN,
          &ix)) {
          work = get_work_amount(line,line_len);
          spent_this_street = work;

          if (bDebug) {
            printf("line %d street %d RAISES work = %d, spent_this_street = %d\n",
              line_no,street,work,spent_this_street);
          }
        }
      }
      else if (bSkipping)
        continue;
      else {
        if (!strncmp(line,summary,SUMMARY_LEN)) {
          if (bDebug)
            printf("line %d SUMMARY line detected; skipping\n",line_no);

          bSkipping = true;

          ending_balance = starting_balance - spent_this_hand + collected_from_pot;

          continue;
        }

        if (!strncmp(line,street_marker,STREET_MARKER_LEN)) {
          num_street_markers++;

          if (num_street_markers > 1) {
            if (street <= 3)
              spent_this_hand += spent_this_street;

            street++;
            spent_this_street = 0;
          }
        }
      }
    }

    if (bShowZero || reupped_count) {
      if (!bCount)
        printf("%s\n",filename);
      else
        printf("%7d %s\n",reupped_count,filename);
    }

    fclose(fptr);
  }

  fclose(fptr0);

  return 0;
}
Esempio n. 8
0
DWORD WINAPI Execute(LPDWORD data)
{
	int i, linenumber;
	char line[256], buf[256], logbuf[100], *prog;
	BOOL error = FALSE;

	obj = NULL;
	light = NULL;

	ULONG arg[MAXARGS];

	for (i = 0; i < MAXARGS; i++)
		arg[i] = NULL;

	prog = ((THREAD_DATA *)data)->szProg;
	pDisplay = ((THREAD_DATA *)data)->pDisplay;
	strcpy(szIncludePath, "");
	strcpy(szPicturePath, "");

	err = rsiSetLogCB(Log);
	if (err)
	{
		rsiGetErrorMsg(buf,err);
		Log(buf);
	}

	err = rsiSetUpdateStatusCB(UpdateStatus);
	if (err)
	{
		rsiGetErrorMsg(buf,err);
		Log(buf);
	}

	err = rsiSetCheckCancelCB(CheckCancel);
	if (err)
	{
		rsiGetErrorMsg(buf,err);
		Log(buf);
	}

	err = rsiSetCooperateCB(Cooperate);
	if (err)
	{
		rsiGetErrorMsg(buf,err);
		Log(buf);
	}

	linenumber = 0;
	include = 0;

	while ((*prog || include > 0) && !error)
	{ 
		GetLine(&prog, line, &linenumber);
		// read command first
		if (!Scan(line, buf, arg))
		{
			i = 0;
			// find command in list	
  			while (commands[i].name && stricmp(buf, commands[i].name))
  		 		i++;
				
			// call corresponding function with "arg" as argument
			if (commands[i].func)
				error = commands[i].func(arg);
			else
				error = ERROR_UNKNOWNCOM;
				
			for (i = 0; i < MAXARGS; i++)
			{
				if (arg[i])
					delete (ULONG *)arg[i];
				arg[i] = NULL;
			}

			if (error)
			{
				if (include)
				{
					sprintf(logbuf, "In include file: \"%s\"", Includefile[include].name);
					pDisplay->Log(logbuf);
					linenumber = Includefile[include].linenumber;
				}
				sprintf(logbuf, "Error executing command in line %i", linenumber);
				pDisplay->Log(logbuf);
				pDisplay->Log(line);
				GetError(logbuf, error);
				pDisplay->Log(logbuf);
			}
		}
	}
	if (error)
	{
		pDisplay->Log("Error occurred");
		pDisplay->Log("Cancel execution");
		// close open include files
		while (include > 0)
		{
			if (Includefile[include].hFile)
				fclose(Includefile[include].hFile);
			include--;
		}
	}
	else
	{
		if (pDisplay->CheckCancel())
			pDisplay->Log("Execution canceled");
		else
			pDisplay->Log("Execution successful");
	}

	return TRUE;
}
Esempio n. 9
0
int main(int argc,char **argv)
{
  int curr_arg;
  bool bDebug;
  bool bConsistency;
  bool bDelta;
  bool bStartingBalance;
  bool bTerse;
  bool bDoubleZero;
  bool bNoBalances;
  bool bStud;
  bool bRazz;
  int player_name_ix;
  int player_name_len;
  FILE *fptr0;
  int filename_len;
  FILE *fptr;
  int line_len;
  int line_no;
  int ix;
  int street;
  int num_street_markers;
  int max_streets;
  int starting_balance;
  int ante;
  int bring_in;
  int spent_this_street;
  int spent_this_hand;
  int end_ix;
  int wagered_amount;
  int uncalled_bet_amount;
  int collected_from_pot;
  int collected_from_pot_count;
  int ending_balance;
  int delta;
  int max_ending_balance;
  int min_ending_balance;
  int max_delta;
  int min_delta;
  int max_starting_balance;
  int min_starting_balance;
  int file_no;
  int dbg_file_no;
  int dbg;
  int work;
  double dwork;
  int prev_ending_balance;

  if ((argc < 3) || (argc > 10)) {
    printf(usage);
    return 1;
  }

  bDebug = false;
  bConsistency = false;
  bDelta = false;
  bStartingBalance = false;
  bTerse = false;
  bDoubleZero = false;
  bNoBalances = false;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-debug")) {
      bDebug = true;
      getcwd(save_dir,_MAX_PATH);
    }
    else if (!strcmp(argv[curr_arg],"-consistency"))
      bConsistency = true;
    else if (!strcmp(argv[curr_arg],"-delta"))
      bDelta = true;
    else if (!strcmp(argv[curr_arg],"-starting_balance"))
      bStartingBalance = true;
    else if (!strcmp(argv[curr_arg],"-terse"))
      bTerse = true;
    else if (!strcmp(argv[curr_arg],"-double_zero"))
      bDoubleZero = true;
    else if (!strcmp(argv[curr_arg],"-no_balances"))
      bNoBalances = true;
    else
      break;
  }

  if (argc - curr_arg != 2) {
    printf(usage);
    return 2;
  }

  if (bDelta && bStartingBalance) {
    printf("can't specify both -delta and -starting_balance\n");
    return 3;
  }

  player_name_ix = curr_arg++;
  player_name_len = strlen(argv[player_name_ix]);

  if ((fptr0 = fopen(argv[curr_arg],"r")) == NULL) {
    printf(couldnt_open,argv[curr_arg]);
    return 4;
  }

  ending_balance = -1;
  prev_ending_balance = -1;

  if (bDelta) {
    max_delta = -1;
    min_delta = 1;
  }
  else if (bStartingBalance) {
    max_starting_balance = -1;
    min_starting_balance = 1;
  }
  else {
    max_ending_balance = -1;
    min_ending_balance = 1;
  }

  file_no = 0;
  dbg_file_no = -1;

  for ( ; ; ) {
    GetLine(fptr0,filename,&filename_len,MAX_FILENAME_LEN);

    if (feof(fptr0))
      break;

    file_no++;

    if (dbg_file_no == file_no)
      dbg = 1;

    if ((fptr = fopen(filename,"r")) == NULL) {
      printf(couldnt_open,filename);
      continue;
    }

    line_no = 0;
    street = 0;
    num_street_markers = 0;
    ante = 0;
    bring_in = 0;
    spent_this_street = 0;
    spent_this_hand = 0;
    uncalled_bet_amount = 0;
    collected_from_pot = 0;
    collected_from_pot_count = 0;

    for ( ; ; ) {
      GetLine(fptr,line,&line_len,MAX_LINE_LEN);

      if (feof(fptr))
        break;

      line_no++;

      if (Contains(true,
        line,line_len,
        pokerstars,POKERSTARS_LEN,
        &ix)) {

        bStud = false;
        bRazz = false;

        if (Contains(true,
          line,line_len,
          stud,STUD_LEN,
          &ix)) {

          bStud = true;
        }
        else if (Contains(true,
          line,line_len,
          razz,RAZZ_LEN,
          &ix)) {

          bRazz = true;
        }

        if (bStud || bRazz)
          max_streets = 4;
        else
          max_streets = 3;
      }
      else if (Contains(true,
        line,line_len,
        argv[player_name_ix],player_name_len,
        &ix)) {

        if (Contains(true,
          line,line_len,
          in_chips,IN_CHIPS_LEN,
          &ix)) {

          line[ix] = 0;

          for (ix--; (ix >= 0) && (line[ix] != '('); ix--)
            ;

          sscanf(&line[ix+1],"%d",&starting_balance);

          if (bConsistency) {
            if ((ending_balance != -1) &&
                (ending_balance != starting_balance))
              printf("discrepancy: %d %s: starting balance of %d != "
                "last ending balance of %d\n",
                starting_balance - ending_balance,filename,
                starting_balance,ending_balance);
          }

          continue;
        }
        else if (Contains(true,
          line,line_len,
          posts_the_ante,POSTS_THE_ANTE_LEN,
          &ix)) {
          ante = get_work_amount(line,line_len);
          spent_this_hand = ante;
          continue;
        }
        else if ((bStud || bRazz) && Contains(true,
          line,line_len,
          brings_in_for,BRINGS_IN_FOR_LEN,
          &ix)) {
          bring_in = get_work_amount(line,line_len);
          spent_this_street += bring_in;
          continue;
        }
        else if (Contains(true,
          line,line_len,
          posts,POSTS_LEN,
          &ix)) {
          spent_this_street += get_work_amount(line,line_len);
          continue;
        }
        else if (!strncmp(line,dealt_to,DEALT_TO_LEN))
          continue;
        else if (Contains(true,
          line,line_len,
          collected,COLLECTED_LEN,
          &ix)) {

          for (end_ix = ix + COLLECTED_LEN; end_ix < line_len; end_ix++) {
            if (line[end_ix] == ' ')
              break;
          }

          line[end_ix] = 0;
          sscanf(&line[ix + COLLECTED_LEN],"%d",&work);

          if (!collected_from_pot_count) {
            spent_this_hand += spent_this_street;
            street++;
            spent_this_street = 0;
          }

          collected_from_pot += work;
          collected_from_pot_count++;

          continue;
        }
        else if (!strncmp(line,uncalled_bet,UNCALLED_BET_LEN)) {
          sscanf(&line[UNCALLED_BET_LEN],"%d",&uncalled_bet_amount);
          spent_this_street -= uncalled_bet_amount;
          continue;
        }
        else if (Contains(true,
          line,line_len,
          folds,FOLDS_LEN,
          &ix)) {
          spent_this_hand += spent_this_street;
          break;
        }
        else if (Contains(true,
          line,line_len,
          bets,BETS_LEN,
          &ix)) {
          spent_this_street += get_work_amount(line,line_len);
        }
        else if (Contains(true,
          line,line_len,
          calls,CALLS_LEN,
          &ix)) {
          spent_this_street += get_work_amount(line,line_len);
        }
        else if (Contains(true,
          line,line_len,
          raises,RAISES_LEN,
          &ix)) {
          spent_this_street = get_work_amount(line,line_len);
        }
      }
      else {
        if (!strncmp(line,summary,SUMMARY_LEN))
          break;

        if (!strncmp(line,street_marker,STREET_MARKER_LEN)) {
          num_street_markers++;

          if (num_street_markers > 1) {
            if (street <= max_streets)
              spent_this_hand += spent_this_street;

            street++;
            spent_this_street = 0;
          }
        }
      }
    }

    fclose(fptr);

    ending_balance = starting_balance - spent_this_hand + collected_from_pot;
    delta = ending_balance - starting_balance;

    if (bDelta) {
      if ((max_delta == -1) || (delta > max_delta)) {
        max_delta = delta;
        strcpy(max_filename,filename);
      }

      if ((min_delta == 1) || (delta < min_delta)) {
        min_delta = delta;
        strcpy(min_filename,filename);
      }
    }
    else if (bStartingBalance) {
      if ((max_starting_balance == -1) || (starting_balance > max_starting_balance)) {
        max_starting_balance = starting_balance;
        strcpy(max_filename,filename);
      }

      if ((min_starting_balance == 1) || (starting_balance < min_starting_balance)) {
        min_starting_balance = starting_balance;
        strcpy(min_filename,filename);
      }
    }
    else {
      if ((max_ending_balance == -1) || (ending_balance > max_ending_balance)) {
        max_ending_balance = ending_balance;
        strcpy(max_filename,filename);
      }

      if ((min_ending_balance == 1) || (ending_balance < min_ending_balance)) {
        min_ending_balance = ending_balance;
        strcpy(min_filename,filename);
      }
    }

    if (bDoubleZero) {
      if ((prev_ending_balance == 0) && (ending_balance == 0))
        ;
      else {
        prev_ending_balance = ending_balance;
        continue;
      }
    }

    prev_ending_balance = ending_balance;

    if (bNoBalances)
      continue;

    if (!bDebug) {
      if (bTerse) {
        if (bDelta)
          printf("%d\n",delta);
        else {
          printf("%10d %10d %10d %s/%s\n",
            starting_balance,delta,ending_balance,save_dir,filename);
        }
      }
      else if (bDelta)
        printf("%10d %s/%s\n",delta,save_dir,filename);
      else if (bStartingBalance)
        printf("%10d %s/%s\n",starting_balance,save_dir,filename);
      else
        printf("%10d %s/%s\n",ending_balance,save_dir,filename);
    }
    else {
      wagered_amount = spent_this_hand + uncalled_bet_amount;

      printf("%s/%s\n",save_dir,filename);
      printf("%10d starting_balance\n",starting_balance);

      if (ante)
        printf("%10d ante\n",ante);

      if (bring_in)
        printf("%10d bring_in\n",bring_in);

      printf("%10d wagered_amount\n",wagered_amount);
      printf("%10d uncalled_bet_amount\n",uncalled_bet_amount);
      printf("%10d spent_this_hand\n",spent_this_hand);
      printf("%10d collected_from_pot\n",collected_from_pot);
      printf("%10d ending_balance\n",ending_balance);
      printf("%10d delta\n",delta);
      printf("%10d num_street_markers\n",num_street_markers);
      printf("%10d streets\n",street);

      if (collected_from_pot && (delta > 0)) {
        dwork = (double)delta / (double)collected_from_pot;
        printf("%10.2lf opm_percentage\n",dwork);
        dwork = (double)ending_balance / (double)starting_balance;
        printf("%10.2lf starting_balance_multiplier\n",dwork);
      }
    }
  }

  fclose(fptr0);

  if (bDoubleZero || bTerse)
    return 0;

  if (bNoBalances)
    return 0;

  if (bDelta) {
    if (max_delta != -1)
      printf("\n%10d %s\n",max_delta,max_filename);

    if (min_delta != 1)
      printf("%10d %s\n",min_delta,min_filename);
  }
  else if (bStartingBalance) {
    if (max_starting_balance != -1)
      printf("\n%10d %s\n",max_starting_balance,max_filename);

    if (min_starting_balance != 1)
      printf("%10d %s\n",min_starting_balance,min_filename);
  }
  else {
    if (max_ending_balance != -1)
      printf("\n%10d %s\n",max_ending_balance,max_filename);

    if (min_ending_balance != 1)
      printf("%10d %s\n",min_ending_balance,min_filename);
  }

  return 0;
}
Esempio n. 10
0
//=====================================================================
bool Rowind::IsFunctioning() {
	if(GetLine() != Null) {
		return true;
	}
	return false;
}
Esempio n. 11
0
int read_ozone(char* fname, short int** out_data, int* doy, int* year, int* nlats,
               int* nlons, float* minlat, float* minlon, float* maxlat,
               float* maxlon, float* latsteps, float* lonsteps,
               float* lat_array, float* lon_array)
{ 
 FILE *fp;
 char line[MAX_STR_LEN+1];
 char dtype[10],month[4],valbuf[4];
 char c_day_of_month[3];
 int day_of_month;
 int irow,icol,i=0,ival;
 int ilat;
 int number;
 short int* data;
 float mylat;
 float comp_lat,comp_lon;
 char hemisphere1, hemisphere2;
 /*
 Day: 260 Sep 17, 2001    EP/TOMS    NRT OZONE    GEN:01.271 Asc LECT: 11:09 AM 
012345678 1 2345678 2 2345678 3 2345678 4 2345678 5 2345678 6 2345678 7 2345678
 Longitudes:  288 bins centered on 179.375 W to 179.375 E  (1.25 degree steps)  
 Latitudes :  180 bins centered on  89.5   S to  89.5   N  (1.00 degree steps)  
 */

 fp = fopen(fname, "r");
 GetLine(fp,line);
 sscanf(line," Day: %3d ",doy);
 strncpy(month,&line[10],3); month[3]='\0';
 strncpy(c_day_of_month,&line[14],2); c_day_of_month[2]='\0';
 strncpy(dtype,&line[26],7); dtype[7]='\0';
 day_of_month= atoi( c_day_of_month );
 *year= atoi( &line[18] );
 printf("year=%d month=%s day_of_month=%d\n",*year,month,day_of_month);

 GetLine(fp,line);
 sscanf(line," Longitudes:  %3d bins centered on %7f W to %7f E  (%5f ", 
        nlons, minlon, maxlon, lonsteps);
 /* OMI data used different index - Feng */
 if(strstr(fname, "omi")) {
   hemisphere1= line[42];  hemisphere2= line[55];  
 }
 else {
 hemisphere1= line[43];  hemisphere2= line[56];
 } 
 *minlon *= (hemisphere1=='S'||hemisphere1=='W'?-1.0:1.0);
 *maxlon *= (hemisphere2=='S'||hemisphere2=='W'?-1.0:1.0);

 GetLine(fp,line);
 sscanf(line," Latitudes :  %3d bins centered on %7f S to %7f N  (%4f ",
        nlats, minlat, maxlat, latsteps);
 /* OMI data used different index - Feng */
 if(strstr(fname, "omi")) {
   hemisphere1= line[42];  hemisphere2= line[55];  
 }
 else {
 hemisphere1= line[43];  hemisphere2= line[56]; 
 }
 *minlat *= (hemisphere1=='S'||hemisphere1=='W'?-1.0:1.0);
 *maxlat *= (hemisphere2=='S'||hemisphere2=='W'?-1.0:1.0);

 comp_lat= *minlat;
 comp_lon= *minlon;

 data = (short int *)calloc(((*nlats)*(*nlons)), sizeof(short int));

 for (icol=0; icol<*nlons; icol++)
   {
   lon_array[icol]= comp_lon;
   comp_lon += *lonsteps;
   } 

 ilat=0;
 for (irow=0; irow<*nlats; irow++)
 {
   ival=0;
   for (icol=0; icol<NLINE; icol++)
     {
     GetLine(fp,line);
     for ( i=0; i<(icol<(NLINE-1)?longline:shortline); i++ )
       {
       
       strncpy(valbuf,&line[i*3+1],3);
       valbuf[3]='\0';
       sscanf(valbuf,"%3d",&number); 
       data[(*nlats-ilat-1)*(*nlons)+ival++]= number;
       /*
       sscanf(&line[i*3+1],"%3d",&data[ival++]);
       */
       }
     }
   sscanf(&line[i*3+1],"   lat =   %f",&mylat);
   if (0 )   printf("*** in=(%s) mylat=(%f) complat=(%f) ***\n",&line[i*3+1],mylat,comp_lat);
   lat_array[*nlats-ilat-1]= comp_lat;
   comp_lat += *latsteps;
   ilat++;
 }

 *out_data= data;
 return 0;
}
Esempio n. 12
0
void main(void)
{	
	M8C_EnableGInt ; // Uncomment this line to enable Global Interrupts
	M8C_EnableIntMask(INT_MSK1, INT_MSK1_DBB01); // Enable DBB01 Interrupt for TempCounter
	M8C_EnableIntMask(INT_MSK1, INT_MSK1_DBB11); // Enable DBB01 Interrupt for MotorDriver
	M8C_EnableIntMask(INT_MSK0, INT_MSK0_GPIO); // Enable GPIO interrupt for Tout
	
	// Start the UART(with no parity), LCD, TempCounter and MotorDriver
	UART_Start(UART_PARITY_NONE);
	LCD_Start();
	TempCounter_EnableInt(); // Enable interrupts for counter
	TempCounter_Start();
	MotorDriver_EnableInt(); // Enable interrupts for counter
	
	// Start I2CHW
	I2CHW_Start();
	I2CHW_EnableMstr();
	I2CHW_EnableInt();
	
	WriteI2C(slaveAddress, 0xAC, 1, 0x02); // Write to access config, sets mode to cooling(POL = 1), also turns 1-SHOT off, continuous conversions
	
	WriteI2C(slaveAddress, 0xA1, 2, (setTemp + tolerance), 0x00); // Sets initial high temp to be setTemp + tolerance
	WriteI2C(slaveAddress, 0xA2, 2, (setTemp - tolerance), 0x00); // Sets initial low temp to be setTemp - tolerance
	WriteI2C(slaveAddress, 0xEE, 0); // This tells the temperature IC to start converting the temperatures
	
	// Writes initial string to LCD. When LCD is updated, only the numbers will be changed
	LCD_Position(0,0); LCD_PrCString("CUR: 00 OFF     ");
	LCD_Position(1,0); LCD_PrCString("SET: 00 FAN OFF ");
	
	// This is the command usage string
	UART_CPutString("#################### Heating/Cooling Stepper Motors ##################\r\n\
#	S ##\r\n\
#		S - Set the desired Temperature\r\n\
#		## - Desired temperature in celsius\r\n\
#\r\n\
#	T ##\r\n\
#		T - Set the desired tolerance\r\n\
#		## - Desired tolerance in celsius\r\n\
#\r\n\
#	M X\r\n\
#		M - Change the mode of the thermostat\r\n\
#		X - C is for cool, H is for heat, F is for off\r\n\
#\r\n\
#	F X S\r\n\
#		F - Change the mode of the fan\r\n\
#		X - A is for automatic fan control, M is for always on\r\n\
#		S - Speed of the fan, H = high, M = medium, L = low\r\n\
#####################################################################\r\n");
	while (1)
	{
		char *cmd;
		char *params;
		
		if (GetLine(buf, &strPos, 79)) // Only process the data if GetLine returns true
		{
			cmd = Lowercase(cstrtok(buf, " ")); // Lowercase the first word from the inputted string
			
			if (strlen(cmd) == 1 && cmd[0] == 's') // If the person entered s
			{	
				int temp;
			
				params = cstrtok(0x00, " "); // Read next word 							
				// If next word isnt number or isnt 1 or 2 characters long, then return error
				if (!IsNumber(params) || strlen(params) < 1 || strlen(params) > 2 || csscanf(params, "%d", &temp) != 1) goto error;
				
				// If there is additional data at end of string or if number is not within 0-99, return error
				if (cstrtok(0x00, " ") != 0x00) goto error;
				if ( temp > 99 || temp < 0) goto error; 
				
				setTemp = temp;
				WriteI2C(slaveAddress, 0xA1, 2, (setTemp + tolerance), 0x00); // Sets high temp to be setTemp + tolerance
				WriteI2C(slaveAddress, 0xA2, 2, (setTemp - tolerance), 0x00); // Sets low temp to be setTemp - tolerance
				updateLCD = TRUE; // Update the LCD
			}
			else if (strlen(cmd) == 1 && cmd[0] == 't') // If the person entered t
			{	
				int tol; 
			
				params = cstrtok(0x00, " "); // Read next word					
				// If next word isnt number or isnt 1 or 2 characters long, then return error
				if (!IsNumber(params) || strlen(params) < 1 || strlen(params) > 2 || csscanf(params, "%d", &tol) != 1) goto error;
				
				// If there is additional data at end of string or if number is not within 0-10, return error
				if (cstrtok(0x00, " ") != 0x00) goto error;
				if (tol < 0 || tol > 10) goto error;
				
				tolerance = tol;
				
				WriteI2C(slaveAddress, 0xA1, 2, (setTemp + tolerance), 0x00); // Sets high temp to be setTemp + tolerance
				WriteI2C(slaveAddress, 0xA2, 2, (setTemp - tolerance), 0x00); // Sets low temp to be setTemp - tolerance
				updateLCD = TRUE; // Update the LCD
				
			}
			else if (strlen(cmd) == 1 && cmd[0] == 'm') // If the person entered m
			{	
				char mode;
			
				params = cstrtok(0x00, " "); // Read next word
				
				// If next word isnt 1 character long, return error
				if (strlen(params) != 1 || csscanf(params, "%c", &mode) != 1) goto error;
				// If there is additional data at end of string, return error
				if (cstrtok(0x00, " ") != 0x00) goto error;
				
				mode = tolower(mode); // Lowercase the character
				
				switch (mode)
				{
					case 'h':
						thermostatMode = 1; // Set mode to heating
						WriteI2C(slaveAddress,0xAC, 1, 0x00); // Change access config on DS1621 to heating(POL = 0)
						break;
						
					case 'c':
						thermostatMode = 2; // Set mode to cooling
						WriteI2C(slaveAddress, 0xAC, 1, 0x02); // Change access config on DS1621 to cooling(POL = 1)
						break;
						
					case 'f': 
						thermostatMode = 0; // Set mode to off
						break;
						
					default:
						goto error; // Invalid character entered, goto error
				}
				CheckFan(); // Check the fan to see if it should be on
			}
			else if (strlen(cmd) == 1 && cmd[0] == 'f') // If the person entered f
			{	
				char mode;
				char speed;
			
				params = cstrtok(0x00, " "); // Read next word
				// If next word isnt 1 character long, then return error
				if (strlen(params) != 1 || csscanf(params, "%c", &mode) != 1) goto error;
				
				params = cstrtok(0x00, " "); // Read next word
				// If next word isnt 1 character long, then return error
				if (strlen(params) != 1 || csscanf(params, "%c", &speed) != 1) goto error;
				// If there is additional data at end of string, return error
				if (cstrtok(0x00, " ") != 0x00) goto error;
				
				speed = tolower(speed); // Lowercase the speed and mode characters entered
				mode = tolower(mode);
				
				switch (mode)
				{
					case 'm':
						fanMode = 0; // Set fan mode to manual
						break;
						
					case 'a':
						fanMode = 1; // Set fan mode to automatic
						break;
						
					default: // Otherwise go to error
						goto error;
				}
				
				MotorDriver_Stop(); // Stop the motor to change the period values
				switch (speed)
				{
					case 'l':
						fanSpeed = 0; // Set fan speed to low
						MotorDriver_WritePeriod(49999); // See report for where these numbers came from
						MotorDriver_WriteCompareValue(25000);
						break;
						
					case 'm':
						fanSpeed = 1; // Set fan speed to medium
						MotorDriver_WritePeriod(9999); // See report for where these numbers came from
						MotorDriver_WriteCompareValue(5000);
						break;
						
					case 'h':
						fanSpeed = 2; // Set fan speed to high
						MotorDriver_WritePeriod(1999); // See report for where these numbers came from
						MotorDriver_WriteCompareValue(1000);
						break;
						
					default: // Otherwise go to error if invalid input entered
						goto error;
				}
				CheckFan(); // Check the fan to see if it should be on
			}
			else 
				goto error;
		}
			
		if (checkTemp) // Check the temperature
		{	
			char buf[2];
			
			ReadI2C(slaveAddress, 0xAA, 2, buf); // Read the temperature from IC, returns 2 bytes
			curTemp = buf[0]; // We just care about the first byte
			checkTemp = FALSE; // Turn flag off so it doesnt keep doing this
		}
		
		if (updateLCD) // Update the LCD
		{	
			char buf[3];
			
			NumToStr(buf, curTemp, 2); // Convert current temp to str
			LCD_Position(0, 5); LCD_PrString(buf); // Print it
			
			LCD_Position(0, 8);
			switch(thermostatMode) // Print thermostat mode
			{
				case 0: LCD_PrCString("OFF "); break;
				case 1: LCD_PrCString("HEAT"); break;
				case 2: LCD_PrCString("COOL"); break;
			}
			
			NumToStr(buf, setTemp, 2); // Convert set temp to str
			LCD_Position(1, 5); LCD_PrString(buf); // Print it
			
			LCD_Position(1, 12);
			if (fanMode == 1 && thermostatMode == 0) LCD_PrCString("OFF"); // Print current fan state
			else if (fanSpeed == 0) LCD_PrCString("LOW");
			else if (fanSpeed == 1) LCD_PrCString("MED");
			else if (fanSpeed == 2) LCD_PrCString("HI ");
			updateLCD = FALSE;
		}
		
		continue;
		error:	
			UART_CPutString("# Invalid format entered. Valid formats are:\r\n\
#	S ##\r\n\
#		S - Set the desired Temperature\r\n\
#		## - Desired temperature in celsius\r\n\
#\r\n\
#	T ##\r\n\
#		T - Set the desired tolerance\r\n\
#		## - Desired tolerance in celsius\r\n\
#\r\n\
#	M X\r\n\
#		M - Change the mode of the thermostat\r\n\
#		X - C is for cool, H is for heat, F is for off\r\n\
#\r\n\
#	F X S\r\n\
#		F - Change the mode of the fan\r\n\
#		X - A is for automatic fan control, M is for always on\r\n\
#		S - Speed of the fan, H = high, M = medium, L = low\r\n\
#####################################################################\r\n");
	}
}
int main(int argc,char **argv)
{
  int m;
  int n;
  bool bNoSort;
  bool bNot;
  int curr_arg;
  FILE *fptr;
  int line_len;
  int num_sessions;
  int session_ix;
  int delta;
  int session_is_blue;
  int prev_session_is_blue;
  int chara;
  int *sort_ixs;
  int num_blue_streaks;
  int blue_streak_ix;
  int retval;
  char *cpt;
  int cumulative_delta;
  int max_cumulative_delta;

  if ((argc < 2) || (argc > 5)) {
    printf(usage);
    return 1;
  }

  bNoSort = false;
  bAscending = false;
  bNot = false;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-no_sort"))
      bNoSort = true;
    else if (!strcmp(argv[curr_arg],"-ascending"))
      bAscending = true;
    else if (!strcmp(argv[curr_arg],"-not"))
      bNot = true;
    else
      break;
  }

  if (argc - curr_arg != 1) {
    printf(usage);
    return 2;
  }

  if ((fptr = fopen(argv[curr_arg],"r")) == NULL) {
    printf(couldnt_open,argv[curr_arg]);
    return 3;
  }

  num_sessions = 0;
  num_blue_streaks = 0;
  cumulative_delta = 0;
  max_cumulative_delta = 0;

  for ( ; ; ) {
    GetLine(fptr,line,&line_len,MAX_LINE_LEN);

    if (feof(fptr))
      break;

    if (!line_len)
      continue;

    chara = line[0];

    if (((chara >= 'a') && (chara <= 'z')) ||
        ((chara >= 'A') && (chara <= 'Z')))
      continue;

    sscanf(&line[11],"%d",&delta);

    cumulative_delta += delta;

    if (cumulative_delta > max_cumulative_delta) {
      if (!bNot)
        session_is_blue = 1;
      else
        session_is_blue = 0;

      max_cumulative_delta = cumulative_delta;
    }
    else {
      if (!bNot)
        session_is_blue = 0;
      else
        session_is_blue = 1;
    }

    if ((session_is_blue == 1) && ((num_sessions == 0) || (prev_session_is_blue == 0)))
      num_blue_streaks++;

    num_sessions++;
    prev_session_is_blue = session_is_blue;
  }

  if ((session_info = (struct session_info_struct *)malloc(
    num_sessions * sizeof (struct session_info_struct))) == NULL) {
    printf(malloc_failed1,num_sessions);
    fclose(fptr);
    return 4;
  }

  if ((blue_streaks = (struct session_info_struct *)malloc(
    num_blue_streaks * sizeof (struct session_info_struct))) == NULL) {
    printf(malloc_failed1,num_blue_streaks);
    fclose(fptr);
    free(session_info);
    return 5;
  }

  if ((sort_ixs = (int *)malloc(
    num_blue_streaks * sizeof (int))) == NULL) {
    printf(malloc_failed2,num_blue_streaks);
    fclose(fptr);
    free(session_info);
    free(blue_streaks);
    return 6;
  }

  for (n = 0; n < num_blue_streaks; n++)
    sort_ixs[n] = n;

  fseek(fptr,0L,SEEK_SET);

  session_ix = 0;
  cumulative_delta = 0;
  max_cumulative_delta = 0;

  for ( ; ; ) {
    GetLine(fptr,line,&line_len,MAX_LINE_LEN);

    if (feof(fptr))
      break;

    if (!line_len)
      continue;

    chara = line[0];

    if (((chara >= 'a') && (chara <= 'z')) ||
        ((chara >= 'A') && (chara <= 'Z')))
      continue;

    retval = get_session_info(line,line_len,&session_info[session_ix]);

    if (retval) {
      printf("get_session_info() failed on line %d: %d\n",
        session_ix+1,retval);
      fclose(fptr);
      free(session_info);
      free(blue_streaks);
      free(sort_ixs);
      return 7;
    }

    cumulative_delta += session_info[session_ix].delta;

    if (cumulative_delta > max_cumulative_delta) {
      if (!bNot)
        session_info[session_ix].session_is_blue = 1;
      else
        session_info[session_ix].session_is_blue = 0;

      max_cumulative_delta = cumulative_delta;
    }
    else {
      if (!bNot)
        session_info[session_ix].session_is_blue = 0;
      else
        session_info[session_ix].session_is_blue = 1;
    }

    if ((session_info[session_ix].session_is_blue == 1) &&
        ((session_ix == 0) || (session_info[session_ix-1].session_is_blue == 0)))
      session_info[session_ix].session_starts_blue_streak = 1;
    else
      session_info[session_ix].session_starts_blue_streak = 0;

    session_ix++;
  }

  fclose(fptr);

  blue_streak_ix = 0;

  for (n = 0; n < num_sessions; n++) {
    if (session_info[n].session_starts_blue_streak) {
      blue_streaks[blue_streak_ix].start_date = session_info[n].start_date;

      blue_streaks[blue_streak_ix].sum = session_info[n].delta;

      for (m = n + 1; (m < num_sessions) && (session_info[m].session_is_blue == 1); m++)
        blue_streaks[blue_streak_ix].sum += session_info[m].delta;

      blue_streaks[blue_streak_ix].end_date = session_info[m - 1].start_date;
      blue_streaks[blue_streak_ix].num_blue_sessions = m - n;

      blue_streak_ix++;
    }
  }

  if (!bNoSort)
    qsort(sort_ixs,num_blue_streaks,sizeof (int),elem_compare);

  for (n = 0; n < num_blue_streaks; n++) {
    printf("%3d ",blue_streaks[sort_ixs[n]].num_blue_sessions);

    cpt = ctime(&blue_streaks[sort_ixs[n]].start_date);
    printf("%s ",format_date(cpt));

    cpt = ctime(&blue_streaks[sort_ixs[n]].end_date);
    printf("%s ",format_date(cpt));

    printf("%10d\n",blue_streaks[sort_ixs[n]].sum);
  }

  free(session_info);
  free(blue_streaks);
  free(sort_ixs);

  return 0;
}
Esempio n. 14
0
int
ParseInput(register DviWidget dw)
{
	int		n, k;
	int		c;
	char		Buffer[BUFSIZ];
	int		NextPage;
	int		otherc;

	StopSeen = 0;

	/*
	 * make sure some state exists
	 */

	if (!dw->dvi.state)
	    push_env (dw);
	for (;;) {
		switch (DviGetC(dw, &c)) {
		case '\n':	
			break;
		case ' ':	/* when input is text */
		case 0:		/* occasional noise creeps in */
			break;
		case '{':	/* push down current environment */
			push_env(dw);
			break;
		case '}':
			pop_env(dw);
			break;
		/*
		 * two motion digits plus a character
		 */
		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			HorizontalMove(dw, (c-'0')*10 +
					   DviGetC(dw,&otherc)-'0');
			/* fall through */
		case 'c':	/* single ascii character */
			DviGetC(dw,&c);
		    	if (c == ' ')
			    break;
			Buffer[0] = c;
			Buffer[1] = '\0';
			(void) PutCharacter (dw, Buffer);
			break;
		case 'C':
			GetWord (dw, Buffer, BUFSIZ);
			(void) PutCharacter (dw, Buffer);
			break;
		case 't':
			Buffer[1] = '\0';
			while (DviGetC (dw, &c) != EOF
			       && c != ' ' && c != '\n') {
				Buffer[0] = c;
				HorizontalMove (dw, PutCharacter (dw, Buffer));
			}
			break;
		case 'u':
			n = GetNumber(dw);
			Buffer[1] = '\0';
			while (DviGetC (dw, &c) == ' ')
				;
			while (c != EOF && c != ' ' && c != '\n') {
				Buffer[0] = c;
				HorizontalMove (dw,
						PutCharacter (dw, Buffer) + n);
				DviGetC (dw, &c);
			}
			break;

		case 'D':	/* draw function */
			(void) GetLine(dw, Buffer, BUFSIZ);
			if (dw->dvi.display_enable)
				ParseDrawFunction(dw, Buffer);
			break;
		case 's':	/* ignore fractional sizes */
			n = GetNumber(dw);
			dw->dvi.state->font_size = n;
			break;
		case 'f':
			n = GetNumber(dw);
			dw->dvi.state->font_number = n;
			break;
		case 'H':	/* absolute horizontal motion */
			k = GetNumber(dw);
			HorizontalGoto(dw, k);
			break;
		case 'h':	/* relative horizontal motion */
			k = GetNumber(dw);
			HorizontalMove(dw, k);
			break;
		case 'w':	/* word space */
			Word (dw);
			break;
		case 'V':
			n = GetNumber(dw);
			VerticalGoto(dw, n);
			break;
		case 'v':
			n = GetNumber(dw);
			VerticalMove(dw, n);
			break;
		case 'P':	/* new spread */
			break;
		case 'p':	/* new page */
			(void) GetNumber(dw);
			NextPage = dw->dvi.current_page + 1;
			RememberPagePosition(dw, NextPage);
			FlushCharCache (dw);
			return(NextPage);
		case 'N':
			n = GetNumber(dw);
			PutNumberedCharacter (dw, n);
			break;
		case 'n':	/* end of line */
			GetNumber(dw);
			GetNumber(dw);
			Newline (dw);
			HorizontalGoto(dw, 0);
			break;
		case 'F':       /* input files */
		case '+':	/* continuation of X device control */
		case 'm':	/* color */
		case '#':	/* comment */
			GetLine(dw, NULL, 0);
			break;
		case 'x':	/* device control */
			ParseDeviceControl(dw);
			break;
		case EOF:
			dw->dvi.last_page = dw->dvi.current_page;
			FlushCharCache (dw);
			return dw->dvi.current_page;
		default:
			break;
		}
	}
}
Esempio n. 15
0
int main(int argc,char **argv)
{
  int curr_arg;
  bool bDelta;
  bool bEntriesAndPaid;
  int poker_style;
  int poker_flavor;
  char letter;
  int n;
  FILE *fptr;
  int filename_len;
  int line_len;
  int retval;
  int buy_in;
  int entry_fee;
  int num_players;
  int num_hands;
  int place;
  int winnings;
  int delta;
  int total_delta;

  if ((argc < 4) || (argc > 7)) {
    printf(usage);
    return 1;
  }

  bDelta = false;
  bEntriesAndPaid = false;
  letter = 'a';

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-delta"))
      bDelta = true;
    else if (!strcmp(argv[curr_arg],"-entries_and_paid"))
      bEntriesAndPaid = true;
    else if (!strncmp(argv[curr_arg],"-letter",7))
      letter = argv[curr_arg][7];
    else
      break;
  }

  if (argc - curr_arg != 3) {
    printf(usage);
    return 2;
  }

  sscanf(argv[curr_arg+1],"%d",&poker_style);

  if ((poker_style < 0) || (poker_style >= NUM_POKER_STYLES)) {
    printf("invalid poker_style\n");
    return 3;
  }

  sscanf(argv[curr_arg+2],"%d",&poker_flavor);

  if ((poker_flavor < 0) || (poker_flavor >= NUM_POKER_FLAVORS)) {
    printf("invalid poker_flavor\n");
    return 4;
  }

  if (bDelta)
    total_delta = 0;

  if (bEntriesAndPaid && (((poker_style == 1) && (poker_flavor == 3)) ||
      ((poker_style == 4) && (poker_flavor == 3))))
    printf("style flavor buy_in entry players hands entries paid place winnings\n\n");
  else
    printf("style flavor buy_in entry players hands place winnings\n\n");

  for (n = 0; n < MAX_SIT_AND_GOS; n++) {
    sprintf(outer_filename,"%c/sng_hands.ls0",letter);

    if ((fptr = fopen(outer_filename,"r")) == NULL)
      break;

    GetLine(fptr,line,&line_len,MAX_FILENAME_LEN);

    if (feof(fptr)) {
      printf(unexpected_eof,outer_filename);
      return 5;
    }

    fclose(fptr);

    retval = get_num_hands(line,line_len,&num_hands);

    if (retval) {
      printf("get_num_hands failed: %d\n",retval);
      return 6;
    }

    sprintf(filename,"%c/%s",letter,line);

    if ((fptr = fopen(filename,"r")) == NULL) {
      printf(couldnt_open,filename);
      return 7;
    }

    GetLine(fptr,line,&line_len,MAX_LINE_LEN);

    if (feof(fptr)) {
      printf(unexpected_eof,filename);
      return 8;
    }

    retval = get_buy_in_and_entry_fee(line,line_len,&buy_in,&entry_fee);

    if (retval) {
      printf("get_buy_in_and_entry_fee() failed: %d\n",retval);
      return 9;
    }

    GetLine(fptr,line,&line_len,MAX_LINE_LEN);

    if (feof(fptr)) {
      printf(unexpected_eof,filename);
      return 10;
    }

    retval = get_num_players(line,line_len,&num_players);

    if (retval) {
      printf("get_num_players() failed: %d\n",retval);
      return 11;
    }

    if (bDelta)
      delta = (buy_in + entry_fee) * -1;

    retval = get_place_and_winnings(argv[curr_arg],strlen(argv[curr_arg]),fptr,&place,&winnings);

    if (retval) {
      printf("get_place_and_winnings() failed: %d\n",retval);
      return 12;
    }

    fclose(fptr);

    if (!bDelta) {
      if (bEntriesAndPaid && ((poker_style == 1) && (poker_flavor == 3))) {
        printf("%5s %6s %6d %5d %7d %5d %7d %4d %5d %8d\n",
          poker_styles[poker_style],poker_flavors[poker_flavor],
          buy_in,entry_fee,num_players,num_hands,6,2,place,winnings);
      }
      else if (bEntriesAndPaid && ((poker_style == 4) && (poker_flavor == 3))) {
        printf("%5s %6s %6d %5d %7d %5d %7d %4d %5d %8d\n",
          poker_styles[poker_style],poker_flavors[poker_flavor],
          buy_in,entry_fee,num_players,num_hands,9,3,place,winnings);
      }
      else {
        printf("%5s %6s %6d %5d %7d %5d %5d %8d\n",
          poker_styles[poker_style],poker_flavors[poker_flavor],
          buy_in,entry_fee,num_players,num_hands,place,winnings);
      }
    }
    else {
      delta += winnings;

      if (bEntriesAndPaid && ((poker_style == 1) && (poker_flavor == 3))) {
        printf("%5s %6s %6d %5d %7d %5d %7d %4d %5d %8d %8d\n",
          poker_styles[poker_style],poker_flavors[poker_flavor],
          buy_in,entry_fee,num_players,num_hands,6,2,place,winnings,delta);
      }
      else if (bEntriesAndPaid && ((poker_style == 4) && (poker_flavor == 3))) {
        printf("%5s %6s %6d %5d %7d %5d %7d %4d %5d %8d %8d\n",
          poker_styles[poker_style],poker_flavors[poker_flavor],
          buy_in,entry_fee,num_players,num_hands,9,3,place,winnings,delta);
      }
      else {
        printf("%5s %6s %6d %5d %7d %5d %5d %8d %8d\n",
          poker_styles[poker_style],poker_flavors[poker_flavor],
          buy_in,entry_fee,num_players,num_hands,place,winnings,delta);
      }

      total_delta += delta;
    }

    letter++;
  }

  if (bDelta) {
    if (!bEntriesAndPaid)
      printf("\n                                                       %8d\n",total_delta);
    else
      printf("\n                                                                    %8d\n",total_delta);
  }

  return 0;
}
Esempio n. 16
0
int main(int argc,char **argv)
{
  int curr_arg;
  bool bVerbose;
  int ge_val;
  FILE *fptr;
  int line_len;
  int line_no;
  int last_ge_line_no;
  int val;
  int intervening;
  int max_intervening;

  if ((argc < 3) || (argc > 4)) {
    printf(usage);
    return 1;
  }

  bVerbose = false;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-verbose"))
      bVerbose = true;
    else
      break;
  }

  if (argc - curr_arg != 2) {
    printf(usage);
    return 2;
  }

  sscanf(argv[curr_arg],"%d",&ge_val);

  if ((fptr = fopen(argv[curr_arg+1],"r")) == NULL) {
    printf(couldnt_open,argv[curr_arg+1]);
    return 3;
  }

  line_no = 0;
  last_ge_line_no = 0;
  max_intervening = 0;

  for ( ; ; ) {
    GetLine(fptr,line,&line_len,MAX_LINE_LEN);

    if (feof(fptr))
      break;

    line_no++;

    sscanf(line,"%d",&val);

    if (val >= ge_val) {
      if (!bVerbose)
        printf("%d\n",val);
      else if (!last_ge_line_no)
        printf("%s %d\n",line,line_no);
      else {
        intervening = line_no - (last_ge_line_no + 1);

        if (intervening > max_intervening)
          max_intervening = intervening;

        printf("%s %d (%d)\n",line,line_no,intervening);
      }

      last_ge_line_no = line_no;
    }
  }

  fclose(fptr);

  printf("max_intervening = %d\n",max_intervening);

  return 0;
}
int main(int argc,char **argv)
{
  FILE *fptr;
  int line_len;
  int line_no;
  int val;
  int max_nonzero_streak;
  int max_nonzero_streak_start_ix;
  int curr_nonzero_streak;
  int curr_nonzero_streak_start_ix;

  if (argc != 2) {
    printf(usage);
    return 1;
  }

  if ((fptr = fopen(argv[1],"r")) == NULL) {
    printf(couldnt_open,argv[1]);
    return 2;
  }

  line_no = 0;
  max_nonzero_streak = 0;
  curr_nonzero_streak = 0;


  for ( ; ; ) {
    GetLine(fptr,line,&line_len,MAX_LINE_LEN);

    if (feof(fptr))
      break;

    sscanf(line,"%d",&val);

    if (!val) {
      if (curr_nonzero_streak > max_nonzero_streak) {
        max_nonzero_streak = curr_nonzero_streak;
        max_nonzero_streak_start_ix = curr_nonzero_streak_start_ix;
      }

      curr_nonzero_streak = 0;
    }
    else {
      if (!curr_nonzero_streak)
        curr_nonzero_streak_start_ix = line_no;

      curr_nonzero_streak++;
    }

    line_no++;
  }

  if (curr_nonzero_streak > max_nonzero_streak) {
    max_nonzero_streak = curr_nonzero_streak;
    max_nonzero_streak_start_ix = curr_nonzero_streak_start_ix;
  }

  fclose(fptr);

  printf("%d (%d)\n",max_nonzero_streak,max_nonzero_streak_start_ix+1);

  return 0;
}
/*
================
CSyntaxRichEditCtrl::OnKeyDown
================
*/
void CSyntaxRichEditCtrl::OnKeyDown( UINT nKey, UINT nRepCnt, UINT nFlags ) {

	if ( m_TextDoc == NULL ) {
		return;
	}

	if ( autoCompleteStart >= 0 ) {
		int sel;

		switch( nKey ) {
			case VK_UP: {		// up arrow
				sel = Max( 0, autoCompleteListBox.GetCurSel() - 1 );
				autoCompleteListBox.SetCurSel( sel );
				return;
			}
			case VK_DOWN: {		// down arrow
				sel = Min( autoCompleteListBox.GetCount() - 1, autoCompleteListBox.GetCurSel() + 1 );
				autoCompleteListBox.SetCurSel( sel );
				return;
			}
			case VK_PRIOR: {	// page up key
				sel = Max( 0, autoCompleteListBox.GetCurSel() - 10 );
				autoCompleteListBox.SetCurSel( sel );
				return;
			}
			case VK_NEXT: {		// page down key
				sel = Min( autoCompleteListBox.GetCount() - 1, autoCompleteListBox.GetCurSel() + 10 );
				autoCompleteListBox.SetCurSel( sel );
				return;
			}
			case VK_HOME: {		// home key
				autoCompleteListBox.SetCurSel( 0 );
				return;
			}
			case VK_END: {
				autoCompleteListBox.SetCurSel( autoCompleteListBox.GetCount() - 1 );
				return;
			}
			case VK_RETURN:		// enter key
			case VK_TAB: {		// tab key
				AutoCompleteInsertText();
				AutoCompleteHide();
				return;
			}
			case VK_LEFT:		// left arrow
			case VK_RIGHT:		// right arrow
			case VK_INSERT:		// insert key
			case VK_DELETE: {	// delete key
				return;
			}
		}
	}

	BracedSectionHide();

	switch( nKey ) {
		case VK_TAB: {		// multi-line tabs
			long selStart, selEnd;

			GetSel( selStart, selEnd );

			// if multiple lines are selected add tabs to, or remove tabs from all of them
			if ( selEnd > selStart ) {
				CString text;

				text = GetSelText();

				if ( GetAsyncKeyState( VK_SHIFT ) & 0x8000 ) {
					if ( idStr::CharIsTab( text[0] ) ) {
						text.Delete( 0, 1 );
					}
					for ( int i = 0; i < text.GetLength() - 2; i++ ) {
						if ( idStr::CharIsNewLine( text[i] ) ) {
							do {
								i++;
							} while( idStr::CharIsNewLine( text[i] ) );
							if ( idStr::CharIsTab( text[i] ) ) {
								text.Delete( i, 1 );
							}
						}
					}
				} else {
					text.Insert( 0, '\t' );
					for ( int i = 0; i < text.GetLength() - 1; i++ ) {
						if ( idStr::CharIsNewLine( text[i] ) ) {
							do {
								i++;
							} while( idStr::CharIsNewLine( text[i] ) );
							text.Insert( i, '\t' );
						}
					}
				}

				ReplaceSel( text, TRUE );
				SetSel( selStart, selStart + text.GetLength() );
			} else {
				ReplaceSel( "\t", TRUE );
			}
			return;
		}
		case VK_RETURN: {	// auto-indentation
			long selStart, selEnd;
			int line, length, numTabs, i;
			char buffer[1024];
			idStr text;

			GetSel( selStart, selEnd );
			line = LineFromChar( selStart );
			length = GetLine( line, buffer, sizeof( buffer ) );
			for ( numTabs = 0; numTabs < length; numTabs++ ) {
				if ( !idStr::CharIsTab( buffer[numTabs] ) ) {
					break;
				}
			}
			bool first = true;
			for ( i = numTabs; i < length; i++ ) {
				if ( buffer[i] == '{' ) {
					numTabs++;
					first = false;
				} else if ( buffer[i] == '}' && !first ) {
					numTabs--;
				}
			}
			text = "\r\n";
			for ( i = 0; i < numTabs; i++ ) {
				text.Append( '\t' );
			}
			ReplaceSel( text, TRUE );
			return;
		}
	}

	m_TextDoc->Freeze( NULL );

	CRichEditCtrl::OnKeyDown( nKey, nRepCnt, nFlags );

	UpdateVisibleRange();

	m_TextDoc->Unfreeze( NULL );
}
Esempio n. 19
0
Component* LinkComp::Copy () { 
    LinkComp* copy = new LinkComp((Line*) GetLine()->Copy());
    
    *copy->GetGraphic() = *GetGraphic();
    return copy;
}
/*
================
CSyntaxRichEditCtrl::OnChar
================
*/
void CSyntaxRichEditCtrl::OnChar( UINT nChar, UINT nRepCnt, UINT nFlags ) {

	if ( nChar == VK_TAB ) {
		return;	// tab is handle in OnKeyDown
	}

	CRichEditCtrl::OnChar( nChar, nRepCnt, nFlags );

	// if the auto-complete list box is up
	if ( autoCompleteStart >= 0 ) {
		long selStart, selEnd;

		if ( charType[nChar] == CT_NAME ) {
			AutoCompleteUpdate();
			return;
		} else if ( nChar == VK_BACK ) {
			GetSel( selStart, selEnd );
			if ( selStart > autoCompleteStart ) {
				AutoCompleteUpdate();
			} else {
				AutoCompleteHide();
			}
			return;
		} else {
			AutoCompleteHide();
		}
	}

	// if the function parameter tool tip is up
	if ( funcParmToolTipStart >= 0 ) {
		long selStart, selEnd;

		if ( nChar == ')' || nChar == VK_ESCAPE ) {
			ToolTipHide();
		} else if ( nChar == VK_BACK ) {
			GetSel( selStart, selEnd );
			if ( selStart < funcParmToolTipStart ) {
				ToolTipHide();
			}
		}
	}

	// show keyword auto-completion
	if ( keyWordAutoCompletion && charType[nChar] == CT_NAME && funcParmToolTipStart < 0 ) {
		long selStart, selEnd;
		int line, column, length, i;
		char buffer[1024];

		GetSel( selStart, selEnd );
		line = LineFromChar( selStart );
		length = GetLine( line, buffer, sizeof( buffer ) );
		column = selStart - LineIndex( line );
		if ( column <= 1 || charType[buffer[column-2]] == CT_WHITESPACE ) {
			if ( column >= length-1 || charType[buffer[column]] == CT_WHITESPACE ) {

				autoCompleteListBox.ResetContent();
				for ( i = 0; keyWords[i].keyWord; i++ ) {
					autoCompleteListBox.AddString( keyWords[i].keyWord );
				}
				AutoCompleteShow( selStart - 1 );
			}
		}
		return;
	}

	// highlight braced sections
	if ( nChar == '{' ) {
		BracedSectionStart( '{', '}' );
	} else if ( nChar == '}' ) {
		BracedSectionEnd( '{', '}' );
	} else if ( nChar == '(' ) {
		BracedSectionStart( '(', ')' );
	} else if ( nChar == ')' ) {
		BracedSectionEnd( '(', ')' );
	} else if ( nChar == '[' ) {
		BracedSectionStart( '[', ']' );
	} else if ( nChar == ']' ) {
		BracedSectionEnd( '[', ']' );
	} else if ( nChar == '<' ) {
		BracedSectionStart( '<', '>' );
	} else if ( nChar == '>' ) {
		BracedSectionEnd( '<', '>' );
	}

	// show object member auto-completion
	if ( nChar == '.' && GetObjectMembers && funcParmToolTipStart < 0 ) {
		int charIndex;
		CString name;

		if ( GetNameBeforeCurrentSelection( name, charIndex ) ) {
			autoCompleteListBox.ResetContent();
			if ( GetObjectMembers( name, autoCompleteListBox ) ) {
				AutoCompleteShow( charIndex );
			}
		}
		return;
	}

	// show function parameter tool tip
	if ( nChar == '(' && GetFunctionParms ) {
		int charIndex;
		CString name;

		if ( GetNameBeforeCurrentSelection( name, charIndex ) ) {
			CString parmString;
			if ( GetFunctionParms( name, parmString ) ) {
				ToolTipShow( charIndex, parmString );
			}
		}
		return;
	}
}
Esempio n. 21
0
inline
screenline_t* GetCurrentLine() {
    return GetLine(cur_ln);
}
Esempio n. 22
0
while(!infile.eof()){
	line = GetLine(&infile);
	
	var = line.Left(line.Find("="));
	val = line.Right(line.GetLength() - line.Find("=") - 1);
	
	if(line.IsEmpty() || line[0] == '[' || val.IsEmpty())
		;
	else if(var == "pallete"){
		long double en;
		m_Calculator.StringToDecimal(val, 10, en);
		m_CurrentPalete = (PaleteE)int(en);
	}		
	else if(var == "sound"){
		if(val == "1")
			m_SndEffects = true;
		else
			m_SndEffects = false;
	}		
	else if(var == "tooltips"){
		if(val == "1")
			m_ToolTips.On(true);
		else
			m_ToolTips.On(false);
	}		
	else if(var == "longoutput"){
		if(val == "1")
			m_OutputV.m_LongOutput = true;
		else
			m_OutputV.m_LongOutput = false;
	}
Esempio n. 23
0
int main(int argc,char **argv)
{
  int curr_arg;
  bool bDebug;
  bool bVerbose;
  int player_name_ix;
  int player_name_len;
  FILE *fptr0;
  int filename_len;
  FILE *fptr;
  int line_len;
  int line_no;
  int retval;
  char *date_string;
  int ix;
  int street;
  int num_street_markers;
  int starting_balance;
  int spent_this_street;
  int spent_this_hand;
  int end_ix;
  int wagered_amount;
  int uncalled_bet_amount;
  int collected_from_pot;
  int collected_from_pot_count;
  int ending_balance;
  int delta;
  int file_no;
  int dbg_file_no;
  int dbg;
  int work;
  int total_wagered;

  if ((argc < 3) || (argc > 5)) {
    printf(usage);
    return 1;
  }

  bDebug = false;
  bVerbose = false;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-debug"))
      bDebug = true;
    else if (!strcmp(argv[curr_arg],"-verbose"))
      bVerbose = true;
    else
      break;
  }

  if (argc - curr_arg != 2) {
    printf(usage);
    return 2;
  }

  player_name_ix = curr_arg++;
  player_name_len = strlen(argv[player_name_ix]);

  if ((fptr0 = fopen(argv[curr_arg],"r")) == NULL) {
    printf(couldnt_open,argv[curr_arg]);
    return 3;
  }

  if (!bVerbose && bDebug) {
    getcwd(save_dir,_MAX_PATH);
    retval = get_date_from_path(save_dir,'/',2,&date_string);

    if (retval) {
      printf("get_date_from_path() on %s failed: %d\n",save_dir,retval);
      return 4;
    }
  }

  ending_balance = -1;

  file_no = 0;
  dbg_file_no = -1;

  if (!bVerbose)
    total_wagered = 0;

  for ( ; ; ) {
    GetLine(fptr0,filename,&filename_len,MAX_FILENAME_LEN);

    if (feof(fptr0))
      break;

    file_no++;

    if (dbg_file_no == file_no)
      dbg = 1;

    if ((fptr = fopen(filename,"r")) == NULL) {
      printf(couldnt_open,filename);
      continue;
    }

    line_no = 0;
    street = 0;
    num_street_markers = 0;
    spent_this_street = 0;
    spent_this_hand = 0;
    uncalled_bet_amount = 0;
    collected_from_pot = 0;
    collected_from_pot_count = 0;

    for ( ; ; ) {
      GetLine(fptr,line,&line_len,MAX_LINE_LEN);

      if (feof(fptr))
        break;

      line_no++;

      if (Contains(true,
        line,line_len,
        argv[player_name_ix],player_name_len,
        &ix)) {

        if (Contains(true,
          line,line_len,
          in_chips,IN_CHIPS_LEN,
          &ix)) {

          line[ix] = 0;

          for (ix--; (ix >= 0) && (line[ix] != '('); ix--)
            ;

          sscanf(&line[ix+1],"%d",&starting_balance);

          continue;
        }
        else if (Contains(true,
          line,line_len,
          posts,POSTS_LEN,
          &ix)) {
          spent_this_street += get_work_amount(line,line_len);
          continue;
        }
        else if (!strncmp(line,dealt_to,DEALT_TO_LEN))
          continue;
        else if (Contains(true,
          line,line_len,
          collected,COLLECTED_LEN,
          &ix)) {

          for (end_ix = ix + COLLECTED_LEN; end_ix < line_len; end_ix++) {
            if (line[end_ix] == ' ')
              break;
          }

          line[end_ix] = 0;
          sscanf(&line[ix + COLLECTED_LEN],"%d",&work);

          if (!collected_from_pot_count) {
            spent_this_hand += spent_this_street;
            street++;
            spent_this_street = 0;
          }

          collected_from_pot += work;
          collected_from_pot_count++;

          continue;
        }
        else if (!strncmp(line,uncalled_bet,UNCALLED_BET_LEN)) {
          sscanf(&line[UNCALLED_BET_LEN],"%d",&uncalled_bet_amount);
          spent_this_street -= uncalled_bet_amount;
          continue;
        }
        else if (Contains(true,
          line,line_len,
          folds,FOLDS_LEN,
          &ix)) {
          spent_this_hand += spent_this_street;
          break;
        }
        else if (Contains(true,
          line,line_len,
          bets,BETS_LEN,
          &ix)) {
          spent_this_street += get_work_amount(line,line_len);
        }
        else if (Contains(true,
          line,line_len,
          calls,CALLS_LEN,
          &ix)) {
          spent_this_street += get_work_amount(line,line_len);
        }
        else if (Contains(true,
          line,line_len,
          raises,RAISES_LEN,
          &ix)) {
          spent_this_street = get_work_amount(line,line_len);
        }
      }
      else {
        if (!strcmp(line,summary))
          break;

        if (!strncmp(line,street_marker,STREET_MARKER_LEN)) {
          num_street_markers++;

          if (num_street_markers > 1) {
            if (street <= 3)
              spent_this_hand += spent_this_street;

            street++;
            spent_this_street = 0;
          }
        }
      }
    }

    fclose(fptr);

    ending_balance = starting_balance - spent_this_hand + collected_from_pot;
    delta = ending_balance - starting_balance;

    wagered_amount = spent_this_hand + uncalled_bet_amount;

    if (!bVerbose)
      total_wagered += wagered_amount;
    else {
      if (!bDebug)
        printf("%d\n",wagered_amount);
      else
        printf("%10d %s\n",wagered_amount,filename);
    }
  }

  fclose(fptr0);

  if (!bVerbose) {
    if (!bDebug)
      printf("%d\n",total_wagered);
    else
      printf("%10d %s\n",total_wagered,date_string);
  }

  return 0;
}
Esempio n. 24
0
void PromptInterpreter(Closure_clp self) {
    Nash_clp nash;
    char *buf;
    int nread;
    int leave;
    Rd_clp raw_in, cooked_rd;
    Wr_clp raw_out, cooked_wr;
    CLine_clp cline;
    CLineCtl_clp clinectl;
    /* Cook the command line */
    raw_in = Pvs(in);
    raw_out = Pvs(out);
    leave = 0;
    cline = NAME_FIND("modules>CLine", CLine_clp);
    cooked_rd = CLine$New(cline, Pvs(in) , Pvs(out), &cooked_wr, &clinectl);  
    Pvs(in) = cooked_rd;
    Pvs(out) = cooked_wr;
    buf = malloc(sizeof(char)*256);
    nash = NewNash(0);

#ifdef CONFIG_NASHLOGIN
    while (!leave) {
	
	printf("\n\nWelcome to %s's Nemesis\n\n%s login: "******"conf>userid", string_t), gethostname());
	
	nread = Rd$GetLine(Pvs(in), buf, 255);
	if (nread) buf[nread-1] = 0;
	if (!strcmp(buf, "reboot")) {
	    printf("Rebooting\n");
	    Nash$ExecuteString(nash, "reboot");
	}
	
	if (!strcmp(buf, "b") || !strcmp(buf, "boot")) {
	    printf("Rebooting\n");
	    Nash$ExecuteString(nash, "b");
	}
	
	if (!strcmp(buf, "root")) {
	    leave = 1;
	} else
	if (!strcmp(buf, "user")) {
	    leave = 1;
	} else
	if (strlen(buf) > 0) {

	  {
	    /* figure out homedirectory */
	    char *newhomedir;
	    char *ptr;
	    char *lastslash;
	    nash_st *st = (nash_st*) (nash->st);
	    newhomedir = malloc(strlen(st->homedir)+strlen(buf));
	    strcpy(newhomedir, st->homedir);
	    ptr = newhomedir;
	    lastslash = ptr;
	    while (*ptr) {
		if (*ptr == '/') lastslash = ptr;
		ptr++;
	    }
	    lastslash++;
	    strcpy(lastslash, buf);
	    free(st->homedir);
	    st->homedir = newhomedir;
	    printf("New home directory will be %s\n", newhomedir);
	    Nash$ExecuteString(nash, "cd ~");
	    leave = 1;
	  }
	}
    }

#endif /* CONFIG_NASHLOGIN */

    Nash$ExecuteString(nash, "source profile.nash");

    while (1) {
	printf("%s ", Nash$GetPrompt(nash));
	nread = Rd$GetLine(Pvs(in), buf, 255);
	TRC(printf("\n"));
	if (nread) {
	    buf[nread-1] = 0;

	    TRC(printf("nread %d buf %s\n", nread, buf+1));

	    Nash$ExecuteString(nash, buf);
	}
	
    }
}
Esempio n. 25
0
int main(int argc,char **argv)
{
  int m;
  int n;
  int p;
  int curr_arg;
  bool bDebug;
  bool bReverse;
  bool bCount;
  bool bExactCount;
  bool bReupped;
  bool bConsecutive;
  bool bShowZero;
  bool bOneAndDone;
  bool bStud;
  bool bMaxFeltDistance;
  bool bStartingStack;
  int starting_stack;
  int hit_felt_count;
  int reupped_count;
  int consecutive_hit_felt_count;
  int exact_count;
  int player_name_ix;
  int player_name_len;
  FILE *fptr0;
  int filename_len;
  FILE *fptr;
  int line_len;
  int line_no;
  int retval;
  int dbg_line_no;
  int ix;
  int street;
  int num_street_markers;
  int max_streets;
  int starting_balance;
  int ante;
  int bring_in;
  int spent_this_street;
  int spent_this_hand;
  int end_ix;
  int uncalled_bet_amount;
  int collected_from_pot;
  int collected_from_pot_count;
  int ending_balance;
  int file_no;
  int dbg_file_no;
  int dbg;
  int work;
  double dwork1;
  double dwork2;
  bool bSkipping;
  int hand_number;
  int last_felted_hand_number;
  int felt_distance;
  int max_felt_distance;
  char *date_string;

  if ((argc < 3) || (argc > 14)) {
    printf(usage);
    return 1;
  }

  bDebug = false;
  bReverse = false;
  bCount = false;
  bExactCount = false;
  bReupped = false;
  bConsecutive = false;
  bShowZero = false;
  bOneAndDone = false;
  bStud = false;
  bMaxFeltDistance = false;
  bStartingStack = false;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-debug"))
      bDebug = true;
    else if (!strcmp(argv[curr_arg],"-reverse"))
      bReverse = true;
    else if (!strcmp(argv[curr_arg],"-count"))
      bCount = true;
    else if (!strncmp(argv[curr_arg],"-exact_count",12)) {
      bExactCount = true;
      sscanf(&argv[curr_arg][12],"%d",&exact_count);
    }
    else if (!strcmp(argv[curr_arg],"-reupped"))
      bReupped = true;
    else if (!strcmp(argv[curr_arg],"-consecutive"))
      bConsecutive = true;
    else if (!strcmp(argv[curr_arg],"-show_zero")) {
      bShowZero = true;
      bCount = true;
    }
    else if (!strcmp(argv[curr_arg],"-one_and_done"))
      bOneAndDone = true;
    else if (!strcmp(argv[curr_arg],"-stud"))
      bStud = true;
    else if (!strcmp(argv[curr_arg],"-max_felt_distance"))
      bMaxFeltDistance = true;
    else if (!strcmp(argv[curr_arg],"-starting_stack"))
      bStartingStack = true;
    else
      break;
  }

  if (argc - curr_arg != 2) {
    printf(usage);
    return 2;
  }

  if (bExactCount && bOneAndDone) {
    printf("can't specify both -exact_countn and -one_and_done\n");
    return 3;
  }

  if (bCount && bStartingStack) {
    printf("can't specify both -count and -starting_stack\n");
    return 4;
  }

  if (bExactCount && !exact_count)
    bShowZero = true;

  player_name_ix = curr_arg++;
  player_name_len = strlen(argv[player_name_ix]);

  if ((fptr0 = fopen(argv[curr_arg],"r")) == NULL) {
    printf(couldnt_open,argv[curr_arg]);
    return 5;
  }

  if (!bStud)
    max_streets = 3;
  else
    max_streets = 4;

  file_no = 0;
  dbg_file_no = -1;

  if (bConsecutive)
    consecutive_hit_felt_count = 0;

  for ( ; ; ) {
    GetLine(fptr0,filename,&filename_len,MAX_FILENAME_LEN);

    if (feof(fptr0))
      break;

    file_no++;

    if (dbg_file_no == file_no)
      dbg = 1;

    if ((fptr = fopen(filename,"r")) == NULL) {
      printf(couldnt_open,filename);
      continue;
    }

    retval = get_date_from_path(filename,'\\',3,&date_string);

    if (retval) {
      printf("get_date_from_path() on %s failed: %d\n",filename,retval);
      continue;
    }

    strcpy(prev_filename,date_string);

    line_no = 0;
    hit_felt_count = 0;
    ending_balance = -1;
    reupped_count = 0;
    hand_number = 0;

    if (bMaxFeltDistance) {
      last_felted_hand_number = 0;
      max_felt_distance = 0;
    }

    for ( ; ; ) {
      GetLine(fptr,line,&line_len,MAX_LINE_LEN);

      if (feof(fptr))
        break;

      line_no++;

      if (line_no == dbg_line_no)
        dbg = 1;

      if (bDebug)
        printf("line %d %s\n",line_no,line);

      if (Contains(true,
        line,line_len,
        argv[player_name_ix],player_name_len,
        &ix)) {

        if (Contains(true,
          line,line_len,
          in_chips,IN_CHIPS_LEN,
          &ix)) {

          hand_number++;

          bSkipping = false;

          if (ending_balance == 0)
            reupped_count++;

          street = 0;
          num_street_markers = 0;
          spent_this_street = 0;
          spent_this_hand = 0;
          uncalled_bet_amount = 0;
          collected_from_pot = 0;
          collected_from_pot_count = 0;

          line[ix] = 0;

          for (ix--; (ix >= 0) && (line[ix] != '('); ix--)
            ;

          sscanf(&line[ix+1],"%d",&starting_balance);

          if (bDebug)
            printf("line %d starting_balance = %d\n",line_no,starting_balance);

          if (bStartingStack && (hand_number == 1))
            starting_stack = starting_balance;

          continue;
        }
        else if (bSkipping)
          continue;
        else if (Contains(true,
          line,line_len,
          posts_the_ante,POSTS_THE_ANTE_LEN,
          &ix)) {
          ante = get_work_amount(line,line_len);
          spent_this_hand = ante;

          continue;
        }
        else if (Contains(true,
          line,line_len,
          posts,POSTS_LEN,
          &ix)) {
          work = get_work_amount(line,line_len);
          spent_this_street += work;

          if (bDebug) {
            printf("line %d street %d POSTS work = %d, spent_this_street = %d\n",
              line_no,street,work,spent_this_street);
          }

          continue;
        }
        else if (Contains(true,
          line,line_len,
          collected,COLLECTED_LEN,
          &ix)) {

          for (end_ix = ix + COLLECTED_LEN; end_ix < line_len; end_ix++) {
            if (line[end_ix] == ' ')
              break;
          }

          line[end_ix] = 0;
          sscanf(&line[ix + COLLECTED_LEN],"%d",&work);

          if (!collected_from_pot_count) {
            spent_this_hand += spent_this_street;
            street++;
            spent_this_street = 0;
          }

          collected_from_pot += work;
          collected_from_pot_count++;

          if (bDebug) {
            printf("line %d street %d COLLECTED work = %d, collected_from_pot = %d\n",
              line_no,street,work,collected_from_pot);
          }

          continue;
        }
        else if (!strncmp(line,uncalled_bet,UNCALLED_BET_LEN)) {
          sscanf(&line[UNCALLED_BET_LEN],"%d",&uncalled_bet_amount);
          spent_this_street -= uncalled_bet_amount;

          if (bDebug) {
            printf("line %d street %d UNCALLED uncalled_bet_amount = %d, spent_this_street = %d\n",
              line_no,street,uncalled_bet_amount,spent_this_street);
          }

          continue;
        }
        else if (Contains(true,
          line,line_len,
          folds,FOLDS_LEN,
          &ix)) {
          spent_this_hand += spent_this_street;

          if (bDebug) {
            printf("line %d street %d FOLDS spent_this_street = %d, spent_this_hand = %d\n",
              line_no,street,spent_this_street,spent_this_hand);
          }

          bSkipping = true;

          ending_balance = starting_balance - spent_this_hand + collected_from_pot;

          continue;
        }
        else if (Contains(true,
          line,line_len,
          bets,BETS_LEN,
          &ix)) {
          work = get_work_amount(line,line_len);
          spent_this_street += work;

          if (bDebug) {
            printf("line %d street %d BETS work = %d, spent_this_street = %d\n",
              line_no,street,work,spent_this_street);
          }
        }
        else if (Contains(true,
          line,line_len,
          calls,CALLS_LEN,
          &ix)) {
          work = get_work_amount(line,line_len);
          spent_this_street += work;

          if (bDebug) {
            printf("line %d street %d CALLS work = %d, spent_this_street = %d\n",
              line_no,street,work,spent_this_street);
          }
        }
        else if (Contains(true,
          line,line_len,
          raises,RAISES_LEN,
          &ix)) {
          work = get_work_amount(line,line_len);
          spent_this_street = work;

          if (bDebug) {
            printf("line %d street %d RAISES work = %d, spent_this_street = %d\n",
              line_no,street,work,spent_this_street);
          }
        }
        else if (bStud && Contains(true,
          line,line_len,
          brings_in_for,BRINGS_IN_FOR_LEN,
          &ix)) {
          bring_in = get_work_amount(line,line_len);
          spent_this_street += bring_in;
          continue;
        }
      }
      else if (bSkipping)
        continue;
      else {
        if (!strncmp(line,summary,SUMMARY_LEN)) {
          if (bDebug)
            printf("line %d SUMMARY line detected; skipping\n",line_no);

          bSkipping = true;

          ending_balance = starting_balance - spent_this_hand + collected_from_pot;

          if (!ending_balance) {
            hit_felt_count++;

            if (bMaxFeltDistance) {
              felt_distance = hand_number - last_felted_hand_number;

              if (felt_distance > max_felt_distance)
                max_felt_distance = felt_distance;

              last_felted_hand_number = hand_number;
            }
          }

          continue;
        }

        if (!strncmp(line,street_marker,STREET_MARKER_LEN)) {
          num_street_markers++;

          if (num_street_markers > 1) {
            if (street <= num_street_markers)
              spent_this_hand += spent_this_street;

            street++;
            spent_this_street = 0;
          }
        }
      }
    }

    if (bOneAndDone) {
      if ((hit_felt_count == 1) && (ending_balance == 0))
        printf("%s\n",filename);
    }
    else if (!bReverse) {
      if (bReupped && (reupped_count == 0))
        ;
      else if (bConsecutive) {
        consecutive_hit_felt_count += hit_felt_count;

        if (ending_balance && (consecutive_hit_felt_count > 0)) {
          printf(fmt,consecutive_hit_felt_count,date_string);
          consecutive_hit_felt_count = 0;
        }
      }
      else if ((bShowZero || hit_felt_count) && (!bExactCount || (hit_felt_count == exact_count))) {
        if (bCount)
          printf(fmt,hit_felt_count,date_string);
        else if (bStartingStack)
          printf(fmt,starting_stack,date_string);
        else {
          if (!bMaxFeltDistance)
            printf("%s\n",filename);
          else
            printf(fmt,max_felt_distance,date_string);
        }
      }
    }
    else {
      if (!hit_felt_count)
        printf("%s\n",filename);
    }

    fclose(fptr);
  }

  if (bConsecutive && (consecutive_hit_felt_count > 0))
    printf(fmt,consecutive_hit_felt_count,prev_filename);

  fclose(fptr0);

  return 0;
}
int CUnit3DLoader::ParseSub(CFileHandler& ifs, UnitModel &model,const string& filename,float3 offset,const string& treename)
{
	string s;
	bool inComment=false;

	Animation* curAnim=0;
	int curAnimFrame=0;

	bool firstGeometryPass=false;

	if(geometryModels.find(treename)==geometryModels.end()){
		geometryModels[treename]=new UnitModelGeometry();
		UnitModelGeometry& geometry=*geometryModels[treename];
		firstGeometryPass=true;
		geometry.normalBuffer=0;
		geometry.indexBuffer=0;
		geometry.numIndeces=0;
		geometry.numVerteces=0;
	}
	model.geometry=geometryModels[treename];
	UnitModelGeometry& geometry=*model.geometry;
	
	geometry.radius=1;
	geometry.height=1;
	geometry.isAnimated=false;

	model.texCoordBuffer=0;

	while(ifs.Peek()!=EOF){
		s=GetWord(ifs);
		MakeLow(s);
		if(s[0]=='/' && !inComment){
			if(s[1]=='/'){
				GetLine(ifs);
				continue;
			}
			if(s[1]=='*')
				inComment=true;
		}
		if(inComment){
			for(int a=0;a<s.size()-1;++a)
				if(s[a]=='*' && s[a+1]=='/')
					inComment=false;
			if(inComment)
				continue;
		}
		if(ifs.Eof())
			break;
		while((s.c_str()[0]=='/') || (s.c_str()[0]=='\n')){
			s=GetLine(ifs);
			s=GetWord(ifs);
			MakeLow(s);
			if(ifs.Eof())
				break;
		}
		if(s=="vertex"){
			int num=atoi(GetWord(ifs).c_str());
			float3 v;
			v.x=atof(GetWord(ifs).c_str());
			v.y=atof(GetWord(ifs).c_str());
			v.z=atof(GetWord(ifs).c_str());
			v-=offset;

			if(firstGeometryPass){
				if(curAnim==0){
					while(geometry.vertex.size()<=num){
						geometry.vertex.push_back(float3(0,0,0));
						geometry.vertexNormal.push_back(float3(0,0,0));
					}
					geometry.vertex[num]=v;
				} else {
					AnimFrame* af=&curAnim->frames[curAnimFrame];
					while(af->vertex.size()<=num){
						af->vertex.push_back(float3());
	//					model.vertexNormal.push_back(float3(0,0,0));
					}
					af->vertex[num]=v;
				}
			}
		} else if(s=="quad"){
			Quad q;
			QuadTex qt;
			for(int a=0;a<4;++a)
				q.verteces[a]=atoi(GetWord(ifs).c_str());
			for(int a=0;a<8;++a)
				qt.texPos[0][a]=atof(GetWord(ifs).c_str());
			qt.texName=GetWord(ifs);
			qt.teamTex=atoi(GetWord(ifs).c_str());
			q.normalType=atoi(GetWord(ifs).c_str());
			model.quadTex.push_back(qt);
			if(firstGeometryPass)
				geometry.quad.push_back(q);

		} else if(s=="tri"){
			Tri t;
			TriTex tt;
			for(int a=0;a<3;++a)
				t.verteces[a]=atoi(GetWord(ifs).c_str());
			for(int a=0;a<3;++a){
				tt.texPos[0][a*2]=1-atof(GetWord(ifs).c_str());
				tt.texPos[0][a*2+1]=1-atof(GetWord(ifs).c_str());
			}
			tt.texName=GetWord(ifs);
			tt.teamTex=atoi(GetWord(ifs).c_str());
			t.normalType=atoi(GetWord(ifs).c_str());
			model.triTex.push_back(tt);
			if(firstGeometryPass)
				geometry.tri.push_back(t);

		} else if(s=="propeller"){
			Propeller p;
			for(int a=0;a<3;++a)
				p.pos[a]=atof(GetWord(ifs).c_str());
			p.size=atof(GetWord(ifs).c_str());
			if(firstGeometryPass)
				geometry.propellers.push_back(p);

		} else if(s=="height"){
			geometry.height=atof(GetWord(ifs).c_str());

		} else if(s=="radius"){
			geometry.radius=atof(GetWord(ifs).c_str());

		} else if(s=="subobject"){
			UnitModel* um=new UnitModel;
			model.subModels.push_back(um);
			um->name=GetWord(ifs);
			float3 off,rot;
			for(int a=0;a<3;++a)
				off[a]=atof(GetWord(ifs).c_str());
			for(int a=0;a<3;++a)
				rot[a]=atof(GetWord(ifs).c_str());
			um->team=model.team;

			char c[100];
			sprintf(c,"%s%d",treename.c_str(),model.subModels.size());
			ParseSub(ifs,*um,filename,off,c);

			um->geometry->offset=off;
			um->geometry->rotVector=rot;
		} else if(s=="endsubobject"){
			return 1;

		} else if(s=="animation"){
			string name=GetWord(ifs);
			if(name=="end")
				curAnim=0;
			else{
				if(geometry.animations.find(name)==geometry.animations.end()){
					geometry.animations[name]=new Animation;
				}
				curAnim=geometry.animations[name];
			}
			curAnimFrame=0;
			geometry.isAnimated=true;

		} else if(s=="keyframe"){
			string num=GetWord(ifs);
			if(num=="end"){
				curAnimFrame=0;
			} else {
				curAnimFrame=atoi(num.c_str());
				float length=atoi(GetWord(ifs).c_str())/25.0f*30.0f;
				if(curAnim){
					while(curAnim->frames.size()<=curAnimFrame){
						curAnim->frames.push_back(AnimFrame());
					}
					curAnim->frames[curAnimFrame].length=length;
				}
			}

		} else {
			if(s!="")
				(*info) << "Unknown token " << s.c_str() << " in " << filename.c_str() << "\n";
		}
	}
	return 1;
}
Esempio n. 27
0
STextOffset TTextLayout::PointToOffset(const TPoint& point, bool round) const
{
	TCoord h = point.h - fInset.h;
	if (h < 0)
		h = 0;
	TCoord v = point.v - fInset.v;
	if (v < 0)
		v = 0;

	uint32 line;
	for (line = 0; line < fLineCount; line++)
	{
		if (fLineBreaks[line].vertOffset > v)
		{
			if (line > 0)
				line--;
			break;
		}
	}
	
	if (line >= fLineCount)
		line = fLineCount - 1;
		
	STextOffset result = LineToOffset(line);
	
	const TChar*	lineStart;
	STextOffset		lineLength;
	TCoord			vertOffset, ascent, height;
	
	GetLine(line, lineStart, lineLength, vertOffset, ascent, height);
	if (lineLength == 0)
		return result;

	const TChar* 	lineEnd = lineStart + lineLength;
	const TChar*	text = lineStart;
	const TChar*	lastText = text;
	TCoord			horizOffset = 0;
	TCoord			lastHorizOffset = 0;
	
	while (text < lineEnd)
	{
		NextCharacter(text);	

		TCoord horizOffset = MeasureText(lineStart, text - lineStart, 0);
		
		if (horizOffset > h)
		{
			if (round && h - lastHorizOffset + 1 >= horizOffset - h)
				return result + (text - lineStart);
			else
				return result + (lastText - lineStart);
		}
		
		lastHorizOffset = horizOffset;
		lastText = text;
	}

	if (round && h - lastHorizOffset + 1 >= horizOffset - h)
		return result + (text - lineStart);
	else
		return result + (lastText - lineStart);
}
Esempio n. 28
0
void C3DTransform::Render(const PARAM3DTRANSFORM & param3d)
{
	RECT rc = {0, 0, m_nSrcWndWidth, m_nSrcWndHeight};

	// 计算当前的动画窗口屏幕坐标
	Quad quad;
	GetQuadByAnimateValue(param3d.nRotateX,param3d.nRotateY, param3d.nRotateZ, param3d.nOffsetZ, &quad);

	// 用于计算矩形->任意四边形的对应关系
	PerspectiveTransform perspective;
	perspective.SetQuad(&quad, &rc);
	perspective.ChangeToFixedPoint();

	int   nWidthDst  = m_nSrcWndWidth-1;   // (300->299),数据范围是它的大小减一
	int   nHeightDst = m_nSrcWndHeight-1; //

	int nDstPitch = nWidthDst*4;

	float fxSrc = 0;
	float fySrc = 0;
	float *pfxSrc = &fxSrc;  // 为了在perspective_transform中使用指针
	float *pfySrc = &fySrc;

	LPBYTE pDstBits=m_pDstBits;
	
	int nPixByte=m_nBitsPixel/8;

#if 1  // 在大循环之前剔除掉一些空白区域
	//将目标图片清空
	memset(pDstBits, 0, nDstPitch * nHeightDst);

	int nMinX = max(0, min(min(min(quad.Ax,quad.Bx),quad.Cx),quad.Dx));
	int nMinY = max(0, min(min(min(quad.Ay,quad.By),quad.Cy),quad.Dy));
	int nMaxX = min(nWidthDst,  max(max(max(quad.Ax,quad.Bx),quad.Cx),quad.Dx));
	int nMaxY = min(nHeightDst, max(max(max(quad.Ay,quad.By),quad.Cy),quad.Dy));

	
	pDstBits += (nMinY*nDstPitch);
	for (int Y = nMinY; Y < nMaxY; Y++)
	{
		LPBYTE pDest=pDstBits;
		for (int X = nMinX; X < nMaxX; X++)
		{
#else
	for (int X = 0, Y = 0; Y < m_nSrcWndHeight; Y++)
	{
		for (X = 0; X < m_nSrcWndWidth; X++)
		{
#endif
			perspective_transform_fp(perspective, X, Y, pfxSrc, pfySrc);

			int nx = 0; //fx;   // 注: 直接赋值 int i = floatvalue; 会产生一个 _ftol()调用
			int ny = 0; //fy;   //     导致效率降低。这里使用内嵌汇编指令。(3D游戏编程大师技巧 P918)

			// 浮点数转整数。 注意:默认的fistp是四舍五入模式。需要通过调用_control87(_MCW_RC, _RC_DOWN);进行调整
#ifndef _WIN64
			__asm	fld    fxSrc;
			__asm	fistp  nx;

			__asm	fld    fySrc;
			__asm	fistp  ny;
#else
            nx = int(fxSrc);
            ny = int(fySrc);
#endif//WIN32

			// 1. ceil的效率非常非常低!千万别在这用
			// 但是有一个问题如果height为300,ySrc=299.99999999时,转成(int)得到的结果是300,
			// 但在这里判断的话是成功的,导致最后崩溃,因此当ySrc>299时即退出
			if (nx < 0 || nx >= nWidthDst || ny < 0 || ny >= nHeightDst)
			{        
				continue;
			}

			// 目标与源图像素对应
#if 0
			//////////////////////////////////////////////////////////////////////////
			// 邻近取样, 速度快,但有锯齿
			((DWORD*)pDstBits)[X] = ((DWORD*)(m_pSrcBits + m_nSrcPitch*(int)ySrc))[(int)xSrc];
#else
			//////////////////////////////////////////////////////////////////////////
			// 二次线性插值,能有效去掉锯齿,但速度非常慢
			//((DWORD*)pDstBits)[X] = Bilinear(m_pSrcBits, m_nSrcPitch, nx, ny, (float)fxSrc, (float)fySrc);

			//
			// 二次线性插值公式推导
			// http://blog.csdn.net/dakistudio/article/details/1767100 二次线性插值公式推导
			//
			// x为fx的向下取整,y为fy的向下取整
			//
			//inline DWORD& Bilinear(BYTE* pBits, const int& nPitch, const int& x, const int& y, const float& fx, const float& fy)
			{
				// 已将原始图片的right/bottom扩大1px,这样在获取 x+1, y+1时达到数组边缘也不会崩溃
				// 取附近的四个像素的颜色值(x,y) (x+1, y) (x, y+1) (x+1, y+1)

				LPBYTE pValue=GetLine(m_pSrcBits, m_nSrcPitch, ny);
				pValue += nx*nPixByte;

				LPBYTE p0=pValue;//(x,y);
				LPBYTE p2=pValue+nPixByte;//(x+1,y)
				pValue+=m_nSrcPitch;//y+1
				LPBYTE p1=pValue;//(x,y+1)
				LPBYTE p3=pValue+nPixByte;//(x+1,y+1)

				// 将浮点数乘法转为定点数乘法。同时优化浮点数转成整数。
				float u = (float)fxSrc - nx;
				float v = (float)fySrc - ny;
			
#ifndef _WIN64
				float fpm3 = FLOAT_TO_FIXP16(u*v);
				float fpm2 = FLOAT_TO_FIXP16(u*(1.0f-v));
				float fpm1 = FLOAT_TO_FIXP16(v*(1.0f-u));
				float fpm0 = FLOAT_TO_FIXP16((1.0f-u)*(1.0f-v));
				int pm3_16 = 0;
				int pm2_16 = 0;
				int pm1_16 = 0;
				int pm0_16 = 0;
				__asm
				{
					fld    fpm3;
					fistp  pm3_16;
					fld    fpm2;
					fistp  pm2_16;
					fld    fpm1;
					fistp  pm1_16;
					fld    fpm0;
					fistp  pm0_16;
				}
#else
                int pm3_16 = int(FLOAT_TO_FIXP16(u*v));
                int pm2_16 = int(FLOAT_TO_FIXP16(u*(1.0f-v)));
                int pm1_16 = int(FLOAT_TO_FIXP16(v*(1.0f-u)));
                int pm0_16 = int(FLOAT_TO_FIXP16((1.0f-u)*(1.0f-v)));
#endif//WIN32
                pDest = pDstBits + X * nPixByte;
				*pDest++=(BYTE)((pm0_16*(*p0++) + pm1_16*(*p1++) + pm2_16*(*p2++) + pm3_16*(*p3++)) >> FIXP16_SHIFT);
				*pDest++=(BYTE)((pm0_16*(*p0++) + pm1_16*(*p1++) + pm2_16*(*p2++) + pm3_16*(*p3++)) >> FIXP16_SHIFT);
				*pDest++=(BYTE)((pm0_16*(*p0++) + pm1_16*(*p1++) + pm2_16*(*p2++) + pm3_16*(*p3++)) >> FIXP16_SHIFT);
				if(nPixByte==4) *pDest++=(BYTE)((pm0_16*(*p0++) + pm1_16*(*p1++) + pm2_16*(*p2++) + pm3_16*(*p3++)) >> FIXP16_SHIFT);
			}
#endif
		}
		pDstBits += nDstPitch;
	}
}



BOOL C3DTransform::SetImage( LPBYTE pSour,LPBYTE pDest,int nWid,int nHei,int nBitsPixel )
{
	if(nBitsPixel!=24 && nBitsPixel!=32) //只支持24和32位
		return FALSE;

	m_nSrcWndWidth=nWid+1,m_nSrcWndHeight=nHei+1;
	m_nSrcPitch=STRIDELEN(m_nSrcWndWidth,nBitsPixel);
	m_pSrcBits=(LPBYTE)calloc(1,m_nSrcPitch*m_nSrcWndHeight);
	m_nBitsPixel=nBitsPixel;
	m_pDstBits=pDest;

	LPBYTE p1=m_pSrcBits+m_nSrcPitch;//bottom-up,跳过最下面一行
	LPBYTE p2=pSour;
	int nLen=STRIDELEN(nWid,nBitsPixel);
	for(int i=0;i<nHei;i++)
	{
		memcpy(p1,p2,nLen);
		p1+=m_nSrcPitch;
		p2+=nLen;
	}
	return TRUE;
}

}//end of namespace
int main(int argc,char **argv)
{
  int curr_arg;
  bool bVerbose;
  bool bSeconds;
  bool bAvg;
  FILE *fptr;
  int line_len;
  int line_no;
  int num_hands;
  int ix;
  int hyphen_ix;
  time_t date1;
  time_t date2;
  int seconds;
  int diff;
  int hours;
  double avg;

  if ((argc < 2) || (argc > 5)) {
    printf(usage);
    return 1;
  }

  bVerbose = false;
  bSeconds = false;
  bAvg = false;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-verbose")) {
      bVerbose = true;
      getcwd(save_dir,_MAX_PATH);
    }
    else if (!strcmp(argv[curr_arg],"-seconds"))
      bSeconds = true;
    else if (!strcmp(argv[curr_arg],"-avg"))
      bAvg = true;
    else
      break;
  }

  if (argc - curr_arg != 1) {
    printf(usage);
    return 2;
  }

  if ((fptr = fopen(argv[curr_arg],"r")) == NULL) {
    printf(couldnt_open,argv[curr_arg]);
    return 3;
  }

  line_no = 0;
  num_hands = 0;

  for ( ; ; ) {
    GetLine(fptr,line,&line_len,MAX_LINE_LEN);

    if (feof(fptr))
      break;

    line_no++;

    if (Contains(true,
      line,line_len,
      pokerstars,POKERSTARS_LEN,
      &ix)) {

      num_hands++;

      hyphen_ix = get_hyphen_ix(line,line_len);

      if (hyphen_ix < 0) {
        printf("line %d: get_hyphen_ix failed\n",line_no);
        return 4;
      }

      line[hyphen_ix + 12] = 0;
      line[line_len - 4] = 0;

      date2 = cvt_date_and_time(&line[hyphen_ix + 2],&line[hyphen_ix + 13]);

      if (date2 == -1L) {
        printf(invalid_date_and_time,line_no,
          &line[hyphen_ix + 2],&line[hyphen_ix + 13]);
        return 5;
      }

      if (line_no == 1)
        date1 = date2;
    }
  }

  fclose(fptr);

  seconds = date2 - date1;

  if (bSeconds || (seconds < 60))
    printf("%d seconds",seconds);
  else {
    diff = seconds;

    if (diff < 60 * 60)
      printf("%d minutes, %d seconds",diff / 60,diff % 60);
    else {
      hours = diff / (60 * 60);
      diff -= (hours * 60 * 60);
      printf("%d hours, %d minutes, %d seconds",hours,diff / 60,diff %60);
    }
  }

  if (bAvg) {
    avg = (double)seconds / (double)(num_hands - 1);

    printf(" (%lf)",avg);
  }

  if (!bVerbose)
    putchar(0x0a);
  else
    printf(" %s\n",save_dir);

  return 0;
}
Esempio n. 30
0
bool CHTMLElement_FrameSet::ValidateTree(CBDParser *pParser, CParseHTMLNode *pThisEle)
{
// <!ELEMENT FRAMESET - - ((FRAMESET|FRAME)+ & NOFRAMES?)
CParseHTMLNode *pEle;
CHTMLElement *pE;
bool bValid=true, bOneFrame=false;

	pEle = (CParseHTMLNode *)pThisEle->GetFirstChild();
	while(pEle && bValid)
		{
		if ((pE = pEle->m_pElement))
			{
			bValid = true;

			if (pE->GetID() == NODE_ID_FRAMESET || pE->GetID() == NODE_ID_FRAME)
				bOneFrame = true;
			else if (pE->GetID() == NODE_ID_NOFRAMES || entIsPCData(pE->GetID()))
				;
			else
				bValid=false;
			}
		//
		pEle = (CParseHTMLNode *)pThisEle->GetNextChild(pEle);
		}
	//
	if (!bValid || !bOneFrame)
		{
		SetValid(false);
		pParser->AddError(0, "The <FRAMESET> tag may only include <FRAMESET>s and <FRAME>s", NULL, NULL, GetLine(), GetCol());
		}
	//
	return true;
}