//script to take series of dark reference images
//modified for any camera Dec 06 Sarah Haigh
//modified for interfacing to DM plug-in Feb 07 Kenta Yoshimura

number ni = 20	// number of images, should be even
number exposure = 1	// exposure in sec
number binning = 1
number siz = 4096
string name, folder
number camW, camH
number top, left, bottom, right

number i
/*
if (!GetNumber("Number of dark references to acquire? : ",16, ni)) exit (0)
if (!GetNumber("Exposure time (s): ",1, exposure)) exit (0)
if (!GetNumber("binning? : ",1, binning)) exit (0)
if (!GetNumber("size of camera? : ",4096, siz)) exit (0)
*/
{
	Number   SIZE_LIMIT = 1024;
	String   group = "FSR";
	TagGroup tag = GetPersistentTagGroup();
	Number   succeed;
	Number   sizeLimits;
	Number   offX, offY;
	
	succeed = tag.TagGroupGetTagAsTagGroup( group, tag );
	if ( !succeed ) Exit( 0 );
	succeed = tag.TagGroupGetTagAsTagGroup( "MTFNPSAcquisition", tag );
	if ( !succeed ) Exit( 0 );

	tag.TagGroupGetTagAsString( "name", name );
	tag.TagGroupGetTagAsNumber( "ni", ni );
	tag.TagGroupGetTagAsString( "folder", folder );
	tag.TagGroupGetTagAsNumber( "exposure", exposure );
	tag.TagGroupGetTagAsNumber( "binning", binning );
	tag.TagGroupGetTagAsNumber( "sizeLimits", sizeLimits );
	tag.TagGroupGetTagAsNumber( "offsetX", offX );
	tag.TagGroupGetTagAsNumber( "offsetY", offY );

	SSCGetSize(camW, camH);
	camW = floor(camW/binning);
	camH = floor(camH/binning);
	if ( sizeLimits && camW>=SIZE_LIMIT )
	{
		siz = SIZE_LIMIT;
		
		top    = offX+floor(camH/2)-floor(siz/2);
		left   = offY+floor(camW/2)-floor(siz/2);
		bottom = top +siz;
		right  = left+siz;
	} else
	{
		siz = camW;
		
		top    = 0;
		left   = 0;
		bottom = top +siz;
		right  = left+siz;
	}
}

//number top = 0, left = 0, bottom = siz/binning, right = siz/binning
Result("\nacquiring dark reference images\n")

// get dark ref so can get rid of it
image ima := SSCGetDarkReference( exposure, binning, top, left, bottom, right )
string prefix = name+"_"+binning+"_"+exposure+"_"
image result := NewImage(prefix+"dark", ima.ImageGetDataType(), siz, siz, ni)
result.ImageGetTagGroup().TagGroupCopyTagsFrom(ima.ImageGetTagGroup())
result.ImageCopyCalibrationFrom(ima)

for (i = 1; i<=ni; i++)
{   //deleteimage(ima)
    //ima := SSCGetDarkReference( exposure, binning, top, left, bottom, right )
    //SaveAsGatan(ima, "darkref"+i)
    if ( SpaceDown() ) {
        if ( OKCancelDialog("Do you want to stop image acquisition?") ) {
            Exit(0);
        }
    }
    result[0, 0, i-1, siz, siz, i] = SSCUnprocessedBinnedAcquire(exposure, binning, top, left, bottom, right)
    Result("dark " + i + "\n")
    }

SaveAsGatan(result, folder+GetName(result))
ShowImage(result)
Result("finished\n")

