//Setting the Spectrum Instruments DAC and ADC cards to operate with SavvyGate. 
//Written by Shahar Seifer, Weizmann institute of Science (C) 2023
// Full code is available at https://github.com/Pr4Et/SavvyScan
//Tested on Spectrum cards:
//8ch ADC: M2p.5923-x4  called /dev/spcm0 (card 0)  , 1024MB, 20MS/s
//2ch DAC: M2p.6541-x4  called /dev/spcm1 (card 1) , 1024MB, 40MS/s, 16 bits
////////////////////////////////////////////////////////////////////////////
#include "../common/ostools/spcm_oswrap.h"
#include "../common/ostools/spcm_ostools.h"
#Note: Using latest library (2022) from Spectrum Instruments, while adding in spcm_lib_card.cpp the missing code for function bSpcMSetupModeRecFIFOSingle from older version (2020)

//Initialization
spcm_dwSetParam_i64(stCardREC.hDrv, SPC_CLOCKMODE, SPC_CM_INTPLL);
spcm_dwSetParam_i32(stCardREC.hDrv, SPCM_X1_MODE, SPCM_XMODE_TRIGOUT); // X1 set as trigger output, showing when trigger is decided after software request
spcm_dwSetParam_i32(stCardREC.hDrv, SPCM_X1_MODE, SPCM_XMODE_TRIGOUT); // X1 set as trigger output, showing when trigger is decided after software request
printf("Connect trig out from ADC card [x1] to AWG [trig-in] instead of HUB syncing.\n");
printf("Connect Clk out from ADC card [x0] to AWG [clk-in] for external sync.\n");
spcm_dwSetParam_i32(stCardREP.hDrv, SPC_TRIG_ORMASK, SPC_TMASK_EXT0); // set sample trigger input to trigger-in socket
spcm_dwSetParam_i32(stCardREP.hDrv, SPC_TRIG_EXT0_MODE, SPC_TM_POS); // Set trig mode to ext. TTL mode (rising edge)
spcm_dwSetParam_i32(stCardREP.hDrv, SPCM_X1_MODE, SPCM_XMODE_TRIGOUT); // X1 set as trigger output, showing when trigger is decided after software request
//To make the ADC reference clock stable for output, according to bjoern.schormann@spec.de: 
spcm_dwSetParam_i32(stCardREC.hDrv, SPC_M2CMD, M2CMD_CARD_WRITESETUP); //should start the clock but not the ADC
spcm_dwSetParam_i64(stCardREC.hDrv, SPC_TRIG_ORMASK, SPC_TMASK_SOFTWARE);

//Some tables related to pattern
int qwMemInBytesREC = NumSamplesPerChREC * BytesPerSample * RECnumchannels;
void* pvBufferREC =(void *) new char[qwMemInBytesREC ];// pvAllocMemPageAligned (qwMemInBytesREC);
void* pvBufferKey = (void*) new char[NumSamplesPerCh * sizeof(double) * REPnumchannels];//will contain the expected locations of the beam in x,y
int NotifyBlock = 32 * 1024 * 1024;
// Here user adds code to initiate scan parameters
//


While (...) //Many scans
{
        //Here user adds code to prepare scan pattern 
        // 
        spcm_dwSetParam_i64(stCardREC.hDrv, SPC_CLOCKMODE, SPC_CM_INTPLL);
        spcm_dwSetParam_i32(stCardREC.hDrv, SPC_CLOCKOUT, 1); // enable the clock out
        spcm_dwSetParam_i32(stCardREC.hDrv, SPC_SAMPLERATE, samplerate); //ADC sampling rate 
        spcm_dwSetParam_i32(stCardREC.hDrv, SPC_M2CMD, M2CMD_CARD_WRITESETUP); //should start the clock but not the ADC
        Sleep(50);
	long long lSamplerate;
        spcm_dwGetParam_i64(stCardREC.hDrv, SPC_SAMPLERATE, &lSamplerate); // Read back the programmed ADC sample rate
        if (samplerate != (int)lSamplerate)
        {
                samplerate = (int)lSamplerate;
                printf("Sample rate not supported, using approximated !");
        }
        spcm_dwSetParam_i32(stCardREP.hDrv, SPC_CLOCKMODE, SPC_CM_EXTREFCLOCK); // Set AWG to use reference clock mode (will obtain reference from ADC card)
        spcm_dwSetParam_i32(stCardREP.hDrv, SPC_REFERENCECLOCK, samplerate); // Reference clock that is fed is samplerate
        spcm_dwSetParam_i32(stCardREP.hDrv, SPC_SAMPLERATE, DACsamplerate); // PLL will generate the lower clock frequency according to requested
        spcm_dwSetParam_i32(stCardREP.hDrv, SPC_CLOCKOUT, 1); // enable the clock out
        spcm_dwSetParam_i32(stCardREP.hDrv, SPC_M2CMD, M2CMD_CARD_WRITESETUP); //start the clock but not the AWG
        spcm_dwGetParam_i64(stCardREP.hDrv, SPC_SAMPLERATE, &lSamplerate); // Read back the programmed AWG sample rate
        DACsamplerate = (int)lSamplerate;
	printf("Pixel time=%.1f [us],  Sample Rate= %d,  AWG rate= %d,  oversampling = %d \n", 1000000.0/DACsamplerate, samplerate, DACsamplerate,oversampling);
	NumSamplesPerChREC = NumSamplesPerCh + pretrigger + more_samples;
	int NumSampNotifyBlock = (int)(NotifyBlock / (BytesPerSample * RECnumchannels));
	int incomplete_Notify = NumSamplesPerChREC % NumSampNotifyBlock;
	if (incomplete_Notify > 0) NumSamplesPerChREC = NumSamplesPerChREC + NumSampNotifyBlock - incomplete_Notify;
	if (!stCardREC.bSetError)
		dwError=bSpcMSetupModeRecFIFOSingle (pstCard, llChannelMask, pretrigger, llBlockToRec, llLoopToRec); //pretrigger of 8 pulses is minimum, but start command is followed seamlessly by a trigger 
        if (!stCardREP.bSetError)
 		bSpcMSetupModeRepStdSingle (pstCard, llChannelMask, NumLocPerCh);
	
	// REPcalculate the amount of data we need and allocate memory buffer
        qwMemInBytesREP = NumLocPerCh * BytesPerSample * REPnumchannels; //was NumSamplesPerCh * BytesPerSample * REPnumchannels;
        pvBufferREP = (void *) new char[qwMemInBytesREP];//pvAllocMemPageAligned (qwMemInBytesREP);
        Send_ArinaGate_pattern();
        Sleep(1000);
	char  szBuffer[1024]; // a character buffer for messages
	bool dwError=false;
	dwError=spcm_dwSetParam_i32(stCardREC.hDrv, SPC_M2CMD, M2CMD_CARD_INVALIDATEDATA); 
        printf("Starting the DMA buffer transfer to AWG, and waiting until data is in board memory\n");
        spcm_dwDefTransfer_i64(stCardREP.hDrv, SPCM_BUF_DATA, SPCM_DIR_PCTOCARD, 0, pvBufferREP, 0, qwMemInBytesREP); //CHECK parameter !!!!
        spcm_dwSetParam_i32(stCardREP.hDrv, SPC_M2CMD, M2CMD_DATA_STARTDMA | M2CMD_DATA_WAITDMA); //Hangs out until pattern is transfered to AWG card memory
        if (!spcm_dwGetErrorInfo_i32(stCardREP.hDrv, NULL, NULL, szBuffer)) printf("... data has been transferred to board memory\n");
        spcm_dwSetParam_i64(stCardREP.hDrv, SPC_M2CMD, M2CMD_DATA_STOPDMA); //added to make sure interrupts not comming from AWG card anymore
        //set parking position
        spcm_dwSetParam_i64(stCardREP.hDrv, SPC_CH0_STOPLEVEL, SPCM_STOPLVL_HIGH);///?
        spcm_dwSetParam_i64(stCardREP.hDrv, SPC_CH1_STOPLEVEL, SPCM_STOPLVL_HIGH);

	int64 llAvailBytes, llBytesPos, lStatus, memcount = 0;
	if (qwMemInBytesREC < NotifyBlock) NotifyBlock = qwMemInBytesREC;
	int64 llLoopToRec = qwMemInBytesREC / NotifyBlock;
	if (qwMemInBytesREC > llLoopToRec * NotifyBlock) llLoopToRec++;
        printf ("Setting DMA transfer to PC memory\n");
        spcm_dwDefTransfer_i64(stCardREC.hDrv, SPCM_BUF_DATA, SPCM_DIR_CARDTOPC, NotifyBlock, pvBufferREC, 0, qwMemInBytesREC);
        //spcm_dwGetParam_i64(stCardREC.hDrv, SPC_DATA_AVAIL_USER_LEN, &llAvailBytes);
        //spcm_dwGetParam_i64(stCardREC.hDrv, SPC_DATA_AVAIL_USER_POS, &llBytesPos);
        //spcm_dwGetParam_i64(stCardREC.hDrv, SPC_M2STATUS, &lStatus);

        printf("Starting all cards: one trigger for all, signal recording in FIFO mode\n");
        printf("Target record size [bytes]: %lld >>> ", qwMemInBytesREC);
        spcm_dwSetParam_i64(stCardREC.hDrv, SPC_DATA_AVAIL_CARD_LEN, 0); 

        // start DMA
        dwError = spcm_dwSetParam_i32(stCardREC.hDrv, SPC_M2CMD, M2CMD_DATA_STARTDMA);//M2CMD_CARD_START
        Sleep(1);
        //Start both AWG and ADC cards
        dwError = spcm_dwSetParam_i32(stCardREP.hDrv, SPC_M2CMD, M2CMD_CARD_START | M2CMD_CARD_ENABLETRIGGER);//will start only after REC card finished all pretrigger acquisition
        dwError = spcm_dwSetParam_i32(stCardREC.hDrv, SPC_M2CMD, M2CMD_CARD_START | M2CMD_CARD_FORCETRIGGER);//start pretrigger acquisition followed by trigger pulse sent to AWG card
        for (int loopn=0; loopn<llLoopToRec; loopn++)
        {
                if (!dwError)
                {
                        dwError = spcm_dwSetParam_i32(stCardREC.hDrv, SPC_M2CMD, M2CMD_DATA_WAITDMA);
                        spcm_dwGetParam_i64(stCardREC.hDrv, SPC_DATA_AVAIL_USER_LEN, &llAvailBytes);
                        if (llAvailBytes != NotifyBlock)
                        {
                                printf("?");
                        }
                        if (llAvailBytes > NotifyBlock)
                        {
                                llAvailBytes = NotifyBlock;
                        }
                        if (qwMemInBytesREC - memcount < NotifyBlock)
                        {
                                llAvailBytes = qwMemInBytesREC - memcount;
                        }
                        spcm_dwSetParam_i64 (stCardREC.hDrv, SPC_DATA_AVAIL_CARD_LEN, llAvailBytes);
                        memcount = memcount + llAvailBytes;
                        printf(" %lld.", memcount);
                }
                else
                {
                        printf ("\n... acquisition did not end well ...\n");
                        break;
                }
        }
        spcm_dwSetParam_i32(stCardREC.hDrv, SPC_M2CMD, M2CMD_CARD_STOP);
        spcm_dwSetParam_i32(stCardREP.hDrv, SPC_M2CMD, M2CMD_CARD_STOP);
        dwError = spcm_dwSetParam_i32(stCardREC.hDrv, SPC_M2CMD, M2CMD_DATA_STOPDMA);
        
        //Here user adds code to read scan data acquired
        // 
}
        
        
