Source

python-axonbinaryfile / axonbinaryfile / _abfmodule.cpp

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
extern "C" {
#include<Python.h>
#include <stdio.h>
#include <assert.h>  
#include"numpy/arrayobject.h"
}
#include<windows.h>
#include"ABFFILES.H"

extern "C" PyMODINIT_FUNC init_abf(void);

/* initial size of the data buffer */
#define START_DATA_BUFSIZE 16384

bool writeMetaData(const char* fname,ABFFileHeader& FH);
bool writeShorts(FILE * pf, const char* name, short* data, int total);
bool writeFloats(FILE * pf, const char* name, float* data, int total);
bool writeChars(FILE * pf, const char* name, char* data, int total);
bool writeStrings(FILE * pf, const char* name, char* data, int total, int maxStringSize);
bool writeLongs(FILE * pf, const char* name, long* data, int total);

BOOL ShowABFError( char *szFileName, int nError )
{
	char szTxt[80];
	if (!ABF_BuildErrorText( nError, szFileName, szTxt, sizeof(szTxt) ))
		sprintf( szTxt, "Unknown error number: %d\r\n", nError );
	printf( "ERROR: %s\n", szTxt );
	return FALSE;
}
#ifdef DEBUGTXT
bool writeMetaData(const char* fname, ABFFileHeader& FH)
{
	FILE* pf = fopen(fname,"w");
	if (!pf) return false;

	// GROUP #1 - File ID and size information
	fprintf(pf,"fFileVersionNumber\t%f\n",FH.fFileVersionNumber);
	fprintf(pf,"nOperationMode\t%d\n",FH.nOperationMode);
	fprintf(pf,"lActualAcqLength\t%d\n",FH.lActualAcqLength);
	fprintf(pf,"nNumPointsIgnored\t%d\n",FH.nNumPointsIgnored);
	fprintf(pf,"lActualEpisodes\t%d\n",FH.lActualEpisodes);
	fprintf(pf,"uFileStartDate\t%d\n",FH.uFileStartDate);
	fprintf(pf,"uFileStartTimeMS\t%d\n",FH.uFileStartTimeMS);
	fprintf(pf,"lStopwatchTime\t%d\n",FH.lStopwatchTime);
	fprintf(pf,"fHeaderVersionNumber\t%f\n",FH.fHeaderVersionNumber);
	fprintf(pf,"nFileType\t%d\n",FH.nFileType);


	// GROUP #2 - File Structure
	fprintf(pf,"lDataSectionPtr\t%d\n",FH.lDataSectionPtr);
	fprintf(pf,"lTagSectionPtr\t%d\n",FH.lTagSectionPtr);
	fprintf(pf,"lNumTagEntries\t%d\n",FH.lNumTagEntries);
	fprintf(pf,"lScopeConfigPtr\t%d\n",FH.lScopeConfigPtr);
	fprintf(pf,"lNumScopes\t%d\n",FH.lNumScopes);
	fprintf(pf,"lDeltaArrayPtr\t%d\n",FH.lDeltaArrayPtr);
	fprintf(pf,"lNumDeltas\t%d\n",FH.lNumDeltas);
	fprintf(pf,"lVoiceTagPtr\t%d\n",FH.lVoiceTagPtr);
	fprintf(pf,"lVoiceTagEntries\t%d\n",FH.lVoiceTagEntries);
	fprintf(pf,"lSynchArrayPtr\t%d\n",FH.lSynchArrayPtr);
	fprintf(pf,"lSynchArraySize\t%d\n",FH.lSynchArraySize);
	fprintf(pf,"nDataFormat\t%d\n",FH.nDataFormat);
	fprintf(pf,"nSimultaneousScan\t%d\n",FH.nSimultaneousScan);
	fprintf(pf,"lStatisticsConfigPtr\t%d\n",FH.lStatisticsConfigPtr);
	fprintf(pf,"lAnnotationSectionPtr\t%d\n",FH.lAnnotationSectionPtr);
	fprintf(pf,"lNumAnnotations\t%d\n",FH.lNumAnnotations);

	/*
	TODO : I don't think this metadata is important
	long     lDACFilePtr[ABF_DACCOUNT];
	long     lDACFileNumEpisodes[ABF_DACCOUNT];
	*/


	// GROUP #3 - Trial hierarchy information
	fprintf(pf,"nADCNumChannels\t%d\n",FH.nADCNumChannels);   
	fprintf(pf,"fADCSequenceInterval\t%f\n",FH.fADCSequenceInterval);   
	fprintf(pf,"uFileCompressionRatio\t%d\n",FH.uFileCompressionRatio);   
	fprintf(pf,"bEnableFileCompression\t%d\n",FH.bEnableFileCompression);   
	fprintf(pf,"fSynchTimeUnit\t%f\n",FH.fSynchTimeUnit);   
	fprintf(pf,"fSecondsPerRun\t%f\n",FH.fSecondsPerRun);   
	fprintf(pf,"lNumSamplesPerEpisode\t%d\n",FH.lNumSamplesPerEpisode);   
	fprintf(pf,"lPreTriggerSamples\t%d\n",FH.lPreTriggerSamples);   
	fprintf(pf,"lEpisodesPerRun\t%d\n",FH.lEpisodesPerRun);   
	fprintf(pf,"lRunsPerTrial\t%d\n",FH.lRunsPerTrial);   
	fprintf(pf,"lNumberOfTrials\t%d\n",FH.lNumberOfTrials);   
	fprintf(pf,"nAveragingMode\t%d\n",FH.nAveragingMode);   
	fprintf(pf,"nUndoRunCount\t%d\n",FH.nUndoRunCount);   
	fprintf(pf,"nFirstEpisodeInRun\t%d\n",FH.nFirstEpisodeInRun);   
	fprintf(pf,"fTriggerThreshold\t%f\n",FH.fTriggerThreshold);   
	fprintf(pf,"nTriggerSource\t%d\n",FH.nTriggerSource);   
	fprintf(pf,"nTriggerAction\t%d\n",FH.nTriggerAction);   
	fprintf(pf,"nTriggerPolarity\t%d\n",FH.nTriggerPolarity);   
	fprintf(pf,"fScopeOutputInterval\t%f\n",FH.fScopeOutputInterval);   
	fprintf(pf,"fEpisodeStartToStart\t%f\n",FH.fEpisodeStartToStart);   
	fprintf(pf,"fRunStartToStart\t%f\n",FH.fRunStartToStart);   
	fprintf(pf,"fTrialStartToStart\t%f\n",FH.fTrialStartToStart);   
	fprintf(pf,"lAverageCount\t%d\n",FH.lAverageCount);   
	fprintf(pf,"nAutoTriggerStrategy\t%d\n",FH.nAutoTriggerStrategy);   
	fprintf(pf,"fFirstRunDelayS\t%f\n",FH.fFirstRunDelayS);   



	// GROUP #4 - Display Parameters
	fprintf(pf,"nDataDisplayMode\t%d\n",FH.nDataDisplayMode);   
	fprintf(pf,"nChannelStatsStrategy\t%d\n",FH.nChannelStatsStrategy);   
	fprintf(pf,"lSamplesPerTrace\t%d\n",FH.lSamplesPerTrace);   
	fprintf(pf,"lStartDisplayNum\t%d\n",FH.lStartDisplayNum);   
	fprintf(pf,"lFinishDisplayNum\t%d\n",FH.lFinishDisplayNum);   
	fprintf(pf,"nShowPNRawData\t%d\n",FH.nShowPNRawData);   
	fprintf(pf,"fStatisticsPeriod\t%f\n",FH.fStatisticsPeriod);   
	fprintf(pf,"lStatisticsMeasurements\t%d\n",FH.lStatisticsMeasurements);   
	fprintf(pf,"nStatisticsSaveStrategy\t%d\n",FH.nStatisticsSaveStrategy);   

	// GROUP #5 - Hardware information
	fprintf(pf,"fADCRange\t%f\n",FH.fADCRange);   
	fprintf(pf,"fDACRange\t%f\n",FH.fDACRange);   
	fprintf(pf,"lADCResolution\t%d\n",FH.lADCResolution);   
	fprintf(pf,"lDACResolution\t%d\n",FH.lDACResolution);   
	fprintf(pf,"nDigitizerADCs\t%d\n",FH.nDigitizerADCs);   
	fprintf(pf,"nDigitizerDACs\t%d\n",FH.nDigitizerDACs);   
	fprintf(pf,"nDigitizerTotalDigitalOuts\t%d\n",FH.nDigitizerTotalDigitalOuts);   
	fprintf(pf,"nDigitizerSynchDigitalOuts\t%d\n",FH.nDigitizerSynchDigitalOuts);   
	fprintf(pf,"nDigitizerType\t%d\n",FH.nDigitizerType);   

	// GROUP #6 Environmental Information
	fprintf(pf,"nExperimentType\t%d\n",FH.nExperimentType);   
	fprintf(pf,"nManualInfoStrategy\t%d\n",FH.nManualInfoStrategy);   
	fprintf(pf,"fCellID1\t%d\n",FH.fCellID1);   
	fprintf(pf,"fCellID2\t%d\n",FH.fCellID2);   
	fprintf(pf,"fCellID3\t%d\n",FH.fCellID3);   
	fprintf(pf,"sProtocolPath\t%s\n",FH.sProtocolPath);   
	fprintf(pf,"sCreatorInfo\t%s\n",FH.sCreatorInfo);   
	fprintf(pf,"sModifierInfo\t%s\n",FH.sModifierInfo);   
	fprintf(pf,"nCommentsEnable\t%d\n",FH.nCommentsEnable);   
	fprintf(pf,"sFileComment\t%s\n",FH.sFileComment);   
	/*
	TODO: I am not sure what type of data this is, if anyone knows send me email.
	short    nTelegraphEnable[ABF_ADCCOUNT];
	short    nTelegraphInstrument[ABF_ADCCOUNT];
	float    fTelegraphAdditGain[ABF_ADCCOUNT];
	float    fTelegraphFilter[ABF_ADCCOUNT];
	float    fTelegraphMembraneCap[ABF_ADCCOUNT];
	float    fTelegraphAccessResistance[ABF_ADCCOUNT];
	short    nTelegraphMode[ABF_ADCCOUNT];
	short    nTelegraphDACScaleFactorEnable[ABF_DACCOUNT];

	// I added the telegraphs below because I believe they are
	// relevant when the amplifier has telegraphs which read out
	// these quantities -clm
	*/
	writeShorts(pf, "nTelegraphEnable",FH.nTelegraphEnable, ABF_ADCCOUNT);
	writeShorts(pf, "nTelegraphInstrument",FH.nTelegraphInstrument, ABF_ADCCOUNT);
	writeFloats(pf, "fTelegraphAdditGain",FH.fTelegraphAdditGain,ABF_ADCCOUNT);
	writeFloats(pf, "fTelegraphFilter", FH.fTelegraphFilter, ABF_ADCCOUNT);
	writeFloats(pf, "fTelegraphMembraneCap", FH.fTelegraphMembraneCap,ABF_ADCCOUNT);
	writeFloats(pf, "fTelegraphAccessResistance", FH.fTelegraphAccessResistance,ABF_ADCCOUNT);
	writeShorts(pf, "nTelegraphMode", FH.nTelegraphMode, ABF_ADCCOUNT);
	writeShorts(pf, "nTelegraphDACScaleFactorEnable", FH.nTelegraphDACScaleFactorEnable, ABF_DACCOUNT);

	/*
	TODO : I don't believe this data is relevant.
	short    nAutoAnalyseEnable;

	GUID     FileGUID;
	float    fInstrumentHoldingLevel[ABF_DACCOUNT];
	unsigned long ulFileCRC;
	short    nCRCEnable;
	*/

	// GROUP #7 - Multi-channel information
	fprintf(pf,"nSignalType\t%d\n",FH.nSignalType);   
	writeShorts(pf,"nADCPtoLChannelMap",FH.nADCPtoLChannelMap,ABF_ADCCOUNT);
	writeShorts(pf,"nADCSamplingSeq",FH.nADCSamplingSeq,ABF_ADCCOUNT);
	writeFloats(pf,"fADCProgrammableGain",FH.fADCProgrammableGain,ABF_ADCCOUNT);
	writeFloats(pf,"fADCDisplayAmplification",FH.fADCDisplayAmplification,ABF_ADCCOUNT);
	writeFloats(pf,"fADCDisplayOffset",FH.fADCDisplayOffset,ABF_ADCCOUNT);
	writeFloats(pf,"fInstrumentScaleFactor",FH.fInstrumentScaleFactor,ABF_ADCCOUNT);
	writeFloats(pf,"fInstrumentOffset",FH.fInstrumentOffset,ABF_ADCCOUNT);
	writeFloats(pf,"fSignalGain",FH.fSignalGain,ABF_ADCCOUNT);
	writeFloats(pf,"fSignalOffset",FH.fSignalOffset,ABF_ADCCOUNT);
	writeFloats(pf,"fSignalLowpassFilter",FH.fSignalLowpassFilter,ABF_ADCCOUNT);
	writeFloats(pf,"fSignalHighpassFilter",FH.fSignalHighpassFilter,ABF_ADCCOUNT);
	writeChars(pf,"nLowpassFilterType",FH.nLowpassFilterType,ABF_ADCCOUNT);
	writeChars(pf,"nHighpassFilterType",FH.nHighpassFilterType,ABF_ADCCOUNT);

	writeStrings(pf,"sADCChannelName",(char*)FH.sADCChannelName,ABF_ADCCOUNT,ABF_ADCNAMELEN);
	writeStrings(pf,"sADCUnits",(char*)FH.sADCUnits,ABF_ADCCOUNT,ABF_ADCNAMELEN);
	writeFloats(pf,"fDACScaleFactor",FH.fDACScaleFactor,ABF_ADCCOUNT);
	writeFloats(pf,"fDACHoldingLevel",FH.fDACHoldingLevel,ABF_ADCCOUNT);
	writeFloats(pf,"fDACCalibrationFactor",FH.fDACCalibrationFactor,ABF_ADCCOUNT);
	writeFloats(pf,"fDACCalibrationOffset",FH.fDACCalibrationOffset,ABF_ADCCOUNT);
	writeStrings(pf,"sDACChannelName",(char*)FH.sDACChannelName,ABF_DACCOUNT,ABF_DACNAMELEN);
	writeStrings(pf,"sDACChannelUnits",(char*)FH.sDACChannelUnits,ABF_DACCOUNT,ABF_DACNAMELEN);
	/*
	this group describes the stimulus waveform if it's used and
	not from a file
	// GROUP #9 - Epoch Waveform and Pulses
	short    nDigitalEnable;
	short    nActiveDACChannel;                     // should retire !
	short    nDigitalDACChannel;
	short    nDigitalHolding;
	short    nDigitalInterEpisode;
	short    nDigitalTrainActiveLogic;                                   
	short    nDigitalValue[ABF_EPOCHCOUNT];
	short    nDigitalTrainValue[ABF_EPOCHCOUNT];                         
	bool     bEpochCompression[ABF_EPOCHCOUNT];
	short    nWaveformEnable[ABF_DACCOUNT];
	short    nWaveformSource[ABF_DACCOUNT];
	short    nInterEpisodeLevel[ABF_DACCOUNT];
	short    nEpochType[ABF_DACCOUNT][ABF_EPOCHCOUNT];
	float    fEpochInitLevel[ABF_DACCOUNT][ABF_EPOCHCOUNT];
	float    fEpochLevelInc[ABF_DACCOUNT][ABF_EPOCHCOUNT];
	long     lEpochInitDuration[ABF_DACCOUNT][ABF_EPOCHCOUNT];
	long     lEpochDurationInc[ABF_DACCOUNT][ABF_EPOCHCOUNT];
	*/
	// GROUP #10 - DAC Output File
	writeFloats(pf,"fDACFileScale",FH.fDACFileScale,ABF_DACCOUNT);
	writeFloats(pf,"fDACFileOffset",FH.fDACFileOffset,ABF_DACCOUNT);
	writeLongs(pf,"lDACFileEpisodeNum",FH.lDACFileEpisodeNum,ABF_DACCOUNT);
	writeShorts(pf,"nDACFileADCNum",FH.nDACFileADCNum,ABF_DACCOUNT);
	writeStrings(pf,"sDACFilePath",(char*)FH.sDACFilePath,ABF_DACCOUNT,ABF_PATHLEN);


	// GROUP #11 - Presweep (conditioning) pulse train
	writeShorts(pf,"nConditEnable",FH.nConditEnable,ABF_DACCOUNT);
	writeLongs(pf,"lConditNumPulses",FH.lConditNumPulses,ABF_DACCOUNT);
	writeFloats(pf,"fBaselineDuration",FH.fBaselineDuration,ABF_DACCOUNT);
	writeFloats(pf,"fBaselineLevel",FH.fBaselineLevel,ABF_DACCOUNT);
	writeFloats(pf,"fStepDuration",FH.fStepDuration,ABF_DACCOUNT);
	writeFloats(pf,"fStepLevel",FH.fStepLevel,ABF_DACCOUNT);
	writeFloats(pf,"fPostTrainPeriod",FH.fPostTrainPeriod,ABF_DACCOUNT);
	writeFloats(pf,"fPostTrainLevel",FH.fPostTrainLevel,ABF_DACCOUNT);
	writeShorts(pf,"nMembTestEnable",FH.nMembTestEnable,ABF_DACCOUNT);
	writeFloats(pf,"fMembTestPreSettlingTimeMS",FH.fMembTestPreSettlingTimeMS,ABF_DACCOUNT);
	writeFloats(pf,"fMembTestPostSettlingTimeMS",FH.fMembTestPostSettlingTimeMS,ABF_DACCOUNT);

	// GROUP #12 - Variable parameter user list
	writeShorts(pf,"nULEnable",FH.nULEnable,ABF_USERLISTCOUNT);
	writeShorts(pf,"nULParamToVary",FH.nULParamToVary,ABF_USERLISTCOUNT);
	writeShorts(pf,"nULRepeat",FH.nULRepeat,ABF_USERLISTCOUNT);
	writeStrings(pf,"sDACFilePath",(char*)FH.sDACFilePath,ABF_USERLISTCOUNT,ABF_USERLISTLEN);

	// GROUP #13 - Statistics measurements
	fprintf(pf,"nStatsEnable\t%d\n",FH.nStatsEnable);   
	fprintf(pf,"nStatsActiveChannels\t%d\n",FH.nStatsActiveChannels);   
	fprintf(pf,"nStatsSearchRegionFlags\t%d\n",FH.nStatsSearchRegionFlags);   
	fprintf(pf,"nStatsSmoothing\t%d\n",FH.nStatsSmoothing);   
	fprintf(pf,"nStatsSmoothingEnable\t%d\n",FH.nStatsSmoothingEnable);   
	fprintf(pf,"nStatsBaseline\t%d\n",FH.nStatsBaseline);   
	fprintf(pf,"nStatsBaselineDAC\t%d\n",FH.nStatsBaselineDAC);   
	fprintf(pf,"lStatsBaselineStart\t%d\n",FH.lStatsBaselineStart);   
	fprintf(pf,"lStatsBaselineEnd\t%d\n",FH.lStatsBaselineEnd);   
	writeLongs(pf,"lStatsMeasurements",FH.lStatsMeasurements,ABF_STATS_REGIONS);
	writeLongs(pf,"lStatsStart",FH.lStatsStart,ABF_STATS_REGIONS);
	writeLongs(pf,"lStatsEnd",FH.lStatsEnd,ABF_STATS_REGIONS);
	writeShorts(pf,"nRiseBottomPercentile",FH.nRiseBottomPercentile,ABF_STATS_REGIONS);
	writeShorts(pf,"nRiseTopPercentile",FH.nRiseTopPercentile,ABF_STATS_REGIONS);
	writeShorts(pf,"nDecayBottomPercentile",FH.nDecayBottomPercentile,ABF_STATS_REGIONS);
	writeShorts(pf,"nDecayTopPercentile",FH.nDecayTopPercentile,ABF_STATS_REGIONS);
	writeShorts(pf,"nStatsChannelPolarity",FH.nStatsChannelPolarity,ABF_ADCCOUNT);
	writeShorts(pf,"nStatsSearchMode",FH.nStatsSearchMode,ABF_STATS_REGIONS);
	writeShorts(pf,"nStatsSearchDAC",FH.nStatsSearchDAC,ABF_STATS_REGIONS);

	// GROUP #14 - Channel Arithmetic
	fprintf(pf,"nArithmeticEnable\t%d\n",FH.nArithmeticEnable);   
	fprintf(pf,"nArithmeticExpression\t%d\n",FH.nArithmeticExpression);   
	fprintf(pf,"fArithmeticLowerLimit\t%f\n",FH.fArithmeticLowerLimit);   
	fprintf(pf,"fArithmeticLowerLimit\t%f\n",FH.fArithmeticLowerLimit);   
	fprintf(pf,"nArithmeticADCNumA\t%d\n",FH.nArithmeticADCNumA);   
	fprintf(pf,"nArithmeticADCNumB\t%d\n",FH.nArithmeticADCNumB);   
	fprintf(pf,"fArithmeticK1\t%f\n",FH.fArithmeticK1);   
	fprintf(pf,"fArithmeticK2\t%f\n",FH.fArithmeticK2);   
	fprintf(pf,"fArithmeticK3\t%f\n",FH.fArithmeticK3);   
	fprintf(pf,"fArithmeticK4\t%f\n",FH.fArithmeticK4);   
	fprintf(pf,"fArithmeticK5\t%f\n",FH.fArithmeticK5);   
	fprintf(pf,"sArithmeticOperator\t%s\n",FH.sArithmeticOperator);   //Test for overflow condition?
	fprintf(pf,"sArithmeticUnits\t%s\n",FH.sArithmeticUnits);   
	// GROUP #15 - Leak subtraction
	fprintf(pf,"nPNPosition\t%d\n",FH.nPNPosition);   
	fprintf(pf,"nPNNumPulses\t%d\n",FH.nPNNumPulses);   
	fprintf(pf,"nPNPolarity\t%d\n",FH.nPNPolarity);   
	fprintf(pf,"fPNSettlingTime\t%f\n",FH.fPNSettlingTime);   
	fprintf(pf,"fPNInterpulse\t%f\n",FH.fPNInterpulse);   
	writeShorts(pf,"nLeakSubtractType",FH.nLeakSubtractType,ABF_DACCOUNT);
	writeFloats(pf,"fPNHoldingLevel",FH.fPNHoldingLevel,ABF_DACCOUNT);
	/* I don't see this defined anywhere
	writeShorts(pf,"nLeakSubtractADCIndex",FH.nLeakSubtractADCIndex,ABF_DACCOUNT);
	*/

	// GROUP #16 - Miscellaneous variables
	fprintf(pf,"nLevelHysteresis\t%d\n",FH.nLevelHysteresis);   
	fprintf(pf,"lTimeHysteresis\t%d\n",FH.lTimeHysteresis);   
	fprintf(pf,"nAllowExternalTags\t%d\n",FH.nAllowExternalTags);   
	fprintf(pf,"nAverageAlgorithm\t%d\n",FH.nAverageAlgorithm);   
	fprintf(pf,"fAverageWeighting\t%f\n",FH.fAverageWeighting);   
	fprintf(pf,"nUndoPromptStrategy\t%d\n",FH.nUndoPromptStrategy);   
	fprintf(pf,"nTrialTriggerSource\t%d\n",FH.nTrialTriggerSource);   
	fprintf(pf,"nStatisticsDisplayStrategy\t%d\n",FH.nStatisticsDisplayStrategy);   
	fprintf(pf,"nExternalTagType\t%d\n",FH.nExternalTagType);   
	fprintf(pf,"lHeaderSize\t%d\n",FH.lHeaderSize);   
	fprintf(pf,"nStatisticsClearStrategy\t%d\n",FH.nStatisticsClearStrategy);   

	// GROUP #17 - Trains parameters
	/*
	TODO : find out about this
	long     lEpochPulsePeriod[ABF_DACCOUNT][ABF_EPOCHCOUNT];
	long     lEpochPulseWidth [ABF_DACCOUNT][ABF_EPOCHCOUNT];
	*/
	// GROUP #18 - Application version data
	fprintf(pf,"nCreatorMajorVersion\t%d\n",FH.nCreatorMajorVersion);   
	fprintf(pf,"nCreatorMinorVersion\t%d\n",FH.nCreatorMinorVersion);   
	fprintf(pf,"nCreatorBugfixVersion\t%d\n",FH.nCreatorBugfixVersion);   
	fprintf(pf,"nCreatorBuildVersion\t%d\n",FH.nCreatorBuildVersion);   
	fprintf(pf,"nModifierMajorVersion\t%d\n",FH.nModifierMajorVersion);   
	fprintf(pf,"nModifierMinorVersion\t%d\n",FH.nModifierMinorVersion);   
	fprintf(pf,"nModifierBugfixVersion\t%d\n",FH.nModifierBugfixVersion);   
	fprintf(pf,"nModifierBuildVersion\t%d\n",FH.nModifierBuildVersion);   

	// GROUP #19 - LTP protocol
	fprintf(pf,"nLTPType\t%d\n",FH.nLTPType);   
	writeShorts(pf,"nLTPUsageOfDAC",FH.nLTPUsageOfDAC,ABF_DACCOUNT);
	writeShorts(pf,"nLTPPresynapticPulses",FH.nLTPPresynapticPulses,ABF_DACCOUNT);

	// GROUP #20 - Digidata 132x Trigger out flag
	fprintf(pf,"nScopeTriggerOut\t%d\n",FH.nScopeTriggerOut);   


	// GROUP #22 - Alternating episodic mode
	fprintf(pf,"nAlternateDACOutputState\t%d\n",FH.nAlternateDACOutputState);   
	fprintf(pf,"nAlternateDigitalOutputState\t%d\n",FH.nAlternateDigitalOutputState);   
	writeShorts(pf,"nAlternateDigitalValue",FH.nAlternateDigitalValue,ABF_EPOCHCOUNT);
	writeShorts(pf,"nAlternateDigitalTrainValue",FH.nAlternateDigitalTrainValue,ABF_EPOCHCOUNT);

	// GROUP #23 - Post-processing actions
	writeFloats(pf,"fPostProcessLowpassFilter",FH.fPostProcessLowpassFilter,ABF_ADCCOUNT);
	writeChars(pf,"nPostProcessLowpassFilterType",FH.nPostProcessLowpassFilterType,ABF_ADCCOUNT);

	// GROUP #24 - Legacy gear shift info
	fprintf(pf,"fLegacyADCSequenceInterval\t%f\n",FH.fLegacyADCSequenceInterval);   
	fprintf(pf,"fLegacyADCSecondSequenceInterval\t%f\n",FH.fLegacyADCSecondSequenceInterval);   
	fprintf(pf,"lLegacyClockChange\t%d\n",FH.lLegacyClockChange);   
	fprintf(pf,"lLegacyNumSamplesPerEpisode\t%d\n",FH.lLegacyNumSamplesPerEpisode);   

	fclose(pf);
	return true;
}
#endif /* DEBUGTXT */

PyObject* createMetaDataDict(ABFFileHeader& FH)
{
  PyObject *dict = PyDict_New();
  // notes:
  // PyDict_SetItem(dict, key, val);
  // PyInt_FromLong(long ival)
  // PyInt_FromString
  // PyLong_FromLong(long v)
  // PyLong_FromDouble
  // PyFloat_FromDouble
  // PyString_FromString(const char*v) (_FromStringAndSize(char*v, ssize_t len)
  // f - float, n - short, l - long, u - UINT, b -bool,
  // arrasys: s - char array, n - short array
  // GROUP #1 - File ID and size information

  // use this semi-automatically generated code snippet to translate
  // the header to python
  
  #include"abf_hdr_snippet.c"

  return dict;
}

#ifdef DEBUGTXT
bool writeLongs(FILE * pf, const char* name, long* data, int total)
{
	fprintf(pf,"%s\t", name);
	for (int i=0; i< total; i++)
	{
		fprintf(pf,"%d%c", data[i], i==total-1?'\n':'\t');
	}
	return true;
}


bool writeShorts(FILE * pf, const char* name, short* data, int total)
{
	fprintf(pf,"%s\t", name);
	for (int i=0; i< total; i++)
	{
		fprintf(pf,"%d%c", data[i], i==total-1?'\n':'\t');
	}
	return true;
}

bool writeFloats(FILE * pf, const char* name, float* data, int total)
{
	fprintf(pf,"%s\t", name);
	for (int i=0; i< total; i++)
	{
		fprintf(pf,"%f%c", data[i], i==total-1?'\n':'\t');
	}
	return true;
}

bool writeChars(FILE * pf, const char* name, char* data, int total)
{
	fprintf(pf,"%s\t", name);
	for (int i=0; i< total; i++)
	{
		fprintf(pf,"%d%c", data[i], i==total-1?'\n':'\t');
	}
	return true;
}

bool writeStrings(FILE * pf, const char* name, char* data, int total, int maxStringSize)
{
	fprintf(pf,"%s\t", name);
	for (int i=0; i< total*maxStringSize; i+= maxStringSize)
	{
		char buf[512];
		for (int j = 0; j < maxStringSize; j ++)
		{
			buf[j] = data[i+j];
		}
		buf[maxStringSize] =0;
		fprintf(pf,"%s%c", buf, i==(total-1)*maxStringSize?'\n':'\t');
	}
	return true;

}
#endif //DEBUGTXT


static PyObject *
abf_test(PyObject *self, PyObject *args)
{
  const char *file_name;
  int ret=42;
  
  if(!PyArg_ParseTuple(args, "s", &file_name)) {
    return NULL;
  }
  printf("file_name:%s\n", file_name);
  return Py_BuildValue("i", ret);
}

static PyObject *
abf_get_header_info(PyObject *self, PyObject *args)
/*
  read ABF file header
 */
{
  const char *file_name;
  char inFname[1024];  
  int hFile;
  int nError;
  ABFFileHeader FH;
  DWORD dwMaxEpi = 0;
  /* claim is max <64k because  why so small only relevant for GAPFREE or EVENT-DETECTED-VARIABLE-LENGTH*/
  UINT uMaxSamples = START_DATA_BUFSIZE; 
  // UINT uNumSamples;

  if(!PyArg_ParseTuple(args, "s", &file_name)) {
    return NULL;
  }


  BOOL bSuccess= ABF_ReadOpen(file_name, &hFile, ABF_DATAFILE, &FH,
			      &uMaxSamples, &dwMaxEpi, &nError);
  if (bSuccess == 0) {
    ShowABFError(inFname, nError);
    // would be good if could raise error -- need to review c-api for exceptions
    return NULL;
  }
  
  PyObject *meta_dict = createMetaDataDict(FH);

  if (!ABF_Close( hFile, &nError ))
    ShowABFError(inFname, nError);

  return Py_BuildValue("N", meta_dict);
}


static PyObject*
abf_get_cmdwaveform(PyObject *self, PyObject *args)
/* abf_get_cmdwaveform(file_name, episode, channel) */
{
  const char *file_name;
  int episode_num;
  int channel_num;
  int hFile;
  int nError;
  ABFFileHeader FH;
  DWORD dwMaxEpi = 0;
  DWORD dwEpisode;
  UINT uMaxSamples = START_DATA_BUFSIZE; 
  UINT uNumSamples;

  

  if(!PyArg_ParseTuple(args, "sii", &file_name,&episode_num,&channel_num)) {
    return NULL;
  }
  printf("file_name: %s, episode_num: %d, channel_num:%d\n", file_name, episode_num, channel_num);

  BOOL bSuccess= ABF_ReadOpen(file_name, &hFile, ABF_DATAFILE, &FH,
			      &uMaxSamples, &dwMaxEpi, &nError);
  if (!bSuccess) {
    return NULL;
  }
  /* !!! Todo: check that channel_num and episode num is in range */
  
  /* figure out size of a cmd waveform*/
  uNumSamples = FH.lNumSamplesPerEpisode/FH.nADCNumChannels;
  printf("uNumSamples=%u\n", uNumSamples);

  npy_intp dims[1];
  dims[0] = uNumSamples;
  PyObject* arrobj = PyArray_SimpleNew(1, dims, NPY_FLOAT);
  float *fptr= (float*)PyArray_DATA(arrobj);
  
  /* GetWaveform stuff */
  dwEpisode=episode_num;
  bSuccess=ABF_GetWaveform(hFile, &FH, channel_num, dwEpisode, fptr, &nError);
  if (!bSuccess) {
    return NULL;
  }

  char inFname[1024];  /* don't remember what's this for !!! */
  if (!ABF_Close( hFile, &nError )) {
    ShowABFError(inFname, nError);
  }
  
  return Py_BuildValue("N", arrobj); /* !!! check on REF counting here*/
  /* end GetWaveformStuff */
}


static PyObject *
abf_read_episodic_file(PyObject *self, PyObject *args)
/*
  quickie code to read an ABF file recorded in episodic stim mode
 */
{
  const char *file_name;
  char inFname[1024];  
  int hFile;
  int nError;
  ABFFileHeader FH;
  DWORD dwMaxEpi = 0;
  /* claim is max <64k because  why so small only relevant for GAPFREE or EVENT-DETECTED-VARIABLE-LENGTH*/
  UINT uMaxSamples = START_DATA_BUFSIZE; 
  UINT uNumSamples;

  if(!PyArg_ParseTuple(args, "s", &file_name)) {
    return NULL;
  }


  BOOL bSuccess= ABF_ReadOpen(file_name, &hFile, ABF_DATAFILE, &FH,
			      &uMaxSamples, &dwMaxEpi, &nError);
  
  uNumSamples = FH.lNumSamplesPerEpisode/FH.nADCNumChannels;
  assert(uNumSamples > 0);

  float* pfBuffer = new float[ uNumSamples];

  DWORD dwEpisode;
#ifdef DEBUGTXT
  FILE* pf = fopen("testing.log","w");
#endif //DEBUGTXT

  // episode, ch, sample_num

  npy_intp dims[3];
  dims[0] = FH.lActualEpisodes; 
  dims[1] = FH.nADCNumChannels;
  dims[2] = uNumSamples;
  PyObject* arrobj = PyArray_SimpleNew(3, dims, NPY_FLOAT);
  float *fptr= (float*)PyArray_DATA(arrobj);


  //  episodes count appeart to start at 1
  for (dwEpisode=1;dwEpisode <= dwMaxEpi; dwEpisode++) {
    for (int nChannel =0; nChannel < FH.nADCNumChannels; nChannel++) {
      
      //some channels might not be used this compensates for that.
      int thisChannel = FH.nADCSamplingSeq[nChannel];

      bSuccess = ABF_ReadChannel( hFile,
				  &FH,
				  thisChannel,
				  dwEpisode,
				  pfBuffer,
				  &uNumSamples, &nError );
      if (!bSuccess)  {
	ShowABFError(inFname, nError);
      }   
      for(long zz=0; zz < dims[2]; zz++) {
	fptr[(dwEpisode-1)*dims[1]*dims[2]+nChannel*dims[2]+zz] = pfBuffer[zz];
      }
    }
  }
#ifdef DEBUGTXT
  fclose(pf);

  sprintf(outFileName,"%s-md.txt",inFname);
  
  if (!writeMetaData("test-md.txt",FH))
    {
      fprintf(stderr,"Couldn't write metadata file\n");
    }
#endif //DEBUGTXT
  PyObject *meta_dict = createMetaDataDict(FH);

  if (!ABF_Close( hFile, &nError ))
    ShowABFError(inFname, nError);

  return Py_BuildValue("NN", meta_dict, arrobj);
}

/*
BOOL WINAPI ABF_GetWaveform(int nFile, const ABFFileHeader *pFH, UINT uDACChannel, DWORD dwEpisode, 
                              float *pfBuffer, int *pnError);

#include "abffiles.h"
//from examples in ABF lib
*/
BOOL ShowWaveforms(char*pszFileName, int nFile, ABFFileHeader *pFH, int nChannel)
{
  int nError;
  DWORD I=0;
  UINT uNumSamples = (UINT)pFH->lNumSamplesPerEpisode/ pFH->nADCNumChannels;
  float *pfBuffer = (float*) malloc(uNumSamples*sizeof(float));
  if(!pfBuffer) {
    printf("Out of mem\n");
    return FALSE;
  }
  for(DWORD i=1; i<=(DWORD)pFH->lActualEpisodes; I++) {
    if(!ABF_GetWaveform(nFile, pFH, nChannel, I, pfBuffer,&nError)) {
      free(pfBuffer);
      return ShowABFError(pszFileName, nError);
    }
    printf("Episode %lu\n", i);
    for(UINT j=0; j<uNumSamples;j++) {
      printf("%g\n", pfBuffer[j]);
    }
  }
  free(pfBuffer);
  return TRUE;
}




static PyMethodDef _abf_methods[] = {
  //  {"abf_smoke_test", abf_test, METH_VARARGS, "test out module compilation"},
  {"get_header_info", abf_get_header_info, METH_VARARGS, "get_header_info(file_name) gets the header information for an abf file and returns a python dictionary."},
  {"read_episodic_file", abf_read_episodic_file, METH_VARARGS, "Read a axon binary file recorded in episodic mode.\n"
" meta, arr = read_episodic_file('filename.abf')\n"
" where meta is a dictionary of the metadata in the file\n"
" arr is 3 dimensional numpy array of floats.\n"
" The array indexes the episode, channel and sample number in the form\n"
"   arr[ <episode number>, <channel_number>, <sample_number>]\n\n"
" Currently, this only suports episodic mode recordings"},
  {"get_cmdwaveform", abf_get_cmdwaveform, METH_VARARGS, ""
   "Read a axon binary file and return the command waveform for that recorded in episodic mode.\n"
   " arr = get_cmdwaveform('filename.abf',dac_channel_num, episode_num)\n"
   " arr is 1 dimensional numpy array of floats (32 bit).\n"},
  {NULL,NULL, 0, NULL}
};

PyMODINIT_FUNC
init_abf(void)
{
  (void) Py_InitModule("_abf", _abf_methods);
  // when ready to add numpy
  import_array();
}