summaryrefslogtreecommitdiff
path: root/cad/plugins/NanoVision-1/src/Plugins/NanorexMMPImportExport/NanorexMMPImportExport.rl
blob: b13016dac3e4f3fd807fa416ae8381081b399b7e (plain)
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
// *********************** GENERATED BY RAGEL 6.0 *******************
// ** Do not edit directly. Edit NanorexMMPImportExport.rl instead **
// ******************************************************************

// Copyright 2008 Nanorex, Inc.  See LICENSE file for details.

#include "NanorexMMPImportExport.h"
#include <Nanorex/Interface/NXAtomData.h>
#include <Nanorex/Utility/NXUtility.h>
#include <QFileInfo>

#define VERBOSE

#if defined(VERBOSE)

#if 0
#define CDEBUG(s) DEBUG_MSG(inputFilename, lineNum, s)
inline void DEBUG_MSG(string const& filename, int line, string const& s)
{
	NXLOG_DEBUG(filename, NXUtility::itos(line)+": "+s);
/*    Nanorex::NXLogger* logger = Nanorex::NXLogger::Instance();
    if (logger != 0)
        logger->log(Nanorex::NXLogLevel_Info, filename, msg.str());*/
}
#endif

#define CERR(s) { cerr << inputFilename << ": " << NXUtility::itos(lineNum) \
<< ": " << s << endl; }
// #define CDEBUG(s) NXLOG_DEBUG(inputFilename, NXUtility::itos(lineNum)+": "+s)
#define CDEBUG(s) { cerr << inputFilename << ": " << NXUtility::itos(lineNum) \
<< ": " << s << endl; }
#define CLOG(s) NXLOG_INFO(inputFilename, NXUtility::itos(lineNum)+": "+s)

#else
#define CDEBUG(s)
#define CLOG(s)
#endif

#define CSEVERE(s) NXLOG_SEVERE(inputFilename, NXUtility::itos(lineNum)+": "+s)



%%{
# Ragel fsm
	
	machine mmp_parser;
	
	include group "group.rl";
	
	
	mmpformat_line =
		'mmpformat'  nonNEWLINEspace+
		digit{6} nonNEWLINEspace+
		'required' nonNEWLINEspace*
		(   ';' nonNEWLINEspace+
		    digit{6} nonNEWLINEspace+
		    'preferred'
		)?
		nonNEWLINEspace*
		EOL;
	
	kelvin_line =
		'kelvin'
		nonNEWLINEspace+
		whole_number % { kelvinTemp = intVal; }
	nonNEWLINEspace*
		EOL;
	
	end_line = 'end' nonNEWLINEspace+;
	
	
main := (nonNEWLINEspace* EOL)*
		mmpformat_line
		WHITESPACE*
		( kelvin_line
		  WHITESPACE*
		)?
		group_view_data_stmt_begin_line
		@ { fhold; fcall group_scanner; }
	WHITESPACE*
		group_mol_struct_stmt_begin_line
		@ { fhold; fcall group_scanner; }
	WHITESPACE*
		end1_line
		WHITESPACE*
		group_clipboard_stmt_begin_line
		@ { fhold; fcall group_scanner; }
	WHITESPACE*
		end_line
		any*
		;
	
# dynamic stack re-sizing
	prepush {
		cerr << "Ragel stack prepush: top = " << top << ", stackSize = " << stackSize << endl;
		if(top == stackSize) {
			stackSize += stackSize;
			stack.resize(stackSize, 0);
			cerr << "Resized stack to " << stackSize << endl;
		}
	}
	
}%%

%% # Ragel FSM data


// static data from Ragel

%% write data;


// static data from class NanorexMMPImportExport

char const NanorexMMPImportExport::_s_bondOrderString[NUM_BOND_TYPES] = {
	'1', '2', '3', 'a', 'g', 'c'
};

char const
NanorexMMPImportExport::_s_bondOrderNameString[NUM_BOND_TYPES][16] =
{
	"single", "double", "triple", "aromatic", "graphitic", "carbomeric"
};

char const NanorexMMPImportExport::_s_hybridizationName[8][8] = {
	"none", "sp", "sp2", "sp3", "X-hyb4", "X-hyb5", "X-hyb6", "X-hyb7"
};

/*static*/
void NanorexMMPImportExport::SetResult(NXCommandResult& commandResult,
                                       int errCode,
                                       string const& errMsg)
{
	commandResult.setResult(errCode);
	vector<QString> message;
	message.push_back(QObject::tr(errMsg.c_str()));
	commandResult.setParamVector(message);
}

// .............................................................................

/* static */
void NanorexMMPImportExport::ClearResult(NXCommandResult& commandResult)
{
	commandResult.setResult((int) NX_CMD_SUCCESS);
	vector<QString> message;
	commandResult.setParamVector(message);
}


/* CONSTRUCTOR */
NanorexMMPImportExport::NanorexMMPImportExport()
{
	reset();
}

/* DESTRUCTOR */
NanorexMMPImportExport::~NanorexMMPImportExport()
{
}


/* FUNCTION: reset */
void NanorexMMPImportExport::reset(void)
{
	inputFilename.clear();
	dataStoreInfo = (NXDataStoreInfo*) NULL;
	
	lineNum = 0;
	insideViewDataGroup = false;
	insideClipboardGroup = false;
	
	atomPtr = NULL;
	bondPtr = NULL;
	foundAtomList.clear();
	targetAtomList.clear();
	molPtr = NULL;
	molSetPtr = NULL;
	molSetPtrStack.clear();
	molStyle = "def";
	
	clipboardGroup = NULL;
	
	// defaultAtomStyle = "def";
	// defaultAtomStyleStack.clear();
	
	// ragel stack
	stackSize = 2;
	stack.clear();
	stack.resize(stackSize, 0);
	
    // initialize the ragel engine
	%% write init;
}


/* FUNCTION: importFromFile */
NXCommandResult*
NanorexMMPImportExport::
importFromFile(NXMoleculeSet *rootMoleculeSetPtr,
               NXDataStoreInfo *dsInfo,
               const std::string& theFilename,
               int /*frameSetId*/, int /*frameIndex*/)
{
	reset();
	bool success = true;
	
	ClearResult(commandResult);
	
	ifstream mmpfile(theFilename.c_str(), ios::in);
	if(!mmpfile) {
		populateCommandResult(&commandResult,
		                      (string("Couldn't open file: ") + theFilename)
		                      .c_str());
		success = false;
	}
	else {
		inputFilename = theFilename;
		dataStoreInfo = dsInfo;
		success = readMMP(mmpfile, rootMoleculeSetPtr);
	}
	
	// Set the meta information about the data store.
	if (success) {
		dataStoreInfo->setIsSingleStructure(true);
	}
	
	return &commandResult;
}


/* FUNCTION: readMMP */
bool NanorexMMPImportExport::readMMP(istream& instream,
                                     NXMoleculeSet *rootMoleculeSetPtr)
{
	p = RagelIstreamPtr(instream);
	pe = RagelIstreamPtr(instream, 0, ios::end);
	eof = pe;
	
	this->rootMoleculeSetPtr = rootMoleculeSetPtr;
	molSetPtr = NULL;
	// molSetPtrStack.push(molSetPtr);
	
    /// @todo handle first 'group' statement and molSetPtrStack initialization
	
    // Ragel parser implementation
	bool success = true;
	%% write exec;
	
    // End-of-parsing sanity checks
	if(molSetPtrStack.size() != 0) {
		NXLOG_WARNING("NanorexMMPImportExport",
		              "At least one group has no matching egroup statement");
	}
	return success;
}


/* FUNCTION newAtom */
void NanorexMMPImportExport::newAtom(int id, int atomicNum, int x, int y, int z,
                                     string const& style)
{
	if(molPtr == NULL) {
		CSEVERE("No parent molecule for atom");
		return;
	}
	
	// error if id was previously specified
	map<int,OBAtom*>::const_iterator atomExistsQuery =
		foundAtomList.find(id);
	if(atomExistsQuery != foundAtomList.end()) {
		NXLOG_SEVERE("NanorexMMPImportExport",
		             "Atom-id " + NXUtility::itos(id) + " is repeated");
		return;
	}
	
	
	atomPtr = molPtr->NewAtom();
	/// @note OpenBabel assigns atomicNum to a 'char' variable so modulo 256
	atomPtr->SetAtomicNum(atomicNum);
	/// @todo set implicit valence based on role (axis, strand etc)
	if(atomicNum >= 200)
		atomPtr->SetImplicitValence(4);
	NXAtomData *atomDataPtr = new NXAtomData(atomicNum);
	atomDataPtr->setIdx(id);
	atomDataPtr->setRenderStyleCode(style);
	assert(atomDataPtr->GetDataType() == NXAtomDataType);
	atomPtr->SetData(atomDataPtr); // atomic number
	assert(atomPtr->HasData(NXAtomDataType));
	// convert to Angstroms
	double const LENGTH_SCALE = 1.0e-3;
	atomPtr->SetVector(double(x) * LENGTH_SCALE,
	                   double(y) * LENGTH_SCALE,
	                   double(z) * LENGTH_SCALE);
	
	foundAtomList[id] = atomPtr;
	
	bondPtr = NULL;	
	
	CDEBUG("atom " + NXUtility::itos(atomId) + " (" + NXUtility::itos(atomicNum)
	       + ") (" + NXUtility::itos(x) + ',' + NXUtility::itos(y) + ',' +
	       NXUtility::itos(z) + ") " + atomStyle);
}


/* FUNCTION: newAtomInfo*/
void NanorexMMPImportExport::newAtomInfo(string const& key,
                                         string const& value)
{
	if(insideViewDataGroup)
		return;
	
	if(atomPtr != NULL) {
		if(key == "atomtype") { // hybridization info
			if(value == "sp") atomPtr->SetHyb(1);
			else if(value == "sp2") atomPtr->SetHyb(2);
			else if(value == "sp2_g") atomPtr->SetHyb(2);
			else if(value == "sp3") atomPtr->SetHyb(3);
			else if(value == "sp3d") atomPtr->SetHyb(3);
            // else ignore
		}
	}
	
	CDEBUG("info atom '" + key + "' = '" + value + "'");
}


/* FUNCTION: newBond */
void NanorexMMPImportExport::newBond(string const& bondType, int targetAtomId)
{
	if(insideViewDataGroup)
		return;
	
	assert(molPtr != NULL && atomPtr != NULL);
	
	map<int,OBAtom*>::iterator targetAtomExistsQuery =
		foundAtomList.find(targetAtomId);
	
	if(targetAtomExistsQuery == foundAtomList.end()) {
		CSEVERE("**ERROR** attempting to bond to non-existent atomID "
		        + NXUtility::itos(targetAtomId));
	}
	else {
		OBAtom *const targetAtomPtr = targetAtomExistsQuery->second;
		// guard against duplicates
		// also a hack to protect against Ragel's duplicate parsing
		// when encountering a blank line
		if(molPtr->GetBond(atomPtr, targetAtomPtr) == NULL) {
			// bond was not previously encountered, include
			int atomId = ((NXAtomData*)(atomPtr->GetData(NXAtomDataType)))->getIdx();
			CDEBUG("bonding atom #" + NXUtility::itos(atomId) +
			       " to atom #" + NXUtility::itos(targetAtomId));
			bondPtr = molPtr->NewBond();
			bondOrder = GetBondOrderFromType(bondType);
			bondPtr->SetBondOrder(bondOrder);
			atomPtr->AddBond(bondPtr);
			targetAtomPtr->AddBond(bondPtr);
			bondPtr->SetBegin(atomPtr);
			bondPtr->SetEnd(targetAtomPtr);
			CDEBUG("bond" + bondType + " " + NXUtility::itos(targetAtomId));
		}
		else {
			CSEVERE("bond to atom #" + NXUtility::itos(targetAtomId) +
			        " already exists");
		}
	}
	
}


/* FUNCTION: GetBondOrderFromType */
int NanorexMMPImportExport::GetBondOrderFromType(string const& type)
{
	if(type == "1")
		return 1;
	else if(type == "2")
		return 2;
	else if(type == "3")
		return 3;
	else if(type == "a")
		return 4;
	else if(type == "c")
		return 5;
	else if (type == "g")
		return 6;
	else {
		return -1;
	}
}


/* FUNCTION: newBondDirection */
void NanorexMMPImportExport::newBondDirection(int atomId1, int atomId2)
{
	/// @todo Implement post-FNANO08
	// no-op for FNANO08
}


/* FUNCTION: newMolecule */
void
NanorexMMPImportExport::newMolecule(string const& name, string const& style)
{
	if(insideViewDataGroup)
		return;
	
	atomPtr = NULL;
	bondPtr = NULL;
	molPtr = molSetPtr->newMolecule();
	molPtr->SetTitle(name.c_str());
	if(style == "")
		molStyle = "def";
	else
		molStyle = style;
	CDEBUG("mol (" + name + ") " + style);
}


/* FUNCTION: newViewDataGroup */
void NanorexMMPImportExport::newViewDataGroup(void)
{
	insideViewDataGroup = true;
	CDEBUG("[special] group (View Data)");
}


void
NanorexMMPImportExport::
newNamedView(std::string const& name,
             double const& qw, double const& qx, double const& qy,
             double const& qz, double const& scale,
             double const& povX, double const& povY,
             double const& povZ, double const& zoomFactor)
{
	// No need to convert to Angstroms - already NV1's internal units
	double const TO_ANG = 1.0 /*1.0e-10*/;
	if(insideViewDataGroup) {
		NXNamedView view(name,
		                 NXQuaternion<double>(qw, qx*TO_ANG,
		                                      qy*TO_ANG, qz*TO_ANG),
		                 scale*TO_ANG,
		                 NXVector3d(povX*TO_ANG, povY*TO_ANG, povZ*TO_ANG),
		                 zoomFactor);
		if(name == "HomeView")
			dataStoreInfo->setHomeView(view);
		else if(name == "LastView")
			dataStoreInfo->setLastView(view);
		else
			dataStoreInfo->addOtherView(view);
	}
	
	CDEBUG("csys (" + name + ") " +
	       '(' + NXUtility::dtos(qw) + ',' + NXUtility::dtos(qx) + ',' +
	       NXUtility::dtos(qz) + ',' + NXUtility::dtos(qz) + ") " +
	       '(' + NXUtility::dtos(scale) + ") " +
	       '(' + NXUtility::dtos(povX) + ',' + NXUtility::dtos(povY) + ',' +
	       NXUtility::dtos(povZ) + ") " +
	       '(' + NXUtility::dtos(zoomFactor) + ')');
}


/* FUNCTION: newMolStructGroup */
void NanorexMMPImportExport::newMolStructGroup(string const& name,
                                               string const& classification)
{
// 	if(insideClipboardGroup && molSetPtr == NULL) {
// 		// no active top-level group
// 		molSetPtr = new NXMoleculeSet;
// 		molSetPtr->setTitle(name);
// 		// dataStoreInfo->addClipboardStructure(molSetPtr);
// 	}
	
	// if in "View Data" group, ignore
	
	// if(molSetPtr != NULL) {
	/*else*/ if(!insideViewDataGroup) {
		// if in principal molecule-set group or active clipboard group
		
		if(molSetPtr == NULL) {
			// must be inside principal structure group
			assert(!insideClipboardGroup);
			molSetPtr = rootMoleculeSetPtr;
		}
// 		else if(!insideClipboardGroup && molSetPtr == NULL) {
// 			// entering principal structure group
// 			// all changes should go to supplied pointer
// 			molSetPtr = rootMoleculeSetPtr;
// 		}
		else {
			// If not at top-level inside principal structure group or
			// clipboard group, allocate new structure
			NXMoleculeSet *newMolSetPtr = new NXMoleculeSet;
			molSetPtr->addChild(newMolSetPtr);
			molSetPtrStack.push_back(molSetPtr);
			molSetPtr = newMolSetPtr;
		}
		molSetPtr->setTitle(name);
		molSetPtr->setGroupClassificationString(classification);
	}
	
	// ++molStructGroupLevel;
	
	CDEBUG("group (" + name + ") " + classification);
}


/* FUNCTION: newClipboardGroup */
void NanorexMMPImportExport::newClipboardGroup(void)
{
	assert(molSetPtr == NULL);
	assert(molSetPtrStack.size() == 0);
	
	if(!insideClipboardGroup && clipboardGroup == (NXMoleculeSet*) NULL) {
		clipboardGroup = new NXMoleculeSet;
		clipboardGroup->setTitle("Clipboard");
		molSetPtr = clipboardGroup;
		insideClipboardGroup = true;
		dataStoreInfo->setClipboardStructure(clipboardGroup);
		CDEBUG("[special] group (Clipboard)");
	}
	else {
		CSEVERE("Redefinition of 'Clipboard' group");
	}
}


/* FUNCTION: endGroup */
void NanorexMMPImportExport::endGroup(string const& name)
{
	// Must ensure that molSetPtr = NULL between top-level structure groups
	// Top-level structure groups are defined as the principal structure group
	// that occurs between the "View Data" and the "Clipboard" groups in the MMP
	// file, and those from various top-level 'group' statements in the
	// "Clipboard" group
	
	string groupName;
	if(insideViewDataGroup)
		groupName = "View Data";
	else if(insideClipboardGroup)
		groupName = (molSetPtr == NULL) ? "Clipboard" : molSetPtr->getTitle();
	else
		groupName = molSetPtr->getTitle();
	
	
	if(name != groupName) {
		NXLOG_WARNING("NanorexMMPImportExport",
		              "egroup (" + name + ") attempting to close "
		              "group (" + groupName + ')');
	}
	
	
	if(insideViewDataGroup) {
		insideViewDataGroup = false;
		molSetPtr = NULL;
	}
	else {
		// non top-level structure groups in clipboard or in the
		// principal structure group
		if(molSetPtrStack.size() == 0)  {
			molSetPtr = NULL;
			if(insideClipboardGroup)
				insideClipboardGroup = false;
		}
		else {
			molSetPtr = molSetPtrStack.back();
			molSetPtrStack.pop_back();
		}
	}
	
	CDEBUG("egroup (" + groupName + ')');
}


/* FUNCTION: newOpenGroupInfo */
void NanorexMMPImportExport::newOpenGroupInfo(std::string const& key,
                                              std::string const& value)
{
	/// @todo
	CDEBUG("info opengroup " + key + " = " + value);
}


/* FUNCTION: newChunkInfo */
void
NanorexMMPImportExport::newChunkInfo(std::string const& key,
                                     std::string const& value)
{
	CDEBUG("info chunk " + key + " = " + value);
	
	if(insideViewDataGroup)
		return;
	
	/// @todo
}


/* FUNCTION: end1 */
void NanorexMMPImportExport::end1(void)
{
	/// @todo
	CDEBUG("end1");
}


/* FUNCTION: exportToFile */
NXCommandResult*
NanorexMMPImportExport::
exportToFile(NXMoleculeSet *molSetPtr,
             NXDataStoreInfo */*dataStoreInfo*/,
             const std::string& theFilename,
             int /*frameSetId*/, int /*frameIndex*/)
{
	NXCommandResult *result = new NXCommandResult();
	result->setResult(NX_CMD_SUCCESS);
	
	ofstream mmpfile(theFilename.c_str(), ios::out);
	if(!mmpfile) {
		populateCommandResult(result,
		                      (string("Couldn't open file: ") + theFilename)
		                      .c_str());
	}
	else {
		PrintMoleculeSet(mmpfile, molSetPtr);
		mmpfile.close();
	}
	return result;
}


/* FUNCTION: GetAtomID */
/* static */
int NanorexMMPImportExport::GetAtomID(OBAtom *atomPtr)
{
	NXAtomData *atomIDData = 
		dynamic_cast<NXAtomData*>(atomPtr->GetData(NXAtomDataType));
	int atomID = atomIDData->getIdx();
	return atomID;
}


/* FUNCTION: GetAtomRenderStyleCode */
/* static */
string const&
NanorexMMPImportExport::GetAtomRenderStyleCode(OBAtom *const atomPtr)
{
	NXAtomData *atomDataPtr =
		dynamic_cast<NXAtomData*>(atomPtr->GetData(NXAtomDataType));
	string const& atomStyle = atomDataPtr->getRenderStyleCode();
	return atomStyle;
}


/* FUNCTION: PrintMolecule */
/* static */
void NanorexMMPImportExport::PrintMolecule(ostream& o,
OBMol *const molPtr)
{
	set<int> prevAtomIdx;
	set<int> prevBondIdx; /// @todo - replace with simple bond count
	
	o << "mol (" << molPtr->GetTitle() << ')' << endl;
	
	OBAtomIterator atomIter;
	OBAtom *atomPtr = NULL;
    // For each atom ...
	for(atomPtr = molPtr->BeginAtom(atomIter);
	    atomPtr != NULL;
	    atomPtr = molPtr->NextAtom(atomIter))
	{
        // ... write the 'atom' line ...
		int atomID = GetAtomID(atomPtr);
		o << "atom " << atomID << " (" << atomPtr->GetAtomicNum() << ") " << '('
			<< atomPtr->x() << ',' << atomPtr->y() << ',' << atomPtr->z()
			<< ") " << GetAtomRenderStyleCode(atomPtr) << endl;
		
		if(atomPtr->GetHyb() != 0) {
			o << "info atom atomtype = "
				<< _s_hybridizationName[atomPtr->GetHyb()];
		}
		
        // ... write the 'bond' lines for this atom ...
        // ... first sort bonds by type ...
		OBBondIterator bondIter;
		OBBond *bondPtr = NULL;
		vector<int> bondCategories[6];
		for(bondPtr = atomPtr->BeginBond(bondIter);
		    bondPtr != NULL;
		    bondPtr = atomPtr->NextBond(bondIter))
		{
            // write bond statement only if target atom was previously written
			OBAtom *nbrAtomPtr = bondPtr->GetNbrAtom(atomPtr);
			int nbrAtomID = GetAtomID(nbrAtomPtr);
			if(prevAtomIdx.find(nbrAtomID) != prevAtomIdx.end()) {
				int bondOrder = bondPtr->GetBondOrder();
				bondCategories[bondOrder-1].push_back(nbrAtomID);
                // record bond for sanity check at end
				prevBondIdx.insert(bondPtr->GetIdx());
			}
		}
		
        // ... write the bonds, one line per type ...
		for(int i=0; i<6; ++i) {
			int J = bondCategories[i].size();
			if(J > 0) {
				o << "bond" << _s_bondOrderString[i];
				for(int j=0; j<J; ++j)
					o << ' ' << bondCategories[i][j];
				o  << endl;
			}
		}
		
        // record atom as 'previously written'
		prevAtomIdx.insert(atomID);
	}
	
    // debug diagnostics
	ostringstream debugMsg;
	debugMsg << "# atoms check ";
	if(molPtr->NumAtoms() == prevAtomIdx.size())
		debugMsg << "PASS ("  << molPtr->NumAtoms() << ')' << endl;
	else
		debugMsg << "FAIL: "
		<< molPtr->NumAtoms() << " != " << prevAtomIdx.size()<< endl;
	
	debugMsg << "# bonds check ";
	if(molPtr->NumBonds() == prevBondIdx.size())
		debugMsg << "PASS (" << molPtr->NumBonds() << ')' << endl;
	else
		debugMsg << "FAIL: "
		<< molPtr->NumBonds() << " != " << prevBondIdx.size()<< endl;
	
	debugMsg.flush();
	NXLOG_DEBUG("NanorexMMPImportExport::PrintMoleculeSet",
	            debugMsg.str().c_str());
}


/* FUNCTION: PrintMoleculeSet */
/* static */
void NanorexMMPImportExport::PrintMoleculeSet(ostream& o,
                                              NXMoleculeSet *const molSetPtr)
{
	// Iterate over all child molecules
	OBMolIterator molIter;
	for(molIter = molSetPtr->moleculesBegin();
	    molIter != molSetPtr->moleculesEnd();
	    ++molIter)
	{
		PrintMolecule(o, *molIter);
	}
	
    // Iterate over all child molecule sets
	NXMoleculeSetIterator molSetIter;
	for(molSetIter = molSetPtr->childrenBegin();
	    molSetIter != molSetPtr->childrenEnd();
	    ++molSetIter)
	{
		PrintMoleculeSet(o, *molSetIter);
	}
}


/* FUNCTION: populateCommandResult */
void
NanorexMMPImportExport::populateCommandResult (NXCommandResult* result,
                                               const string& message)
{
	result->setResult(NX_PLUGIN_REPORTS_ERROR);
	vector<QString> resultVector;
	resultVector.push_back("OpenBabelImportExport");
	resultVector.push_back(message.c_str());
	result->setParamVector(resultVector);
}

Q_EXPORT_PLUGIN2 (NanorexMMPImportExport, NanorexMMPImportExport)