--[[
	This script identifies the image properties of Digital X-Ray (DX) modality images

	At the present time, no modality-specific properties or logic are handled by this 
	script, leaving ExtractCommon as the sole sequence property extraction handler.  This 
	may be changed at a future date, at which point this comment block would be updated 
	with an appropriate summary.
 
     Mahesh Nagarajan		26 JUNE 2006
     -	Added new property "Thumbnail Group" for DX images based on certain key values
          recognized in (0018, 1400) ACQ Acquisition Device Processing Description
	Mahesh Nagarajan		12 FEB 2006
	-	Site customized code will be removed and re-located to ExtractCT.site files -> starting 
		with 11.5, unless extraction routines are fundamentally flawed, all change requests will 
		be incorporated into a site file.
	-	In accordance to the statement above, ExtractThumbnailGroupDX() is moved into a site
		file for Univ. ofWisconsin
	Mahesh Nagarajan		14 MAR 2008
	-	Fixed inconsistencies found between this branch (EXP) and the live sequencing script
		branch found by Shudong during code review
	-    Bringing back ExtractThumbnailGroupDX() as part of the effort to bring back pieces 
		of site customized code into the scripts (for now)
	Mahesh Nagarajan	12 JUN 2008
	-	Disabling the ExtractThumbnailDX function for Montreal as it interferes
		with acquisition time thumbnail sorting for this site
    James Zhang     24 JULY 2009
    -   Bringing back ExtractThumbnailGroupDX() which was not called in the past,
        to fix CRDB00077644.
    -   Adding more possible values for ACQ_DEV_PROCESS_TAG
        to fix REI 13971.
    James Zhang     18 Sep 2009
    -   Customizing for North Country Hospital and Health Center to extract series
        description from ACQ View Position tag[0018 5101] their GE studies,
        as per REI 13293(CRDB00079737).
    James Zhang     10 Nov 2009
    -   Customizing for RUIS  to assign Thumbnail Group values,
        as per REI 10966(CRDB00080784).
    James Zhang     05 July 2010
    -   Fixed ExtractThumbnailGroupDX as descripted in CRDB00088971.
--]]


function RegisterProperties()
-- ////////////////////////////////////////////////////////////////////////////
-- This function is called automatically at load of script to register any
-- modality specific properties.  Prior to IP Library build 39 it must be 
-- present even if empty.
-- Modality specific property IDs (3711,1X01)- (3711,1XFF) range
--     If modality specific properties need to be defined, then replace X in the above 
--     numeric ranges with a value that is distinct from those used by other modalities.
-- ////////////////////////////////////////////////////////////////////////////
end

-- ////////////////////////////////////////////////////////////////////////////
-- Modality specific string definitions 
--	If extraction requires reference to specific value strings (e.g. for substring
--      matching) define them here rather than in-line.
-- ////////////////////////////////////////////////////////////////////////////


-- ////////////////////////////////////////////////////////////////////////////
-- Modality specific property extraction functions 
--      Any modality specific extraction logic would be encapsulated in functions
--      defined below.  By standard convention, these shall have names of the form
--	Extract<Property><Modality>, where <Property> is the name of the property
--	being handled and <Modality> is the character prefix for this modality. 
-- ////////////////////////////////////////////////////////////////////////////

function ExtractDescriptionDX() 
-- ////////////////////////////////////////////////////////////////////////////
	-- This function sets the image description property of the image based
	-- on an examination of the header values and previously derived image
	-- properties.  The set property is returned.
	--
	-- This method will always return some kind of property.  If it can't
	-- come up with anything else, it will use a question mark for the
	-- image description just so that we have something to show in the UI.
	--
	-- IMPORTANT: As this function makes use of derived properties, it should
	-- be called LAST, after all other extraction functions have been run.
-- ///////////////////////////////////////////////////////////////////////////

    -- Site hack for North Country Hospital and Health Center,
    -- who wants View Position as series description for GE studies.
	local SiteName = GetAttr(INSTITUTION_NAME_TAG)
	if (SiteName~=nil and (ValueForTag(INSTITUTION_NAME_TAG) == [[North Country Hospital and Health Center]])) then
        local ManufacturerName = GetAttr(DEVICE_MANUFACTURER_TAG)
		if (ManufacturerName~=nil and ValueForTag(DEVICE_MANUFACTURER_TAG) == [["GE Healthcare"]]) then
            local ModelName = GetAttr(DEVICE_MODEL_TAG)
            if (ModelName~=nil and ValueForTag(DEVICE_MODEL_TAG) == [["Thunder Platform"]]) then
                local ViewPos = ValueForTag(VIEW_POSITION_TAG)
                if (ViewPos ~= nil) then
                    return NewPropWithValue(SERIES_DESC_PROP, ViewPos)
                end
            end
        end
    end

    -- If the common function was already successful finding a good description value...
    local seriesDescProp = GetAttr( SERIES_DESC_PROP )
    if (seriesDescProp) then
        -- If it isn't just the special no-info placeholder...
        if (seriesDescProp:Get(1) ~= "?") then
            TraceC( "Common script found description... skipping special DX logic.\n" )
            return seriesDescProp;
            --==============================================
        end
    end
    
    TraceC( "No good description found by common script... using special DX logic.\n" )      
  
    -- Try to build a descriptive sentence by using derived properties
    local seriesDescStr
    seriesDescStr = SmartAppendWords( ValueForTag(PROJECTION_PROP), " ", ValueForTag(LATERALITY_PROP) )
    seriesDescStr = SmartAppendWords( seriesDescStr, " ", ValueForTag(BODY_REGION_PROP) )
      
    -- If we have an image type other than boring old "Original"...
    local imageTypeStr = ValueForTag(IMAGE_TYPE_PROP) 
    if (imageTypeStr and imageTypeStr ~= "Original" and imageTypeStr ~= "ORIGINAL") then 
        -- Append non-boring image type to custom series description
        seriesDescStr = SmartAppendWords( seriesDescStr, " ", imageTypeStr )
    end
        
    -- If we had no success above...
    if (not seriesDescStr or string.len(seriesDescStr) == 0) then
        TraceC( "No components available for building series description.\n" )
        seriesDescStr = "?"
    end
       
    return NewPropWithValue( SERIES_DESC_PROP, seriesDescStr )

end

function ExtractThumbnailGroupDX()
-- ///////////////////////////////////////////////////////////////////////////
-- This function was written at Universiy of Wisconsin for rads who would like
-- DX studies to have a specific order both on the thumbnails and the *all images*
-- series. This is accomplsihed by assigning certain thumbnail group numbers to
-- specific type of images. The current numbering scheme is..
--
-- AP/PA Original          --  01
-- AP/PA Soft Tissue    --  04
-- AP/PA Bone             --  07
-- Lateral                   --  10

-- Modify the numbering scheme so that image with CAD markers are at the last.
-- This would be based on on the series description tag
-- CAD  	                    -- 12
-- CAD Results 	        -- 12
-- ///////////////////////////////////////////////////////////////////////////
    local grpValue = nil
	
	--$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
	-- Customization code for RUIS to place unpair series in front of laterality:
    -- 1. [0018, 5101] = PA or AP
    -- 2. [0018, 5101] = TAN
    -- 3. [0018, 5101] = Anything else, including but not limited to
    --                          OBL/RAO/RPO/LAO/LPO/AX/SMV/R/L
    -- 4. [0018, 5101] = LL or RL or LAT
	local SiteName = GetAttr(INSTITUTION_NAME_TAG)
	if (SiteName~=nil and BestWordMatchInAttr(SiteName, "Hopital du Sacre Coeur de Mtl")) then
        local tag = GetAttr(VIEW_POSITION_TAG)
        if (tag == nil) then
            return nil
        else
            if (BestWordMatchInAttr(tag, "AP", "PA")) then
                grpValue = "01"
            elseif (BestWordMatchInAttr(tag, "TAN")) then
                grpValue = "04"
            elseif (BestWordMatchInAttr(tag, "LL", "RL", "LAT")) then
                grpValue = "10"
            else
                grpValue = "07"
            end
            
            return NewPropWithValue(THUMBNAIL_GRP_PROP, grpValue)
        end
	end
	--$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
		
    local AcqDeviceProcDescAttr = GetAttr(ACQ_DEV_PROCESS_TAG)
    local SeriesDescTag = GetAttr(SERIES_DESC_TAG)
    
    local acqdeviceprocdesc = ValueForTag(ACQ_DEV_PROCESS_TAG)

    if (AcqDeviceProcDescAttr) then
        -- Examples of value "postero anterior": REI 13971\Bad\iew0001/vew0002/view0005.dcm
        if (BestMatchInAttr(AcqDeviceProcDescAttr, "postero-anterior", "antero-posterior", "postero anterior", "antero posterior")) then
            grpValue = "01"

        -- Example of value "Soft-Tissue": REI 13971\Bad\view0002.dcm
		elseif (BestMatchInAttr(AcqDeviceProcDescAttr, "Soft_Tissue", "Soft-Tissue")) then
            grpValue = "04"
        		
		elseif (BestMatchInAttr(AcqDeviceProcDescAttr, "Bone")) then
            grpValue = "07"
        		
        -- Example of value "left-lateral": REI 13971\Good\view0004.dcm
		elseif (BestMatchInAttr(AcqDeviceProcDescAttr, "left lateral", "left-lateral")) then
            grpValue = "10"
	     
        end		
    end

	if (SeriesDescTag~=nil and BestWordMatchInAttr(SeriesDescTag, "CAD", "CAD RESULTS" )) then 
		grpValue = "12" 
	end
    
    return NewPropWithValue( THUMBNAIL_GRP_PROP, grpValue )            
end

-- ////////////////////////////////////////////////////////////////////////////
-- The Execute function is the single function called by the sequence engine
-- when encountering images of a modality for which this script is applicable.
-- This function is called after ExtractCommon's Execute function and should
-- directly invoke any modality specific property extraction functions defined
-- above in the desired order.
-- ////////////////////////////////////////////////////////////////////////////

function Execute()

    TraceC("Extract DX executing...\n")

    -- If this is the wrong script for the supplied image...
    if (not SanityOK("DX")) then
      return nil
      -- =====================================================
    end

    -- Tag our output with the script version
    NewPropWithValue( MODALITY_SCRIPT_VER_PROP, "$Revision: 5 $ - $Modtime: 5/07/10 11:19a $ - DX" )
    
    -- Insert calls to any modality specific extraction functions here.
    ExtractDescriptionDX()
    ExtractThumbnailGroupDX()

    TraceC("Extract DX complete.\n")
    --==============================================
end
