void GSetForkFailureOptionMsgCommand::Execute() throw (GException) {
    LOG_LEVEL4("Execute()");

    std::auto_ptr<GResponseMsgData> poResponse(CreateInitializedResponse(GSetForkFailureOptionMsgDataXML::CXMLTag, GMsgCmdDataFactory::CInterfaceVersion));

    try {
        GSetForkFailureOptionMsgData * pRequestData(static_cast<GSetForkFailureOptionMsgData *> (m_pData));
        if (pRequestData == NULL) {
            throw GEXCEPTION("Null pointer for GSetForkFailureOptionMsgData *pRequestData");
        }
        pRequestData->Validate();

        // Set up our data to return over the XML message back to the CRIND
        // In this case it's a simple success or failure that the Fork Failure Option
        // sent was valid and that we were able to store it in the config file.
        if (GMediaManagerFactory::IsAValidForkFailureOption(pRequestData->GetType()) && SETCONF_TO_FILESYSTEM(eDisplayManagerMediaManagerForkFailedRestart, pRequestData->GetType())) {
            poResponse->SetResponseCode(GResponseMsgData::eOk);
        } else {
            poResponse->SetResponseCode(GResponseMsgData::eInvalidForkFailureOption);
        }
    } catch (GException& e) {
        LOG_LEVEL1(QString("Exception: ") + e.GetMessage());

        poResponse->SetResponseCode(GResponseMsgData::eInvalidForkFailureOption);
    }

    SetResponseNamespace(poResponse);
    m_pResponse = poResponse.release();
}
void GDownloadGraphicMsgCommand::Execute() throw(GException)
{
	LOG_LEVEL4("Execute()");

	std::auto_ptr<GResponseMsgData> poResponse(new GResponseMsgData());
	if (poResponse.get() == NULL)
	{
		QString strExMsg("Error creating response message for ");
		strExMsg += GDownloadGraphicMsgDataXML::CXMLTag;
		strExMsg += " message.";
		throw GEXCEPTION(strExMsg);
	}

	poResponse->SetInterfaceVersion(GMsgCmdDataFactory::CInterfaceVersion);
	poResponse->SetCommand(GDownloadGraphicMsgDataXML::CXMLTag);
	poResponse->SetResponseCode(GResponseMsgData::eOk);

	{
		GAbsMsgData * pRequestData(static_cast<GAbsMsgData *>(m_pData));
		if (pRequestData != NULL)
		{
			poResponse->SetNamespacePrefix(pRequestData->GetNamespacePrefix());
			poResponse->SetNamespaceURI(pRequestData->GetNamespaceURI());
		}
	}

	m_pResponse = poResponse.release();
}
Пример #3
0
int GColorPalette::GetRed(int iRegister) throw(GException)
{
	if(iRegister < CFirstRegister || iRegister > CLastRegister)	
	{
		throw GEXCEPTION(QString("Invalid Register"));
	}
	return m_aryColors[iRegister - 1]->GetRed();
}
Пример #4
0
int CombineGadget::
process( GadgetContainerMessage<ISMRMRD::ImageHeader>* m1,
	 GadgetContainerMessage< hoNDArray< std::complex<float> > >* m2)
{

  // Get the dimensions
  size_t nx = m2->getObjectPtr()->get_size(0);
  size_t ny = m2->getObjectPtr()->get_size(1);
  size_t nz = m2->getObjectPtr()->get_size(2);
  size_t nc = m2->getObjectPtr()->get_size(3);

  // Create a new message with an hoNDArray for the combined image
  GadgetContainerMessage< hoNDArray<std::complex<float> > >* m3 = 
    new GadgetContainerMessage< hoNDArray<std::complex<float> > >();

  std::vector<size_t> dimensions(3);
  dimensions[0] = nx;
  dimensions[1] = ny; 
  dimensions[2] = nz;

  try{m3->getObjectPtr()->create(&dimensions);}
  catch (std::runtime_error &err){
  	GEXCEPTION(err,"CombineGadget, failed to allocate new array\n");
    return -1;
  }

  std::complex<float>* d1 = m2->getObjectPtr()->get_data_ptr();
  std::complex<float>* d2 = m3->getObjectPtr()->get_data_ptr();

  size_t img_block = nx*ny*nz;

  for (size_t z = 0; z < nz; z++) {
    for (size_t y = 0; y < ny; y++) {
      for (size_t x = 0; x < nx; x++) {
	float mag = 0;
	float phase = 0;
	size_t offset = z*ny*nx+y*nx+x;
	for (size_t c = 0; c < nc; c++) {
	  float mag_tmp = norm(d1[offset + c*img_block]);
	  phase += mag_tmp*arg(d1[offset + c*img_block]);
	  mag += mag_tmp;
	}
	d2[offset] = std::polar(std::sqrt(mag),phase);
      }
    }
  }

  // Modify header to match the size and change the type to real
  m1->getObjectPtr()->channels = 1;

  // Now add the new array to the outgoing message
  m1->cont(m3);

  // Release the old data
  m2->release();

  return this->next()->putq(m1);
}
Пример #5
0
void GColorPalette::SetColor(int iReg, int iRed, int iGreen, int iBlue)  throw(GException)
{
	if(iReg < CFirstRegister || iReg > CLastRegister)	
	{
		throw GEXCEPTION(QString("Invalid Register"));
	}	
	
	m_aryColors[iReg - 1]->SetRed(iRed);
	m_aryColors[iReg - 1]->SetGreen(iGreen);
	m_aryColors[iReg - 1]->SetBlue(iBlue);
}
void GSetPersonalityMsgCommand::Execute() throw(GException)
{
	LOG_LEVEL4("Execute()");
	
	std::auto_ptr<GResponseMsgData> poResponse(CreateInitializedResponse(GSetPersonalityMsgDataXML::CXMLTag, GMsgCmdDataFactory::CInterfaceVersion));
	
	try
	{
		GSetPersonalityMsgData *pRequestData(static_cast<GSetPersonalityMsgData *>(m_pData));
		if( pRequestData == NULL )
		{
			throw GEXCEPTION("Null pointer for GSetPersonalityMsgData *pRequestData");
		}
		pRequestData->Validate();

		QString strPersonality("");
		static QString const qsDefaultPersonality("default");

		if( pRequestData->GetPersonality() == qsDefaultPersonality )
		{
			strPersonality = GETCONF_STR_FROM_FILESYSTEM(eDisplayManagerPersonalityName);
		}
		else if( GPersonality::IsAValidPersonality(pRequestData->GetPersonality()) )
		{
			strPersonality = pRequestData->GetPersonality();
		}

		if( (!strPersonality.isEmpty()) && (SETCONF(eDisplayManagerPersonalityName, strPersonality)) )
		{
			poResponse->SetResponseCode(GResponseMsgData::eOk);

			QSharedPointer<GPersonalityView> pGPersonalityView = GPersonalityView::GetInstance();

			pGPersonalityView->RefreshPersonality();
		}
		else
		{
			poResponse->SetResponseCode(GResponseMsgData::eInvalidPersonality);
		}
	}
	catch( GException& e )
	{
		LOG_LEVEL1(QString("Excepcion: ")+e.GetMessage());

		poResponse->SetResponseCode(GResponseMsgData::eInvalidPersonality);
	}

	SetResponseNamespace(poResponse);
	m_pResponse=poResponse.release();
}
void GGdiDrawTextMsgCommand::Execute() throw(GException)
{
	LOG_LEVEL3("Execute()");
	
	std::auto_ptr<GResponseMsgData> poResponse(CreateInitializedResponse(GGdiDrawTextMsgDataXML::CXMLTag, GMsgCmdDataFactory::CInterfaceVersion));

	try
	{
		GGdiDrawTextMsgData *pRequestData(static_cast<GGdiDrawTextMsgData *>(m_pData));
		if( pRequestData == NULL )
		{
			throw GEXCEPTION("Null pointer for GGdiDrawTextMsgData *pRequestData");
		}
		pRequestData->Validate();

		GGDIText oText;
		oText.SetBGColor(pRequestData->GetBGColor());
		oText.SetFGColor(pRequestData->GetFGColor());
		oText.SetText(pRequestData->GetText());
		oText.SetXLoc(pRequestData->GetXLoc());
		oText.SetYLoc(pRequestData->GetYLoc());
		oText.SetFont(pRequestData->GetFont());
		oText.SetAttr(pRequestData->GetAttr());

		QSharedPointer<GGDIModel> pModel(GGDIModelSingleton::GetInstance()->GetModel());
        {
            QMutexLocker mtxScope(pModel->GetMutex());
            pModel->DrawText(oText, pRequestData->GetSynchronousRequest());
        }

		poResponse->SetResponseCode(GResponseMsgData::eOk);
	}
	catch( GException& e )
	{
		LOG_LEVEL1(QString("Excepcion: ")+e.GetMessage());

		poResponse->SetResponseCode(GResponseMsgData::eGDIError);
	}
	
	SetResponseNamespace(poResponse);
	m_pResponse=poResponse.release();
}
GISMsgCmdDataFactory * GISMsgCmdDataFactory::GetInstance() throw(GException)
{
	LOG_LEVEL4("GetInstance()");

	m_mutex.lock();

	if( m_pGISMsgCmdDataFactory == NULL )
	{
		m_pGISMsgCmdDataFactory = new GISMsgCmdDataFactory();
	}

	m_mutex.unlock();

	if( m_pGISMsgCmdDataFactory == NULL )
	{
		 throw( GEXCEPTION("GISMsgCmdDataFactory::GetInstance() made a NULL pointer.") );
	}

	return m_pGISMsgCmdDataFactory;
}
void GGstLaunchMediaManager::StartVideo(const int iVideoWidth, const int iVideoHeight, const int iVideoTopLeftX, const int iVideoTopLeftY, const QString &strVideoFile) throw(GException)
{

	LOG_LEVEL4("StartVideo()");

	if (!QFile::exists(m_strVideoFilePath+strVideoFile)) { // first check to see if the video exists in the default applause directory
    	if(!QFile::exists(m_strVideoPlayCommandFilePath + strVideoFile)) { // if not there, see if this is the "VideoPlay" command file from the POS
    		LOG_LEVEL3(QString("Video playback: THROWING EXCEPTION: Video File (%1) to play was not found.").arg(strVideoFile));
    		throw GEXCEPTION(QString("Video playback: Video File (%1) to play was not found.").arg(strVideoFile));
    	}
    	else {
    		m_strCurrentVideoFilePath = m_strVideoPlayCommandFilePath;
    	}
    }
    else {
    	m_strCurrentVideoFilePath = m_strVideoFilePath;
    }

    LOG_LEVEL3(QString("Video playback: Video file (%1) found").arg(m_strCurrentVideoFilePath + strVideoFile));

	emit SignalStartVideo(iVideoWidth, iVideoHeight, iVideoTopLeftX, iVideoTopLeftY, strVideoFile);

}
GKeyEventMsgData* GKeyEventMsgDataXML::UnMarshall(QByteArray & strXML) throw(GException)
{
	LOG_LEVEL4("UnMarshall()");

	GKeyEventMsgData* poRequest = new GKeyEventMsgData();
	QDomDocument oDoc;
	QDomNodeList oNodes;
	
	try
	{
		QString sErrorMsg;
		int iErrorLine;
		int iErrorColumn;

		// Set Document content
	    if( !oDoc.setContent(strXML, true, &sErrorMsg, &iErrorLine, &iErrorColumn) )
	    {
	    	LOG_LEVEL1( QString("UnMarshall error: Error building dom tree[%1]").arg(QString(strXML)).simplified() );
	    	LOG_LEVEL1( QString("[%1][%2][%3]").arg(sErrorMsg).arg(iErrorLine).arg(iErrorColumn).simplified() );

	    	throw GEXCEPTION(QString("Error building dom tree"));
	    }

	    // Check root tag name
	    QDomElement oRoot(oDoc.documentElement());
	    if (oRoot.tagName() != CXMLTag) 
    	{
	    	throw GEXCEPTION(QString("Error: key_event opening tag not detected"));
    	}
	    
	    // Load Interface Version
	    oNodes = oRoot.elementsByTagName(CXMLVersion);
	    if(oNodes.count() == 1) 
	    {
	    	poRequest->SetInterfaceVersion(oNodes.item(0).toElement().text());
	    }
	    
	    // Load Key Code
	    oNodes = oRoot.elementsByTagName(CXMLKeyCode);
	    if(oNodes.count() == 1) 
	    {
	    	poRequest->SetKeyCode(oNodes.item(0).toElement().text());
	    }

	    // Load SynchronizeMessage
	    oNodes = oRoot.elementsByTagName(CXMLSynchronousRequest);
	    if(oNodes.count() >= 1)
	    {
	    	poRequest->SetSynchronousRequest(true);
	    }

	    // Load Namespace Prefix
	    poRequest->SetNamespacePrefix(oRoot.prefix());

		// Load Namespace URI
	    poRequest->SetNamespaceURI(oRoot.namespaceURI());

	} 
	catch(GException &ex)
	{
		delete poRequest;
		poRequest = NULL;
		throw;
	}

	return poRequest;
}
Пример #11
0
  int NoiseAdjustGadget::process(GadgetContainerMessage<ISMRMRD::AcquisitionHeader>* m1, GadgetContainerMessage< hoNDArray< std::complex<float> > >* m2)
  {
    bool is_noise = m1->getObjectPtr()->isFlagSet(ISMRMRD::ISMRMRD_ACQ_IS_NOISE_MEASUREMENT);
    unsigned int channels = m1->getObjectPtr()->active_channels;
    unsigned int samples = m1->getObjectPtr()->number_of_samples;

    //TODO: Remove this
    if ( measurement_id_.empty() ) {
      unsigned int muid = m1->getObjectPtr()->measurement_uid;
      std::ostringstream ostr;
      ostr << muid;
      measurement_id_ = ostr.str();
    }

    if ( is_noise ) {
      if (noiseCovarianceLoaded_) {
	m1->release(); //Do not accumulate noise when we have a loaded noise covariance
	return GADGET_OK;
      }
      
      // this noise can be from a noise scan or it can be from the built-in noise
      if ( number_of_noise_samples_per_acquisition_ == 0 ) {
	number_of_noise_samples_per_acquisition_ = samples;
      }

      if ( noise_dwell_time_us_ < 0 ) {
	if (noise_dwell_time_us_preset_ > 0.0) {
	  noise_dwell_time_us_ = noise_dwell_time_us_preset_;
	} else {
	  noise_dwell_time_us_ = m1->getObjectPtr()->sample_time_us;
	}
      }

      //If noise covariance matrix is not allocated
      if (noise_covariance_matrixf_.get_number_of_elements() != channels*channels) {
	std::vector<size_t> dims(2, channels);
	try {
	  noise_covariance_matrixf_.create(&dims);
	  noise_covariance_matrixf_once_.create(&dims);
	} catch (std::runtime_error& err) {
	  GEXCEPTION(err, "Unable to allocate storage for noise covariance matrix\n" );
	  return GADGET_FAIL;
	}

	Gadgetron::clear(noise_covariance_matrixf_);
	Gadgetron::clear(noise_covariance_matrixf_once_);
	number_of_noise_samples_ = 0;
      }

      std::complex<float>* cc_ptr = noise_covariance_matrixf_.get_data_ptr();
      std::complex<float>* data_ptr = m2->getObjectPtr()->get_data_ptr();
      
      hoNDArray< std::complex<float> > readout(*m2->getObjectPtr());
      gemm(noise_covariance_matrixf_once_, readout, true, *m2->getObjectPtr(), false);
      Gadgetron::add(noise_covariance_matrixf_once_, noise_covariance_matrixf_, noise_covariance_matrixf_);

      number_of_noise_samples_ += samples;
      m1->release();
      return GADGET_OK;
    }


    //We should only reach this code if this data is not noise.
    if ( perform_noise_adjust_ ) {
      //Calculate the prewhitener if it has not been done
      if (!noise_decorrelation_calculated_ && (number_of_noise_samples_ > 0)) {
	if (number_of_noise_samples_ > 1) {
	  //Scale
	  noise_covariance_matrixf_ *= std::complex<float>(1.0/(float)(number_of_noise_samples_-1));
	  number_of_noise_samples_ = 1; //Scaling has been done
	}
	computeNoisePrewhitener();
	acquisition_dwell_time_us_ = m1->getObjectPtr()->sample_time_us;
	if ((noise_dwell_time_us_ == 0.0f) || (acquisition_dwell_time_us_ == 0.0f)) {
	  noise_bw_scale_factor_ = 1.0f;
	} else {
	  noise_bw_scale_factor_ = (float)std::sqrt(2.0*acquisition_dwell_time_us_/noise_dwell_time_us_*receiver_noise_bandwidth_);
	}

	noise_prewhitener_matrixf_ *= std::complex<float>(noise_bw_scale_factor_,0.0);

	GDEBUG("Noise dwell time: %f\n", noise_dwell_time_us_);
	GDEBUG("Acquisition dwell time: %f\n", acquisition_dwell_time_us_);
	GDEBUG("receiver_noise_bandwidth: %f\n", receiver_noise_bandwidth_);
	GDEBUG("noise_bw_scale_factor: %f", noise_bw_scale_factor_);
      }

      if (noise_decorrelation_calculated_) {
          //Apply prewhitener
          if ( noise_prewhitener_matrixf_.get_size(0) == m2->getObjectPtr()->get_size(1) ) {
               hoNDArray<std::complex<float> > tmp(*m2->getObjectPtr());
               gemm(*m2->getObjectPtr(), tmp, noise_prewhitener_matrixf_);
          } else {
               if (!pass_nonconformant_data_) {
                     m1->release();
                     GERROR("Number of channels in noise prewhitener %d is incompatible with incoming data %d\n", noise_prewhitener_matrixf_.get_size(0), m2->getObjectPtr()->get_size(1));
                     return GADGET_FAIL;
               }
          }
      }
    }

    if (this->next()->putq(m1) == -1) {
      GDEBUG("Error passing on data to next gadget\n");
      return GADGET_FAIL;
    }
    
    return GADGET_OK;

  }
GGdiDrawTextMsgData* GGdiDrawTextMsgDataXML::UnMarshall(QByteArray & strXML) throw(GException)
{
	LOG_LEVEL4("UnMarshall()");

	GGdiDrawTextMsgData* poRequest = new GGdiDrawTextMsgData();
	QDomDocument oDoc;
	QDomNodeList oNodes;
	int iLoc;
	bool bCastOk;
	
	try
	{
		QString sErrorMsg;
		int iErrorLine;
		int iErrorColumn;

		// Set Document content
	    if( !oDoc.setContent(strXML, true, &sErrorMsg, &iErrorLine, &iErrorColumn) )
	    {
	    	LOG_LEVEL1( QString("UnMarshall error: Error building dom tree[%1]").arg(QString(strXML)).simplified() );
	    	LOG_LEVEL1( QString("[%1][%2][%3]").arg(sErrorMsg).arg(iErrorLine).arg(iErrorColumn).simplified() );

	    	throw GEXCEPTION(QString("Error building dom tree"));
	    }

	    // Check root tag name
	    QDomElement oRoot(oDoc.documentElement());
	    if (oRoot.tagName() != CXMLTag) 
    	{
	    	throw GEXCEPTION(QString("Error: gdi_drawtext_request opening tag not detected"));
    	}
	    
	    // Load Interface Version
	    oNodes = oRoot.elementsByTagName(CXMLVersion);
	    if(oNodes.count() == 1) 
	    {
	    	poRequest->SetInterfaceVersion(oNodes.item(0).toElement().text());
	    }
	    
	    // Load BGColor
	    oNodes = oRoot.elementsByTagName(CXMLBGColor);
	    if(oNodes.count() == 1) 
	    {
	    	poRequest->SetBGColor(oNodes.item(0).toElement().text());
	    }
	    	    
	    // Load FGColor
	    oNodes = oRoot.elementsByTagName(CXMLFGColor);
	    if(oNodes.count() == 1) 
	    {
	    	poRequest->SetFGColor(oNodes.item(0).toElement().text());
	    }    
	    
	    // Load Text
	    oNodes = oRoot.elementsByTagName(CXMLText);
	    if(oNodes.count() == 1) 
	    {
	    	if( oNodes.item(0).toElement().text().isEmpty() )
	    	{
	    		QXmlStreamReader oXmlBuffer(strXML);

	    		while( !oXmlBuffer.isEndDocument() && oXmlBuffer.name().toString() != CXMLText )
	    		{
	    			oXmlBuffer.readNext();
	    		}

	    		if( oXmlBuffer.name().toString() == CXMLText )
	    		{
	    			poRequest->SetText(oXmlBuffer.readElementText());
	    		}
	    	}
	    	else
	    	{
	    		poRequest->SetText(oNodes.item(0).toElement().text());
	    	}
	    }

	    // Load XLoc
	    oNodes = oRoot.elementsByTagName(CXMLXLoc);
	    if(oNodes.count() == 1) 
	    {	    	
	    	iLoc = oNodes.item(0).toElement().text().toInt(&bCastOk);
	    	if(bCastOk) 
	    	{
	    		poRequest->SetXLoc(iLoc);
	    	}
	    	else
	    	{
	    		throw GEXCEPTION(QString("XLoc casting error."));
	    	}
	    }		    
	    
	    // Load YLoc
	    oNodes = oRoot.elementsByTagName(CXMLYLoc);
	    if(oNodes.count() == 1) 
	    {	    	
	    	iLoc = oNodes.item(0).toElement().text().toInt(&bCastOk);
	    	if(bCastOk) 
	    	{
	    		poRequest->SetYLoc(iLoc);
	    	}
	    	else
	    	{
	    		throw GEXCEPTION(QString("YLoc casting error."));
	    	}
	    }	
	    
	    // Load Font
	    oNodes = oRoot.elementsByTagName(CXMLFont);
	    if(oNodes.count() == 1) 
	    {
	    	poRequest->SetFont(oNodes.item(0).toElement().text());
	    }
	    
	    // Load Attr
	    oNodes = oRoot.elementsByTagName(CXMLAttr);
	    if(oNodes.count() == 1) 
	    {
	    	poRequest->SetAttr(oNodes.item(0).toElement().text());
	    }

	    // Load SynchronizeMessage
	    oNodes = oRoot.elementsByTagName(CXMLSynchronousRequest);
	    if(oNodes.count() >= 1)
	    {
	    	poRequest->SetSynchronousRequest(true);
	    }

	    // Load Namespace Prefix
	    poRequest->SetNamespacePrefix(oRoot.prefix());

		// Load Namespace URI
	    poRequest->SetNamespaceURI(oRoot.namespaceURI());

	} 
	catch(GException &ex)
	{
		delete poRequest;
		poRequest = NULL;
		throw;
	}

	return poRequest;
}
Пример #13
0
int IEVChannelSumGadget::process(GadgetContainerMessage< ISMRMRD::ImageHeader>* m1)
{
	GadgetContainerMessage<hoNDArray< float > > *unfiltered_unwrapped_msg_ptr =     AsContainerMessage<hoNDArray<float>>(m1->cont());

	GadgetContainerMessage<hoNDArray< float > > *filtered_unwrapped_msg_ptr =   AsContainerMessage<hoNDArray<float>>(unfiltered_unwrapped_msg_ptr->cont());
	GadgetContainerMessage<ISMRMRD::MetaContainer> *meta;
	
	static int c=0;	
	int e;
	int echo = m1->getObjectPtr()->contrast;
	float inv_echo_time;

	int echo_offset=yres*xres*num_ch*echo;

	if(!filtered_unwrapped_msg_ptr || !unfiltered_unwrapped_msg_ptr)
	{
		GERROR("Wrong types received in IEVChannelSumGadget. Filtered and unfiltered phase expected.\n");
		return GADGET_FAIL;
	}
	
	 meta = AsContainerMessage<ISMRMRD::MetaContainer>(filtered_unwrapped_msg_ptr->cont());
	
	//float* filtered_phase_ptr= filtered_unwrapped_msg_ptr->getObjectPtr()->get_data_ptr();
	
	m1->getObjectPtr()->channels=1; //yes?
	inv_echo_time=1/echoTimes[echo];//to avoid millions of divisions per slice

	memcpy(filtered_phase_ptr+echo_offset, filtered_unwrapped_msg_ptr->getObjectPtr()->get_data_ptr(), xres*yres*num_ch*sizeof(float));
	
	for (int i = 0; i < xres*yres*num_ch; i++) 

		freq_ptr[echo_offset+i] = filtered_phase_ptr[echo_offset+i]*inv_echo_time;

	hdr_ptr[echo]=*(m1->getObjectPtr());
	
	if(meta)
	{
		meta->getObjectPtr()->append("StudyInstanceUID", studyInstanceUID.c_str());//may be in xml header, may not be, in that case put it in xml so it can get to dicom
		char TE[10];
		sprintf(TE, "%f", echoTimes[echo]*1000);
		meta->getObjectPtr()->append("TE", TE);

		attributes[echo]=*(meta->getObjectPtr());
	}
	unfiltered_unwrapped_msg_ptr->release();//all data have been copied
	if(echo==(numEchos-1))
	{	
		
		float* weights= new float[xres*yres*num_ch];
		float** channel_weights= new float* [num_ch];
		float* to_normalize = new float[xres*yres];
		int ch;
		
		if(iev.value()==int(IEV::YES))//just to allow this to work without IEV/make it very easy to compare
		{
			#pragma omp parallel //expanded parallel --- to allow sample to be allocated once
			{
				float* sample = new float[numEchos];
				int start = omp_get_thread_num()/omp_get_num_threads()*xres*yres*num_ch;
				int end = (omp_get_thread_num()+1)/omp_get_num_threads()*xres*yres*num_ch;
				for(int i =start; i <end; i++)
				{
					/////////
					for(int j = 0; j < numEchos; j++)
						sample[j]=freq_ptr[i+j*xres*yres*num_ch];     //assuming all(6-10 at at time) pages can be held in memory, this isn't terrible
					
					weights[i]=stdev(sample, numEchos);		//find standard deviation between echoes
					/////				
				}
				delete[] sample;
			}
			
			#pragma omp parallel for private(ch)
			for(ch = 0; ch < num_ch; ch++)
			{	
				float* temp_array;
		
			
				channel_weights[ch]=&weights[ch*xres*yres];
				medianFilter(channel_weights[ch], xres, yres);
				for (int i = 0; i < xres*yres; i++)
				{
				  channel_weights[ch][i]=1/(channel_weights[ch][i]+FLT_MIN);		//weight as inverse, 
				}
			
			}
			
			for (int i = 0; i < xres*yres; i++)
				to_normalize[i]	= 0;	

			for(int ch=0; ch< num_ch; ch++)		
				for (int i = 0; i < xres*yres; i++)
				{
				to_normalize[i]+=channel_weights[ch][i];
				}
	
			for(int ch=0; ch< num_ch; ch++)		
				for (int i = 0; i < xres*yres; i++)
				{
				channel_weights[ch][i]/=to_normalize[i];			//normalize weights
				}
			
		}
		else
		{
			#pragma omp parallel for private(ch)
			for(int ch=0; ch< num_ch; ch++)	
			{
				channel_weights[ch]=&weights[ch*xres*yres];	
				for (int i = 0; i < xres*yres; i++)
				{
				channel_weights[ch][i]=1;			
				}
			}
		}
		for(e=0; e<numEchos; e++)
		{

			hdr_ptr[e].channels=1;
			hdr_ptr[e].contrast=e;
			hdr_ptr[e].data_type = ISMRMRD::ISMRMRD_FLOAT;//GADGET_IMAGE_REAL_FLOAT;
			hdr_ptr[e].image_type = ISMRMRD::ISMRMRD_IMTYPE_PHASE;//There is no frequency image type
			hdr_ptr[e].slice= (hdr_ptr[e].image_index) % num_slices;//was hdr_ptr[e].image_index___-1_____) % num_slices before decrementor was added upstream
						
			if(output_phase.value())
			{
				//
				GadgetContainerMessage<ISMRMRD::ImageHeader>* phase_hdr = new GadgetContainerMessage<ISMRMRD::ImageHeader>(hdr_ptr[e]);
				//*(phase_hdr->getObjectPtr()) =*(hdr_ptr[e]->getObjectPtr());
				GadgetContainerMessage<hoNDArray< float > > *comb_phase_msg = new GadgetContainerMessage<hoNDArray< float > >();
				phase_hdr->getObjectPtr()->image_series_index=series_id_offset+1;
				try{comb_phase_msg->getObjectPtr()->create(xres,yres);}	

				catch (std::runtime_error &err){
				GEXCEPTION(err,"Unable to create output image\n");
				return GADGET_FAIL;  
				}
				float* output_ptr=comb_phase_msg->getObjectPtr()->get_data_ptr();
				phase_hdr->cont(comb_phase_msg);
				//	
				for (int i = 0; i < xres*yres; i++)
				{
				output_ptr[i]=filtered_phase_ptr[e*xres*yres*num_ch+i]*channel_weights[0][i]; //instead of setting to 0 and adding first channel
				}
				for(int ch=1; ch< num_ch; ch++)	
					for (int i = 0; i < xres*yres; i++)
					{
						output_ptr[i]+=filtered_phase_ptr[e*xres*yres*num_ch+xres*yres*ch+i]*channel_weights[ch][i];; //instead of setting to 0 and adding first channel
					}						
				//
				if(meta)
				{
				GadgetContainerMessage<ISMRMRD::MetaContainer>* meta = new GadgetContainerMessage<ISMRMRD::MetaContainer>(attributes[e]); 
						
				comb_phase_msg->cont(meta);	
				
				}
				//
				if (this->next()->putq(phase_hdr) == -1) {
				m1->release();
					GERROR("Unable to put collapsed images on next gadget's queue\n");
				return GADGET_FAIL; 
				}
				
			}
			if(output_LFS.value())
			{
				//
				GadgetContainerMessage<ISMRMRD::ImageHeader>* freq_hdr=new GadgetContainerMessage<ISMRMRD::ImageHeader>(hdr_ptr[e]);
				//*(freq_hdr->getObjectPtr()) =*(hdr_ptr[e]->getObjectPtr());
				GadgetContainerMessage<hoNDArray< float > > *comb_freq_msg = new GadgetContainerMessage<hoNDArray< float > >();
				freq_hdr->getObjectPtr()->image_series_index=series_id_offset+output_phase.value()+1;
				try{comb_freq_msg->getObjectPtr()->create(xres,yres);}	

				catch (std::runtime_error &err){
				GEXCEPTION(err,"Unable to create output image\n");
				return GADGET_FAIL;  
				}
				float* output_ptr=comb_freq_msg->getObjectPtr()->get_data_ptr();
				freq_hdr->cont(comb_freq_msg);
				freq_hdr->getObjectPtr()->image_type = 6;
				//
				for (int i = 0; i < xres*yres; i++)
					output_ptr[i]=freq_ptr[e*xres*yres*num_ch+i]*channel_weights[0][i]; //instead of setting to 0 and adding first channel
				for(int ch=1; ch< num_ch; ch++)		
					for (int i = 0; i < xres*yres; i++)
					{
						output_ptr[i]+=freq_ptr[e*xres*yres*num_ch+xres*yres*ch+i]*channel_weights[ch][i];
					}
				//
				if(meta)
				{
				GadgetContainerMessage<ISMRMRD::MetaContainer>* meta = new GadgetContainerMessage<ISMRMRD::MetaContainer>(attributes[e]); 
				meta->getObjectPtr()->set(GADGETRON_DATA_ROLE, GADGETRON_IMAGE_FREQMAP);
				//*(meta->getObjectPtr())=*(attributes[e]->getObjectPtr());
				comb_freq_msg->cont(meta);	
				}
				//
				if (this->next()->putq(freq_hdr) == -1) {
				//m1->release();
					GERROR("Unable to put collapsed images on next gadget's queue\n");
				return GADGET_FAIL; 
				}
			
			}
			
			
		}
		delete[] to_normalize;
		delete[] weights;
		delete[] channel_weights;
		//if(output.value()==int(OUTPUT::PHASE))
		//	delete[] unfiltered_phase_ptr;
		

	}
	


		
	return GADGET_OK;
}