Пример #1
0
    Ref<Result> MultiFormatUPCEANReader::decodeRow(int rowNumber, Ref<BitArray> row) {
      // Compute this location once and reuse it on multiple implementations
      int size = readers.size();
      for (int i = 0; i < size; i++) {
        Ref<OneDReader> reader = readers[i];
        Ref<Result> result = reader->decodeRow(rowNumber, row);
        if (result.empty()) {
          continue;
        }

        // Special case: a 12-digit code encoded in UPC-A is identical to a "0"
        // followed by those 12 digits encoded as EAN-13. Each will recognize such a code,
        // UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with "0".
        // Individually these are correct and their readers will both read such a code
        // and correctly call it EAN-13, or UPC-A, respectively.
        //
        // In this case, if we've been looking for both types, we'd like to call it
        // a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read
        // UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A
        // result if appropriate.
        if (result->getBarcodeFormat() == BarcodeFormat_EAN_13) {
          const std::string& text = (result->getText())->getText();
          if (text[0] == '0') {
            Ref<String> resultString(new String(text.substr(1)));
            Ref<Result> res(new Result(resultString, result->getRawBytes(),
                result->getResultPoints(), BarcodeFormat_UPC_A));
            return res;
          }
        }
        return result;
      }
      return Ref<Result>();
    }
Пример #2
0
/*
    Assuming Returned data looks like this:
    +CIFSR:STAIP,"192.168.11.2"
    +CIFSR:STAMAC,"18:fe:34:9f:3a:f5"
    grabbing IP from first set of quotation marks
*/
char* ESP8266::getIPAddress()
{
    char result[30] = {0};
    int check = 0;
    check = sendCommand("AT+CIFSR", NULL, result, 1000);
    //pc.printf("\r\nReceivedInfo for IP Command is: %s\r\n",result);
    ip = ipString;
    if(check) {
        // Success
        string resultString(result);
        uint8_t pos1 = 0, pos2 = 0;
        //uint8_t pos3 = 0, pos4 = 0;
        pos1 = resultString.find("+CIFSR:STAIP");
        pos1 = resultString.find('"',pos1);
        pos2 = resultString.find('"',pos1+1);
        //pos3 = resultString.find('"',pos2+1); //would find mac address
        //pos4 = resultString.find('"',pos3+1);
        strncpy(ipString,resultString.substr(pos1,pos2).c_str(),sizeof(ipString));
        ipString[pos2 - pos1 +1] = 0; // null terminate string correctly.
        INFO("IP: %s",ipString);
        ip = ipString;

    } else {
        // Failure
        ERR("getIPAddress() failed");
        ip = NULL;
    }
    return ip;
}
Пример #3
0
        string removeKdigits(string num, int k)
        {
            if (k >= num.size())
            {
                return "0";
            }
            stack<int> increasing_indice;
            int i = 0;
            while (k > 0)
            {
                while (true)
                {
                    if (increasing_indice.size() == 0)
                    {
                        increasing_indice.push(i++);
                    }
                    else if (num[i] >= num[increasing_indice.top()])
                    {
                        increasing_indice.push(i++);
                    }
                    else
                    {
                        break;
                    }
                }
                int index_to_remove = increasing_indice.top();
                num[index_to_remove] = ' ';
                increasing_indice.pop();
                k--;
            }

            bool leading = true;
            char* resultBuffer = new char[num.size() - k + 1];
            size_t j = 0;
            for (size_t i = 0; i < num.size(); i++)
            {
                if (num[i] != ' ')
                {
                    if (!leading || num[i] != '0')
                    {
                        resultBuffer[j++] = num[i];
                        leading = false;
                    }
                }
            }

            if (leading)
            {
                resultBuffer[j++] = '0';
                leading = false;
            }

            resultBuffer[j++] = '\0';
            string resultString(resultBuffer);
            delete[] resultBuffer;
            return resultString;
        }
Пример #4
0
Ref<Result> UPCAReader::maybeReturnResult(Ref<Result> result) {
    const std::string& text = (result->getText())->getText();
    if (text[0] == '0') {
        Ref<String> resultString(new String(text.substr(1)));
        Ref<Result> res(new Result(resultString, result->getRawBytes(), result->getResultPoints(), BarcodeFormat_UPC_A));
        return res;
    } else {
        throw ReaderException("Not UPC-A barcode.");
    }
}
Пример #5
0
void InlineResult::report()
{
    // User may have suppressed reporting via setReported(). If so, do nothing.
    if (inlReported)
    {
        return;
    }

    inlReported = true;

#ifdef DEBUG

    // Optionally dump the result
    if (VERBOSE)
    {
        const char* format = "INLINER: during '%s' result '%s' reason '%s' for '%s' calling '%s'\n";
        const char* caller = (inlCaller == nullptr) ? "n/a" : inlCompiler->eeGetMethodFullName(inlCaller);
        const char* callee = (inlCallee == nullptr) ? "n/a" : inlCompiler->eeGetMethodFullName(inlCallee);

        JITDUMP(format, inlContext, resultString(), reasonString(), caller, callee);
    }

    // If the inline failed, leave information on the call so we can
    // later recover what observation lead to the failure.
    if (isFailure() && (inlCall != nullptr))
    {
        // compiler should have revoked candidacy on the call by now
        assert((inlCall->gtFlags & GTF_CALL_INLINE_CANDIDATE) == 0);

        inlCall->gtInlineObservation = static_cast<unsigned>(inlObservation);
    }

#endif // DEBUG

    if (isDecided())
    {
        const char* format = "INLINER: during '%s' result '%s' reason '%s'\n";
        JITLOG_THIS(inlCompiler, (LL_INFO100000, format, inlContext, resultString(), reasonString()));
        COMP_HANDLE comp = inlCompiler->info.compCompHnd;
        comp->reportInliningDecision(inlCaller, inlCallee, result(), reasonString());
    }
}
static bool isStyleSheetInjectedForURLAtPath(WebViewTest* test, const char* path)
{
    test->loadURI(kServer->getURIForPath(path).data());
    test->waitUntilLoadFinished();

    GOwnPtr<GError> error;
    WebKitJavascriptResult* javascriptResult = test->runJavaScriptAndWaitUntilFinished(kStyleSheetTestScript, &error.outPtr());
    g_assert(javascriptResult);
    g_assert(!error.get());

    GOwnPtr<char> resultString(WebViewTest::javascriptResultToCString(javascriptResult));
    return !g_strcmp0(resultString.get(), kStyleSheetTestScriptResult);
}
Пример #7
0
 Ref<Result> UPCAReader::maybeReturnResult(Ref<Result> result) {
   if (result.empty()) {
     return result;
   }
   const std::string& text = (result->getText())->getText();
   if (text[0] == '0') {
     Ref<String> resultString(new String(text.substr(1)));
     Ref<Result> res(new Result(resultString, result->getRawBytes(), result->getResultPoints(),
         BarcodeFormat_UPC_A));
     return res;
   }
   return Ref<Result>();
 }
Пример #8
0
void CcurrentTimeDlg::OnTimer(UINT_PTR nIDEvent)
{
	SYSTEMTIME  curTime;
	::GetLocalTime(&curTime);
	CString StrMilli;
	StrMilli.Format(L"%d", curTime.wMilliseconds);
	CString StrSec;
	StrSec.Format(L"%02d", curTime.wSecond);
	CString StrMin;
	StrMin.Format(L"%02d", curTime.wMinute);
	CString StrHours;
	StrHours.Format(L"%02d", curTime.wHour);
	CString separator (":");
	CString resultString(StrHours + separator + StrMin + separator + StrSec + separator + StrMilli);
	///////////////////////
	SetDlgItemText(IDC_STATIC_My, resultString);
}
Пример #9
0
std::string toUtf8String( const std::wstring &wideString )
{
	int utf8Size = ::WideCharToMultiByte( CP_UTF8, 0, wideString.c_str(), -1, NULL, 0, NULL, NULL );
	if( utf8Size == 0 ) {
		throw Exception( "Error in UTF-16 to UTF-8 conversion." );
	}

	std::vector<char> resultString( utf8Size );

	int convResult = ::WideCharToMultiByte( CP_UTF8, 0, wideString.c_str(), -1, &resultString[0], utf8Size, NULL, NULL );

	if( convResult != utf8Size ) {
		throw Exception( "Error in UTF-16 to UTF-8 conversion." );
	}

	return std::string( &resultString[0] );
}
Пример #10
0
PRUnichar *nsImportStringBundle::GetStringByID(PRInt32 aStringID,
                                               nsIStringBundle *aBundle)
{
  if (aBundle)
  {
    PRUnichar *ptrv = nsnull;
    nsresult rv = aBundle->GetStringFromID(aStringID, &ptrv);

    if (NS_SUCCEEDED(rv) && ptrv)
      return(ptrv);
  }

  nsString resultString(NS_LITERAL_STRING("[StringID "));
  resultString.AppendInt(aStringID);
  resultString.AppendLiteral("?]");

  return ToNewUnicode(resultString);
}
Пример #11
0
std::wstring toWideString( const std::string &utf8String )
{
	int wideSize = ::MultiByteToWideChar( CP_UTF8, 0, utf8String.c_str(), -1, NULL, 0 );
	if( wideSize == ERROR_NO_UNICODE_TRANSLATION ) {
		throw Exception( "Invalid UTF-8 sequence." );
	}
	else if( wideSize == 0 ) {
		throw Exception( "Error in UTF-8 to UTF-16 conversion." );
	}

	std::vector<wchar_t> resultString( wideSize );
	int convResult = ::MultiByteToWideChar( CP_UTF8, 0, utf8String.c_str(), -1, &resultString[0], wideSize );
	if( convResult != wideSize ) {
		throw Exception( "Error in UTF-8 to UTF-16 conversion." );
	}

	return std::wstring( &resultString[0] );
}
Пример #12
0
PRUnichar *nsImportStringBundle::GetStringByName(const char *aName,
                                                 nsIStringBundle *aBundle)
{
  if (aBundle)
  {
    PRUnichar *ptrv = nsnull;
    nsresult rv = aBundle->GetStringFromName(
        NS_ConvertUTF8toUTF16(aName).get(), &ptrv);

    if (NS_SUCCEEDED(rv) && ptrv)
      return(ptrv);
  }

  nsString resultString(NS_LITERAL_STRING("[StringName "));
  resultString.Append(NS_ConvertUTF8toUTF16(aName).get());
  resultString.AppendLiteral("?]");

  return ToNewUnicode(resultString);
}
Пример #13
0
PRUnichar *nsEudoraStringBundle::GetStringByID(int32_t stringID)
{
  if (!m_pBundle)
    m_pBundle = GetStringBundle();

  if (m_pBundle)
  {
    PRUnichar *ptrv = nullptr;
    nsresult rv = m_pBundle->GetStringFromID(stringID, &ptrv);

    if (NS_SUCCEEDED(rv) && ptrv)
      return ptrv;
  }

  nsString resultString(NS_LITERAL_STRING("[StringID "));
  resultString.AppendInt(stringID);
  resultString.AppendLiteral("?]");

  return ToNewUnicode(resultString);
}
Пример #14
0
void MainWindow::onGameFinishedWithResult(GameResult *result)
{
    QString resultString("%1 wins");
    if(result->winner)
    {
        resultString = resultString.arg(result->winner->name());
    }
    else
    {
        resultString = resultString.arg("Noone");
    }

    m_ui->resultWidget->addItem(new QListWidgetItem(resultString, m_ui->resultWidget));


    m_ui->player1Label->setText(QString("%1: %2").arg(result->player1->name()).arg(m_model->wins(result->player1)));
    m_ui->player2Label->setText(QString("%1: %2").arg(result->player2->name()).arg(m_model->wins(result->player2)));

    m_controller->restartGame();
}
Пример #15
0
std::string getCurrentBinaryFileFQN() {
    #ifdef WIN32
        TCHAR result[MAX_PATH];
        std::basic_string<TCHAR> resultString(result, GetModuleFileName(NULL, result, MAX_PATH));
        return std::string(resultString.begin(), resultString.end());
    #else
        char fqnOfBinary[FILENAME_MAX];
        char pathToProcessImage[FILENAME_MAX];

        sprintf(pathToProcessImage, "/proc/%d/exe", getpid());
        const ssize_t lengthOfFqn = readlink(pathToProcessImage, fqnOfBinary, sizeof(fqnOfBinary) - 1);

        if (lengthOfFqn != -1) {
            fqnOfBinary[lengthOfFqn] = '\0';
            return std::string(std::move(fqnOfBinary));
        }
        else {
            return std::string("");
        }
    #endif
    }
Пример #16
0
JSValue *convertNPVariantToValue(ExecState*, const NPVariant* variant, RootObject* rootObject)
{
    JSLock lock;
    
    NPVariantType type = variant->type;

    if (type == NPVariantType_Bool)
        return jsBoolean(NPVARIANT_TO_BOOLEAN(*variant));
    if (type == NPVariantType_Null)
        return jsNull();
    if (type == NPVariantType_Void)
        return jsUndefined();
    if (type == NPVariantType_Int32)
        return jsNumber(NPVARIANT_TO_INT32(*variant));
    if (type == NPVariantType_Double)
        return jsNumber(NPVARIANT_TO_DOUBLE(*variant));
    if (type == NPVariantType_String) {
        NPUTF16 *stringValue;
        unsigned int UTF16Length;
        convertNPStringToUTF16(&variant->value.stringValue, &stringValue, &UTF16Length); // requires free() of returned memory
        UString resultString((const UChar *)stringValue,UTF16Length);
        free(stringValue);
        return jsString(resultString);
    }
    if (type == NPVariantType_Object) {
        NPObject *obj = variant->value.objectValue;
        
        if (obj->_class == NPScriptObjectClass)
            // Get JSObject from NP_JavaScriptObject.
            return ((JavaScriptObject *)obj)->imp;

        // Wrap NPObject in a CInstance.
        return Instance::createRuntimeObject(Instance::CLanguage, obj, rootObject);
    }
    
    return jsUndefined();
}
Пример #17
0
std::string replaceChar(const std::string& str, char c, const std::string& rep) {

	int count = 0;
	for(int i = 0; i < str.size(); ++i) {	//	count the number of c occurences
		if(str[i] == c) {
			++count;
		}
	}

	int size = str.size() + count * (rep.size() - 1); //size of the new string; each copied rep will occupy the space previously occupied by c + rep.size() - 1 chars
	std::vector<char> resultString(size);	//buffer for the new string
	for(int i = str.size() - 1, j = size - 1; i >= 0; --i, --j) { //	iterate backwards over str
		if(str[i] == c) { //we have to replace
			j -= (rep.size() - 1); // shift pointer to the place where rep will start in the resultString
			for(int k = 0; k < rep.size(); ++k) {
				resultString[j + k] = rep[k];
			}
		} else {	//	just copy a single char from str
			resultString[j] = str[i];
		}
	}

	return std::string(resultString.begin(), resultString.end());
}
Пример #18
0
		Ref<Result> UPCEANReader::decodeRow(int rowNumber, Ref<BitArray> row, int startGuardRange[]){
			
			std::string tmpResultString;
			std::string& tmpResultStringRef = tmpResultString;
			int endStart;
			try {
				endStart = decodeMiddle(row, startGuardRange, 2 /*reference findGuardPattern*/ , tmpResultStringRef);
			} catch (ReaderException re) {
				if (startGuardRange!=NULL) {
					delete [] startGuardRange;
					startGuardRange = NULL;
				}
				throw re;
			}
			
			int* endRange = decodeEnd(row, endStart);
						
#pragma mark QuietZone needs some change
			// Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
			// spec might want more whitespace, but in practice this is the maximum we can count on.
//			int end = endRange[1];
//			int quietEnd = end + (end - endRange[0]);
//			if (quietEnd >= row->getSize() || !row->isRange(end, quietEnd, false)) {
//				throw ReaderException("Quiet zone asserrt fail.");
//			}
			
			if (!checkChecksum(tmpResultString)) {
				if (startGuardRange!=NULL) {
					delete [] startGuardRange;
					startGuardRange = NULL;
				}
				if (endRange!=NULL) {
					delete [] endRange;
					endRange = NULL;
				}
				throw ReaderException("Checksum fail.");
			}
			
			Ref<String> resultString(new String(tmpResultString));
			
			float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;
			float right = (float) (endRange[1] + endRange[0]) / 2.0f;
			
			std::vector< Ref<ResultPoint> > resultPoints(2);
			Ref<OneDResultPoint> resultPoint1(new OneDResultPoint(left, (float) rowNumber));
			Ref<OneDResultPoint> resultPoint2(new OneDResultPoint(right, (float) rowNumber));
			resultPoints[0] = resultPoint1;
			resultPoints[1] = resultPoint2;
			
			ArrayRef<unsigned char> resultBytes(1);
			
			if (startGuardRange!=NULL) {
				delete [] startGuardRange;
				startGuardRange = NULL;
			}
			if (endRange!=NULL) {
				delete [] endRange;
				endRange = NULL;
			}
			
			Ref<Result> res(new Result(resultString, resultBytes, resultPoints, getBarcodeFormat()));
			return res;
		}
Пример #19
0
  Ref<Result> Code39Reader::decodeRow(int rowNumber, Ref<BitArray> row) {
    int* start = NULL;
    try {
      start = findAsteriskPattern(row);
      int nextStart = start[1];
      int end = row->getSize();

      // Read off white space
      while (nextStart < end && !row->get(nextStart)) {
        nextStart++;
      }

      std::string tmpResultString;

      const int countersLen = 9;
      int counters[countersLen];
      for (int i = 0; i < countersLen; i++) {
        counters[i] = 0;
      }
      char decodedChar;
      int lastStart;
      do {
        if (!recordPattern(row, nextStart, counters, countersLen)) {
          throw ReaderException("");
        }
        int pattern = toNarrowWidePattern(counters, countersLen);
        if (pattern < 0) {
          throw ReaderException("pattern < 0");
        }
        decodedChar = patternToChar(pattern);
        tmpResultString.append(1, decodedChar);
        lastStart = nextStart;
        for (int i = 0; i < countersLen; i++) {
          nextStart += counters[i];
        }
        // Read off white space
        while (nextStart < end && !row->get(nextStart)) {
          nextStart++;
        }
      } while (decodedChar != '*');
      tmpResultString.erase(tmpResultString.length()-1, 1);// remove asterisk

      // Look for whitespace after pattern:
      int lastPatternSize = 0;
      for (int i = 0; i < countersLen; i++) {
        lastPatternSize += counters[i];
      }
      int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
      // If 50% of last pattern size, following last pattern, is not whitespace,
      // fail (but if it's whitespace to the very end of the image, that's OK)
      if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
        throw ReaderException("too short end white space");
      }

      if (usingCheckDigit) {
        int max = tmpResultString.length() - 1;
        unsigned int total = 0;
        for (int i = 0; i < max; i++) {
          total += alphabet_string.find_first_of(tmpResultString[i], 0);
        }
        if (total % 43 != alphabet_string.find_first_of(tmpResultString[max], 0)) {
          throw ReaderException("");
        }
        tmpResultString.erase(max, 1);
      }

      Ref<String> resultString(new String(tmpResultString));
      if (extendedMode) {
        resultString = decodeExtended(tmpResultString);
      }

      if (tmpResultString.length() == 0) {
        // Almost surely a false positive
        throw ReaderException("");
      }

      float left = (float) (start[1] + start[0]) / 2.0f;
      float right = (float) (nextStart + lastStart) / 2.0f;

      std::vector< Ref<ResultPoint> > resultPoints(2);
      Ref<OneDResultPoint> resultPoint1(
        new OneDResultPoint(left, (float) rowNumber));
      Ref<OneDResultPoint> resultPoint2(
        new OneDResultPoint(right, (float) rowNumber));
      resultPoints[0] = resultPoint1;
      resultPoints[1] = resultPoint2;

      ArrayRef<unsigned char> resultBytes(1);

      Ref<Result> res(new Result(
                        resultString, resultBytes, resultPoints, BarcodeFormat_CODE_39));

      delete [] start;
      return res;
    } catch (ReaderException const& re) {
      delete [] start;
      return Ref<Result>();
    }
  }
Пример #20
0
std::string Soar_Instance::Message_Library(const char* pMessage)
{
    std::string resultString("CLI extension command failed.");
    Soar_Loaded_Library* libraryInfo;
    
    /* -- Convert command to lower case -- */
    std::string lFullCommand(pMessage);
    std::transform(lFullCommand.begin(), lFullCommand.end(), lFullCommand.begin(), ::tolower);
    
    /* -- Compose the library name = CLI extension name + SoarLib.
     *    Note that the LoadExternalLibrary command will take care of any platform-specific
     *    extensions. -- */
    std::string lCLIExtensionName = lFullCommand.substr(0, lFullCommand.find(' '));
    std::string lMessage = lFullCommand.substr(lCLIExtensionName.size() + 1, lFullCommand.size() - 1);
    lCLIExtensionName += "soarlib";
    
    std::map< std::string, Soar_Loaded_Library* >::iterator iter = (*m_loadedLibraries).find(lCLIExtensionName.c_str());
    if (iter == (*m_loadedLibraries).end())
    {
        // load library
        std::string result = m_Kernel->LoadExternalLibrary(lCLIExtensionName.c_str());
        
        // zero length is success
        if (result.size() != 0)
        {
            resultString = "Could not load library " + lCLIExtensionName + ": " + result;
            return resultString;
        }
    }
    /* -- A new library will register itself, so it will now have a
     *    libraryInfo entry even if it was not found above. -- */
    libraryInfo = (*m_loadedLibraries)[lCLIExtensionName.c_str()];
    
    if (((lMessage == "on") && libraryInfo->isOn) || ((lMessage == "off") && !libraryInfo->isOn))
    {
        resultString = "CLI extension " + lCLIExtensionName + "is already " + lMessage + ".  Ignoring command.";
        return resultString;
    }
    if (lMessage == "off")
    {
        resultString = "Turning off CLI modules is currently disabled. Will be fixed in future version.  Restart Soar to turn off for now.";
        return resultString;
    }
    void* success = libraryInfo->libMessageFunction(lMessage.c_str(), NULL);
    if (!success)
    {
        resultString = "Message " + lMessage + " to CLI library " + lCLIExtensionName + " returned unsuccessful.";
        return resultString;
    }
    else
    {
        // Note that may be other possible messages in the future, so these
        // arent' the only two cases.
        if (lMessage == "on")
        {
            libraryInfo->isOn = true;
            resultString = "\n" + lCLIExtensionName + " CLI module loaded and enabled.\n";
            m_Output_Manager->print_trace(resultString.c_str());
        }
        else if (lMessage == "off")
        {
            resultString = lCLIExtensionName + " CLI module deactivated.\n";
            m_Output_Manager->print_trace(resultString.c_str());
            libraryInfo->isOn = false;
        }
    }
    
    resultString.erase();
    return resultString;
}
Пример #21
0
void MHResidentProgram::CallProgram(bool fIsFork, const MHObjectRef &success, const MHSequence<MHParameter *> &args, MHEngine *engine)
{
    if (! m_fAvailable)
    {
        Preparation(engine);
    }

    //  if (m_fRunning) return; // Strictly speaking there should be only one instance of a program running at a time.
    Activation(engine);
    MHLOG(MHLogDetail, QString("Calling program %1").arg(m_Name.Printable()));

    try
    {
        // Run the code.
        if (m_Name.Equal("GCD"))   // GetCurrentDate - returns local time.
        {
            if (args.Size() == 2)
            {
                time_t epochSeconds = 0;
                short int timeZone = 0;
#if HAVE_GETTIMEOFDAY
                struct timeval   time;
                struct timezone  zone;

                if (gettimeofday(&time, &zone) == -1)
                {
                    MHLOG(MHLogDetail, QString("gettimeofday() failed"));
                }

                epochSeconds     = time.tv_sec;
                timeZone = zone.tz_minuteswest;
#elif HAVE_FTIME
                struct timeb timebuffer;
                if (ftime(&timebuffer) == -1)
                {
                    MHLOG(MHLogDetail, QString("ftime() failed"));
                }
                epochSeconds = timebuffer.time;
                timeZone = timebuffer.timezone;
#else
#error Configuration error? No ftime() or gettimeofday()?
#endif
                // Adjust the time to local.  TODO: Check this.
                epochSeconds -= timeZone * 60;
                // Time as seconds since midnight.
                int nTimeAsSecs = epochSeconds % (24 * 60 * 60);
                // Modified Julian date as number of days since 17th November 1858.
                // 1st Jan 1970 was date 40587.
                int nModJulianDate = 40587 + epochSeconds / (24 * 60 * 60);

                engine->FindObject(*(args.GetAt(0)->GetReference()))->SetVariableValue(nModJulianDate);
                engine->FindObject(*(args.GetAt(1)->GetReference()))->SetVariableValue(nTimeAsSecs);
                SetSuccessFlag(success, true, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("FDa"))   // FormatDate
        {
            if (args.Size() == 4)
            {
                // This is a bit like strftime but not quite.
                MHOctetString format;
                GetString(args.GetAt(0), format, engine);
                int date = GetInt(args.GetAt(1), engine); // As produced in GCD
                int time = GetInt(args.GetAt(2), engine);
                // Convert to a Unix date (secs since 1st Jan 1970) but adjusted for time zone.
                time_t timet = (date - 40587) * (24 * 60 * 60) + time;
                struct tm *timeStr = gmtime(&timet);
                MHOctetString result;

                for (int i = 0; i < format.Size(); i++)
                {
                    unsigned char ch = format.GetAt(i);
                    char buffer[5]; // Largest text is 4 chars for a year + null terminator

                    if (ch == '%')
                    {
                        i++;

                        if (i == format.Size())
                        {
                            break;
                        }

                        ch = format.GetAt(i);
                        buffer[0] = 0;

                        switch (ch)
                        {
                            case 'Y':
                                sprintf(buffer, "%04d", timeStr->tm_year + 1900);
                                break;
                            case 'y':
                                sprintf(buffer, "%02d", timeStr->tm_year % 100);
                                break;
                            case 'X':
                                sprintf(buffer, "%02d", timeStr->tm_mon + 1);
                                break;
                            case 'x':
                                sprintf(buffer, "%1d", timeStr->tm_mon + 1);
                                break;
                            case 'D':
                                sprintf(buffer, "%02d", timeStr->tm_mday);
                                break;
                            case 'd':
                                sprintf(buffer, "%1d", timeStr->tm_mday);
                                break;
                            case 'H':
                                sprintf(buffer, "%02d", timeStr->tm_hour);
                                break;
                            case 'h':
                                sprintf(buffer, "%1d", timeStr->tm_hour);
                                break;
                            case 'I':

                                if (timeStr->tm_hour == 12 || timeStr->tm_hour == 0)
                                {
                                    strcpy(buffer, "12");
                                }
                                else
                                {
                                    sprintf(buffer, "%02d", timeStr->tm_hour % 12);
                                }

                                break;
                            case 'i':

                                if (timeStr->tm_hour == 12 || timeStr->tm_hour == 0)
                                {
                                    strcpy(buffer, "12");
                                }
                                else
                                {
                                    sprintf(buffer, "%1d", timeStr->tm_hour % 12);
                                }

                                break;
                            case 'M':
                                sprintf(buffer, "%02d", timeStr->tm_min);
                                break;
                            case 'm':
                                sprintf(buffer, "%1d", timeStr->tm_min);
                                break;
                            case 'S':
                                sprintf(buffer, "%02d", timeStr->tm_sec);
                                break;
                            case 's':
                                sprintf(buffer, "%1d", timeStr->tm_sec);
                                break;
                                // TODO: These really should be localised.
                            case 'A':

                                if (timeStr->tm_hour < 12)
                                {
                                    strcpy(buffer, "AM");
                                }
                                else
                                {
                                    strcpy(buffer, "PM");
                                }

                                break;
                            case 'a':

                                if (timeStr->tm_hour < 12)
                                {
                                    strcpy(buffer, "am");
                                }
                                else
                                {
                                    strcpy(buffer, "pm");
                                }

                                break;
                            default:
                                buffer[0] = ch;
                                buffer[1] = 0;
                        }

                        result.Append(buffer);
                    }
                    else
                    {
                        result.Append(MHOctetString(&ch, 1));
                    }
                }

                MHParameter *pResString = args.GetAt(3);
                engine->FindObject(*(pResString->GetReference()))->SetVariableValue(result);
                SetSuccessFlag(success, true, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("GDW"))   // GetDayOfWeek - returns the day of week that the date occurred on.
        {
            if (args.Size() == 2)
            {
                int date = GetInt(args.GetAt(0), engine); // Date as produced in GCD
                // Convert to a Unix date (secs since 1st Jan 1970) but adjusted for time zone.
                time_t timet = (date - 40587) * (24 * 60 * 60);
                struct tm *timeStr = gmtime(&timet);
                // 0 => Sunday, 1 => Monday etc.
                engine->FindObject(*(args.GetAt(1)->GetReference()))->SetVariableValue(timeStr->tm_wday);
                SetSuccessFlag(success, true, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("Rnd"))   // Random
        {
            if (args.Size() == 2)
            {
                int nLimit = GetInt(args.GetAt(0), engine);
                MHParameter *pResInt = args.GetAt(1);
                int r = random() % (nLimit + 1);
                engine->FindObject(
                    *(pResInt->GetReference()))->SetVariableValue(r);
                SetSuccessFlag(success, true, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("CTC"))   // CastToContentRef
        {
            // Converts a string to a ContentRef.
            if (args.Size() == 2)
            {
                MHOctetString string;
                GetString(args.GetAt(0), string, engine);
                MHContentRef result;
                result.m_ContentRef.Copy(string);
                engine->FindObject(*(args.GetAt(1)->GetReference()))->SetVariableValue(result);
                SetSuccessFlag(success, true, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("CTO"))   // CastToObjectRef
        {
            // Converts a string and an integer to an ObjectRef.
            if (args.Size() == 3)
            {
                MHObjectRef result;
                GetString(args.GetAt(0), result.m_GroupId, engine);
                result.m_nObjectNo = GetInt(args.GetAt(1), engine);
                engine->FindObject(*(args.GetAt(2)->GetReference()))->SetVariableValue(result);
                SetSuccessFlag(success, true, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("GSL"))   // GetStringLength
        {
            if (args.Size() == 2)
            {
                // Find a substring within a string and return an index to the position.
                MHOctetString string;
                GetString(args.GetAt(0), string, engine);
                MHParameter *pResInt = args.GetAt(1);
                SetSuccessFlag(success, true, engine);
                engine->FindObject(*(pResInt->GetReference()))->SetVariableValue(string.Size());
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("GSS"))   // GetSubString
        {
            if (args.Size() == 4)   // Extract a sub-string from a string.
            {
                MHOctetString string;
                GetString(args.GetAt(0), string, engine);
                int nBeginExtract = GetInt(args.GetAt(1), engine);
                int nEndExtract = GetInt(args.GetAt(2), engine);

                if (nBeginExtract < 1)
                {
                    nBeginExtract = 1;
                }

                if (nBeginExtract > string.Size())
                {
                    nBeginExtract = string.Size();
                }

                if (nEndExtract < 1)
                {
                    nEndExtract = 1;
                }

                if (nEndExtract > string.Size())
                {
                    nEndExtract = string.Size();
                }

                MHParameter *pResString = args.GetAt(3);
                // Returns beginExtract to endExtract inclusive.
                engine->FindObject(*(pResString->GetReference()))->SetVariableValue(
                    MHOctetString(string, nBeginExtract - 1, nEndExtract - nBeginExtract + 1));
                SetSuccessFlag(success, true, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("SSS"))   // SearchSubString
        {
            if (args.Size() == 4)
            {
                // Find a substring within a string and return an index to the position.
                MHOctetString string, searchString;
                GetString(args.GetAt(0), string, engine);
                int nStart = GetInt(args.GetAt(1), engine);

                if (nStart < 1)
                {
                    nStart = 1;
                }

                GetString(args.GetAt(2), searchString, engine);
                // Strings are indexed from one.
                int nPos;

                for (nPos = nStart - 1; nPos <= string.Size() - searchString.Size(); nPos++)
                {
                    int i;

                    for (i = 0; i < searchString.Size(); i++)
                    {
                        if (searchString.GetAt(i) != string.GetAt(i + nPos))
                        {
                            break;
                        }
                    }

                    if (i == searchString.Size())
                    {
                        break;    // Found a match.
                    }
                }

                // Set the result.
                MHParameter *pResInt = args.GetAt(3);
                SetSuccessFlag(success, true, engine); // Set this first.

                if (nPos <= string.Size() - searchString.Size())   // Found
                {
                    // Set the index to the position of the string, counting from 1.
                    engine->FindObject(*(pResInt->GetReference()))->SetVariableValue(nPos + 1);
                }
                else   // Not found.  Set the result index to -1
                {
                    engine->FindObject(*(pResInt->GetReference()))->SetVariableValue(-1);
                }
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("SES"))   // SearchAndExtractSubString
        {
            if (args.Size() == 5)
            {
                // Find a substring within a string and return an index to the position
                // and the prefix to the substring.
                MHOctetString string, searchString;
                GetString(args.GetAt(0), string, engine);
                int nStart = GetInt(args.GetAt(1), engine);

                if (nStart < 1)
                {
                    nStart = 1;
                }

                GetString(args.GetAt(2), searchString, engine);
                // Strings are indexed from one.
                int nPos;

                for (nPos = nStart - 1; nPos <= string.Size() - searchString.Size(); nPos++)
                {
                    int i;

                    for (i = 0; i < searchString.Size(); i++)
                    {
                        if (searchString.GetAt(i) != string.GetAt(i + nPos))
                        {
                            break;    // Doesn't match
                        }
                    }

                    if (i == searchString.Size())
                    {
                        break;    // Found a match.
                    }
                }

                // Set the results.
                MHParameter *pResString = args.GetAt(3);
                MHParameter *pResInt = args.GetAt(4);
                SetSuccessFlag(success, true, engine); // Set this first.

                if (nPos <= string.Size() - searchString.Size())   // Found
                {
                    // Set the index to the position AFTER the string, counting from 1.
                    engine->FindObject(*(pResInt->GetReference()))->SetVariableValue(nPos + 1 + searchString.Size());
                    // Return the sequence from nStart-1 of length nPos-nStart+1
                    MHOctetString resultString(string, nStart - 1, nPos - nStart + 1);
                    engine->FindObject(*(pResString->GetReference()))->SetVariableValue(resultString);
                }
                else   // Not found.  Set the result string to empty and the result index to -1
                {
                    engine->FindObject(*(pResInt->GetReference()))->SetVariableValue(-1);
                    engine->FindObject(*(pResString->GetReference()))->SetVariableValue(MHOctetString(""));
                }
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("GSI"))   // SI_GetServiceIndex
        {
            // Returns an index indicating the service
            if (args.Size() == 2)
            {
                MHOctetString string;
                GetString(args.GetAt(0), string, engine);
                MHParameter *pResInt = args.GetAt(1);
                // The format of the service is dvb://netID.[transPortID].serviceID
                // where the IDs are in hex.
                // or rec://svc/lcn/N where N is the "logical channel number" i.e. the Freeview channel.
                QString str = QString::fromUtf8((const char *)string.Bytes(), string.Size());
                int nResult = engine->GetContext()->GetChannelIndex(str);
                engine->FindObject(*(pResInt->GetReference()))->SetVariableValue(nResult);
                SetSuccessFlag(success, nResult >= 0, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("TIn"))   // SI_TuneIndex - Fork not allowed
        {
            // Tunes to an index returned by GSI
            if (args.Size() == 1)
            {
                int nChannel = GetInt(args.GetAt(0), engine);
                bool res = nChannel >= 0 ? engine->GetContext()->TuneTo(
                               nChannel, engine->GetTuneInfo()) : false;
                SetSuccessFlag(success, res, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }
        else if (m_Name.Equal("TII"))   // SI_TuneIndexInfo
        {
            // Indicates whether to perform a subsequent TIn quietly or normally.
            if (args.Size() == 1)
            {
                int tuneinfo = GetInt(args.GetAt(0), engine);
                engine->SetTuneInfo(tuneinfo);
                SetSuccessFlag(success, true, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }
        else if (m_Name.Equal("BSI"))   // SI_GetBasicSI
        {
            // Returns basic SI information about the service indicated by an index
            // returned by GSI.
            // Returns networkID, origNetworkID, transportStreamID, serviceID
            if (args.Size() == 5)
            {
                int channelId = GetInt(args.GetAt(0), engine);
                int netId, origNetId, transportId, serviceId;
                // Look the information up in the database.
                bool res = engine->GetContext()->GetServiceInfo(channelId, netId, origNetId,
                                                                transportId, serviceId);

                if (res)
                {
                    engine->FindObject(*(args.GetAt(1)->GetReference()))->SetVariableValue(netId);
                    engine->FindObject(*(args.GetAt(2)->GetReference()))->SetVariableValue(origNetId);
                    engine->FindObject(*(args.GetAt(3)->GetReference()))->SetVariableValue(transportId);
                    engine->FindObject(*(args.GetAt(4)->GetReference()))->SetVariableValue(serviceId);
                }

                SetSuccessFlag(success, res, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }
        else if (m_Name.Equal("GBI"))   // GetBootInfo
        {
            // Gets the NB_info field.
            MHERROR("GetBootInfo ResidentProgram is not implemented");
        }
        else if (m_Name.Equal("CCR"))   // CheckContentRef
        {
            // Sees if an item with a particular content reference is available
            // in the carousel.  This looks like it should block until the file
            // is available.  The profile recommends that this should be forked
            // rather than called.
            if (args.Size() == 3)
            {
                MHUnion un;
                un.GetValueFrom(*(args.GetAt(0)), engine);
                un.CheckType(MHUnion::U_ContentRef);
                MHContentRef fileName;
                fileName.Copy(un.m_ContentRefVal);
                QString csPath = engine->GetPathName(fileName.m_ContentRef);
                bool result = false;
                QByteArray text;

                // Try to load the object.
                if (! csPath.isEmpty())
                {
                    result = engine->GetContext()->GetCarouselData(csPath, text);
                }

                // Set the result variable.
                MHParameter *pResFlag = args.GetAt(1);
                engine->FindObject(*(pResFlag->GetReference()))->SetVariableValue(result);
                MHParameter *pResCR = args.GetAt(2);
                // Copy the file name to the resulting content ref.
                engine->FindObject(*(pResCR->GetReference()))->SetVariableValue(fileName);
                SetSuccessFlag(success, true, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }
        else if (m_Name.Equal("CGR"))   // CheckGroupIDRef
        {
            // Sees if an application or scene with a particular group id
            // is available in the carousel.
            MHERROR("CheckGroupIDRef ResidentProgram is not implemented");
        }
        else if (m_Name.Equal("VTG"))   // VideoToGraphics
        {
            // Video to graphics transformation.
            MHERROR("VideoToGraphics ResidentProgram is not implemented");
        }
        else if (m_Name.Equal("SWA"))   // SetWidescreenAlignment
        {
            // Sets either LetterBox or Centre-cut-out mode.
            // Seems to be concerned with aligning a 4:3 scene with an underlying 16:9 video
            MHERROR("SetWidescreenAlignment ResidentProgram is not implemented");
        }
        else if (m_Name.Equal("GDA"))   // GetDisplayAspectRatio
        {
            // Returns the aspcet ratio.  4:3 => 1, 16:9 => 2
            MHERROR("GetDisplayAspectRatio ResidentProgram is not implemented");
        }
        else if (m_Name.Equal("CIS"))   // CI_SendMessage
        {
            // Sends a message to a DVB CI application
            MHERROR("CI_SendMessage ResidentProgram is not implemented");
        }
        else if (m_Name.Equal("SSM"))   // SetSubtitleMode
        {
            // Enable or disable subtitles in addition to MHEG.
            if (args.Size() == 1) {
                bool status = GetBool(args.GetAt(0), engine);
                MHLOG(MHLogNotifications, QString("NOTE SetSubtitleMode %1")
                    .arg(status ? "enabled" : "disabled"));
                // TODO Notify player
                SetSuccessFlag(success, true, engine);
            }
            else SetSuccessFlag(success, false, engine);
        }

        else if (m_Name.Equal("WAI"))   // WhoAmI
        {
            // Return a concatenation of the strings we respond to in
            // GetEngineSupport(UKEngineProfile(X))
            if (args.Size() == 1)
            {
                MHOctetString result;
                result.Copy(engine->MHEGEngineProviderIdString);
                result.Append(" ");
                result.Append(engine->GetContext()->GetReceiverId());
                result.Append(" ");
                result.Append(engine->GetContext()->GetDSMCCId());
                engine->FindObject(*(args.GetAt(0)->GetReference()))->SetVariableValue(result);
                SetSuccessFlag(success, true, engine);
            }
            else
            {
                SetSuccessFlag(success, false, engine);
            }
        }

        else if (m_Name.Equal("DBG"))   // Debug - optional
        {
            QString message = "DEBUG: ";

            for (int i = 0; i < args.Size(); i++)
            {
                MHUnion un;
                un.GetValueFrom(*(args.GetAt(i)), engine);

                switch (un.m_Type)
                {
                    case MHUnion::U_Int:
                        message.append(QString("%1").arg(un.m_nIntVal));
                        break;
                    case MHParameter::P_Bool:
                        message.append(un.m_fBoolVal ? "True" : "False");
                        break;
                    case MHParameter::P_String:
                        message.append(QString::fromUtf8((const char *)un.m_StrVal.Bytes(), un.m_StrVal.Size()));
                        break;
                    case MHParameter::P_ObjRef:
                        message.append(un.m_ObjRefVal.Printable());
                        break;
                    case MHParameter::P_ContentRef:
                        message.append(un.m_ContentRefVal.Printable());
                        break;
                    case MHParameter::P_Null:
                        break;
                }
            }

            MHLOG(MHLogNotifications, message);
        }

        else if (m_Name.Equal("SBI"))   // SetBroadcastInterrupt
        {
            // Required for NativeApplicationExtension
            // En/dis/able program interruptions e.g. green button
            if (args.Size() == 1) {
                bool status = GetBool(args.GetAt(0), engine);
                MHLOG(MHLogNotifications, QString("NOTE SetBroadcastInterrupt %1")
                    .arg(status ? "enabled" : "disabled"));
                // Nothing todo at present
                SetSuccessFlag(success, true, engine);
            }
            else SetSuccessFlag(success, false, engine);
        }

        // InteractionChannelExtension
        else if (m_Name.Equal("GIS")) { // GetICStatus
            if (args.Size() == 1)
            {
                int ICstatus = engine->GetContext()->GetICStatus();
                MHLOG(MHLogNotifications, "NOTE InteractionChannel " + QString(
                    ICstatus == 0 ? "active" : ICstatus == 1 ? "inactive" :
                    ICstatus == 2 ? "disabled" : "undefined"));
                engine->FindObject(*(args.GetAt(0)->GetReference()))->SetVariableValue(ICstatus);
                SetSuccessFlag(success, true, engine);
            }
            else SetSuccessFlag(success, false, engine);
        }
        else if (m_Name.Equal("RDa")) { // ReturnData
            if (args.Size() >= 3)
            {
                MHOctetString string;
                GetString(args.GetAt(0), string, engine);
                QString url = QString::fromUtf8((const char *)string.Bytes(), string.Size());

                // Variable name/value pairs
                QStringList params;
                int i = 1;
                for (; i + 2 < args.Size(); i += 2)
                {
                    GetString(args.GetAt(i), string, engine);
                    QString name = QString::fromUtf8((const char *)string.Bytes(), string.Size());
                    QString val;
                    MHUnion un;
                    un.GetValueFrom(*(args.GetAt(i+1)), engine);
                    switch (un.m_Type) {
                    case MHUnion::U_Int:
                        val = QString::number(un.m_nIntVal);
                        break;
                    case MHParameter::P_Bool:
                        val = un.m_fBoolVal ? "true" : "false";
                        break;
                    case MHParameter::P_String:
                        val = QString::fromUtf8((const char*)un.m_StrVal.Bytes(), un.m_StrVal.Size());
                        break;
                    case MHParameter::P_ObjRef:
                        val = un.m_ObjRefVal.Printable();
                        break;
                    case MHParameter::P_ContentRef:
                        val = un.m_ContentRefVal.Printable();
                        break;
                    case MHParameter::P_Null:
                        val = "<NULL>";
                        break;
                    default:
                        val = QString("<type %1>").arg(un.m_Type);
                        break;
                    }
                    params += name + "=" + val;
                }
                // TODO
                MHLOG(MHLogNotifications, "NOTE ReturnData '" + url + "' { " + params.join(" ") + " }");
                // HTTP response code, 0= none
                engine->FindObject(*(args.GetAt(i)->GetReference()))->SetVariableValue(0);
                // HTTP response data
                string = "";
                engine->FindObject(*(args.GetAt(i+1)->GetReference()))->SetVariableValue(string);
                SetSuccessFlag(success, false, engine);
            }
            else SetSuccessFlag(success, false, engine);
        }
        else if (m_Name.Equal("SHF")) { // SetHybridFileSystem
            if (args.Size() == 2)
            {
                MHOctetString string;
                GetString(args.GetAt(0), string, engine);
                QString str = QString::fromUtf8((const char *)string.Bytes(), string.Size());
                GetString(args.GetAt(1), string, engine);
                QString str2 = QString::fromUtf8((const char *)string.Bytes(), string.Size());
                // TODO
                MHLOG(MHLogNotifications, QString("NOTE SetHybridFileSystem %1=%2")
                    .arg(str).arg(str2));
                SetSuccessFlag(success, false, engine);
            }
            else SetSuccessFlag(success, false, engine);
        }

        else
        {
            MHERROR(QString("Unknown ResidentProgram %1").arg(m_Name.Printable()));
        }
    }
    catch (char const *)
    {
        // If something went wrong set the succeeded flag to false
        SetSuccessFlag(success, false, engine);
        // And continue on.  In particular we need to deactivate.
    }

    Deactivation(engine);

    // At the moment we always treat Fork as Call.  If we do get a Fork we should signal that we're done.
    if (fIsFork)
    {
        engine->EventTriggered(this, EventAsyncStopped);
    }
}
Пример #22
0
		Ref<Result> Code128Reader::decodeRow(int rowNumber, Ref<BitArray> row) {
		  int* startPatternInfo = NULL;
		  try {
        startPatternInfo = findStartPattern(row);
        int startCode = startPatternInfo[2];
        int codeSet;
        switch (startCode) {
          case CODE_START_A:
            codeSet = CODE_CODE_A;
            break;
          case CODE_START_B:
            codeSet = CODE_CODE_B;
            break;
          case CODE_START_C:
            codeSet = CODE_CODE_C;
            break;
          default:
            throw ReaderException("");
        }

        bool done = false;
        bool isNextShifted = false;

        std::string tmpResultString;
        std::stringstream tmpResultSStr; // used if its Code 128C

        int lastStart = startPatternInfo[0];
        int nextStart = startPatternInfo[1];
        int counters[countersLength] = {0,0,0,0,0,0};

        int lastCode = 0;
        int code = 0;
        int checksumTotal = startCode;
        int multiplier = 0;
        bool lastCharacterWasPrintable = true;

        while (!done) {
          bool unshift = isNextShifted;
          isNextShifted = false;

          // Save off last code
          lastCode = code;

          // Decode another code from image
          try {
            code = decodeCode(row, counters, sizeof(counters)/sizeof(int), nextStart);
          } catch (ReaderException const& re) {
            throw re;
          }

          // Remember whether the last code was printable or not (excluding CODE_STOP)
          if (code != CODE_STOP) {
            lastCharacterWasPrintable = true;
          }

          // Add to checksum computation (if not CODE_STOP of course)
          if (code != CODE_STOP) {
            multiplier++;
            checksumTotal += multiplier * code;
          }

          // Advance to where the next code will to start
          lastStart = nextStart;
          int _countersLength = sizeof(counters) / sizeof(int);
          for (int i = 0; i < _countersLength; i++) {
            nextStart += counters[i];
          }

          // Take care of illegal start codes
          switch (code) {
            case CODE_START_A:
            case CODE_START_B:
            case CODE_START_C:
              throw ReaderException("");
          }

          switch (codeSet) {

            case CODE_CODE_A:
              if (code < 64) {
                tmpResultString.append(1, (char) (' ' + code));
              } else if (code < 96) {
                tmpResultString.append(1, (char) (code - 64));
              } else {
                // Don't let CODE_STOP, which always appears, affect whether whether we think the
                // last code was printable or not.
                if (code != CODE_STOP) {
                  lastCharacterWasPrintable = false;
                }
                switch (code) {
                  case CODE_FNC_1:
                  case CODE_FNC_2:
                  case CODE_FNC_3:
                  case CODE_FNC_4_A:
                    // do nothing?
                    break;
                  case CODE_SHIFT:
                    isNextShifted = true;
                    codeSet = CODE_CODE_B;
                    break;
                  case CODE_CODE_B:
                    codeSet = CODE_CODE_B;
                    break;
                  case CODE_CODE_C:
                    codeSet = CODE_CODE_C;
                    break;
                  case CODE_STOP:
                    done = true;
                    break;
                }
              }
              break;
            case CODE_CODE_B:
              if (code < 96) {
                tmpResultString.append(1, (char) (' ' + code));
              } else {
                if (code != CODE_STOP) {
                  lastCharacterWasPrintable = false;
                }
                switch (code) {
                  case CODE_FNC_1:
                  case CODE_FNC_2:
                  case CODE_FNC_3:
                  case CODE_FNC_4_B:
                    // do nothing?
                    break;
                  case CODE_SHIFT:
                    isNextShifted = true;
                    codeSet = CODE_CODE_C;
                    break;
                  case CODE_CODE_A:
                    codeSet = CODE_CODE_A;
                    break;
                  case CODE_CODE_C:
                    codeSet = CODE_CODE_C;
                    break;
                  case CODE_STOP:
                    done = true;
                    break;
                }
              }
              break;
            case CODE_CODE_C:
              tmpResultSStr.str(std::string());
              // the code read in this case is the number encoded directly
              if (code < 100) {
                if (code < 10) {
 					        tmpResultSStr << '0';
 				        }
                tmpResultSStr << code;
 				        tmpResultString.append(tmpResultSStr.str());
              } else {
                if (code != CODE_STOP) {
                  lastCharacterWasPrintable = false;
                }
                switch (code) {
                  case CODE_FNC_1:
                    // do nothing?
                    break;
                  case CODE_CODE_A:
                    codeSet = CODE_CODE_A;
                    break;
                  case CODE_CODE_B:
                    codeSet = CODE_CODE_B;
                    break;
                  case CODE_STOP:
                    done = true;
                    break;
                }
              }
              break;
          }

          // Unshift back to another code set if we were shifted
          if (unshift) {
            switch (codeSet) {
              case CODE_CODE_A:
                codeSet = CODE_CODE_C;
                break;
              case CODE_CODE_B:
                codeSet = CODE_CODE_A;
                break;
              case CODE_CODE_C:
                codeSet = CODE_CODE_B;
                break;
            }
          }

        }

        // Check for ample whitespace following pattern, but, to do this we first need to remember that
        // we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left
        // to read off. Would be slightly better to properly read. Here we just skip it:
        int width = row->getSize();
        while (nextStart < width && row->get(nextStart)) {
          nextStart++;
        }
        long minResult = 0;
#ifndef NOFMAXL
        minResult = fminl(width, nextStart + (nextStart - lastStart)/ 2);
#else
        minResult = fmin(width, nextStart + (nextStart - lastStart)/ 2);
#endif
        if (!row->isRange(nextStart, minResult, false)) {
          throw ReaderException("");
        }

        // Pull out from sum the value of the penultimate check code
        checksumTotal -= multiplier * lastCode;
        // lastCode is the checksum then:
        if (checksumTotal % 103 != lastCode) {
          throw ReaderException("");
        }

        // Need to pull out the check digits from string
        int resultLength = tmpResultString.length();
        // Only bother if the result had at least one character, and if the checksum digit happened to
        // be a printable character. If it was just interpreted as a control code, nothing to remove.
        if (resultLength > 0 && lastCharacterWasPrintable) {
          if (codeSet == CODE_CODE_C) {
            tmpResultString.erase(resultLength - 2, resultLength);
          } else {
            tmpResultString.erase(resultLength - 1, resultLength);
          }
        }

        Ref<String> resultString(new String(tmpResultString));
        if (tmpResultString.length() == 0) {
          // Almost surely a false positive
          throw ReaderException("");
        }

        float left = (float) (startPatternInfo[1] + startPatternInfo[0]) / 2.0f;
        float right = (float) (nextStart + lastStart) / 2.0f;

        std::vector< Ref<ResultPoint> > resultPoints(2);
        Ref<OneDResultPoint> resultPoint1(new OneDResultPoint(left, (float) rowNumber));
        Ref<OneDResultPoint> resultPoint2(new OneDResultPoint(right, (float) rowNumber));
        resultPoints[0] = resultPoint1;
        resultPoints[1] = resultPoint2;

        delete [] startPatternInfo;
        ArrayRef<unsigned char> resultBytes(1);
        return Ref<Result>(new Result(resultString, resultBytes, resultPoints,
            BarcodeFormat_CODE_128));
			} catch (ReaderException const& re) {
			  delete [] startPatternInfo;
			  return Ref<Result>();
			}
		}