コード例 #1
0
void GraphicsLinesForCurves::print () const
{
  QString text;
  QTextStream str (&text);

  printStream ("", str);
  std::cerr << text.toLatin1().data();
}
コード例 #2
0
FollowStreamDialog::FollowStreamDialog(QWidget &parent, CaptureFile &cf, follow_type_t type) :
    WiresharkDialog(parent, cf),
    ui(new Ui::FollowStreamDialog),
    follow_type_(type),
    truncated_(false),
    save_as_(false)
{
    ui->setupUi(this);

    setAttribute(Qt::WA_DeleteOnClose, true);
    memset(&follow_info_, 0, sizeof(follow_info_));
    follow_info_.show_type = SHOW_ASCII;
    follow_info_.show_stream = BOTH_HOSTS;

    ui->teStreamContent->installEventFilter(this);

    // XXX Use recent settings instead
    resize(parent.width() * 2 / 3, parent.height());

    QComboBox *cbcs = ui->cbCharset;
    cbcs->blockSignals(true);
    cbcs->addItem(tr("ASCII"), SHOW_ASCII);
    cbcs->addItem(tr("C Arrays"), SHOW_CARRAY);
    cbcs->addItem(tr("EBCDIC"), SHOW_EBCDIC);
    cbcs->addItem(tr("Hex Dump"), SHOW_HEXDUMP);
    cbcs->addItem(tr("UTF-8"), SHOW_UTF8);
    cbcs->addItem(tr("YAML"), SHOW_YAML);
    cbcs->addItem(tr("Raw"), SHOW_RAW);
    cbcs->blockSignals(false);

    b_filter_out_ = ui->buttonBox->addButton(tr("Hide this stream"), QDialogButtonBox::ActionRole);
    connect(b_filter_out_, SIGNAL(clicked()), this, SLOT(filterOut()));

    b_print_ = ui->buttonBox->addButton(tr("Print"), QDialogButtonBox::ActionRole);
    connect(b_print_, SIGNAL(clicked()), this, SLOT(printStream()));

    b_save_ = ui->buttonBox->addButton(tr("Save as" UTF8_HORIZONTAL_ELLIPSIS), QDialogButtonBox::ActionRole);
    connect(b_save_, SIGNAL(clicked()), this, SLOT(saveAs()));

    ProgressFrame::addToButtonBox(ui->buttonBox, &parent);

    connect(ui->buttonBox, SIGNAL(helpRequested()), this, SLOT(helpButton()));
    connect(ui->teStreamContent, SIGNAL(mouseMovedToTextCursorPosition(int)),
            this, SLOT(fillHintLabel(int)));
    connect(ui->teStreamContent, SIGNAL(mouseClickedOnTextCursorPosition(int)),
            this, SLOT(goToPacketForTextPos(int)));
    connect(&cap_file_, SIGNAL(captureFileClosing()), this, SLOT(captureFileClosing()));

    fillHintLabel(-1);
}
コード例 #3
0
FollowStreamDialog::FollowStreamDialog(QWidget *parent, follow_type_t type, capture_file *cf) :
    QDialog(parent),
    ui(new Ui::FollowStreamDialog),
    cap_file_(cf),
    follow_type_(type),
    save_as_(false)
{
    ui->setupUi(this);

    setAttribute(Qt::WA_DeleteOnClose, true);
    memset(&follow_info_, 0, sizeof(follow_info_));

    ui->teStreamContent->installEventFilter(this);

    // XXX Use recent settings instead
    if (parent) {
        resize(parent->width() * 2 / 3, parent->height());
    }

    QComboBox *cbcs = ui->cbCharset;
    cbcs->blockSignals(true);
    cbcs->addItem("ASCII", SHOW_ASCII);
    cbcs->addItem("C Arrays", SHOW_CARRAY);
    cbcs->addItem("EBCDIC", SHOW_EBCDIC);
    cbcs->addItem("Hex Dump", SHOW_HEXDUMP);
    cbcs->addItem("UTF-8", SHOW_RAW);
    cbcs->addItem("YAML", SHOW_YAML);
    cbcs->blockSignals(false);

    b_filter_out_ = ui->buttonBox->addButton(tr("Hide this stream"), QDialogButtonBox::ActionRole);
    connect(b_filter_out_, SIGNAL(clicked()), this, SLOT(filterOut()));

    b_print_ = ui->buttonBox->addButton(tr("Print"), QDialogButtonBox::ActionRole);
    connect(b_print_, SIGNAL(clicked()), this, SLOT(printStream()));

    b_save_ = ui->buttonBox->addButton(tr("Save as..."), QDialogButtonBox::ActionRole);
    connect(b_save_, SIGNAL(clicked()), this, SLOT(saveAs()));

    connect(ui->buttonBox, SIGNAL(helpRequested()), this, SLOT(helpButton()));
    connect(ui->teStreamContent, SIGNAL(mouseMovedToTextCursorPosition(int)),
            this, SLOT(fillHintLabel(int)));
    connect(ui->teStreamContent, SIGNAL(mouseClickedOnTextCursorPosition(int)),
            this, SLOT(goToPacketForTextPos(int)));

    fillHintLabel(-1);
}
コード例 #4
0
ファイル: ccforest.cpp プロジェクト: rashadkm/grass_cmake
template<class T> void
ccforest<T>::printEdgeStream() {
  printStream(cout, edgeStream);
}
コード例 #5
0
ファイル: ccforest.cpp プロジェクト: rashadkm/grass_cmake
void
ccforest<T>::printRootStream() {
  findAllRoots();  /* find all the roots if not done */
  printStream(cout, rootStream);
}
コード例 #6
0
ファイル: ccforest.cpp プロジェクト: rashadkm/grass_cmake
void ccforest<T>::findAllRoots(int depth) {
  if(foundAllRoots) return;
  foundAllRoots = 1;
  Rtimer rt;
  rt_start(rt);

  if(depth > 5) {
	cerr << "WARNING: excessive recursion in ccforest (ignored)" << endl;
  }

  int explicitRootCount = 0;
  assert(!superTree);
  superTree = new ccforest<T>();

  if (stats)
    DEBUG_CCFOREST *stats << "sort edgeStream (by cclabel)): ";
  keyCmpKeyvalueType<T> fo;
  sort(&edgeStream, fo); /* XXX -changed this to use a cmp obj  */

  /* time forward processing */
  EMPQueueAdaptive<cckeyvalue,T> *pq =
	new EMPQueueAdaptive<cckeyvalue,T>();	/* parent queue */

  size_t streamLength = edgeStream->stream_len();
  T prevSrc = T(-1);
  T parent = T(-1);
  ccedge prevEdge;
  for(unsigned int i=0; i<streamLength; i++) {
	ccedge *e;
	AMI_err ae = edgeStream->read_item(&e);
	assert(ae == AMI_ERROR_NO_ERROR);

#if(0)
	if (stats) {
	    DEBUG_CCFOREST *stats << "------------------------------" << endl;
	    DEBUG_CCFOREST *stats << "processing edge " << *e << endl;
	}
	DEBUG_CCFOREST pq->print();
#endif

	if(*e == prevEdge) {
	  if (stats)
	    DEBUG_CCFOREST *stats << "\tduplicate " << *e << " removed\n";
	  continue; /* already have this done */
	}
	prevEdge = *e;

	if (stats)
	  DEBUG_CCFOREST *stats << "processing edge " << *e << endl;

	/* find root (assign parent) */
	if(e->src() != prevSrc) {
	  prevSrc = e->src();
	  cckeyvalue kv;
	  /* check if we have a key we don't use. */
	  while(pq->min(kv) && (kv.getPriority() < e->src())) {
		pq->extract_min(kv);
		assert(kv.src() >= kv.dst());
		removeDuplicates(kv.src(), kv.dst(), *pq);
		ae = rootStream->write_item(kv); /* save root */
		assert(ae == AMI_ERROR_NO_ERROR);	
	  }
	  /* try to find our root */
	  if(pq->min(kv) && ((e->src() == kv.getPriority()))) {
		pq->extract_min(kv);
		parent = kv.getValue();
		removeDuplicates(e->src(), parent, *pq);
	  } else {
		parent = e->src();		/* we are root */
		explicitRootCount++;
		/* technically, we could skip this part. the lookup function
           automatically assumes that values without parents are roots */
	  }

	  /* save result */
	  cckeyvalue kroot(e->src(), parent);
	  assert(kroot.src() >= kroot.dst());
	  ae = rootStream->write_item(kroot);
	  assert(ae == AMI_ERROR_NO_ERROR);
	}
#ifndef NDEBUG
	cckeyvalue kv2;
	assert(pq->is_empty() || (pq->min(kv2) && kv2.getPriority() > e->src()));
#endif

	/* insert */
	cckeyvalue kv(e->dst(), parent);
	assert(kv.src() >= kv.dst());
	pq->insert(kv);

	/* cout << "identified: " << kroot << endl; */
  }

  /* drain the priority queue */
  if (stats)
    DEBUG_CCFOREST *stats << "draining priority queue" << endl;
  while (!pq->is_empty()) {
	cckeyvalue kv;
	pq->extract_min(kv);
	assert(kv.src() >= kv.dst());
	if (stats)
	  DEBUG_CCFOREST *stats << "processing edge " << kv << endl;

	removeDuplicates(kv.src(), kv.dst(), *pq);
	AMI_err ae = rootStream->write_item(kv);
	assert(ae == AMI_ERROR_NO_ERROR);
  }
  delete pq;

  /* note that rootStream is naturally ordered by src */

  if(superTree->size()) {
        if (stats) {
	    DEBUG_CCFOREST *stats << "resolving cycles..." << endl;
	    /* printStream(rootStream); */
	    DEBUG_CCFOREST *stats << "sort rootStream: ";
        }

	AMI_STREAM<cckeyvalue> *sortedRootStream; 
	dstCmpKeyvalueType<T> dstfo;
	sortedRootStream = sort(rootStream, dstfo); 
	/* XXX replaced this to use a cmp object -- laura
	   AMI_STREAM<cckeyvalue>*sortedRootStream=new AMI_STREAM<cckeyvalue>();
	   AMI_err ae = AMI_sort(rootStream, sortedRootStream, valueCmp); 
	   assert(ae == AMI_ERROR_NO_ERROR);
	*/
	delete rootStream;

	cckeyvalue *kv;
	T parent;
	AMI_err ae;
	
	AMI_STREAM<cckeyvalue>* relabeledRootStream
	  = new AMI_STREAM<cckeyvalue>();
	ae = sortedRootStream->seek(0);
	superTree->findAllRoots(depth+1);
	while((ae = sortedRootStream->read_item(&kv)) == AMI_ERROR_NO_ERROR) {
	  parent = superTree->findNextRoot(kv->dst());
	  ae = relabeledRootStream->write_item(cckeyvalue(kv->src(), parent));
	  assert(ae == AMI_ERROR_NO_ERROR);
	}
	delete sortedRootStream;

        if (stats)
	    DEBUG_CCFOREST *stats << "sort relabeledRootStream: ";
	rootStream = sort(relabeledRootStream, fo);
	/* laura: changed  this
	   rootStream = new AMI_STREAM<cckeyvalue>();
	   ae = AMI_sort(relabeledRootStream, rootStream);
	   assert(ae == AMI_ERROR_NO_ERROR);
	*/
	delete relabeledRootStream;

        if (stats)
	    DEBUG_CCFOREST *stats << "resolving cycles... done." << endl;
  }
  rootStream->seek(0);

  if (stats){
    DEBUG_CCFOREST *stats << "Rootstream length="
					  << rootStream->stream_len() << endl;
    DEBUG_CCFOREST printStream(*stats, rootStream);
    DEBUG_CCFOREST *stats << "Explicit root count=" << explicitRootCount << endl;
  }

  rt_stop(rt);
  if (stats)
    stats->recordTime("ccforest::findAllRoots",  (long int)rt_seconds(rt));
}
コード例 #7
0
FollowStreamDialog::FollowStreamDialog(QWidget &parent, CaptureFile &cf, follow_type_t type) :
    WiresharkDialog(parent, cf),
    ui(new Ui::FollowStreamDialog),
    b_find_(NULL),
    follow_type_(type),
    follower_(NULL),
    show_type_(SHOW_ASCII),
    truncated_(false),
    client_buffer_count_(0),
    server_buffer_count_(0),
    client_packet_count_(0),
    server_packet_count_(0),
    last_packet_(0),
    last_from_server_(0),
    turns_(0),
    save_as_(false),
    use_regex_find_(false),
    terminating_(false)
{
    ui->setupUi(this);
    loadGeometry(parent.width() * 2 / 3, parent.height());

    switch(type)
    {
    case FOLLOW_TCP:
        follower_ = get_follow_by_name("TCP");
        break;
    case FOLLOW_SSL:
        follower_ = get_follow_by_name("SSL");
        break;
    case FOLLOW_UDP:
        follower_ = get_follow_by_name("UDP");
        break;
    case FOLLOW_HTTP:
        follower_ = get_follow_by_name("HTTP");
        break;
    default :
        g_assert_not_reached();
    }

    memset(&follow_info_, 0, sizeof(follow_info_));
    follow_info_.show_stream = BOTH_HOSTS;

    ui->teStreamContent->installEventFilter(this);

    connect(ui->leFind, SIGNAL(useRegexFind(bool)), this, SLOT(useRegexFind(bool)));

    QComboBox *cbcs = ui->cbCharset;
    cbcs->blockSignals(true);
    cbcs->addItem(tr("ASCII"), SHOW_ASCII);
    cbcs->addItem(tr("C Arrays"), SHOW_CARRAY);
    cbcs->addItem(tr("EBCDIC"), SHOW_EBCDIC);
    cbcs->addItem(tr("Hex Dump"), SHOW_HEXDUMP);
    cbcs->addItem(tr("UTF-8"), SHOW_UTF8);
    cbcs->addItem(tr("UTF-16"), SHOW_UTF16);
    cbcs->addItem(tr("YAML"), SHOW_YAML);
    cbcs->addItem(tr("Raw"), SHOW_RAW);
    cbcs->blockSignals(false);

    b_filter_out_ = ui->buttonBox->addButton(tr("Filter Out This Stream"), QDialogButtonBox::ActionRole);
    connect(b_filter_out_, SIGNAL(clicked()), this, SLOT(filterOut()));

    b_print_ = ui->buttonBox->addButton(tr("Print"), QDialogButtonBox::ActionRole);
    connect(b_print_, SIGNAL(clicked()), this, SLOT(printStream()));

    b_save_ = ui->buttonBox->addButton(tr("Save as" UTF8_HORIZONTAL_ELLIPSIS), QDialogButtonBox::ActionRole);
    connect(b_save_, SIGNAL(clicked()), this, SLOT(saveAs()));

    b_back_ = ui->buttonBox->addButton(tr("Back"), QDialogButtonBox::ActionRole);
    connect(b_back_, SIGNAL(clicked()), this, SLOT(backButton()));

    ProgressFrame::addToButtonBox(ui->buttonBox, &parent);

    connect(ui->buttonBox, SIGNAL(helpRequested()), this, SLOT(helpButton()));
    connect(ui->teStreamContent, SIGNAL(mouseMovedToTextCursorPosition(int)),
            this, SLOT(fillHintLabel(int)));
    connect(ui->teStreamContent, SIGNAL(mouseClickedOnTextCursorPosition(int)),
            this, SLOT(goToPacketForTextPos(int)));
    connect(&cap_file_, SIGNAL(captureEvent(CaptureEvent *)),
            this, SLOT(captureEvent(CaptureEvent *)));

    fillHintLabel(-1);
}
コード例 #8
0
ファイル: cst.c プロジェクト: diversoft/RHESSys
int main(int argc, char *argv[])
{

    /* Constants.
       If no command line argument is provided that specifies a raster map for
       these values, then use the constant value for the entire mapset.
     */
    float ManningsN         = 0.05;
    float streamTopWidth    = 1.0;
    float streamBottomWidth = 1.0;
    float streamDepth       = 1.0;

    /* local variable declarations */
    bool done = false;
    bool printed;
    char *pEnd;
    char *endPtr;
    double demValue;
    double distance;
    float inVal;
    int basinMaskValue;
    int	i;
    int j;
    int k;
    int index;
    int maxr, maxc;
    int row, col;
    int streamCnt = 0;
    int streamId;
    struct Cell_head basin_header;
    struct Cell_head dem_header;
    struct Cell_head hill_header;
    struct Cell_head ManningsN_header;
    struct Cell_head patch_header;
    struct Cell_head stream_header;
    struct Cell_head streamTopWidth_header;
    struct Cell_head streamBottomWidth_header;
    struct Cell_head streamDepth_header;
    struct Cell_head zone_header;

    streamEntry *nStreamPtr = NULL;
    streamEntry *streamEntryPtr = NULL;

    /* filenames for each image and file */
    char  name[MAXS], name2[MAXS];
    char* rnhill;
    char* rnzone;
    char* rnpatch;
    char* rndem;
    char* rnstream;
    char* rnbasin;
    char* rnManningsN;
    char* rnStreamTopWidth;
    char* rnStreamBottomWidth;
    char* rnStreamDepth;
    char* tmpStr;

    /* set pointers for images */

    double *dem;
    int    *patch;
    int    *hill;
    int    *zone;
    int	   *stream;
    int	   *basin;
    int    iPass;
    int    maxPasses;
    float  *slope;
    float  *ManningsN_map = NULL;
    float  *streamDepth_map = NULL;
    float  *streamTopWidth_map = NULL;
    float  *streamBottomWidth_map = NULL;

    // GRASS init
    G_gisinit(argv[0]);

    // GRASS module header
    struct GModule* module;
    module = G_define_module();
    module->keywords = "RHESSys";
    module->description = "Creates a stream table file for input into RHESSys";

    // GRASS arguments
    struct Option* output_name_opt = G_define_option();
    output_name_opt->key = "output";
    output_name_opt->type = TYPE_STRING;
    output_name_opt->required = YES;
    output_name_opt->description = "Output name";

    struct Option* stream_raster_opt = G_define_option();
    stream_raster_opt->key = "stream";
    stream_raster_opt->type = TYPE_STRING;
    stream_raster_opt->required = YES;
    stream_raster_opt->description = "stream";

    struct Option* dem_raster_opt = G_define_option();
    dem_raster_opt->key = "dem";
    dem_raster_opt->type = TYPE_STRING;
    dem_raster_opt->required = YES;
    dem_raster_opt->description = "dem";

    struct Option* patch_raster_opt = G_define_option();
    patch_raster_opt->key = "patch";
    patch_raster_opt->type = TYPE_STRING;
    patch_raster_opt->required = YES;
    patch_raster_opt->description = "patch";

    struct Option* zone_raster_opt = G_define_option();
    zone_raster_opt->key = "zone";
    zone_raster_opt->type = TYPE_STRING;
    zone_raster_opt->required = YES;
    zone_raster_opt->description = "zone";

    struct Option* hill_raster_opt = G_define_option();
    hill_raster_opt->key = "hill";
    hill_raster_opt->type = TYPE_STRING;
    hill_raster_opt->required = YES;
    hill_raster_opt->description = "hill";

    struct Option* basin_raster_opt = G_define_option();
    basin_raster_opt->key = "basin";
    basin_raster_opt->type = TYPE_STRING;
    basin_raster_opt->required = NO;
    basin_raster_opt->description = "basin";

    struct Option* ManningsN_raster_opt = G_define_option();
    ManningsN_raster_opt->key = "ManningsN";
    ManningsN_raster_opt->type = TYPE_STRING;
    ManningsN_raster_opt->required = NO;
    ManningsN_raster_opt->description = "ManningsN";

    struct Option* streamTopWidth_raster_opt = G_define_option();
    streamTopWidth_raster_opt->key = "streamTopWidth";
    streamTopWidth_raster_opt->type = TYPE_STRING;
    streamTopWidth_raster_opt->required = NO;
    streamTopWidth_raster_opt->description = "streamTopWidth";

    struct Option* streamBottomWidth_raster_opt = G_define_option();
    streamBottomWidth_raster_opt->key = "streamBottomWidth";
    streamBottomWidth_raster_opt->type = TYPE_STRING;
    streamBottomWidth_raster_opt->required = NO;
    streamBottomWidth_raster_opt->description = "streamBottomWidth";

    struct Option* streamDepth_raster_opt = G_define_option();
    streamDepth_raster_opt->key = "streamDepth";
    streamDepth_raster_opt->type = TYPE_STRING;
    streamDepth_raster_opt->required = NO;
    streamDepth_raster_opt->description = "streamDepth";

    /* Max passes to make through the list of streams in order to determine downstream reaches. */
    struct Option* maxPasses_opt = G_define_option();
    maxPasses_opt->key = "maxPasses";
    maxPasses_opt->type = TYPE_INTEGER;
    maxPasses_opt->required = NO;
    maxPasses_opt->description = "maxPasses";

    /* Note that coor->answer is not given a default value. */
    struct Flag* verbose_flag  = G_define_flag();
    verbose_flag ->key = 'v';
    verbose_flag ->description = "print verbose information";

    struct Flag* debug_flag  = G_define_flag();
    debug_flag ->key = 'd';
    debug_flag ->description = "print debug info";

    // Parse GRASS arguments
    if (G_parser(argc, argv))
        exit(1);

    // Get values from GRASS arguments
    // Name for output files
    rndem    = dem_raster_opt->answer;
    rnpatch  = patch_raster_opt->answer;
    rnzone   = zone_raster_opt->answer;
    rnhill   = hill_raster_opt->answer;
    rnstream = stream_raster_opt->answer;
    rnbasin  = basin_raster_opt->answer;

    // For the arguments streamTopWidth, streamBottomWidth, streamDepth, ManningsN,
    // either a constant value or a map name can be specified. If a constant value (a float)
    // is specified, then this value will be used for every cell in the map. If a mapname is
    // specified, then values from the map will be used.

    rnManningsN = ManningsN_raster_opt->answer;
    rnStreamTopWidth = streamTopWidth_raster_opt->answer;
    rnStreamBottomWidth = streamBottomWidth_raster_opt->answer;
    rnStreamDepth = streamDepth_raster_opt->answer;
    tmpStr = maxPasses_opt->answer;
    debug = debug_flag->answer;
    verbose = verbose_flag->answer;

    if (tmpStr == NULL) {
    	maxPasses = 1;
    } else {
    	maxPasses = atoi(tmpStr);
    }
    if (maxPasses == 0)
        maxPasses = 1;
       printf("Max passes: %d\n", maxPasses);
        printf("Max passes: %d\n", maxPasses);

    if (verbose)
        printf("Max passes: %d\n", maxPasses);

    if (rnbasin != NULL) {
        basin = (int*)raster2array(rnbasin, &basin_header, NULL, NULL, CELL_TYPE);
    }

    /* ManningsN can be specified on the command line as either a raster map name or a
       constant value.
     */

    if (rnManningsN != NULL) {
        inVal = strtof(rnManningsN, &pEnd);
        if (pEnd != rnManningsN) {
            ManningsN = inVal;
            if (verbose)
                printf("Using constant value from command line for ManningsN: %7.3f\n", ManningsN);
        } else {
            if (verbose)
                printf("Using map for ManningsN: %s\n", rnManningsN);
            ManningsN_map = (float*)raster2array(rnManningsN, &ManningsN_header, NULL, NULL, FCELL_TYPE);
        }
    }

    if (rnStreamTopWidth != NULL) {
        inVal = strtof(rnStreamTopWidth, &pEnd);
        if (pEnd != rnStreamTopWidth) {
            streamTopWidth = inVal;
            if (verbose)
                printf("Using constant value from command line for stream top width: %7.3f\n", streamTopWidth);
        } else {
            if (verbose)
                printf("Using map for top width: %s\n", rnStreamTopWidth);
            streamTopWidth_map = (float*)raster2array(rnStreamTopWidth, &streamTopWidth_header, NULL, NULL, FCELL_TYPE);
        }
    }

    if (rnStreamBottomWidth != NULL) {
        inVal = strtof(rnStreamBottomWidth, &pEnd);
        if (pEnd != rnStreamBottomWidth) {
            streamBottomWidth = inVal;
            if (verbose)
                printf("Using constant value from command line for stream bottom width: %7.3f\n", streamBottomWidth);
        } else {
            if (verbose)
                printf("Using map for bottom width: %s\n", rnStreamBottomWidth);
            streamBottomWidth_map = (float*)raster2array(rnStreamBottomWidth, &streamBottomWidth_header, NULL, NULL, FCELL_TYPE);
        }
    }

    if (rnStreamDepth != NULL) {
        inVal = strtof(rnStreamDepth, &pEnd);
        if (pEnd != rnStreamDepth) {
            streamDepth = inVal;
            if (verbose)
                printf("Using constant value from command line for stream depth: %7.3f\n", streamDepth);
        } else {
            if (verbose)
                printf("Using map for stream depth: %s\n", rnStreamDepth);
            streamDepth_map = (float*)raster2array(rnStreamDepth, &streamDepth_header, NULL, NULL, FCELL_TYPE);
        }
    }

    //printf("Reading input data for %s...\n\n", rndem);

    dem = (double*)raster2array(rndem, &dem_header, NULL, NULL, DCELL_TYPE);
    hill = (int*)raster2array(rnhill, &hill_header, NULL, NULL, CELL_TYPE);
    patch = (int*)raster2array(rnpatch, &patch_header, NULL, NULL, CELL_TYPE);
    stream = (int*)raster2array(rnstream, &stream_header, &maxr, &maxc, CELL_TYPE);
    zone = (int*)raster2array(rnzone, &zone_header, NULL, NULL, CELL_TYPE);

    //cellResolution = (dem_header.ew_res + dem_header.ns_res)/2.0;
    cellResolution = dem_header.ew_res;
    if (verbose)
        printf("DEM raster cell resolution: %7.2f\n", cellResolution);


    if (verbose) {
        printf("maxr: %d\n", maxr);
        printf("maxc: %d\n", maxc);
        printf("Cataloging streams...\n");
    }

    streamEntry *newStreamPtr = NULL;

    /* Loop though the stream raster map and collect info on each stream reach that is found.
       Only include stream reaches that are within the basin boundaries.
     */

    for (row = 0; row < maxr; ++row) {
        for (col = 0; col < maxc; ++col) {
            index = col + row*maxc;

            /* If a basin name was provided on the command line, only process cells within the basin. */
            if (rnbasin != NULL) {
                basinMaskValue = basin[index];
                if ((basinMaskValue == -2147483648) || (basinMaskValue == 0))
                    continue;
            }

            //streamId = ((int*)stream)[index];
            streamId = stream[index];
            if (streamId != -2147483648) {
                //printf("streamid: %i\n", streamId);
                newStreamPtr = findStreamEntry(streamId, &streamEntryPtr, &streamCnt);
                newStreamPtr->pixelCount = newStreamPtr->pixelCount + 1;

                addBasinDivision(newStreamPtr, index, zone, hill, patch);

                // Adding .5 to col, row causes position of center of cell to be returned.
                //xPos = G_col_to_easting((double) col + .5, &stream_header);
                //yPos = G_row_to_northing((double) row + .5, &stream_header);
                //printf("streamId: %d, xPos: %7.2f, yPos: %7.2f\n", streamId, xPos, yPos);

                demValue = dem[index];
                //printf("height: %6.2f\n", demValue);

                // Set max height if this DEM value is higher than current max.
                if (demValue > newStreamPtr->maxElevation) {
                    newStreamPtr->maxElevation = demValue;
                }

                // Set min height if this DEM value is lower than current min.
                if (demValue < newStreamPtr->minElevation) {
                    newStreamPtr->minElevation = demValue;
                }

                if (ManningsN_map != NULL) {
                    newStreamPtr->ManningsN += ManningsN_map[index];
                }

                if (streamTopWidth_map != NULL) {
                    newStreamPtr->streamTopWidth += streamTopWidth_map[index];
                }

                if (streamBottomWidth_map != NULL) {
                    newStreamPtr->streamBottomWidth += streamBottomWidth_map[index];
                }

                if (streamDepth_map != NULL) {
                    newStreamPtr->streamDepth += streamDepth_map[index];
                }
            }
        }
    }

    if (verbose)
        printf("Searching for stream intersections...\n");

    streamEntry *currentStreamPtr;
    streamEntry *adjacentStreamPtr;
    int nRow, nCol;
    int patchCnt = 0;
    bool relaxedRules;

    /* Loop though the raster map, and look for stream intersections, on this pass determining only
       the downstream intersections from the current raster cell.
     */
    for (row = 0; row < maxr; ++row) {
        for (col = 0; col < maxc; ++col) {
            index = col + row*maxc;

            /* If a basin name was provided on the command line, only process cells within the basin. */
            if (rnbasin != NULL) {
                basinMaskValue = basin[index];
                if ((basinMaskValue == -2147483648) || (basinMaskValue == 0))
                    continue;
            }

            streamId = ((int*)stream)[index];
            patchCnt += 1;
            if (streamId != -2147483648) {
                currentStreamPtr = findStreamEntry(streamId, &streamEntryPtr, &streamCnt);
                if (debug)
                    printf("Checking intersections for stream %d, min elev: %f, max elev: %f\n", streamId, currentStreamPtr->minElevation, currentStreamPtr->maxElevation);

                /* Check adjacent cells (8) of current raster cell and check for stream intersections, i.e.

                        A  A  A
                        A  C  A
                        A  A  A

                   where 'C' is the current raster cell and 'A' is an adjacent cell.
                */

                /* We are searching for an intersection of the current raster cell with a downstream reach, and may find one before
                   all eight adjacent pixels are checked. We are going to check all eight however, because there may be multiple
                   intersecting downstream reaches, and we will select the lowest one.
                 */

                relaxedRules = false;
                /* Check upper left adjacent cell */
                checkStreamIntxns(currentStreamPtr, streamId, row + 1, col - 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);

                /* Check upper center adjacent cell */
                checkStreamIntxns(currentStreamPtr, streamId, row + 1, col,     maxc, streamEntryPtr, streamCnt, stream, relaxedRules);

                /* Check upper right adjacent cell */
                checkStreamIntxns(currentStreamPtr, streamId, row + 1, col + 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);

                /* Check center right adjacent cell */
                checkStreamIntxns(currentStreamPtr, streamId, row,     col + 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);

                /* Check lower right adjacent cell */
                checkStreamIntxns(currentStreamPtr, streamId, row - 1, col + 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);

                /* Check lower center adjacent cell */
                checkStreamIntxns(currentStreamPtr, streamId, row - 1, col,     maxc, streamEntryPtr, streamCnt, stream, relaxedRules);

                /* Check lower left adjacent cell */
                checkStreamIntxns(currentStreamPtr, streamId, row - 1, col - 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);

                /* Check center left adjacent cell */
                checkStreamIntxns(currentStreamPtr, streamId, row,     col - 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);
            }
        }
    }

    /* Loop through streams, assign stream wide values */
    for (i = 0; i < streamCnt ; i++) {
        currentStreamPtr = streamEntryPtr + i;
        if (debug)
            printf("high: %f, low: %f\n", currentStreamPtr->maxElevation, currentStreamPtr->minElevation);

        //G_begin_distance_calculations();

        //distance = G_distance(currentStreamPtr->headXpos, currentStreamPtr->headYpos, currentStreamPtr->outletXpos, currentStreamPtr->outletYpos);

        // If the stream only contains one or two pixels, distance will be calculated to be 0.0.
        // If this is the case, then artificially set distance to the cell resolution, the width of one pixel.
        if (distance == 0.0 && currentStreamPtr->pixelCount == 2)
            distance = cellResolution;
        else
            distance = currentStreamPtr->pixelCount * cellResolution;

        // As of 6/4 we are calculating slope simply as ((max. elev. - min. elevation) / number of pixels in the stream reach).
        if (currentStreamPtr->maxElevation == currentStreamPtr->minElevation) {
            currentStreamPtr->slope = 0;
        } else {
            // Calculate slope: m = (y2 - y1)/(x2 - x1)
            currentStreamPtr->slope = (currentStreamPtr->maxElevation - currentStreamPtr->minElevation) / distance;
        }

        /* Calculate mean ManningsN */
        if (ManningsN_map != NULL) {
            currentStreamPtr->ManningsN = currentStreamPtr->ManningsN / currentStreamPtr->pixelCount;
        } else {
            currentStreamPtr->ManningsN = ManningsN;
        }

        /* Calculate mean stream top width */
        if (streamTopWidth_map != NULL) {
            currentStreamPtr->streamTopWidth = currentStreamPtr->streamTopWidth / currentStreamPtr->pixelCount;
        } else {
            currentStreamPtr->streamTopWidth = streamTopWidth;
        }

        /* Calculate mean stream bottom width */
        if (streamBottomWidth_map != NULL) {
            currentStreamPtr->streamBottomWidth = currentStreamPtr->streamBottomWidth / currentStreamPtr->pixelCount;
        } else {
            currentStreamPtr->streamBottomWidth = streamBottomWidth;
        }

        /* Calculate mean stream depth */
        if (streamDepth_map  != NULL) {
            currentStreamPtr->streamDepth = currentStreamPtr->streamDepth / currentStreamPtr->pixelCount;
        } else {
            currentStreamPtr->streamDepth = streamDepth;
        }
    }

    relaxedRules = true;
    for (iPass = 1; iPass <= maxPasses; iPass++) {
        if (debug)
            printf("pass: %d\n", iPass);
        int noDownstreamReach = 0;
        for (i = 0; i < streamCnt ; i++) {
            currentStreamPtr = streamEntryPtr + i;
            if (currentStreamPtr->downstreamReach.streamId == -1)
                noDownstreamReach++;
        }

        // There should always be at least one stream that is the outlet to the basin.
        if (noDownstreamReach == 1)
            break;

        if (debug)
            printf("%d streams have no outlet.\n", noDownstreamReach);

        for (row = 0; row < maxr; ++row) {
            for (col = 0; col < maxc; ++col) {
                index = col + row*maxc;

                /* If a basin name was provided on the command line, only process cells within the basin. */
                if (rnbasin != NULL) {
                    basinMaskValue = basin[index];
                    if (basinMaskValue == -2147483648)
                        continue;
                }

                streamId = stream[index];

                if (streamId != -2147483648) {
                    currentStreamPtr = findStreamEntry(streamId, &streamEntryPtr, &streamCnt);
                    if (currentStreamPtr->downstreamReach.streamId == -1) {
                        if (debug)
                            printf("Rechecking stream %d, min elev: %f, max elev: %f\n", streamId, currentStreamPtr->minElevation, currentStreamPtr->maxElevation);
                        checkStreamIntxns(currentStreamPtr, streamId, row + 1, col - 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);
                        checkStreamIntxns(currentStreamPtr, streamId, row + 1, col,     maxc, streamEntryPtr, streamCnt, stream, relaxedRules);
                        checkStreamIntxns(currentStreamPtr, streamId, row + 1, col + 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);
                        checkStreamIntxns(currentStreamPtr, streamId, row,     col + 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);
                        checkStreamIntxns(currentStreamPtr, streamId, row - 1, col + 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);
                        checkStreamIntxns(currentStreamPtr, streamId, row - 1, col,     maxc, streamEntryPtr, streamCnt, stream, relaxedRules);
                        checkStreamIntxns(currentStreamPtr, streamId, row - 1, col - 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);
                        checkStreamIntxns(currentStreamPtr, streamId, row,     col - 1, maxc, streamEntryPtr, streamCnt, stream, relaxedRules);
                    }
                }
            }
        }
    }

    int noDownstreamReach = 0;
    for (i = 0; i < streamCnt ; i++) {
        currentStreamPtr = streamEntryPtr + i;
        if (currentStreamPtr->downstreamReach.streamId == -1)
            noDownstreamReach++;
    }

    if (verbose)
        printf("Final count of stream reaches without an outlet: %d\n", noDownstreamReach);

    /* Now that all possible downstream reaches have been defined, we must make another pass through the stream array in
       order to determine all the upstream reaches, simply by check where the downstream reaches have been assigned
       and reverse mapping upstream reaches accordingly. Remember that we have only assigned one downstream reach to each
       reach, bu may assign multiple upstream reaches to each reach.
    */

    streamEntry *downstreamPtr = NULL;
    int downstreamId;

    //printf("Assigning upstream reaches\n");
    for (i = 0; i < streamCnt ; i++) {
        currentStreamPtr = streamEntryPtr + i;
        streamId = currentStreamPtr->streamId;
        row = currentStreamPtr->downstreamReach.row;
        col = currentStreamPtr->downstreamReach.col;

        // Print stream info for debugging purposes
        //printf("%d, %7.2f, %7.2f\n", streamId, currentStreamPtr->minElevation, currentStreamPtr->maxElevation);

        downstreamId = currentStreamPtr->downstreamReach.streamId;
        /* There still may be reaches that are not connected to any other stream. */
        if (downstreamId == -1)
            continue;

        /* Find the the stream reach entry that is downstream from the current stream. */
        downstreamPtr = findStreamEntry(downstreamId, &streamEntryPtr, &streamCnt);

        /* Now add the current stream as an upstream entry to the downstream reaches' entry */
        //printf("Checking stream %d for downstreamId %d\n", streamId, downstreamId);
        addUpstreamIntxn(downstreamPtr, currentStreamPtr, row, col);
    }

    /* Loop through all streams and print info out to a file */
    FILE *streamOutFile = fopen(output_name_opt->answer, "w");
    if (verbose)
        printf("Writing out file %s\n", output_name_opt->answer);

    fprintf(streamOutFile, "%i\n", streamCnt);
    //fprintf(streamOutFile, "%i\n", patchCnt);
    streamEntry *highestStreamPtr;

    /* The streams are printed out highest elevation to lowest. */
    while (done != true) {

        highestStreamPtr = findHighestStream(&streamEntryPtr, &streamCnt);

        if (highestStreamPtr == NULL) {
            break;
        }

        // Print stream info to output file specified on the command line.
        printed = printStream(highestStreamPtr, streamOutFile, &streamEntryPtr, &streamCnt);

        if (printed != true) {
            break;
        }

    }

    fclose(streamOutFile);
    if (verbose)
        printf("Program %s Done\n", argv[0]);

    return EXIT_SUCCESS;

    /* end cst.c */
}