Exemple #1
0
void DeleteRRN(LPEDIT lp)
{
	int nFrag, nOffset, nPos ;

	ReformatFragments(lp) ;

	/* nOffset points to the beginning of the current line to be read */
	nPos = nOffset = 0 ;
	while (nOffset < lp->strlen)
	{
		if (lp->npdata[nOffset] == '\r' &&
		    lp->npdata[nOffset + 1] == '\r' &&
		    lp->npdata[nOffset + 2] == '\n')
		{
			/* Skip the soft line break; update frag table */
			nOffset += 3 ;
			lp->strlen -= 3 ;
			nFrag = FindLine(lp, nOffset) ;
			if (lp->nCurFragment >= nFrag)
				lp->lpidx -= 3 ;
			if (FindLine(lp, lp->anchor) >= nFrag)
				lp->anchor -= 3 ;
			while (nFrag < lp->nFragments)
				lp->lpFragments[nFrag++].nOffset -= 3 ;
		}
		else
			lp->npdata[nPos++] = lp->npdata[nOffset++] ;
	}
	lp->state &= ~ES_FORMATLINE ;
}
Exemple #2
0
void Placebo()
{
	int i;
	
  ir_transmit_off();
  fAssertEnable = YesNo("Debug");
  kill_process(ipMotor);
  if (YesNo("Start Light"))
    start_machine(START_LIGHT_PORT);
  ipMotor = start_process(MotorDriver());
  CompeteInit(0);
  Orient();

	FindLine();

  while (1)
  	{
  	Hard(90);
  	Move(-100, -100);
  	Move(80, 80);
  	Hard(90);
  	Move(-200, -200);
  	msleep(1000L);
  	Chop(3);
  	Move(50, 50);
  	Wheelie();
  	}
}
Exemple #3
0
/*******************************************************************************
 *  ReadString
 *
 *  Returns FALSE on I/O error or memory allocation failure; sets *p_str to NULL
 *  if line cannot be found or can't be parsed.
 *
 */
static BOOL ReadString(FILE *file, CHAR buffer[], INT bufsize, LPCSTR key,
    	LPSTR *p_str)
{
    CHAR    *cp;

    if (FindLine(file, buffer, bufsize, key) == FALSE)
    	return FALSE;

    if (buffer[0] == '\0')
    {
    	*p_str = NULL;
	return TRUE;
    }

    cp = buffer + strlen(key);	    	    	    /* first char after key */
    if (*cp == '\0')
    {
    	*p_str = NULL;
	return TRUE;
    }

    while (isspace(*cp))    	    	/* find first non-whitespace char */
    	++cp;

    *p_str = HeapAlloc(PSDRV_Heap, 0, strlen(cp) + 1);
    if (*p_str == NULL)
    	return FALSE;

    strcpy(*p_str, cp);
    return TRUE;
}
Exemple #4
0
/*******************************************************************************
 *  ReadFloat
 *
 *  Finds and parses a line of the form '<key> <value>', where value is a
 *  number.  Sets *p_found to FALSE if a corresponding line cannot be found, or
 *  it cannot be parsed; also sets *p_ret to 0.0, so calling functions can just
 *  skip the check of *p_found if the item is not required.
 *
 */
static BOOL ReadFloat(FILE *file, CHAR buffer[], INT bufsize, LPCSTR key,
    	FLOAT *p_ret, BOOL *p_found)
{
    CHAR    *cp, *end_ptr;
    double  d;

    if (FindLine(file, buffer, bufsize, key) == FALSE)
    	return FALSE;

    if (buffer[0] == '\0')  	    /* line not found */
    {
    	*p_found = FALSE;
	*p_ret = 0.0;
	return TRUE;
    }

    cp = buffer + strlen(key);	    	    	    /* first char after key */
    errno = 0;
    d = strtod(cp, &end_ptr);

    if (end_ptr == cp || errno != 0 || DoubleToFloat(p_ret, d) == FALSE)
    {
    	WARN("Error parsing line '%s'\n", buffer);
    	*p_found = FALSE;
	*p_ret = 0.0;
	return TRUE;
    }

    *p_found = TRUE;
    return TRUE;
}
Exemple #5
0
void InsertRRN(LPEDIT lp)
{
	int nRRN, nFrag, nOffset, nPos ;

	if (AutoHScroll(lp))
		return ;	/* Don't word wrap if we auto-h-scroll */

	ReformatFragments(lp) ;

	for (nRRN = nFrag = 0 ; nFrag < lp->nFragments ; nFrag++)
	{
		if (!lp->lpFragments[nFrag].nLength)
			continue ;
		if (lp->npdata[lp->lpFragments[nFrag].nOffset +
			   lp->lpFragments[nFrag].nLength] != '\n' &&
		   (lp->npdata[lp->lpFragments[nFrag].nOffset +
			   lp->lpFragments[nFrag].nLength] != '\r' ||
		    lp->npdata[lp->lpFragments[nFrag].nOffset +
		           lp->lpFragments[nFrag].nLength + 1] != '\n'))
			nRRN++ ;
	}

	nPos = lp->strlen - 1 ;
	lp->strlen += 3 * nRRN ;

	if (lp->strlen > lp->memlen)
	{
		while (lp->strlen > lp->memlen)
			lp->memlen += 0x20 ;
		EditMemoryAPI(lp->hWnd, EMA_UNLOCK, lp->hData, 0L) ;
		lp->hData = (HANDLE)EditMemoryAPI(lp->hWnd, EMA_REALLOC,
						lp->hData, lp->memlen) ;
		lp->npdata = (LPSTR)EditMemoryAPI(lp->hWnd, EMA_LOCK, lp->hData, 0L) ;
	}

	/* nOffset will hold the character after this line in the buffer */
	nOffset = lp->strlen - 1 ;
	for (nFrag = lp->nFragments - 1 ; nFrag >= 0 ; nFrag--)
	{
		if (nOffset <= 0)
			continue ; 
		if (lp->npdata[nPos] != '\n')
		{
			lp->npdata[nOffset--] = '\n' ;
			lp->npdata[nOffset--] = '\r' ;
			lp->npdata[nOffset--] = '\r' ;
			if (lp->nCurFragment > nFrag)
				lp->lpidx += 3 ;
			if (FindLine(lp, lp->anchor) > nFrag)
				lp->anchor += 3 ;
		}
		while(nPos >= lp->lpFragments[nFrag].nOffset)
			lp->npdata[nOffset--] = lp->npdata[nPos--] ; 
		lp->lpFragments[nFrag].nOffset = nOffset + 1 ;
	}
	lp->state |= ES_FORMATLINE ;
}
Exemple #6
0
/*******************************************************************************
 *  ReadBBox
 *
 *  Similar to ReadFloat above.
 *
 */
static BOOL ReadBBox(FILE *file, CHAR buffer[], INT bufsize, AFM *afm,
    	BOOL *p_found)
{
    CHAR    *cp, *end_ptr;
    double  d;

    if (FindLine(file, buffer, bufsize, "FontBBox") == FALSE)
    	return FALSE;

    if (buffer[0] == '\0')
    {
    	*p_found = FALSE;
	return TRUE;
    }

    errno = 0;

    cp = buffer + sizeof("FontBBox");
    d = strtod(cp, &end_ptr);
    if (end_ptr == cp || errno != 0 ||
    	    DoubleToFloat(&(afm->FontBBox.llx), d) == FALSE)
    	goto parse_error;

    cp = end_ptr;
    d = strtod(cp, &end_ptr);
    if (end_ptr == cp || errno != 0 ||
    	    DoubleToFloat(&(afm->FontBBox.lly), d) == FALSE)
    	goto parse_error;

    cp = end_ptr;
    d = strtod(cp, &end_ptr);
    if (end_ptr == cp || errno != 0
    	    || DoubleToFloat(&(afm->FontBBox.urx), d) == FALSE)
    	goto parse_error;

    cp = end_ptr;
    d = strtod(cp, &end_ptr);
    if (end_ptr == cp || errno != 0
    	    || DoubleToFloat(&(afm->FontBBox.ury), d) == FALSE)
    	goto parse_error;

    *p_found = TRUE;
    return TRUE;

    parse_error:
    	WARN("Error parsing line '%s'\n", buffer);
	*p_found = FALSE;
	return TRUE;
}
Exemple #7
0
void scContUnit::PasteText( const scContUnit*	srcPara,
							long&				offset )
{
	try {
		if ( offset == 0 ) {
			TypeSpec ts = srcPara->GetDefaultSpec();
			if ( ts.ptr() )
				SetDefaultSpec( ts );
		}
			
			// paste the specs in
		fSpecRun.InsertRun( offset, srcPara->GetContentSize(), srcPara->GetSpecRun() );

			// paste the text in
		fCharArray.Paste( ((scContUnit*)srcPara)->GetCharArray(), offset );
		Mark( scREBREAK );

#ifdef _RUBI_SUPPORT
			// paste the rubis in
		if ( fRubiArray || srcPara->GetRubiArray() ) {
	
			if ( fRubiArray && !srcPara->GetRubiArray() )
				fRubiArray->BumpRubiData( offset, srcPara->GetContentSize() );
			else if ( !fRubiArray && srcPara->GetRubiArray() ) {
				AllocRubiArray( *srcPara->GetRubiArray() );
				fRubiArray->BumpRubiData( 0, offset );
			}
			else
				fRubiArray->Paste( *srcPara->GetRubiArray(), offset, srcPara->GetContentSize() );
		}
#endif

		scTextline* txl = FindLine( offset );
		if ( txl )
			txl->Mark( scREPAINT ); /* force repaint */

		long startOffset = offset;
		offset += srcPara->GetContentSize();

		fSpecRun.SetContentSize( GetContentSize() );
		
		fCharArray.RepairText( fSpecRun, startOffset, offset );
	} 
	catch( ... ) {
		SCDebugBreak(); // remove stuff from the paragraph
		throw;
	} 
}
Exemple #8
0
void MainMenu()
{
  func = -1;

  while (!stop_button())
    {
    funcLast = func;
    func = ScaleKnob(1, 27);

    if (FDispMenu(1, "Calibrate Lookdown")) CalibrateLookdown();
    if (FDispMenu(2, "Compete!")) Compete();
    if (FDispMenu(3, "Placebo")) Placebo();
    if (FDispMenu(4, "Dance!")) Chop(10);
    if (FDispMenu(5, "Calibrate Soft")) CalibrateSoft();
    if (FDispMenu(6, "Calibrate Hard")) CalibrateHard();
    if (FDispMenu(7, "Speed Calibration")) CalibrateSpeed();

    if (FDispMenu(8, "Lookdown Test")) LookdownTest();
    if (FDispMenu(9, "Orientation")) Orient();
    if (FDispMenu(10, "Straight 1000")) Move(1000,1000);
    if (FDispMenu(11, "Left 90 Soft")) Soft(90, 1);
    if (FDispMenu(12, "Left 90 Hard")) Hard(90);

    if (FDispMenu(13, "Find Line")) FindLine();
    if (FDispMenu(14, "Line Follow")) LineFollower();

    if (FDispMenu(15, "Record"))
      RecordMove(WSetting("Record move", 0, 9));
    if (FDispMenu(16, "Playback"))
      PlayMove(WSetting("Play move", 0, 9));

    /* hbtest.c functions */

    if (FDispMenu(17, "Servo Test")) ServoTest();
    if (FDispMenu(18, "Calibrate Gate")) CalibrateGate();
    if (FDispMenu(19, "Soft Turn Test")) SoftTest();
    if (FDispMenu(20, "Hard Turn Test")) HardTest();
    if (FDispMenu(21, "Spin Test!")) Spinner();
    if (FDispMenu(22, "Shake Test!")) Shaker();
    if (FDispMenu(23, "Bump Test")) BumpTest();

    if (FDispMenu(24, "Test Motors")) testmotors();
    if (FDispMenu(25, "Test Digitals")) testdigitals();
    if (FDispMenu(26, "Test Analogs")) testanalogs();
    if (FDispMenu(27, "Assert Enable")) AssertEnable();
    }
}
Exemple #9
0
bool TextDocument::CursorCreate(GCursor *c, int X, int Y)
{
	bool Status = FALSE;
	if (c)
	{
		char *StartOfLine = FindLine(Y);

		c->Parent = this;
		c->y = Y;
		c->Length = StrLen(StartOfLine);
		c->Offset = (StartOfLine) ? ((long) StartOfLine - (long) Data) : 0;
		c->x = min(X, c->Length);

		Status = TRUE;
	}
	return Status;
}
gcc_pure
static int
FindCrash(const char *p)
{
  /* see if there was a crash; this check is very simple, but I hope
     it's good enough to avoid false positives */

  const char *q = strstr(p, ">>> org.xcsoar");
  if (q == nullptr || strstr(q, "fault addr") == nullptr)
    return 0;

  const char *r = strstr(FindLine(p, q), "pid:");
  if (r == nullptr)
    return 0;

  return atoi(r + 4);
}
Exemple #11
0
bool HttpHeader::ParseHeaderItem(const char* pBuffer, int nDataLen, int& nHeaderLen)
{
    int nConsoleLen = 0;
    int nColonPos = 0;
    int nRNPos = 0;
    
    const char* pPos = pBuffer;
    while (true)
    {
        if (!FindLine(pPos, nDataLen, nColonPos, nRNPos, nConsoleLen))
        {
            return false;
        }
        if (nRNPos == 0) //\r\n\r\n meet
        {
            nHeaderLen += nConsoleLen;
            break;
        }
        
        if (nColonPos == -1) //none : found
        {
            return false;
        }
        
        if (nRNPos <= (nColonPos + 1)) //empty value
        {
            return false;
        }
        
        const std::string strName(pPos, nColonPos);
        const std::string strValue(pPos + nColonPos + 1, nRNPos - nColonPos - 1);
        
        HttpHeaderItem nItem;
        nItem.m_strName = TrimString(strName, ' ');
        nItem.m_strValue = TrimString(strValue, ' ');
        m_nItemArray.push_back(nItem);
                
        nHeaderLen += nConsoleLen;
        pPos += nConsoleLen;
        nDataLen -= nConsoleLen;
    }
    
    return true;
}
Exemple #12
0
void Compete()
{
  int i;

  ir_transmit_off();
  fAssertEnable = YesNo("Debug");
  kill_process(ipMotor);
  if (YesNo("Start Light"))
    start_machine(START_LIGHT_PORT);
  ipMotor = start_process(MotorDriver());
  CompeteInit(0);
  Orient();
  while (1)
    {
    FindLine();
    CollectBalls();
    /* BUG: We don't really know if we have a ball here */
    DumpBall();
    ReturnForMore();
    }
  printf("C1");
}
Exemple #13
0
bool FloorFilter::GetFloorLine(
    const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &input_cloud,
    const std::vector<int> &indices,
    Eigen::ParametrizedLine<float, 3> *line, std::vector<int> *inlier_indices) {
  Eigen::ParametrizedLine<float, 3> sensor_floor_intersection_line;
  if (!FindSensorPlaneIntersection(input_cloud->header.stamp, &sensor_floor_intersection_line)) {
    // It is impossible to find a correct floor line because the
    // sensor plane is either parallel to the floor line or intersects
    // with it behind the robot.
    return false;
  }
  Eigen::Vector3f y_axis(0, 1, 0);
  if (!FindLine(input_cloud, indices, line, inlier_indices)) {
    ROS_DEBUG("RANSAC couldn't find a floor line.");
    *line = sensor_floor_intersection_line;
  }
  else if (!geometry::VectorsParallel(line->direction(), y_axis, max_floor_x_rotation_)) {
    ROS_DEBUG("The angle between the found floor line and the x-y-plane above threshold."
              "Rejecting the line and using the intersection between x-y-plane and sensor plane.");
    inlier_indices->clear();
    *line = sensor_floor_intersection_line;
  }
  return true;
}
Exemple #14
0
void WebEditBox::DrawThisOnly (DISPLAY_INT x, DISPLAY_INT y, WebGraphics *gc)
{
	WebChar c;
	long line;

	WebRect box;
	GetFrameRect(&box);
	box.Shift(x,y);

//	gc->StartBuffer();                      // begin buffering graphics commands
	gc->Rectangle(&box, GetBgColor(gc), GetBgColor(gc), 1);	// draw background
	DrawFrame(&box, gc);

	// save the current graphics context clip rectangle and set clipping to the
	//  text display region of the widget
	GetTextRect(&box);
	box.Shift(x,y);
	WebRect clipSave;
	gc->GetClip(&clipSave);
	if (clipSave.Overlaps(&box))
	{
		WebRect clip(box);
		clip.And(&clipSave);
		gc->SetClip(&clip);

		miXOffset = (mpHScroll)? mpHScroll->GetPosition() : 0;
		miYOffset = (mpVScroll)? mpVScroll->GetPosition() : 0;

		// render our text
		WebFont font = mFont.GetFont();
		if (mpText && font)
		{
			// this loop draws up to the last line
			for (line=0; line<(miNumLines-1); line++)
			{
				c = mpText[GetLineOffset(line+1)];
				mpText[GetLineOffset(line+1)] = 0;
				DrawText(gc, box.left - miXOffset, box.top - miYOffset + (line * WEB_FONT_HEIGHT(font)),
				         mpText + GetLineOffset(line), GetTextColor(gc), 0, 0, font);
				mpText[GetLineOffset(line+1)] = c;
			}

			// now draw the last line of text.
			DrawText(gc, box.left - miXOffset, box.top - miYOffset + (line*WEB_FONT_HEIGHT(font)),
			         mpText + GetLineOffset(line), GetTextColor(gc), 0, 0, font);

			// if we have the focus, draw the cursor
			if ((mFlags & DISPLAY_FLAG_FOCUS) && !(mFlags & DISPLAY_FLAG_DISABLED))
			{
				// now render the selected portion in reverse video (if we have one)
				if (mEditFlags & EDIT_FLAG_HAS_SELECTION)
				{
					long begin = EBSMIN(miCursorPos, miSelectBegin);
					long end = EBSMAX(miCursorPos, miSelectBegin);
					long beginLine = FindLine(begin), endLine = FindLine(end);
					DISPLAY_INT textLeft;
					long currentBegin, currentEnd;

					for (line=beginLine; line<=endLine; line++)
					{
						currentBegin = EBSMAX(begin, GetLineOffset(line));
						if (line == endLine)
						{
							currentEnd = end;
						}
						else
						{
							currentEnd = EBSMIN(end, GetLineOffset(line+1));
						}
						textLeft = gc->TextWidthLen(mpText + GetLineOffset(line), font, EBSMAX(0, begin - GetLineOffset(line)));

						c = mpText[currentEnd];
						mpText[currentEnd] = 0;
						DrawText(gc, box.left - miXOffset + textLeft,
						             box.top - miYOffset + (line*WEB_FONT_HEIGHT(font)),
						             mpText + currentBegin, GetBgColor(gc), GetSelectColor(gc), 1, font);
						mpText[currentEnd] = c;
					}
				}

				DISPLAY_INT cursorX = box.left - miXOffset +
					gc->TextWidthLen(mpText + GetLineOffset(miCurrentLine), font, miCursorPos - GetLineOffset(miCurrentLine)) ;
				box.Set(cursorX, box.top - miYOffset + WEB_FONT_HEIGHT(font)*miCurrentLine,
				        cursorX, box.top - miYOffset + WEB_FONT_HEIGHT(font)*(miCurrentLine+1));
				gc->Rectangle(&box, GetSelectColor(gc), GetSelectColor(gc), 1);
			}

		}

		gc->SetClip(&clipSave);	 // restore the clip rectangle
	} // if clip overlaps

/*	if (mpVScroll && mpHScroll)
	{
		GetCornerRect(&box);
		box.Shift(x,y);
		gc->Rectangle(&box, LIGHTGRAY, LIGHTGRAY, 1);
	}*/

//	gc->EndBuffer();	     // send all buffered commands to the display

}
Exemple #15
0
void HttpHeader::Parse(const char* pBuffer, int nDataLen, int& nHeaderLen)
{
    nHeaderLen = 0;
    
    bool bMayResp = strncasecmp(pBuffer, "HTTP", 4) == 0;
    bool bMayReq = (nDataLen > 3 && (strncasecmp(pBuffer, "GET", 3) == 0 ||
                    strncasecmp(pBuffer, "PUT", 3) == 0)) ||
                   (nDataLen > 4 && (strncasecmp(pBuffer, "HEAD", 4) == 0 ||
                    strncasecmp(pBuffer, "POST", 4) == 0)) ||
                   (nDataLen > 5 && strncasecmp(pBuffer, "TRACE", 5) == 0) ||
                   (nDataLen > 6 && strncasecmp(pBuffer, "DELETE", 6) == 0) ||
                   (nDataLen > 7 && (strncasecmp(pBuffer, "OPTIONS", 7) == 0 ||
                    strncasecmp(pBuffer, "CONNECT", 7))) == 0;
    
    if (!bMayReq && !bMayResp)
        return;
    
    int nPos = 0;
    int nConsoleLen = 0;
    int nColonPos = 0;
    int nRNPos = 0;
    
    if (!FindLine(pBuffer, nDataLen, nColonPos, nRNPos, nConsoleLen))
    {
        return;
    }
    
    StringArray nArray;
    SplitString(pBuffer, nRNPos, ' ', nArray);
    if (nArray.size() != 3)
        return;
    
    if (bMayResp)
    {
        StringArray nVerArray;
        SplitString(nArray[0], '/', nVerArray);
        if (nVerArray.size() != 2)
            return;
        
        m_bRequest = false;
        m_strVersion = nVerArray[1];
        m_nRespCode = Strint2Int(nArray[1]);
    }
    else
    {
        StringArray nVerArray;
        SplitString(nArray[2], '/', nVerArray);
        if (nVerArray.size() != 2)
            return;
        
        m_bRequest = true;
        m_strVersion = nVerArray[1];
        m_strMethod = nArray[0];
        m_strUrl = nArray[1];
    }
    
    int nItemLen = 0;
    if (ParseHeaderItem(pBuffer + nConsoleLen, nDataLen - nConsoleLen, nItemLen))
    {
        nHeaderLen = nConsoleLen + nItemLen;
    }
}
Exemple #16
0
static void UpdateFromFocus (EditorWidget ew)
	{ ew -> editor.curx = ew -> editor.focusbeginx;
	  ew -> editor.cury = ew -> editor.focusbeginy;
	  ew -> editor.curlin = FindLine (ew, ew -> editor.cury);
	};
Exemple #17
0
void BrowseTo(HWND hwnd, char *msg)
{
    static char name[256];
    int ofs;
    if (defaultWorkArea)
        return ;
    if (!browsing)
    {
        if (msg)
        {
            strcpy(name, msg);
            browsing = TRUE;
        }
        else
            browsing = SendMessage(hwnd, WM_WORDUNDERCURSOR, 0, (LPARAM)name);
        if (!PropGetBool(NULL, "BROWSE_INFORMATION") && browsing)
        {
            ExtendedMessageBox("Browse Info Alert", MB_OK, 
                "Browse information not enabled");
            browsing = FALSE;
            return ;
        }
    }
    else
    {
        SendMessage(hwnd, WM_WORDUNDERCURSOR, 0, (LPARAM)name);
    }
    if (browsing)
    {
        sqlite3 *db = NULL;
        DWINFO info;
        CHARRANGE charrange;
        int curline;
        char *filname;
        PROJECTITEM *pj;
        if (msg)
        {
            curline =  - 2;
            filname = "";
        }
        else
        {
            SendDlgItemMessage(hwnd, ID_EDITCHILD, EM_EXGETSEL, (WPARAM)0, 
                (LPARAM) &charrange);
            curline = SendDlgItemMessage(hwnd, ID_EDITCHILD, EM_EXLINEFROMCHAR,
                0, (LPARAM)charrange.cpMin) + 1;
            filname = (char*)SendMessage(hwnd, WM_FILENAME, 0, 0);
        }
        memset(&info, 0, sizeof(info));
        db = BrowseOpenDBByHWND(hwnd, &pj);
        if (!db)
        {
            return ;
        }
        if (FindLine(db, filname, curline, name, info.dwName, &info.dwLineNo))
        {
            char *p = strrchr(info.dwName, '\\');
            if (p)
                strcpy(info.dwTitle, p + 1);
            info.logMRU = FALSE;
            info.newFile = FALSE;
            InsertBrowse(name, curline);
            CreateDrawWindow(&info, TRUE);
        }
        DBClose(db);
    }
    browsing = FALSE;
}
Exemple #18
0
void scContUnit::CharInsert( long		computedOffset,
							 long&		offset,
							 scKeyRecord&	keyRec,
							 long&		tmMove,
							 short& 	rebreak,
							 Bool		textCleared,
							 TypeSpec	clearedSpec )
{
#if SCDEBUG > 1
	{
		static int doit;
		if ( doit )
			fSpecRun.PrintRun( "scContUnit::CharInsert" );
	}
#endif

#ifdef _RUBI_SUPPORT
	if ( fRubiArray ) {
		if ( fRubiArray->IsRubiData( offset + computedOffset ) ) {
			scRubiData rd;
			fRubiArray->GetRubiAt( rd, offset + computedOffset );
			fCharArray.Transform( rd.fStartOffset, rd.fEndOffset, eRemoveJapTran, 0 );

			fRubiArray->DeleteRubiData( offset );
			if ( !fRubiArray->GetNumItems() )
				DeleteRubiArray();
		}
	}
#endif

	if ( computedOffset >= 0 )
		fCharArray.SetNumSlots( fCharArray.GetNumItems() + 1 );
	
	fCharArray.CharInsert( tmMove, 
						   fSpecRun, 
#ifdef _RUBI_SUPPORT
						   fRubiArray,
#endif
						   offset, 
						   keyRec, 
						   textCleared,
						   clearedSpec );

	fSpecRun.SetContentSize( GetContentSize() );

#if SCDEBUG > 1
	{
		static int doit;
		if ( doit )
			fSpecRun.PrintRun( "void scContUnit::CharInsert 2" );
	}
#endif
			
	scTextline* txl = FindLine( offset );
	if ( txl )
		txl->Mark( scREPAINT ); /* force repaint */

	Mark( scREBREAK );

	rebreak = true;
}
void ReadCrop (char *filename, croptbl_struct *croptbl)
{
    FILE           *crop_file;
    char            cmdstr[MAXSTRING];
    char            temp[MAXSTRING];
    int             j;

    crop_file = fopen (filename, "r");
    CheckFile (crop_file, filename);

    /* Read crop description file */
    /* First count how many crop types are there in the description file */
    croptbl->number = CountOccurance (crop_file, "NAME");

    croptbl->cropName = (char **)malloc (croptbl->number * sizeof (char *));
    croptbl->userSeedingDate =
        (int *)malloc (croptbl->number * sizeof (int));
    croptbl->userFloweringDate =
        (int *)malloc (croptbl->number * sizeof (int));
    croptbl->userMaturityDate =
        (int *)malloc (croptbl->number * sizeof (int));
    croptbl->userMaximumSoilCoverage =
        (double *)malloc (croptbl->number * sizeof (double));

    croptbl->userMaximumRootingDepth =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userExpectedYieldAvg =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userExpectedYieldMax =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userExpectedYieldMin =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userPercentMoistureInYield =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userFractionResidueStanding =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userFractionResidueRemoved =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userClippingBiomassThresholdUpper =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userClippingBiomassThresholdLower =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userClippingTiming =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userClippingDestiny =
        (int *)malloc (croptbl->number * sizeof (int));
    croptbl->userTranspirationMinTemperature =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userTranspirationThresholdTemperature =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userColdDamageMinTemperature =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userColdDamageThresholdTemperature =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userTemperatureBase =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userTemperatureOptimum =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userTemperatureMaximum =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userShootPartitionInitial =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userShootPartitionFinal =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userRadiationUseEfficiency =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userTranspirationUseEfficiency =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userHIx =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userHIo =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userHIk =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userEmergenceTT =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userNMaxConcentration =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userNDilutionSlope =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userKc =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userAnnual =
        (int *)malloc (croptbl->number * sizeof (int));
    croptbl->userLegume =
        (int *)malloc (croptbl->number * sizeof (int));
    croptbl->userC3orC4 =
        (int *)malloc (croptbl->number * sizeof (int));
    croptbl->userExtinctionCoefficient =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userPlantingDensity =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->userClippingStart =
        (int *)malloc (croptbl->number * sizeof (int));
    croptbl->userClippingEnd =
        (int *)malloc (croptbl->number * sizeof (int));
    croptbl->LWP_StressOnset =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->LWP_WiltingPoint =
        (double *)malloc (croptbl->number * sizeof (double));
    croptbl->transpirationMax =
        (double *)malloc (croptbl->number * sizeof (double));

    /* Rewind to the beginning of file */
    FindLine (crop_file, "BOF");

    /* Read crop properties */
    for (j = 0; j < croptbl->number; j++)
    {
        croptbl->cropName[j] = (char *)malloc (MAXSTRING * sizeof (char));
        NextLine (crop_file, cmdstr);
        ReadKeywordStr (cmdstr, "NAME", croptbl->cropName[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordInt (cmdstr, "AVERAGE_SEEDING_DATE", &croptbl->userSeedingDate[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordInt (cmdstr, "AVERAGE_50%_FLOWERING_DATE", &croptbl->userFloweringDate[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordInt (cmdstr, "AVERAGE_MATURITY_DATE", &croptbl->userMaturityDate[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "MAXIMUM_SOIL_COVERAGE", &croptbl->userMaximumSoilCoverage[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "MAXIMUM_ROOTING_DEPTH", &croptbl->userMaximumRootingDepth[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "AVERAGE_EXPECTED_YIELD", &croptbl->userExpectedYieldAvg[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "MAXIMUM_EXPECTED_YIELD", &croptbl->userExpectedYieldMax[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "MINIMUM_EXPECTED_YIELD", &croptbl->userExpectedYieldMin[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "COMMERCIAL_YIELD_MOISTURE", &croptbl->userPercentMoistureInYield[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "STANDING_RESIDUE_AT_HARVEST", &croptbl->userFractionResidueStanding[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "RESIDUE_REMOVED", &croptbl->userFractionResidueRemoved[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "CLIPPING_BIOMASS_THRESHOLD_UPPER", &croptbl->userClippingBiomassThresholdUpper[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "CLIPPING_BIOMASS_THRESHOLD_LOWER", &croptbl->userClippingBiomassThresholdLower[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "HARVEST_TIMING", &croptbl->userClippingTiming[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordStr (cmdstr, "CLIPPING_BIOMASS_DESTINY", temp);
        if (strcasecmp ("REMOVE", temp) == 0)
        {
            croptbl->userClippingDestiny[j] = REMOVE_CLIPPING;
        }
        else if (strcasecmp ("RETURN", temp) == 0)
        {
            croptbl->userClippingDestiny[j] = RETURN_CLIPPING;
        }
        else if (strcasecmp ("GRAZING", temp) == 0)
        {
            croptbl->userClippingDestiny[j] = GRAZING_CLIPPING;
        }
        else
        {
            printf ("Option %s not recoganized!\n", temp);
            exit (1);
        }

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "MIN_TEMPERATURE_FOR_TRANSPIRATION", &croptbl->userTranspirationMinTemperature[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "THRESHOLD_TEMPERATURE_FOR_TRANPIRATION", &croptbl->userTranspirationThresholdTemperature[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "MIN_TEMPERATURE_FOR_COLD_DAMAGE", &croptbl->userColdDamageMinTemperature[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "THRESHOLD_TEMPERATURE_FOR_COLD_DAMAGE", &croptbl->userColdDamageThresholdTemperature[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "BASE_TEMPERATURE_FOR_DEVELOPMENT", &croptbl->userTemperatureBase[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "OPTIMUM_TEMPERATURE_FOR_DEVELOPEMENT", &croptbl->userTemperatureOptimum[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "MAX_TEMPERATURE_FOR_DEVELOPMENT", &croptbl->userTemperatureMaximum[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "INITIAL_PARTITIONING_TO_SHOOT", &croptbl->userShootPartitionInitial[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "FINAL_PARTITIONING_TO_SHOOT", &croptbl->userShootPartitionFinal[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "RADIATION_USE_EFFICIENCY", &croptbl->userRadiationUseEfficiency[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "TRANSPIRATION_USE_EFFICIENCY", &croptbl->userTranspirationUseEfficiency[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "MAXIMUM_HARVEST_INDEX", &croptbl->userHIx[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "MINIMUM_HARVEST_INDEX", &croptbl->userHIo[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "HARVEST_INDEX", &croptbl->userHIk[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "THERMAL_TIME_TO_EMERGENCE", &croptbl->userEmergenceTT[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "N_MAX_CONCENTRATION", &croptbl->userNMaxConcentration[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "N_DILUTION_SLOPE", &croptbl->userNDilutionSlope[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "KC", &croptbl->userKc[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordInt (cmdstr, "ANNUAL", &croptbl->userAnnual[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordInt (cmdstr, "LEGUME", &croptbl->userLegume[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordInt (cmdstr, "C3", &croptbl->userC3orC4[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "LWP_STRESS_ONSET", &croptbl->LWP_StressOnset[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "LWP_WILTING_POINT", &croptbl->LWP_WiltingPoint[j]);

        NextLine (crop_file, cmdstr);
        ReadKeywordDouble (cmdstr, "TRANSPIRATION_MAX", &croptbl->transpirationMax[j]);
    }

    fclose (crop_file);
}
Exemple #20
0
static void Init( void )
{
   GLint errorPos;

   /* Yes, this could be expressed more efficiently */
   static const char *fragProgramText =
      "!!ARBfp1.0\n"
#if DO_FRAGMENT_FOG
      "OPTION ARB_fog_linear; \n"
#endif
      "PARAM Diffuse = state.material.diffuse; \n"
      "PARAM Specular = state.material.specular; \n"
      "PARAM LightPos = program.local[3]; \n"
      "TEMP lightDir, normal, len; \n"
      "TEMP dotProd, specAtten; \n"
      "TEMP diffuseColor, specularColor; \n"

      "# Compute normalized light direction \n"
      "DP3 len.x, LightPos, LightPos; \n"
      "RSQ len.y, len.x; \n"
      "MUL lightDir, LightPos, len.y; \n"

      "# Compute normalized normal \n"
      "DP3 len.x, fragment.texcoord[0], fragment.texcoord[0]; \n"
      "RSQ len.y, len.x; \n"
      "MUL normal, fragment.texcoord[0], len.y; \n"

      "# Compute dot product of light direction and normal vector\n"
      "DP3 dotProd, lightDir, normal; \n"

      "MUL diffuseColor, Diffuse, dotProd;            # diffuse attenuation\n"

      "POW specAtten.x, dotProd.x, {20.0}.x;          # specular exponent\n"

      "MUL specularColor, Specular, specAtten.x;      # specular attenuation\n"

#if DO_FRAGMENT_FOG
      "# need to clamp color to [0,1] before fogging \n"
      "ADD_SAT result.color, diffuseColor, specularColor; # add colors\n"
#else
      "# clamping will be done after program's finished \n"
      "ADD result.color, diffuseColor, specularColor; # add colors\n"
#endif
      "END \n"
      ;

   static const char *vertProgramText =
      "!!ARBvp1.0\n"
      "ATTRIB pos = vertex.position; \n"
      "ATTRIB norm = vertex.normal; \n"
      "PARAM modelview[4] = { state.matrix.modelview }; \n"
      "PARAM modelviewProj[4] = { state.matrix.mvp }; \n"
      "PARAM invModelview[4] = { state.matrix.modelview.invtrans }; \n"

      "# typical modelview/projection transform \n"
      "DP4 result.position.x, pos, modelviewProj[0]; \n"
      "DP4 result.position.y, pos, modelviewProj[1]; \n"
      "DP4 result.position.z, pos, modelviewProj[2]; \n"
      "DP4 result.position.w, pos, modelviewProj[3]; \n"

      "# transform normal by inv transpose of modelview, put in tex0 \n"
      "DP3 result.texcoord[0].x, norm, invModelview[0]; \n"
      "DP3 result.texcoord[0].y, norm, invModelview[1]; \n"
      "DP3 result.texcoord[0].z, norm, invModelview[2]; \n"
      "DP3 result.texcoord[0].w, norm, invModelview[3]; \n"

#if DO_FRAGMENT_FOG
      "# compute fog coordinate = vertex eye-space Z coord (negated)\n"
      "DP4 result.fogcoord, -pos, modelview[2]; \n"
#endif
      "END\n";
      ;

   if (!glutExtensionSupported("GL_ARB_vertex_program")) {
      printf("Sorry, this demo requires GL_ARB_vertex_program\n");
      exit(1);
   }
   if (!glutExtensionSupported("GL_ARB_fragment_program")) {
      printf("Sorry, this demo requires GL_ARB_fragment_program\n");
      exit(1);
   }
         
   /*
    * Get extension function pointers.
    */
   glProgramLocalParameter4fvARB_func = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) glutGetProcAddress("glProgramLocalParameter4fvARB");
   assert(glProgramLocalParameter4fvARB_func);

   glProgramLocalParameter4dARB_func = (PFNGLPROGRAMLOCALPARAMETER4DARBPROC) glutGetProcAddress("glProgramLocalParameter4dARB");
   assert(glProgramLocalParameter4dARB_func);

   glGetProgramLocalParameterdvARB_func = (PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) glutGetProcAddress("glGetProgramLocalParameterdvARB");
   assert(glGetProgramLocalParameterdvARB_func);

   glGenProgramsARB_func = (PFNGLGENPROGRAMSARBPROC) glutGetProcAddress("glGenProgramsARB");
   assert(glGenProgramsARB_func);

   glProgramStringARB_func = (PFNGLPROGRAMSTRINGARBPROC) glutGetProcAddress("glProgramStringARB");
   assert(glProgramStringARB_func);

   glBindProgramARB_func = (PFNGLBINDPROGRAMARBPROC) glutGetProcAddress("glBindProgramARB");
   assert(glBindProgramARB_func);

   glIsProgramARB_func = (PFNGLISPROGRAMARBPROC) glutGetProcAddress("glIsProgramARB");
   assert(glIsProgramARB_func);

   glDeleteProgramsARB_func = (PFNGLDELETEPROGRAMSARBPROC) glutGetProcAddress("glDeleteProgramsARB");
   assert(glDeleteProgramsARB_func);

   /*
    * Fragment program
    */
   glGenProgramsARB_func(1, &FragProg);
   assert(FragProg > 0);
   glBindProgramARB_func(GL_FRAGMENT_PROGRAM_ARB, FragProg);
   glProgramStringARB_func(GL_FRAGMENT_PROGRAM_ARB,
                           GL_PROGRAM_FORMAT_ASCII_ARB,
                           strlen(fragProgramText),
                           (const GLubyte *) fragProgramText);
   glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorPos);
   if (glGetError() != GL_NO_ERROR || errorPos != -1) {
      int l = FindLine(fragProgramText, errorPos);
      printf("Fragment Program Error (pos=%d line=%d): %s\n", errorPos, l,
             (char *) glGetString(GL_PROGRAM_ERROR_STRING_ARB));
      exit(0);
   }
   assert(glIsProgramARB_func(FragProg));

   /*
    * Do some sanity tests
    */
   {
      GLdouble v[4];
      glProgramLocalParameter4dARB_func(GL_FRAGMENT_PROGRAM_ARB, 8,
                                   10.0, 20.0, 30.0, 40.0);
      glGetProgramLocalParameterdvARB_func(GL_FRAGMENT_PROGRAM_ARB, 8, v);
      assert(v[0] == 10.0);
      assert(v[1] == 20.0);
      assert(v[2] == 30.0);
      assert(v[3] == 40.0);
   }

   /*
    * Vertex program
    */
   glGenProgramsARB_func(1, &VertProg);
   assert(VertProg > 0);
   glBindProgramARB_func(GL_VERTEX_PROGRAM_ARB, VertProg);
   glProgramStringARB_func(GL_VERTEX_PROGRAM_ARB,
                           GL_PROGRAM_FORMAT_ASCII_ARB,
                           strlen(vertProgramText),
                           (const GLubyte *) vertProgramText);
   glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorPos);
   if (glGetError() != GL_NO_ERROR || errorPos != -1) {
      int l = FindLine(fragProgramText, errorPos);
      printf("Vertex Program Error (pos=%d line=%d): %s\n", errorPos, l,
             (char *) glGetString(GL_PROGRAM_ERROR_STRING_ARB));
      exit(0);
   }
   assert(glIsProgramARB_func(VertProg));

   /*
    * Misc init
    */
   glClearColor(0.3, 0.3, 0.3, 0.0);
   glEnable(GL_DEPTH_TEST);
   glEnable(GL_LIGHT0);
   glEnable(GL_LIGHTING);
   glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, Diffuse);
   glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Specular);
   glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 20.0);

#if DO_FRAGMENT_FOG
   {
      /* Green-ish fog color */
      static const GLfloat fogColor[4] = {0.5, 1.0, 0.5, 0};
      glFogi(GL_FOG_MODE, GL_LINEAR);
      glFogfv(GL_FOG_COLOR, fogColor);
      glFogf(GL_FOG_START, 5.0);
      glFogf(GL_FOG_END, 25.0);
      glEnable(GL_FOG);
   }
#endif

   printf("GL_RENDERER = %s\n", (char *) glGetString(GL_RENDERER));
   printf("Press p to toggle between per-pixel and per-vertex lighting\n");
}
Exemple #21
0
int doDark (ACSInfo *acs2d, SingleGroup *x, float *meandark) {
  
  /* arguments:
   ACSInfo *acs     i: calibration switches, etc
   SingleGroup *x    io: image to be calibrated; written to in-place
   float *meandark    o: mean of dark image values subtracted
   */
  
  extern int status;

  const float darkscaling = 3.0;  /* Extra idle time */
  
  SingleGroupLine y, z;	/* y and z are scratch space */
  int extver = 1;		/* get this imset from dark image */
  int rx, ry;		/* for binning dark down to size of x */
  int x0, y0;		/* offsets of sci image */
  int same_size;		/* true if no binning of ref image required */
  int avg = 0;		/* bin2d should sum values within each bin */
  int scilines; 			/* number of lines in science image */
  int i, j;
  float mean, dark;
  float weight, wdark;    /* weights for line averages */
  int update;
  float darktime;
  
  int FindLine (SingleGroup *, SingleGroupLine *, int *, int *, int *, int *, int *);
  int sub1d (SingleGroup *, int, SingleGroupLine *);
  int trim1d (SingleGroupLine *, int, int, int, int, int, SingleGroupLine *);
  int DetCCDChip (char *, int, int, int *);
  void AvgSciValLine (SingleGroupLine *, short, float *, float *);
  int multk1d (SingleGroupLine *, float);
  
  
	initSingleGroupLine (&y);
	
	scilines = x->sci.data.ny;

  /* Compute DARKTIME */
  /* SBC does not have FLASH keywords */
  if (acs2d->detector == MAMA_DETECTOR)
    darktime = acs2d->exptime;
  else {
    darktime = acs2d->exptime + acs2d->flashdur;

    /* Post-SM4 non-BIAS WFC only */
    /* TARGNAME unavailable, assume EXPTIME=0 means BIAS */
    if (acs2d->detector == WFC_CCD_DETECTOR && acs2d->expstart > SM4MJD && acs2d->exptime > 0)
      darktime += darkscaling;
  }
  
	/* Compute correct extension version number to extract from
   reference image to correspond to CHIP in science data.
   */
	if (acs2d->pctecorr == PERFORM) {
    if (DetCCDChip (acs2d->darkcte.name, acs2d->chip, acs2d->nimsets, &extver) )
      return (status);
  } else {
    if (DetCCDChip (acs2d->dark.name, acs2d->chip, acs2d->nimsets, &extver) )
      return (status);
  }
	
	if (acs2d->verbose) {
		sprintf(MsgText,"Performing dark subtraction on chip %d in imset %d",acs2d->chip, extver);
		trlmessage(MsgText);
	}
  
	/* Get the dark image data. */
  if (acs2d->pctecorr == PERFORM) {
    openSingleGroupLine (acs2d->darkcte.name, extver, &y);
  } else {
    openSingleGroupLine (acs2d->dark.name, extver, &y);
  }
	if (hstio_err())
    return (status = OPEN_FAILED);
  
  
	/* Compare binning of science image and reference image;
   get same_size and high_res flags, and get info about
   binning and offset for use by bin2d.
   */
	if (FindLine (x, &y, &same_size, &rx, &ry, &x0, &y0))
    return (status);
  
  if (rx != 1 || ry != 1) {
		sprintf(MsgText,"Reference image and input are not binned to the same pixel size!");
		trlmessage(MsgText);
  }
	if (acs2d->verbose){
		sprintf(MsgText,"Image has an offset of %d,%d",x0,y0);
		trlmessage(MsgText);
	}
  
	mean = 0.0;
  weight = 0.0;
  
	/* Bin the dark image down to the actual size of x. */
  
	initSingleGroupLine (&z);
	allocSingleGroupLine (&z, x->sci.data.nx);
	for (i=0, j=y0; i < scilines; i++,j++) { 
    
    /* We are working with a sub-array and need to apply the
     proper section from the reference image to the science image.
     */
		if (acs2d->pctecorr == PERFORM) {
      getSingleGroupLine (acs2d->darkcte.name, j, &y);
    } else {
      getSingleGroupLine (acs2d->dark.name, j, &y);
    }
    
    /*
     rx = 1;
     */
    update = NO;
    
    if (trim1d (&y, x0, y0, rx, avg, update, &z)) {
			trlerror ("(darkcorr) size mismatch.");
			return (status);
    }
    
    multk1d(&z, darktime);
    
    AvgSciValLine (&z, acs2d->sdqflags, &dark, &wdark);
    
		/* Sum the contribution from each line */			
		mean += dark * wdark;
		weight += wdark;
    
    status = sub1d (x, i, &z);
		if (status)
			return (status);
	}
	freeSingleGroupLine (&z);			/* done with z */
  
  /*	} */
  
	closeSingleGroupLine (&y);
	freeSingleGroupLine (&y);
  
	/* Compute the mean for the entire image */	
	if (scilines > 0) 
		*meandark = mean / weight; 
	else 
		*meandark = 0.;
	
	return (status);
}
Exemple #22
0
int main(int argc, char ** argv)
{
    if(argc != 6 )
      {
	cout <<"Usage: lobmaskCF_Levine <BasalGangliaThalamus_File(BGT)> <Singulate_Mask_File> <OutputFile> -g GridFile"<<endl;
	cout<<"To generate mask for Collenergic Fibres. By: Dr. Azhar Quddus"<<endl;
	exit(1);
      }

    info hdr_info;
    string fname(argv[1]);
    string cfname(argv[2]);

    //Read Header & Make Grid info
    read_analyze_header(fname + ".hdr", hdr_info);

    if(hdr_info.datatype == 2) make_grid<uchar>(argc, argv);
    else {
        if(hdr_info.datatype == 4) make_grid<short>(argc, argv);
        else {
            cout << "Input file has wrong datatype:"
                 <<" only uchar and short are allowed. Exiting... " << endl;
            exit(1);
        }
    }

    int xgrid=grid.sagital[2]-grid.sagital[1];

    //Read Image files
    uchar *img=read_analyze<uchar>(fname, hdr_info);
    uchar *cing=read_analyze<uchar>(cfname, hdr_info);

    //Make Blank Volume
   uchar *mask = new uchar[volume];
   if(!mask) {
       cout << "Memory allocation failed. Exiting..." << endl;
       exit(1);
   }
   fill(mask, mask + volume, (uchar)BACKGROUND);

   //Copy Singulate into output mask
   memcpy(mask,cing,volume);

    //Make Axial slice
   int axial_area=sz[0] * sz[1];
   uchar *axial_in=new uchar[axial_area];
   uchar *axial_out=new uchar[axial_area];

   if(!axial_in || !axial_out)
     {
       cout << "Failed to allocate memory for trace masks. Exiting..." << endl;
       exit(1);
     }

   fill(axial_in, axial_in + axial_area, BACKGROUND);

   //Find Strip end (from top)
   int oldWidth=0;
   int Width=0;
   int slice_break=0;
   int breakSlicesfromTop=0;

   for(int i=sz[2]-1;i>=0;i--)
     {
       get_Axial_Slice(axial_in,img,i);
       if(!Blank_Slice(axial_in,axial_area))
	 {
	   Width=MaxWidth(axial_in,sz[1], sz[0]);
	   breakSlicesfromTop++;
	 }

       if(oldWidth==0)
	 oldWidth=Width;

       if(oldWidth!=0 && Width!=0 && oldWidth!=Width)
	 {
	   slice_break=i+1;
	   break;
	 }
     }
   cout<<"Slice Break 1:"<<slice_break<<endl;

   int stSlices=3 * breakSlicesfromTop;

   //Find full curve end (from top)
   int slice_break2=0;
   for(int i=slice_break;i>=0;i--)
     {
       get_Axial_Slice(axial_in,img,i);
       bool line=true;
       int r=grid.coronal[9];

       if(!FindLine(axial_in,sz[1],sz[0],r))
	 {
	   slice_break2=i+1;
	   break;
	 }
     }
   cout<<"Slice Break 2:"<<slice_break2<<endl;


   cout<<"Valid Slices:";

//Processing Half-Curved regions...
   for(int i=0;i<slice_break2;i++)
     {
       int LastRow=0;

       get_Axial_Slice(axial_in,img,i);
       get_Axial_Slice(axial_out,mask,i);

       if(!Blank_Slice(axial_in,axial_area))
	 {cout<<i<<" " ;
	   for(int r=0;r<sz[1];r++)
	     for(int c=0;c<sz[0];c++)
	       {
		 int pos=r*sz[0]+c;
		 if(axial_in[pos]==0 && axial_in[pos+1]>0)
		   {
		     int C=c+(int)((double)xgrid/4.0);
		     for(int lc=C;lc > (C-xgrid/2);lc--)
		       axial_out[r*sz[0]+lc]=12;
		   }

		 if(axial_in[pos]==0 && axial_in[pos-1]>0)
		   {
		     int C=c-(int)((double)xgrid/4.0);
		     for(int lc=C;lc < (C+xgrid/2);lc++)
		       axial_out[r*sz[0]+lc]=14;
		   }
	       }
	 }

       set_Axial_Slice(axial_out, mask,i);
     }

   //Processing Full-Curved regions...
   for(int i=slice_break2;i<slice_break;i++)
     {
       get_Axial_Slice(axial_in,img,i);
       get_Axial_Slice(axial_out,mask,i);

       if(!Blank_Slice(axial_in,axial_area))
	 {cout<<i<<" " ;
	   for(int r=0;r<sz[1];r++)
	     for(int c=0;c<sz[0];c++)
	       {
		 int pos=r*sz[0]+c;
		 if(axial_in[pos]==0 && axial_in[pos+1]>0)
		   {
int C=c+3;
		     for(int lc=C;lc > (C-xgrid/2);lc--)
		       axial_out[r*sz[0]+lc]=12;
		   }

		 if(axial_in[pos]==0 && axial_in[pos-1]>0)
		   {
int C=c-3;
		     for(int lc=C;lc < (C+xgrid/2);lc++)
		       axial_out[r*sz[0]+lc]=14;
		   }
	       }
	 }

       set_Axial_Slice(axial_out, mask,i);
     }
   
   //Generating straight regions...
   int LTR=grid.coronal[6];
   int LBR=grid.coronal[13];
   int LRC=(int)((double)grid.sagital[3]-(double)xgrid/2.0);
   int LLC=LRC-(int)((double)xgrid/2.0);
LRC=LRC+3;
LLC=LLC+3;

   int RTR=LTR;
   int RBR=LBR;
   int RLC=(int)((double)grid.sagital[5]+(double)xgrid/2.0);
   int RRC=RLC+(int)((double)xgrid/2.0);
RLC=RLC-3;
RRC=RRC-3;

   for(int i=slice_break;i < (slice_break + stSlices); i++)
     {
       get_Axial_Slice(axial_in,img,i);

       cout<<i<<" ";

       get_Axial_Slice(axial_out,mask,i);

       for(int r=LTR;r<=LBR;r++)
	 for(int c=LLC;c<=LRC;c++)
	   axial_out[r*sz[1]+c]=12;

       for(int r=RTR;r<=RBR;r++)
	 for(int c=RLC;c<=RRC;c++)
	   axial_out[r*sz[1]+c]=14;

       set_Axial_Slice(axial_out, mask,i);
     }
     
    // output
    hdr_info.max = 15;
    hdr_info.min = 0;
    hdr_info.datatype = 2;
    cout<<endl;
    cout << "Writing: "<< argv[3]<<"...";
    write_analyze(string(argv[3]), mask,  hdr_info);
    cout <<"Done!"<<endl;
    
    delete [] mask;
    delete [] img;
    delete [] cing;
    delete [] axial_in;
    delete [] axial_out;
    return 0;
}  // end of main
Exemple #23
0
int doDark (WF3Info *wf32d, SingleGroup *x, float *meandark) {

/* arguments:
WF3Info *wf3       i: calibration switches, etc
SingleGroup *x    io: image to be calibrated; written to in-place
float *meandark	   o: mean of dark image values subtracted
*/

    extern int status;

    SingleGroupLine y, z;	/* y and z are scratch space */
    int extver = 1;		/* get this imset from dark image */
    int rx, ry;			/* for binning dark down to size of x */
    int x0, y0;			/* offsets of sci image */
    int same_size;		/* true if no binning of ref image required */
    int avg = 0;		/* bin2d should sum values within each bin */
    int scilines; 		/* number of lines in science image */
    int i, j;
    float mean, dark;
    float weight, wdark;    	/* weights for line averages */
    int update;
    float gain[NAMPS];
    float rn2[NAMPS];       	/* only need this to call get_nsegn */

    int FindLine (SingleGroup *, SingleGroupLine *, int *, int *, int *,
		  int *, int *);
    int sub1d (SingleGroup *, int, SingleGroupLine *);
    int trim1d (SingleGroupLine *, int, int, int, int, int, SingleGroupLine *);
    int DetCCDChip (char *, int, int, int *);
    void get_nsegn (int, int, int, int, float *, float*, float *, float *);
    void AvgSciValLine (SingleGroupLine *, short, float *, float *);
    void multgn1d (SingleGroupLine *, int, int, int, float *, float);


	initSingleGroupLine (&y);
	
	scilines = x->sci.data.ny;

	/* Compute correct extension version number to extract from
	   reference image to correspond to CHIP in science data.  */
	if (DetCCDChip(wf32d->dark.name, wf32d->chip, wf32d->nimsets, &extver))
	    return (status);	
	
	if (wf32d->verbose) {
	    sprintf (MsgText,
		     "Performing dark subtraction on chip %d in imset %d",
		     wf32d->chip, extver);
	    trlmessage(MsgText);
	}

	/* Get the dark image data. */
	openSingleGroupLine (wf32d->dark.name, extver, &y);
	if (hstio_err())
	    return (status = OPEN_FAILED);

	/* Compare binning of science image and reference image;
	   get same_size flag, and get info about binning and offset
	   for use by bin2d.
	*/
	if (FindLine (x, &y, &same_size, &rx, &ry, &x0, &y0))
	    return (status);
    
	/* Return with error if reference data not binned same as input */
	if (rx != 1 || ry != 1) {
	    closeSingleGroupLine (&y);
	    freeSingleGroupLine (&y);
	    sprintf (MsgText,
	    "DARK image and input are not binned to the same pixel size!");
	    trlerror(MsgText);
	    return (status = SIZE_MISMATCH);
	}
	if (wf32d->verbose){
	    sprintf(MsgText,"Image has an offset of %d,%d",x0,y0);
	    trlmessage(MsgText);
	}

	mean = 0.0;
	weight = 0.0;
    
	/* Multiply the dark image by the exposure time and divide by the
	   atodgain (or just by exposure time for the MAMAs), and
	   subtract it from x.
	*/
    
	for (i = 0; i < NAMPS; i++) {
	     gain[i] = 0.;
	     rn2[i] = 0.;
	}
	get_nsegn (wf32d->detector, wf32d->chip, wf32d->ampx, wf32d->ampy,
		   wf32d->atodgain, wf32d->readnoise, gain, rn2);

	initSingleGroupLine (&z);
	allocSingleGroupLine (&z, x->sci.data.nx);
	for (i=0, j=y0; i < scilines; i++,j++) { 

	     /* We are working with a sub-array and need to apply the
		proper section from the reference image to the science image.
	     */
	     getSingleGroupLine (wf32d->dark.name, j, &y);

             update = NO;

	     if (trim1d (&y, x0, y0, rx, avg, update, &z)) {
		 trlerror ("(darkcorr) size mismatch.");
		 return (status);
	     }

	     multgn1d(&z, j, wf32d->ampx, wf32d->ampy, gain, wf32d->exptime[0]);

	     AvgSciValLine (&z, wf32d->sdqflags, &dark, &wdark);

	     /* Sum the contribution from each line */			
	     mean += dark * wdark;
	     weight += wdark;

	     status = sub1d (x, i, &z);
	     if (status)
		 return (status);
	}
	freeSingleGroupLine (&z);			/* done with z */

	closeSingleGroupLine (&y);
	freeSingleGroupLine (&y);

	/* Compute the mean for the entire image */	
	if (scilines > 0) 
	    *meandark = mean / weight; 
	else 
	    *meandark = 0.;
	
	return (status);
}
Exemple #24
0
void WebEditBox::SetCursorPosition (long index)
{
	WebEditString::SetCursorPosition(index);
	miCurrentLine = FindLine(miCursorPos);
	mEditFlags |= EDIT_FLAG_ENSURE_CURSOR_VISIBLE;
}
Exemple #25
0
// TOOD: map flags; detect wrap around
void Edit::OnFindDialog(wxFindDialogEvent& event)
{
  wxEventType type = event.GetEventType();

  if(type == wxEVT_FIND || type == wxEVT_FIND_NEXT)
  {
  	const wxString find = event.GetFindString();
    const int curPos = FindLine(event);
    if(curPos > -1) {
      GotoPos(curPos);
      SetSelectionStart(curPos);
      SetSelectionEnd(curPos + find.size());
    }
    else {
      wxLogMessage(wxT("Unable to find \"%s\""), find);
    }
  }
  else if(type == wxEVT_FIND_REPLACE)
  {
    const wxString find = event.GetFindString();
    const int curPos = FindLine(event);
    if(curPos > -1) {
      SetSelectionStart(curPos);
      SetSelectionEnd(curPos + find.size());
      ReplaceSelection(event.GetReplaceString());
    }
    else {
      wxLogMessage(wxT("Unable to find \"%s\""), find);
    }
  }
  else if(type == wxEVT_FIND_REPLACE_ALL) 
  {
    const wxString find = event.GetFindString();
    const wxString replace = event.GetReplaceString();

    const long minPos = GetCurrentPos();
    const long maxPos = GetLastPosition();
    
    int count = 0;
    int curPos = FindText(minPos, maxPos, find);
    while(curPos > minPos) {
      ++count;
      SetSelectionStart(curPos);
      SetSelectionEnd(curPos + find.size());
      ReplaceSelection(replace);
      curPos = FindText(curPos + replace.size(), maxPos, find);
    }
    wxLogMessage(wxT("Replaced %d instance(s) of \"%s\" were replaced with \"%s\""), count, find, replace);
  }
  // FIX ME...
  else if(type == wxEVT_FIND_CLOSE)
  {
/*  
  	if(event.GetDialog() == m_dlgFind) {
  		wxDELETE(m_dlgFind);
  		m_dlgFind = NULL;
  	}
  	else if(event.GetDialog() == m_dlgReplace) {
  		wxDELETE(m_dlgReplace);
  		m_dlgReplace = NULL;
  	}
*/
  }
}
void ReadSoilInit (char *filename, soiltbl_struct *soiltbl)
{
    FILE           *soil_file;
    char            cmdstr[MAXSTRING];
    int             match;
    int             index;
    int             layer;
    int             i, j;

    /* 
     * Open soil initialization file
     */
    soil_file = fopen (filename, "r");
    CheckFile (soil_file, filename);

    soiltbl->totalLayers = (int *) malloc (soiltbl->number * sizeof (int));
    soiltbl->clay_lyr = (double **) malloc (soiltbl->number * sizeof (double *));
    soiltbl->sand_lyr = (double **) malloc (soiltbl->number * sizeof (double *));
    soiltbl->iom_lyr = (double **) malloc (soiltbl->number * sizeof (double *));
    soiltbl->bd_lyr = (double **) malloc (soiltbl->number * sizeof (double *));
    soiltbl->NO3_lyr = (double **) malloc (soiltbl->number * sizeof (double *));
    soiltbl->NH4_lyr = (double **) malloc (soiltbl->number * sizeof (double *));

    /* Read soil file */
    FindLine (soil_file, "BOF");

    for (i = 0; i < soiltbl->number; i++)
    {
        NextLine (soil_file, cmdstr);
        ReadKeywordInt (cmdstr, "SOIL_TYPE", &index);

        if (i != index - 1)
        {
            printf ("Cannot read information of the %dth soil type!\n",
                i + 1);
            printf (".soilinit file format error!\n");
            exit (1);
        }

        NextLine (soil_file, cmdstr);
        ReadKeywordInt (cmdstr, "TOTAL_LAYERS", &soiltbl->totalLayers[i]);

        soiltbl->clay_lyr[i] =
            (double *) malloc (soiltbl->totalLayers[i] * sizeof (double));
        soiltbl->sand_lyr[i] =
            (double *) malloc (soiltbl->totalLayers[i] * sizeof (double));
        soiltbl->iom_lyr[i] =
            (double *) malloc (soiltbl->totalLayers[i] * sizeof (double));
        soiltbl->bd_lyr[i] =
            (double *) malloc (soiltbl->totalLayers[i] * sizeof (double));
        soiltbl->NO3_lyr[i] =
            (double *) malloc (soiltbl->totalLayers[i] * sizeof (double));
        soiltbl->NH4_lyr[i] =
            (double *) malloc (soiltbl->totalLayers[i] * sizeof (double));
        
        /* Skip header */
        NextLine (soil_file, cmdstr);

        for (j = 0; j < soiltbl->totalLayers[i]; j++)
        {
            NextLine (soil_file, cmdstr);
            match = sscanf (cmdstr, "%d %lf %lf %lf %lf %lf %lf", &layer,
                &soiltbl->clay_lyr[i][j], &soiltbl->sand_lyr[i][j],
                &soiltbl->iom_lyr[i][j], &soiltbl->bd_lyr[i][j],
                &soiltbl->NO3_lyr[i][j], &soiltbl->NH4_lyr[i][j]);

            if (match != 7 || j != layer - 1)
            {
                printf ("Cannot read information of the %dth layer of the %dth"
                    "soil type!\n", j + 1, i + 1);
                printf (".soilinit file format error!\n");
                exit (1);
            }
        }
    }

    fclose (soil_file);
}
void ReadCyclesCtrl (char *filename, agtbl_struct *agtbl, int numele)
{
    FILE           *simctrl_file;
    //time_t          rawtime;
    //struct tm      *timestamp;
    char            cmdstr[MAXSTRING];
    int             i;
    int             match;
    int             index;

    /* Open simulation control file */
    simctrl_file = fopen (filename, "r");
    CheckFile (simctrl_file, filename);

    agtbl->op = (int *)malloc (numele * sizeof (int));
    agtbl->rotsz = (int *)malloc (numele * sizeof (int));
    agtbl->auto_N = (int *)malloc (numele * sizeof (int));
    agtbl->auto_P = (int *)malloc (numele * sizeof (int));
    agtbl->auto_S = (int *)malloc (numele * sizeof (int));

    /* Read simulation control file */
    FindLine (simctrl_file, "BOF");

    NextLine (simctrl_file, cmdstr);
    for (i = 0; i < numele; i++)
    {
        NextLine (simctrl_file, cmdstr);
        match = sscanf (cmdstr, "%d %d %d %d %d %d", &index, &agtbl->op[i], &agtbl->rotsz[i], &agtbl->auto_N[i], &agtbl->auto_P[i], &agtbl->auto_S[i]);
        if (match != 6)
        {
            printf ("Cannot read information of the %dth element!\n", i + 1);
            printf (".cycles file format error!\n");
            exit (1);
        }
    }

    FindLine (simctrl_file, "OPERATION_FILE");

    i = 0;
    while (1)
    {
        NextLine (simctrl_file, cmdstr);
        
        if (strcasecmp (cmdstr, "EOF") == 0)
        {
            break;
        }

        match = sscanf (cmdstr, "%d %s", &index, agtbl->opfilen[i]);
        if (match != 2 || i != index - 1)
        {
            printf ("Cannot read operation file information!\n");
            printf (".cycles file format error!\n");
            PihmExit (1);
        }
        i++;
    }

    agtbl->nopfile = i;

    fclose (simctrl_file);

    //rawtime = (int)ctrl->starttime;
    //timestamp = gmtime (&rawtime);
    //ctrl->simStartYear = timestamp->tm_year + 1900;

    //rawtime = (int)ctrl->endtime;
    //timestamp = gmtime (&rawtime);
    //ctrl->simEndYear = timestamp->tm_year + 1900 - 1;

    //ctrl->totalYears = ctrl->simEndYear - ctrl->simStartYear + 1;
}
Exemple #28
0
void LexStream::Dump()
{
    FILE* tokfile;
    // +1 for '\0' +4 for length(".tok")
    char* tokfile_name = new char[FileNameLength() + 5];
    strcpy(tokfile_name, FileName());
    strcat(tokfile_name, StringConstant::U8S_DO_tok);

    if ((tokfile = SystemFopen(tokfile_name, "w")) == NULL)
    {
        Coutput << "*** Cannot open LexStream dump output file "
                << tokfile_name << endl;
        return;
    }

    RereadInput();
    SetUpComments();

    TokenIndex tok = 0;
    for (CommentIndex com = FirstComment(tok);
         com > 0 && com < NumComments() && PrecedingToken(com) == tok; com++)
    {
        fprintf(tokfile, "*%5d ", com);
        fprintf(tokfile, "%s", FileName());
        fprintf(tokfile, ", line %d.%d: ",
                FindLine(comments[com].location),
                FindColumn(comments[com].location - 1) + 1);
        for (const wchar_t* s = CommentString(com); *s; s++)
            fprintf(tokfile, "%c", *s);
        fprintf(tokfile, "\n");
    }
    do
    {
        tok = Gettoken();
        fprintf(tokfile, "%6d ", tok);
        fprintf(tokfile, " %s", FileName());
        fprintf(tokfile, ", %cline %d.%d: %s %s  ",
                (AfterEol(tok) ? '*' : ' '),
                Line(tok), (Kind(tok) == TK_EOF ? 0 : Column(tok)),
                token_type(Kind(tok)),
                (tokens[tok].Deprecated() ? "(d)" : " "));
        for (const wchar_t* s = NameString(tok); *s; s++)
            fprintf(tokfile, "%c", *s);
        fprintf(tokfile, "\n");

        for (CommentIndex com = FirstComment(tok);
             com > 0 && com < NumComments() && PrecedingToken(com) == tok; com++)
        {
            fprintf(tokfile, "*%5d ", com);
            fprintf(tokfile, " %s", FileName());
            fprintf(tokfile, ", line %d.%d: ",
                    FindLine(comments[com].location),
                    FindColumn(comments[com].location - 1) + 1);
            for (const wchar_t* s = CommentString(com); *s; s++)
                fprintf(tokfile, "%c", *s);
            fprintf(tokfile, "\n");
        }
    } while (Kind(tok) != TK_EOF);

    DestroyInput();
    fprintf(tokfile, "\n");
#ifdef UNIQUE_NAMES
    fprintf(tokfile, "\nThe unique names are:\n\n");
    for (int i = 0; i < control.name_table.symbol_pool.length(); i++)
    {
        fprintf(tokfile, "%4d ", i);
        for (const wchar_t* s = control.name_table.symbol_pool[i].name();
             *s; s++)
        {
            fprintf(tokfile, "%c", *s);
        }
        fprintf(tokfile, "\n");
    }
#endif // UNIQUE_NAMES

    if (tokfile)
        fclose(tokfile);
    delete [] tokfile_name;
}
Exemple #29
0
int HPosAtIndex(LPEDIT lp, int idx)
{
	register int line = FindLine(lp, idx) ;
	return HPosAt(lp, line, idx - lp->lpFragments[line].nOffset) ;
}
void ReadOperation (const agtbl_struct *agtbl, mgmttbl_struct *mgmttbl, const croptbl_struct *croptbl)
{
    FILE           *op_file;
    char            cmdstr[MAXSTRING];
    char            filename[MAXSTRING];
    int             ntill;
    int             nplnt;
    int             nirrg;
    int             nfert;
    int             nautoirrg;
    int             i, j, k;
    cropmgmt_struct *cropmgmt;
    op_struct      *q;

    mgmttbl->number = agtbl->nopfile;

    mgmttbl->cropmgmt =
        (cropmgmt_struct *)malloc (mgmttbl->number * sizeof (cropmgmt_struct));

    for (i = 0; i < mgmttbl->number; i++)
    {
        cropmgmt = &mgmttbl->cropmgmt[i];

        cropmgmt->usingAutoIrr = 0;

        sprintf (filename, "input/%s/%s", project, agtbl->opfilen[i]);
        op_file = fopen (filename, "r");
        CheckFile (op_file, filename);

        FindLine (op_file, "BOF");
        nplnt = CountOccurance (op_file, "PLANTING");

        FindLine (op_file, "BOF");
        ntill = CountOccurance (op_file, "TILLAGE");

        FindLine (op_file, "BOF");
        nirrg = CountOccurance (op_file, "FIXED_IRRIGATION");

        FindLine (op_file, "BOF");
        nfert = CountOccurance (op_file, "FIXED_FERTILIZATION");

        FindLine (op_file, "BOF");
        nautoirrg = CountOccurance (op_file, "AUTO_IRRIGATION");

        cropmgmt->totalCropsPerRotation = nplnt;
        if (nplnt > 0)
        {
            cropmgmt->plantingOrder = (op_struct *)malloc (nplnt * sizeof (op_struct));

            /* Rewind to the beginning of file and read all planting operations */
            FindLine (op_file, "BOF");

            for (j = 0; j < nplnt; j++)
            {
                q = &(cropmgmt->plantingOrder[j]);

                FindLine (op_file, "PLANTING");

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "YEAR", &q->opYear);

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "DOY", &q->opDay);

                NextLine (op_file, cmdstr);
                ReadKeywordStr (cmdstr, "CROP", q->cropName);

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "USE_AUTO_IRR", &q->usesAutoIrrigation);
                if (q->usesAutoIrrigation == 0)
                {
                    q->usesAutoIrrigation = -1;
                }
                else
                {
                    cropmgmt->usingAutoIrr = 1;
                }

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "USE_AUTO_FERT", &q->usesAutoFertilization);
                if (q->usesAutoFertilization == 0)
                {
                    q->usesAutoFertilization = -1;
                }

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "FRACTION", &q->plantingDensity);

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "CLIPPING_START", &q->clippingStart);
                if (q->clippingStart > 366 || q->clippingStart < 1)
                {
                    printf ("ERROR: Please specify valid DOY for clipping start date!\n");
                    exit (1);
                }
                
                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "CLIPPING_END", &q->clippingEnd);
                if (q->clippingEnd > 366 || q->clippingEnd < 1)
                {
                    printf ("ERROR: Please specify valid DOY for clipping end date!\n");
                    exit (1);
                }

                q->status = 0;

                /* Link planting order and crop description */
                for (k = 0; k < croptbl->number; k++)
                {
                    if (strcmp (q->cropName, croptbl->cropName[k]) == 0)
                    {
                        q->plantID = k;
                        break;
                    }
                }
                if (k >= croptbl->number)
                {
                    printf ("ERROR: Cannot find the plant description of %s, please check your input file\n", q->cropName);
                    exit (1);
                }
            }
        }

        cropmgmt->numTillage = ntill;
        if (ntill > 0)
        {
            cropmgmt->Tillage = (op_struct *)malloc (ntill * sizeof (op_struct));

            /* Rewind to the beginning of file and read all tillage operations */
            FindLine (op_file, "BOF");

            for (j = 0; j < ntill; j++)
            {
                q = &(cropmgmt->Tillage[j]);

                FindLine (op_file, "TILLAGE");

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "YEAR", &q->opYear);

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "DOY", &q->opDay);

                NextLine (op_file, cmdstr);
                ReadKeywordStr (cmdstr, "TOOL", q->opToolName);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "DEPTH", &q->opDepth);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "SOIL_DISTURB_RATIO", &q->opSDR);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "MIXING_EFFICIENCY", &q->opMixingEfficiency);

                NextLine (op_file, cmdstr);
                ReadKeywordStr (cmdstr, "CROP_NAME", q->cropNameT);

                /* Check if the specified crop exists */
                if (strcasecmp (q->cropNameT, "N/A") != 0 &&
                    strcasecmp (q->cropNameT, "All") != 0 &&
                    !CropExist (q->cropNameT, croptbl))
                {
                    printf ("ERROR: Crop name %s not recognized!\n", q->cropNameT);
                    exit (1);
                }

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "FRAC_THERMAL_TIME", &q->fractionThermalTime);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "KILL_EFFICIENCY", &q->killEfficiency);

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "GRAIN_HARVEST", &q->grainHarvest);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "FORAGE_HARVEST", &q->forageHarvest);

                q->status = 0;
            }
        }

        cropmgmt->numFertilization = nfert;
        if (nfert > 0)
        {
            cropmgmt->FixedFertilization = (op_struct *)malloc (nfert * sizeof (op_struct));

            /* Rewind to the beginning of file and read all fertilization
             * operations */
            FindLine (op_file, "BOF");

            for (j = 0; j < nfert; j++)
            {
                q = &(cropmgmt->FixedFertilization[j]);

                FindLine (op_file, "FIXED_FERTILIZATION");

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "YEAR", &q->opYear);

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "DOY", &q->opDay);

                NextLine (op_file, cmdstr);
                ReadKeywordStr (cmdstr, "SOURCE", q->opSource);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "MASS", &q->opMass);

                NextLine (op_file, cmdstr);
                ReadKeywordStr (cmdstr, "FORM", q->opForm);

                NextLine (op_file, cmdstr);
                ReadKeywordStr (cmdstr, "METHOD", q->opMethod);

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "LAYER", &q->opLayer);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "C_ORGANIC", &q->opC_Organic);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "C_CHARCOAL", &q->opC_Charcoal);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "N_ORGANIC", &q->opN_Organic);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "N_CHARCOAL", &q->opN_Charcoal);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "N_NH4", &q->opN_NH4);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "N_NO3", &q->opN_NO3);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "P_ORGANIC", &q->opP_Organic);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "P_CHARCOAL", &q->opP_Charcoal);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "P_INORGANIC", &q->opP_Inorganic);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "K", &q->opK);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "S", &q->opS);

                q->status = 0;

                if (q->opC_Organic + q->opC_Charcoal + q->opN_Organic + q->opN_Charcoal + q->opN_NH4 + q->opN_NO3 + q->opP_Organic + q->opP_Charcoal + q->opP_Inorganic + q->opK + q->opS <= 1.0)
                {
                    q->opMass /= 1000.0;
                }
                else
                {
                    printf ("ERROR: Added fertilization fractions must be <= 1\n");
                    exit (1);
                }
            }
        }

        cropmgmt->numIrrigation = nirrg;
        if (nirrg  > 0)
        {
            cropmgmt->FixedIrrigation = (op_struct *)malloc (nirrg * sizeof (op_struct));

            /* Rewind to the beginning of file and read all irrigation
             * operations */
            FindLine (op_file, "BOF");

            for (j = 0; j < nirrg; j++)
            {
                q = &(cropmgmt->FixedIrrigation[j]);

                FindLine (op_file, "FIXED_IRRIGATION");

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "YEAR", &q->opYear);
                
                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "DOY", &q->opDay);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "VOLUME", &q->opVolume);

                q->status = 0;
            }
        }

        cropmgmt->numAutoIrrigation = nautoirrg;
        if (nautoirrg > 0)
        {
            cropmgmt->autoIrrigation = (autoirr_struct *)malloc (nautoirrg * sizeof (autoirr_struct));
            /* Rewind to the beginning of file and read all planting operations */
            FindLine (op_file, "BOF");

            for (j = 0; j < nautoirrg; j++)
            {
                FindLine (op_file, "AUTO_IRRIGATION");

                NextLine (op_file, cmdstr);
                ReadKeywordStr (cmdstr, "CROP", cropmgmt->autoIrrigation[j].cropName);

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "START_DAY", &cropmgmt->autoIrrigation[j].startDay);

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "STOP_DAY", &cropmgmt->autoIrrigation[j].stopDay);

                NextLine (op_file, cmdstr);
                ReadKeywordDouble (cmdstr, "WATER_DEPLETION", &cropmgmt->autoIrrigation[j].waterDepletion);

                NextLine (op_file, cmdstr);
                ReadKeywordInt (cmdstr, "LAST_SOIL_LAYER", &cropmgmt->autoIrrigation[j].lastSoilLayer);
            }
        }

        /* Link plating order and auto irrigation */
        for (j = 0; j < cropmgmt->totalCropsPerRotation; j++)
        {
            if (cropmgmt->usingAutoIrr && cropmgmt->plantingOrder[j].usesAutoIrrigation == 1)
            {
                for (k = 0; k < nautoirrg; k++)
                {
                    if (strcmp (cropmgmt->plantingOrder[j].cropName, cropmgmt->autoIrrigation[k].cropName) == 0)
                    {
                        cropmgmt->plantingOrder[j].usesAutoIrrigation = k;
                        break;
                    }
                }
                if (k >= nautoirrg)
                {
                    printf ("ERROR: Cannot find the description of auto irrigation for %s!\n", cropmgmt->plantingOrder[j].cropName);
                    exit (1);
                }
            }
            else
                cropmgmt->plantingOrder[j].usesAutoIrrigation = -1;
        }

        fclose (op_file);
    }
}