--[[
   This grouping script partition ultrasound (US) images as follows:
   Every multi-frame image needs to be assigned to an unique sequence.
   All still need to be grouped in the same series 
 
	Cristian Bonciu,        August-September 2004        
	-	Created and  implemented the functionality from pseudo-code prototypes provided by Allan 
	Mahesh Nagarajan		26 SEP 2005		
	-	Added additional grouping hint for images added to the "All Still" sequence. Also changed 
		the name of this sequence to "All Stills US"
	Allan Noordvyk			11 NOV 2005
	-	Added support for "Color Stills" sequence containing subset of those still frame
		images which are color, using the newly introduced "Color" property.
	Mahesh Nagarajan		12 DEC 2005
	-	Added sorting hints for (0008, 0023) Image (Content) Date and (0008, 0033) Image
		(Content) Time (in response to CRDB00037876)
	Mahesh Nagarajan		12 JAN 2005
	-	Added site customizable disabling of Color Stills sequence, based on feedback
		from Fletcher-Allan.
	Mahesh Nagarajan		18 JAN 2006	
	-	Added sort hint for ID SOP Instance UID just before filename
	Mahesh Nagarajan		27 JAN 2006
	-	Grouping by filename is a bad idea as when two studies are merged, the
		images with the same filename are grouped together.
	Mahesh Nagarajan		02 MAY 2006
	-	Added more variations of Fletcher-Allen to ensure that they dont see the freakin'
		"color stills" thumbnail
	-	The above change is temporarily disabled until FAHC can make up its mind on whether
		they want the "Color Stills" thumbnail.
	Mahesh Nagarajan		02 MAY 2006
	-	Added code to ensure that the "color stills" thumbnail is disabled for University
		of Wisconsin hospital
	Mahesh Nagarajan		27 JUL2006
	-	Added code to ensure that the "color stills" thumbnail is disabled for University
		of Wisconsin hospital
	-	Changed grouping hint for Color Stills sequence from META Version Info to Color 
		property as the latter is less likely to not exist.
	Mahesh Nagarajan		16 NOV 2006
	-	Disabled color stills sequence for O'Connor Hospital as it causes printing of duplicate images
	Mahesh Nagarajan		01 FEB 2007
	-	MAJOR SCRIPT REVAMP; please compare with earlier version on VSS if necessary	
	-	Site customized code will be removed and re-located to GroupUS.site files -> starting with 11.5, 
		unless extraction	routines are fundamentally flawed, all change requests will be incorporated there.
	- 	Modified syntaxes for grouping and sorting hints as part of v11.5 re-write
	Mahesh Nagarajan		07 MAR 2007
	-	With new v11.5 syntaxes, the sequence names are set when the grouping hints are created, as opposed
		to the old behaviour where the name was set when the image was added. This means that different grouping
		hints need to be created for cine and still images.
	Mahesh Nagarajan		17 MAY 2007
	-	Removed the modality prefix and sort suffix from sort names as it looked stupid
	Mahesh Nagarajan		22 MAY 2007
	-	Toshiba has started sending 4D US datasets; and the current US scripts are not sufficient
		to handle these images. The required behavior is that each 4D image be split into its own sequence;
		a 4D image is indicated by the presence of the value "US_4D_Live" in private tag (0029, 1028)	
		Ref: CRDB00051024
	Mahesh Nagarajan		11 FEB 2008
	-	Adding back site-specific code snippets; after a long discussion with Cristian B., it is understood that this code has to stay 
		in the code until proper site files have been installed. Such code is added back but within "dollar sign" demarcations to ensure 
		easy removal at a later date.				
	James Zhang             January 08, 2010
		Added code to ensure that the "color stills" thumbnail is disabled for
        Halifax Regional Hospital, as requested by CRDB00083022 (REI 17506)
--]]

function DeclareTags()
end

function RegisterSortingHintTypes( )
-- ////////////////////////////////////////////////////////////////////////////
-- This function will register the various sort orders that are created for CT
-- ////////////////////////////////////////////////////////////////////////////
    RegisterHintType( "ACQUISITION TIME SORT", "Acquisition Time" )
	RegisterHintType( "IMAGE NUMBER SORT", "Image Number" )
    RegisterHintType( "FILE NAME SORT", "File Name" )		
end

function Execute()
-- ////////////////////////////////////////////////////////////////////////////
-- This function will create grouping and sorting hints for CT Sequencing 
-- ////////////////////////////////////////////////////////////////////////////

    DeclareTags()
    
	-- ////////////////////////////////////////////////////////////////////
	-- generates the hints for the sequencer as follows 
	-- use SOP instance UID for the multiframe images to generate unique 
	-- sequences for each multiframe image
	-- use FRAME_TYPE_PROP to create and subsequently add all the stills
	-- to the same sequence
	-- ///////////////////////////////////////////////////////////////////

    -- If this is the wrong script for the supplied image...
    if (not SanityOK("US")) then
      return nil
      -- =====================================================
    end
    
    -- Define constants so intended sort order, when used, is more readable.
    local ASCENDING_ORDER = true
    local DESCENDING_ORDER = false

	-- MaxN: Note that the default sort for US is by acquisition time; so we do not
	-- have a seperate "default" sort scheme like we did for CT & MR. 
	local sortHint01 = SortingHint:new( "Acquisition Time", "ACQUISITION TIME SORT" )
	sortHint01:AddEntry(ACQUISITON_DATETIME_TAG,ASCENDING_ORDER)
    sortHint01:AddEntry(ACQUISITON_DATE_TAG,ASCENDING_ORDER)
    sortHint01:AddEntry(ACQUISITON_TIME_TAG,ASCENDING_ORDER)
    sortHint01:AddEntry(IMAGE_ACQUISITION_DATE_TAG,ASCENDING_ORDER)    
    sortHint01:AddEntry(IMAGE_ACQUISITON_TIME_TAG,ASCENDING_ORDER)
    sortHint01:AddEntry(INSTANCE_NUMBER_TAG,ASCENDING_ORDER)   
    sortHint01:AddEntry(IMAGE_UID_TAG,ASCENDING_ORDER)
    sortHint01:AddEntry(ALI_IMAGE_FILENAME_TAG,ASCENDING_ORDER)
    
	-- Create a "Sort Hint Set" here; all alternate sorts will be added to this one if they are created
	local sortHintSet01 = SortingHintSet:new( )
	sortHintSet01:AddHint( sortHint01, true ) 
    
	-- Creating an image number sort for US - created only if (0020, 0013) REL Image Number exists
	if (HasAttr(INSTANCE_NUMBER_TAG)) then
		local sortHint02 = SortingHint:new( "Image Number", "IMAGE NUMBER SORT" )
		sortHint02:AddEntry( INSTANCE_NUMBER_TAG, ASCENDING_ORDER ) 
		
		-- If we are here, then the image number sort was created successfully; adding it to the sort hint set for CT
		sortHintSet01:AddHint( sortHint02 )
	end
	
	-- Not checking for file name as it should always exist
	local sortHint03 = SortingHint:new( "File Name", "FILE NAME SORT" )
	sortHint03:AddEntry( ALI_IMAGE_FILENAME_TAG, true )
	sortHintSet01:AddHint( sortHint03 )
	
	-- Creating a bogus "sort hint set" for cine clips; this used to be "nil" in the old implementation. This is not allowed 
	-- in the new implementation so we just add a sort hint for image UID
	local sortHint04 = SortingHint:new( "Image UID", "IMAGE UID SORT" )
	sortHint04:AddEntry(IMAGE_UID_TAG,ASCENDING_ORDER)
	
	local sortHintSet02 = SortingHintSet:new( )
	sortHintSet02:AddHint( sortHint04, true ) 

	-- Grouping hints coming up
	local frameTypeAttr = GetAttr(FRAME_TYPE_PROP)
	
	-- fail-safe code if US images were not treated properly during the extraction phase
	if( not frameTypeAttr ) then -- something went wrong when extracting common props 
        ReportError("Extract US script","No multiframe property available")
        
		local groupHint01 = GroupingHint:new( ValueForTag( SERIES_DESC_PROP, "?" ) )
		groupHint01:AddEntry(SERIES_UID_TAG)
        
		AddImage2Sequence( "US Sequence", groupHint01, sortHintSet01 )
        return 
    end
        
    local sFrameType = frameTypeAttr:Get(1)
    if( sFrameType ~= "Still" ) then
		local groupHint01 = GroupingHint:new( "Cine" )
        groupHint01:AddEntry(IMAGE_UID_TAG)    -- assign each distinct cine file to its own sequence
		
        AddImage2Sequence( "Cine", groupHint01, sortHintSet02 )    -- no need for sorting (can assume frames in right order)
        return
        -- =====================================================
    end

	-- Must Check if the image is a 4D image; if so, must break this out into a seperate sequence
	-- Currently applies to images from Toshiba only
	if (ValueForTag(TOSHIBA_4DDATA_TAG) == "US_4D_LIVE") then
        local groupHint01 = GroupingHint:new( "4D Data" )
		groupHint01:AddEntry(IMAGE_UID_TAG)    -- assign each distinct cine file to its own sequence
		
		AddImage2Sequence( "4D Data", groupHint01, sortHintSet02 )
		return	
	end	
	
    -- If we are here then we are dealing with a still frame image.
    -- add all still frames to one sequence
	local groupHint01 = GroupingHint:new( "*All Stills* US" )
    groupHint01:AddEntry(MODALITY_TAG)
    groupHint01:AddEntry(FRAME_TYPE_PROP)

	AddImage2Sequence( "*All Stills* US", groupHint01,	sortHintSet01 )
	
	--$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
	local showColorStills = true
    local SiteName = GetAttr( INSTITUTION_NAME_TAG )
	
	--[[
    FAHC_VAL = "FAHC"   -- Fletcher-Allan
    FAH_VAL = "FAH"     -- Alternate form for Fletcher-Allan
    FAHC_LONG_VAL = "Fletcher Allen"
    MCHV_ACC_US2_VAL = "MCHV ACC US2"
    ULTRASOUND_VAL = "ULTRASOUND"
    MCHV_RM4_VAL = "MCHV RM 4"
    MCHV_RM5_VAL = "MCHV RM 5"
    FETAL_DIAG_CTR_VAL = "Fetal Diagnostic Center RM 3"
    UVM_FETAL_CTR_VAL = "UVM Fetal DX Center"
--]]
       
    UW_HOSP_VAL = "UW Hospital"		-- University of Wisconsin
    UW_SPCE_HOSP_VAL = "UW  Hospital"	-- Alternate for U of WI
    UW_HEALTH_VAL = "UW Health"		-- Alternate for U of WI
    UNIV_WI_VAL = "University of WI"	-- Alternate for U of WI
    UNIV_SPCE_WI_VAL = "University  of  WI"	-- Alternate for U of WI
    HILLSBORO_VAL = "Hillsboro"		-- Alternate for U of WI
	OCONNOR_VAL = "O'CONNOR HOSPITAL"
	O_CONNOR_VAL = "O CONNOR HOSPITAL"
	SAMC_VAL = "SAMC"
	FREEHOLD_VAL = "Freehold Radiology"
	GREAT_FALLS_VAL = "GREAT FALLS CLINIC"
    HALIFAX_REGIONAL_VAL = "HALIFAX REGIONAL HOSPITAL"
	
    if ( SiteName ~= nil and BestWordMatchInAttr(SiteName, UW_HOSP_VAL, UW_SPCE_HOSP_VAL, 
                                                    UNIV_SPCE_WI_VAL, UW_HEALTH_VAL, UNIV_WI_VAL, 
                                                    HILLSBORO_VAL, OCONNOR_VAL, O_CONNOR_VAL, 
                                                    SAMC_VAL, FREEHOLD_VAL, GREAT_FALLS_VAL,
                                                    HALIFAX_REGIONAL_VAL) ) then
		showColorStills = false
	end
	
	--$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
	
	-- Creating a seperate sequence for still images with color
	if (ValueForTag( COLOR_PROP ) == "Yes" and (showColorStills==true)) then
        
        --- Also add the image to the "Color Stills" sequence
        local groupHint02 = GroupingHint:new( "*Color Stills*" )
        
        -- HACK: Not allowed to have an empty group hint so we need one that won't vary in any image
        groupHint02:AddEntry(COLOR_PROP) -- should have value of "YES" in all images 

        AddImage2Sequence( "*Color Stills*", groupHint02, sortHintSet01 )
    end

end