Debian Codegraph @

cmd/transmute.go

raw
1 // ===========================================================================
2 //
3 // PUBLIC DOMAIN NOTICE
4 // National Center for Biotechnology Information (NCBI)
5 //
6 // This software/database is a "United States Government Work" under the
7 // terms of the United States Copyright Act. It was written as part of
8 // the author's official duties as a United States Government employee and
9 // thus cannot be copyrighted. This software/database is freely available
10 // to the public for use. The National Library of Medicine and the U.S.
11 // Government do not place any restriction on its use or reproduction.
12 // We would, however, appreciate having the NCBI and the author cited in
13 // any work or product based on this material.
14 //
15 // Although all reasonable efforts have been taken to ensure the accuracy
16 // and reliability of the software and data, the NLM and the U.S.
17 // Government do not and cannot warrant the performance or results that
18 // may be obtained by using this software or data. The NLM and the U.S.
19 // Government disclaim all warranties, express or implied, including
20 // warranties of performance, merchantability or fitness for any particular
21 // purpose.
22 //
23 // ===========================================================================
24 //
25 // File Name: transmute.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package main
32
33 import (
34 "bufio"
35 "compress/gzip"
36 "encoding/base64"
37 "eutils"
38 "fmt"
39 "html"
40 "io"
41 "maps"
42 "net/url"
43 "os"
44 "path/filepath"
45 "regexp"
46 "runtime"
47 "runtime/debug"
48 "runtime/pprof"
49 "slices"
50 "strconv"
51 "strings"
52 "sync"
53 "unicode"
54 )
55
56 // XML FORMATTING FUNCTIONS
57
58 // createFormatters does concurrent reformatting, using flush-left to remove leading spaces
59 func createFormatters(parent string, format string, inp <-chan eutils.XMLRecord) <-chan eutils.XMLRecord {
60
61 if inp == nil {
62 return nil
63 }
64
65 out := make(chan eutils.XMLRecord, eutils.ChanDepth())
66 if out == nil {
67 eutils.DisplayError("Unable to create formatter channel")
68 os.Exit(1)
69 }
70
71 if format == "" {
72 format = "flush"
73 }
74
75 // xmlFormatter reads partitioned XML from channel and formats on a per-record basis
76 xmlFormatter := func(wg *sync.WaitGroup, parent string, inp <-chan eutils.XMLRecord, out chan<- eutils.XMLRecord) {
77
78 // report when this formatter has no more records to process
79 defer wg.Done()
80
81 // read partitioned XML from producer channel
82 for ext := range inp {
83
84 idx := ext.Index
85 ident := ext.Ident
86 text := ext.Text
87
88 if text == "" {
89 // should never see empty input data
90 out <- eutils.XMLRecord{Index: idx, Ident: ident, Text: text}
91 continue
92 }
93
94 // str := doFormat(text[:], parent)
95
96 frm := eutils.FormatRecord(text, parent, eutils.FormatArgs{Format: format})
97 str := eutils.ChanToString(frm)
98
99 // send even if empty to get all record counts for reordering
100 out <- eutils.XMLRecord{Index: idx, Ident: ident, Text: str}
101 }
102 }
103
104 var wg sync.WaitGroup
105
106 // launch multiple formatter goroutines
107 for range eutils.NumServe() {
108 wg.Add(1)
109 go xmlFormatter(&wg, parent, inp, out)
110 }
111
112 // launch separate anonymous goroutine to wait until all formatters are done
113 go func() {
114 wg.Wait()
115 close(out)
116 }()
117
118 return out
119 }
120
121 // processFormat reformats XML for ease of reading
122 func processFormat(rdr <-chan eutils.XMLBlock, args []string) {
123
124 if rdr == nil || args == nil {
125 return
126 }
127
128 // skip past command name
129 args = args[1:]
130
131 format := ""
132 xml := ""
133 doctype := ""
134
135 doCombine := false
136 doSelf := false
137 doComment := false
138 doCdata := false
139
140 if len(args) > 0 {
141 // look for [compact|flush|indent|expand] specification
142 format = args[0]
143 if strings.HasPrefix(format, "-") {
144 // ran into next argument, default to indent
145 format = "indent"
146 } else {
147 // skip past first argument
148 args = args[1:]
149 }
150 } else {
151 format = "indent"
152 }
153
154 // look for remaining arguments
155 for len(args) > 0 {
156
157 switch args[0] {
158 case "-xml":
159 args = args[1:]
160 // -xml argument must be followed by value to use in xml line
161 if len(args) < 1 || strings.HasPrefix(args[0], "-") {
162 eutils.DisplayError("-xml argument is missing")
163 os.Exit(1)
164 }
165 xml = args[0]
166 args = args[1:]
167 case "-doctype":
168 args = args[1:]
169 if len(args) > 0 {
170 // if -doctype argument followed by value, use instead of DOCTYPE line
171 doctype = args[0]
172 args = args[1:]
173 }
174 /*
175 // allow setting of unicode, script, and mathml flags within -format
176 case "-unicode":
177 if len(args) < 2 {
178 eutils.DisplayError("Unicode argument is missing")
179 os.Exit(1)
180 }
181 // unicodePolicy = args[1]
182 args = args[2:]
183 case "-script":
184 if len(args) < 2 {
185 eutils.DisplayError("Script argument is missing")
186 os.Exit(1)
187 }
188 // scriptPolicy = args[1]
189 args = args[2:]
190 case "-mathml":
191 if len(args) < 2 {
192 eutils.DisplayError("MathML argument is missing")
193 os.Exit(1)
194 }
195 // mathmlPolicy = args[1]
196 args = args[2:]
197 */
198
199 // also allow setting additional processing flags within -format (undocumented)
200 case "-combine", "-combined":
201 // explicit flag to remove internal top-level tags, replaces -separate
202 doCombine = true
203 args = args[1:]
204 case "-separate", "-separated":
205 // deprecated, leaves default behavior of not combining internal top-level objects from multiple chunked reads
206 args = args[1:]
207 case "-self", "-self-closing":
208 doSelf = true
209 args = args[1:]
210 case "-comment":
211 doComment = true
212 args = args[1:]
213 case "-cdata":
214 doCdata = true
215 args = args[1:]
216 default:
217 eutils.DisplayError("Unrecognized option after -format command")
218 os.Exit(1)
219 }
220 }
221
222 tknq := eutils.CreateTokenizer(rdr)
223
224 frgs := eutils.FormatArgs{
225 Format: format, XML: xml, Doctype: doctype,
226 Combine: doCombine, Self: doSelf,
227 Comment: doComment, Cdata: doCdata}
228
229 frm := eutils.FormatTokens(tknq, frgs)
230
231 eutils.ChanToStdout(frm)
232 }
233
234 // processTokens shows individual tokens in stream (undocumented)
235 func processTokens(rdr <-chan eutils.XMLBlock) {
236
237 if rdr == nil {
238 return
239 }
240
241 tknq := eutils.CreateTokenizer(rdr)
242
243 if tknq == nil {
244 eutils.DisplayError("Unable to create debug tokenizer")
245 os.Exit(1)
246 }
247
248 var buffer strings.Builder
249
250 count := 0
251 indent := 0
252
253 for tkn := range tknq {
254
255 tag := tkn.Tag
256 name := tkn.Name
257 attr := tkn.Attr
258
259 switch tag {
260 case eutils.STARTTAG:
261 buffer.WriteString("ST: ")
262 for range indent {
263 buffer.WriteString(" ")
264 }
265 buffer.WriteString(name)
266 buffer.WriteString("\n")
267 if attr != "" {
268 buffer.WriteString("AT: ")
269 for range indent {
270 buffer.WriteString(" ")
271 }
272 buffer.WriteString(attr)
273 buffer.WriteString("\n")
274 }
275 indent++
276 case eutils.SELFTAG:
277 buffer.WriteString("SL: ")
278 for range indent {
279 buffer.WriteString(" ")
280 }
281 buffer.WriteString(name)
282 buffer.WriteString("/")
283 buffer.WriteString("\n")
284 if attr != "" {
285 buffer.WriteString("AT: ")
286 for range indent {
287 buffer.WriteString(" ")
288 }
289 buffer.WriteString(attr)
290 buffer.WriteString("\n")
291 }
292 case eutils.STOPTAG:
293 indent--
294 buffer.WriteString("SP: ")
295 for range indent {
296 buffer.WriteString(" ")
297 }
298 buffer.WriteString(name)
299 buffer.WriteString("/")
300 buffer.WriteString("\n")
301 case eutils.CONTENTTAG:
302 ctype := tkn.Cont
303 if (ctype & eutils.LFTSPACE) != 0 {
304 if (ctype & eutils.RGTSPACE) != 0 {
305 buffer.WriteString("FL: ")
306 } else {
307 buffer.WriteString("LF: ")
308 }
309 } else if (ctype & eutils.RGTSPACE) != 0 {
310 buffer.WriteString("RT: ")
311 } else {
312 buffer.WriteString("VL: ")
313 }
314 for range indent {
315 buffer.WriteString(" ")
316 }
317 buffer.WriteString(name)
318 buffer.WriteString("\n")
319 case eutils.CDATATAG:
320 buffer.WriteString("CD: ")
321 for range indent {
322 buffer.WriteString(" ")
323 }
324 buffer.WriteString(name)
325 buffer.WriteString("\n")
326 case eutils.COMMENTTAG:
327 buffer.WriteString("CO: ")
328 for range indent {
329 buffer.WriteString(" ")
330 }
331 buffer.WriteString(name)
332 buffer.WriteString("\n")
333 case eutils.DOCTYPETAG:
334 buffer.WriteString("DC: ")
335 for range indent {
336 buffer.WriteString(" ")
337 }
338 buffer.WriteString(name)
339 buffer.WriteString("\n")
340 case eutils.PROCESSTAG:
341 buffer.WriteString("PT: ")
342 for range indent {
343 buffer.WriteString(" ")
344 }
345 buffer.WriteString(name)
346 buffer.WriteString("\n")
347 case eutils.NOTAG:
348 buffer.WriteString("NO:")
349 if indent != 0 {
350 buffer.WriteString(" (indent ")
351 buffer.WriteString(strconv.Itoa(indent))
352 buffer.WriteString(")")
353 }
354 buffer.WriteString("\n")
355 case eutils.ISCLOSED:
356 buffer.WriteString("CL:")
357 if indent != 0 {
358 buffer.WriteString(" (indent ")
359 buffer.WriteString(strconv.Itoa(indent))
360 buffer.WriteString(")")
361 }
362 buffer.WriteString("\n")
363 txt := buffer.String()
364 if txt != "" {
365 // print final buffer
366 fmt.Fprintf(os.Stdout, "%s", txt)
367 }
368 return
369 default:
370 buffer.WriteString("UNKONWN:")
371 if indent != 0 {
372 buffer.WriteString(" (indent ")
373 buffer.WriteString(strconv.Itoa(indent))
374 buffer.WriteString(")")
375 }
376 buffer.WriteString("\n")
377 }
378
379 count++
380 if count > 1000 {
381 count = 0
382 txt := buffer.String()
383 if txt != "" {
384 // print current buffered output
385 fmt.Fprintf(os.Stdout, "%s", txt)
386 }
387 buffer.Reset()
388 }
389 }
390 }
391
392 // processOutline displays outline of XML structure
393 func processOutline(rdr <-chan eutils.XMLBlock, max int) {
394
395 if rdr == nil {
396 return
397 }
398
399 tknq := eutils.CreateTokenizer(rdr)
400
401 if tknq == nil {
402 eutils.DisplayError("Unable to create outline tokenizer")
403 os.Exit(1)
404 }
405
406 var buffer strings.Builder
407
408 count := 0
409 indent := 0
410
411 for tkn := range tknq {
412
413 tag := tkn.Tag
414 name := tkn.Name
415
416 switch tag {
417 case eutils.STARTTAG:
418 if name == "eSummaryResult" ||
419 name == "eLinkResult" ||
420 name == "eInfoResult" ||
421 name == "PubmedArticleSet" ||
422 name == "DocumentSummarySet" ||
423 name == "INSDSet" ||
424 name == "Entrezgene-Set" ||
425 name == "TaxaSet" {
426 break
427 }
428 if max == 0 || indent < max {
429 for range indent {
430 buffer.WriteString(" ")
431 }
432 buffer.WriteString(name)
433 buffer.WriteString("\n")
434 }
435 indent++
436 case eutils.SELFTAG:
437 if max == 0 || indent < max {
438 for range indent {
439 buffer.WriteString(" ")
440 }
441 buffer.WriteString(name)
442 buffer.WriteString("\n")
443 }
444 case eutils.STOPTAG:
445 indent--
446 case eutils.DOCTYPETAG:
447 case eutils.PROCESSTAG:
448 case eutils.NOTAG:
449 case eutils.ISCLOSED:
450 txt := buffer.String()
451 if txt != "" {
452 // print final buffer
453 fmt.Fprintf(os.Stdout, "%s", txt)
454 }
455 return
456 default:
457 }
458
459 count++
460 if count > 1000 {
461 count = 0
462 txt := buffer.String()
463 if txt != "" {
464 // print current buffered output
465 fmt.Fprintf(os.Stdout, "%s", txt)
466 }
467 buffer.Reset()
468 }
469 }
470 }
471
472 // processSynopsis displays paths to XML elements
473 func processSynopsis(rdr <-chan eutils.XMLBlock, leaf bool, delim string) {
474
475 if rdr == nil {
476 return
477 }
478
479 tknq := eutils.CreateTokenizer(rdr)
480
481 if tknq == nil {
482 eutils.DisplayError("Unable to create synopsis tokenizer")
483 os.Exit(1)
484 }
485
486 var buffer strings.Builder
487 count := 0
488
489 // synopsisLevel recursive definition
490 var synopsisLevel func(string) bool
491
492 synopsisLevel = func(parent string) bool {
493
494 for tkn := range tknq {
495
496 tag := tkn.Tag
497 name := tkn.Name
498
499 switch tag {
500 case eutils.STARTTAG:
501 if name == "eSummaryResult" ||
502 name == "eLinkResult" ||
503 name == "eInfoResult" ||
504 name == "PubmedArticleSet" ||
505 name == "DocumentSummarySet" ||
506 name == "INSDSet" ||
507 name == "Entrezgene-Set" ||
508 name == "TaxaSet" {
509 break
510 }
511 if leaf {
512 if name == "root" ||
513 name == "opt" ||
514 name == "anon" {
515 break
516 }
517 }
518 if !leaf {
519 // show all paths, including container objects
520 if parent != "" {
521 buffer.WriteString(parent)
522 buffer.WriteString(delim)
523 }
524 buffer.WriteString(name)
525 buffer.WriteString("\n")
526 }
527 path := parent
528 if path != "" {
529 path += delim
530 }
531 path += name
532 if synopsisLevel(path) {
533 return true
534 }
535 case eutils.SELFTAG:
536 if parent != "" {
537 buffer.WriteString(parent)
538 buffer.WriteString(delim)
539 }
540 buffer.WriteString(name)
541 buffer.WriteString("\n")
542 case eutils.STOPTAG:
543 // break recursion
544 return false
545 case eutils.CONTENTTAG:
546 if leaf {
547 // only show endpoint paths
548 if parent != "" {
549 buffer.WriteString(parent)
550 buffer.WriteString("\n")
551 }
552 }
553 case eutils.DOCTYPETAG:
554 case eutils.PROCESSTAG:
555 case eutils.NOTAG:
556 case eutils.ISCLOSED:
557 txt := buffer.String()
558 if txt != "" {
559 // print final buffer
560 fmt.Fprintf(os.Stdout, "%s", txt)
561 }
562 return true
563 default:
564 }
565
566 count++
567 if count > 1000 {
568 count = 0
569 txt := buffer.String()
570 if txt != "" {
571 // print current buffered output
572 fmt.Fprintf(os.Stdout, "%s", txt)
573 }
574 buffer.Reset()
575 }
576 }
577 return true
578 }
579
580 for {
581 // may have concatenated XMLs, loop through all
582 if synopsisLevel("") {
583 return
584 }
585 }
586 }
587
588 // processFilter modifies XML content, comments, or CDATA
589 func processFilter(rdr <-chan eutils.XMLBlock, args []string) {
590
591 if rdr == nil || args == nil {
592 return
593 }
594
595 tknq := eutils.CreateTokenizer(rdr)
596
597 if tknq == nil {
598 eutils.DisplayError("Unable to create filter tokenizer")
599 os.Exit(1)
600 }
601
602 var buffer strings.Builder
603
604 count := 0
605
606 // skip past command name
607 args = args[1:]
608
609 max := len(args)
610 if max < 1 {
611 eutils.DisplayError("Insufficient command-line arguments supplied to transmute -filter")
612 os.Exit(1)
613 }
614
615 pttrn := args[0]
616
617 args = args[1:]
618 max--
619
620 if max < 2 {
621 eutils.DisplayError("No object name supplied to transmute -filter")
622 os.Exit(1)
623 }
624
625 type ActionType int
626
627 const (
628 NOACTION ActionType = iota
629 DORETAIN
630 DOREMOVE
631 DOENCODE
632 DODECODE
633 DOSHRINK
634 DOEXPAND
635 DOACCENT
636 )
637
638 action := args[0]
639
640 what := NOACTION
641 switch action {
642 case "retain":
643 what = DORETAIN
644 case "remove":
645 what = DOREMOVE
646 case "encode":
647 what = DOENCODE
648 case "decode":
649 what = DODECODE
650 case "shrink":
651 what = DOSHRINK
652 case "expand":
653 what = DOEXPAND
654 case "accent":
655 what = DOACCENT
656 default:
657 eutils.DisplayError("Unrecognized action '%s' supplied to transmute -filter", action)
658 os.Exit(1)
659 }
660
661 trget := args[1]
662
663 which := eutils.NOTAG
664 switch trget {
665 case "attribute", "attributes":
666 which = eutils.ATTRIBTAG
667 case "content", "contents":
668 which = eutils.CONTENTTAG
669 case "cdata", "CDATA":
670 which = eutils.CDATATAG
671 case "comment", "comments":
672 which = eutils.COMMENTTAG
673 case "object":
674 // object normally retained
675 which = eutils.OBJECTTAG
676 case "container":
677 which = eutils.CONTAINERTAG
678 default:
679 eutils.DisplayError("Unrecognized target '%s' supplied to transmute -filter", trget)
680 os.Exit(1)
681 }
682
683 inPattern := false
684 prevName := ""
685
686 for tkn := range tknq {
687
688 tag := tkn.Tag
689 name := tkn.Name
690 attr := tkn.Attr
691
692 switch tag {
693 case eutils.STARTTAG:
694 prevName = name
695 if name == pttrn {
696 inPattern = true
697 if which == eutils.CONTAINERTAG && what == DOREMOVE {
698 continue
699 }
700 }
701 if inPattern && which == eutils.OBJECTTAG && what == DOREMOVE {
702 continue
703 }
704 buffer.WriteString("<")
705 buffer.WriteString(name)
706 if attr != "" {
707 if which != eutils.ATTRIBTAG || what != DOREMOVE {
708 attr = strings.TrimSpace(attr)
709 attr = eutils.CompressRunsOfSpaces(attr)
710 buffer.WriteString(" ")
711 buffer.WriteString(attr)
712 }
713 }
714 buffer.WriteString(">\n")
715 case eutils.SELFTAG:
716 if inPattern && which == eutils.OBJECTTAG && what == DOREMOVE {
717 continue
718 }
719 buffer.WriteString("<")
720 buffer.WriteString(name)
721 if attr != "" {
722 if which != eutils.ATTRIBTAG || what != DOREMOVE {
723 attr = strings.TrimSpace(attr)
724 attr = eutils.CompressRunsOfSpaces(attr)
725 buffer.WriteString(" ")
726 buffer.WriteString(attr)
727 }
728 }
729 buffer.WriteString("/>\n")
730 case eutils.STOPTAG:
731 if name == pttrn {
732 inPattern = false
733 if which == eutils.OBJECTTAG && what == DOREMOVE {
734 continue
735 }
736 if which == eutils.CONTAINERTAG && what == DOREMOVE {
737 continue
738 }
739 }
740 if inPattern && which == eutils.OBJECTTAG && what == DOREMOVE {
741 continue
742 }
743 buffer.WriteString("</")
744 buffer.WriteString(name)
745 buffer.WriteString(">\n")
746 case eutils.CONTENTTAG:
747 if inPattern && which == eutils.OBJECTTAG && what == DOREMOVE {
748 continue
749 }
750 if inPattern && which == eutils.CONTENTTAG && what == DOEXPAND {
751 var words []string
752 if strings.Contains(name, "|") {
753 words = strings.FieldsFunc(name, func(c rune) bool {
754 return c == '|'
755 })
756 } else if strings.Contains(name, ",") {
757 words = strings.FieldsFunc(name, func(c rune) bool {
758 return c == ','
759 })
760 } else {
761 words = strings.Fields(name)
762 }
763 between := ""
764 for _, item := range words {
765 max := len(item)
766 for max > 1 {
767 ch := item[max-1]
768 if ch != '.' && ch != ',' && ch != ':' && ch != ';' {
769 break
770 }
771 // trim trailing punctuation
772 item = item[:max-1]
773 // continue checking for runs of punctuation at end
774 max--
775 }
776 if eutils.HasFlankingSpace(item) {
777 item = strings.TrimSpace(item)
778 }
779 if item != "" {
780 if between != "" {
781 buffer.WriteString(between)
782 }
783 buffer.WriteString(item)
784 buffer.WriteString("\n")
785 between = "</" + prevName + ">\n<" + prevName + ">\n"
786 }
787 }
788 continue
789 }
790 if inPattern && which == tag {
791 switch what {
792 case DORETAIN:
793 // default behavior for content - can use -filter X retain content as a no-op
794 case DOREMOVE:
795 continue
796 case DOENCODE:
797 name = html.EscapeString(name)
798 case DODECODE:
799 name = html.UnescapeString(name)
800 case DOSHRINK:
801 name = eutils.CompressRunsOfSpaces(name)
802 case DOACCENT:
803 if eutils.IsNotASCII(name) {
804 name = eutils.TransformAccents(name, true, false)
805 }
806 default:
807 continue
808 }
809 }
810 // content normally printed
811 if eutils.HasFlankingSpace(name) {
812 name = strings.TrimSpace(name)
813 }
814 buffer.WriteString(name)
815 buffer.WriteString("\n")
816 case eutils.CDATATAG:
817 if inPattern && which == eutils.OBJECTTAG && what == DOREMOVE {
818 continue
819 }
820 if inPattern && which == tag {
821 switch what {
822 case DORETAIN:
823 // cdata requires explicit retain command
824 case DOREMOVE:
825 continue
826 case DOENCODE:
827 name = html.EscapeString(name)
828 case DODECODE:
829 name = html.UnescapeString(name)
830 case DOSHRINK:
831 name = eutils.CompressRunsOfSpaces(name)
832 case DOACCENT:
833 if eutils.IsNotASCII(name) {
834 name = eutils.TransformAccents(name, true, false)
835 }
836 default:
837 continue
838 }
839 // cdata normally removed
840 if eutils.HasFlankingSpace(name) {
841 name = strings.TrimSpace(name)
842 }
843 buffer.WriteString(name)
844 buffer.WriteString("\n")
845 }
846 case eutils.COMMENTTAG:
847 if inPattern && which == eutils.OBJECTTAG && what == DOREMOVE {
848 continue
849 }
850 if inPattern && which == tag {
851 switch what {
852 case DORETAIN:
853 // comment requires explicit retain command
854 case DOREMOVE:
855 continue
856 case DOENCODE:
857 name = html.EscapeString(name)
858 case DODECODE:
859 name = html.UnescapeString(name)
860 case DOSHRINK:
861 name = eutils.CompressRunsOfSpaces(name)
862 case DOACCENT:
863 if eutils.IsNotASCII(name) {
864 name = eutils.TransformAccents(name, true, false)
865 }
866 default:
867 continue
868 }
869 // comment normally removed
870 if eutils.HasFlankingSpace(name) {
871 name = strings.TrimSpace(name)
872 }
873 buffer.WriteString(name)
874 buffer.WriteString("\n")
875 }
876 case eutils.DOCTYPETAG:
877 case eutils.PROCESSTAG:
878 case eutils.NOTAG:
879 case eutils.ISCLOSED:
880 txt := buffer.String()
881 if txt != "" {
882 // print final buffer
883 fmt.Fprintf(os.Stdout, "%s", txt)
884 }
885 return
886 default:
887 }
888
889 count++
890 if count > 1000 {
891 count = 0
892 txt := buffer.String()
893 if txt != "" {
894 // print current buffered output
895 fmt.Fprintf(os.Stdout, "%s", txt)
896 }
897 buffer.Reset()
898 }
899 }
900 }
901
902 // STRING CONVERTERS
903
904 func encodeURL(inp io.Reader) {
905
906 if inp == nil {
907 return
908 }
909
910 data, _ := io.ReadAll(inp)
911 txt := string(data)
912 txt = strings.TrimSuffix(txt, "\n")
913
914 str := url.QueryEscape(txt)
915
916 os.Stdout.WriteString(str)
917 if !strings.HasSuffix(str, "\n") {
918 os.Stdout.WriteString("\n")
919 }
920 }
921
922 func decodeURL(inp io.Reader) {
923
924 if inp == nil {
925 return
926 }
927
928 byt, _ := io.ReadAll(inp)
929 txt := string(byt)
930 txt = strings.TrimSuffix(txt, "\n")
931
932 str, _ := url.QueryUnescape(txt)
933
934 os.Stdout.WriteString(str)
935 if !strings.HasSuffix(str, "\n") {
936 os.Stdout.WriteString("\n")
937 }
938 }
939
940 func encodeB64(inp io.Reader) {
941
942 if inp == nil {
943 return
944 }
945
946 data, _ := io.ReadAll(inp)
947
948 str := base64.StdEncoding.EncodeToString(data)
949
950 os.Stdout.WriteString(str)
951 if !strings.HasSuffix(str, "\n") {
952 os.Stdout.WriteString("\n")
953 }
954 }
955
956 func decodeB64(inp io.Reader) {
957
958 if inp == nil {
959 return
960 }
961
962 byt, _ := io.ReadAll(inp)
963
964 data, _ := base64.StdEncoding.DecodeString(string(byt))
965 str := string(data)
966
967 os.Stdout.WriteString(str)
968 if !strings.HasSuffix(str, "\n") {
969 os.Stdout.WriteString("\n")
970 }
971 }
972
973 func makePlain(inp io.Reader) {
974
975 if inp == nil {
976 return
977 }
978
979 byt, _ := io.ReadAll(inp)
980 str := string(byt)
981 str = strings.TrimSuffix(str, "\n")
982
983 if str != "" {
984 if eutils.IsNotASCII(str) {
985 str = eutils.TransformAccents(str, true, false)
986 if eutils.HasUnicodeMarkup(str) {
987 str = eutils.RepairUnicodeMarkup(str, eutils.SPACE)
988 }
989 }
990 if eutils.HasBadSpace(str) {
991 str = eutils.CleanupBadSpaces(str)
992 }
993 if eutils.HasAngleOrAmpersandEncoding(str) {
994 str = eutils.RepairTableMarkup(str, eutils.SPACE)
995 // str = eutils.RemoveEmbeddedMarkup(str, NOMARKUP)
996 str = eutils.RemoveHTMLDecorations(str)
997 str = eutils.CompressRunsOfSpaces(str)
998 }
999 }
1000
1001 os.Stdout.WriteString(str)
1002 if !strings.HasSuffix(str, "\n") {
1003 os.Stdout.WriteString("\n")
1004 }
1005 }
1006
1007 func decodeHGVS(inp io.Reader) {
1008
1009 if inp == nil {
1010 return
1011 }
1012
1013 byt, _ := io.ReadAll(inp)
1014 txt := string(byt)
1015
1016 os.Stdout.WriteString("<HGVS>\n")
1017
1018 str := eutils.ParseHGVS(txt)
1019
1020 os.Stdout.WriteString(str)
1021 if !strings.HasSuffix(str, "\n") {
1022 os.Stdout.WriteString("\n")
1023 }
1024
1025 os.Stdout.WriteString("</HGVS>\n")
1026 }
1027
1028 // COLUMN ALIGNMENT FORMATTER
1029
1030 // processAlign aligns a tab-delimited table by individual column widths
1031 func processAlign(inp io.Reader, args []string) {
1032
1033 // tab-delimited-table to padded-by-spaces alignment inspired by
1034 // Steve Kinzler's align script - see http://kinzler.com/me/align/
1035
1036 if inp == nil {
1037 return
1038 }
1039
1040 mrg := 0
1041 pdg := 0
1042 mnw := 0
1043 aln := ""
1044
1045 // skip past command name
1046 args = args[1:]
1047
1048 for len(args) > 0 {
1049
1050 switch args[0] {
1051 case "-g":
1052 if len(args) > 1 && args[1] == "t" {
1053 // special case to use tab character between columns
1054 pdg = -1
1055 } else {
1056 pdg = eutils.GetNumericArg(args, "-g spacing between columns", 0, 1, 30)
1057 }
1058 args = args[2:]
1059 case "-h":
1060 mrg = eutils.GetNumericArg(args, "-i indent before columns", 0, 1, 30)
1061 args = args[2:]
1062 case "-w":
1063 mnw = eutils.GetNumericArg(args, "-w minimum column width", 0, 1, 30)
1064 args = args[2:]
1065 case "-a":
1066 aln = eutils.GetStringArg(args, "-a column alignment code string")
1067 args = args[2:]
1068 default:
1069 eutils.DisplayError("Unrecognized option after -align command")
1070 os.Exit(1)
1071 }
1072 }
1073
1074 algn := eutils.AlignColumns(inp, mrg, pdg, mnw, aln)
1075
1076 if algn == nil {
1077 eutils.DisplayError("Unable to create alignment function")
1078 os.Exit(1)
1079 }
1080
1081 eutils.ChanToStdout(algn)
1082
1083 return
1084 }
1085
1086 // SEQUENCE EDITING
1087
1088 func readOneFastaSequence(inp io.Reader) string {
1089
1090 fsta := eutils.FASTAConverter(inp, false)
1091
1092 // return first FASTA sequence
1093 for fsa := range fsta {
1094 return fsa.Sequence
1095 }
1096
1097 return ""
1098 }
1099
1100 func readOneFastaWithID(inp io.Reader) (string, string) {
1101
1102 fsta := eutils.FASTAConverter(inp, false)
1103
1104 // return first FASTA sequence
1105 for fsa := range fsta {
1106 return fsa.Sequence, fsa.SeqID
1107 }
1108
1109 return "", ""
1110 }
1111
1112 func sequenceFormat(inp io.Reader, args []string) {
1113
1114 if inp == nil {
1115 return
1116 }
1117
1118 width := 70
1119 requireHeader := false
1120 caseSensitive := false
1121
1122 // skip past command name
1123 args = args[1:]
1124
1125 for len(args) > 0 {
1126
1127 switch args[0] {
1128 case "-width":
1129 width = eutils.GetNumericArg(args, "number of characters per line", 70, 1, 100)
1130 args = args[2:]
1131 case "-header":
1132 requireHeader = true
1133 args = args[1:]
1134 case "-case", "-sensitive":
1135 caseSensitive = true
1136 args = args[1:]
1137 default:
1138 eutils.DisplayError("Unrecognized option after -fasta command")
1139 os.Exit(1)
1140 }
1141 }
1142
1143 eutils.FormatFASTA(inp, width, requireHeader, caseSensitive)
1144 }
1145
1146 func sequenceRemove(inp io.Reader, args []string) {
1147
1148 if inp == nil {
1149 return
1150 }
1151
1152 first := ""
1153 last := ""
1154
1155 // skip past command name
1156 args = args[1:]
1157
1158 for len(args) > 0 {
1159
1160 switch args[0] {
1161 case "-first":
1162 first = eutils.GetStringArg(args, "Bases to delete at beginning")
1163 first = strings.ToUpper(first)
1164 args = args[2:]
1165 case "-last":
1166 last = eutils.GetStringArg(args, "Bases to delete at end")
1167 last = strings.ToUpper(last)
1168 args = args[2:]
1169 default:
1170 eutils.DisplayError("Unrecognized option after -remove command")
1171 os.Exit(1)
1172 }
1173 }
1174
1175 str := readOneFastaSequence(inp)
1176
1177 str = eutils.SequenceRemove(str, first, last)
1178
1179 os.Stdout.WriteString(str)
1180 if !strings.HasSuffix(str, "\n") {
1181 os.Stdout.WriteString("\n")
1182 }
1183 }
1184
1185 func sequenceRetain(inp io.Reader, args []string) {
1186
1187 if inp == nil {
1188 return
1189 }
1190
1191 lead := 0
1192 trail := 0
1193
1194 // skip past command name
1195 args = args[1:]
1196
1197 for len(args) > 0 {
1198
1199 switch args[0] {
1200 case "-leading":
1201 lead = eutils.GetNumericArg(args, "Bases to keep at beginning", 0, -1, -1)
1202 args = args[2:]
1203 case "-trailing":
1204 trail = eutils.GetNumericArg(args, "Bases to keep at end", 0, -1, -1)
1205 args = args[2:]
1206 default:
1207 eutils.DisplayError("Unrecognized option after -retain command")
1208 os.Exit(1)
1209 }
1210 }
1211
1212 str := readOneFastaSequence(inp)
1213
1214 str = eutils.SequenceRetain(str, lead, trail)
1215
1216 os.Stdout.WriteString(str)
1217 if !strings.HasSuffix(str, "\n") {
1218 os.Stdout.WriteString("\n")
1219 }
1220 }
1221
1222 func sequenceReplace(inp io.Reader, args []string) {
1223
1224 if inp == nil {
1225 return
1226 }
1227
1228 pos := 0
1229 del := ""
1230 ins := ""
1231 lower := false
1232
1233 // skip past command name
1234 args = args[1:]
1235
1236 for len(args) > 0 {
1237
1238 switch args[0] {
1239 case "-offset", "-offset0", "-offset-0":
1240 pos = eutils.GetNumericArg(args, "0-based position", 0, -1, -1)
1241 args = args[2:]
1242 case "-column", "-offset1", "-offset-1":
1243 val := eutils.GetNumericArg(args, "1-based position", 1, -1, -1)
1244 pos = val - 1
1245 args = args[2:]
1246 case "-delete":
1247 del = eutils.GetStringArg(args, "Number to delete")
1248 del = strings.ToUpper(del)
1249 args = args[2:]
1250 case "-insert":
1251 ins = eutils.GetStringArg(args, "Bases to insert")
1252 ins = strings.ToUpper(ins)
1253 args = args[2:]
1254 case "-lower":
1255 lower = true
1256 args = args[1:]
1257 default:
1258 eutils.DisplayError("Unrecognized option after -replace command")
1259 os.Exit(1)
1260 }
1261 }
1262
1263 str := readOneFastaSequence(inp)
1264
1265 if lower {
1266 str = strings.ToLower(str)
1267 }
1268
1269 str = eutils.SequenceReplace(str, pos, del, ins)
1270
1271 os.Stdout.WriteString(str)
1272 if !strings.HasSuffix(str, "\n") {
1273 os.Stdout.WriteString("\n")
1274 }
1275 }
1276
1277 func sequenceExtract(inp io.Reader, args []string) {
1278
1279 if inp == nil {
1280 return
1281 }
1282
1283 featLoc := ""
1284 isOneBased := true
1285 lower := false
1286
1287 // skip past command name
1288 args = args[1:]
1289
1290 for len(args) > 0 {
1291
1292 switch args[0] {
1293 case "-0-based":
1294 isOneBased = false
1295 args = args[1:]
1296 case "-1-based":
1297 isOneBased = true
1298 args = args[1:]
1299 case "-lower":
1300 lower = true
1301 args = args[1:]
1302 default:
1303 // read output of xtract -insd feat_location qualifier
1304 featLoc = args[0]
1305 args = args[1:]
1306 }
1307 }
1308
1309 if featLoc == "" {
1310 eutils.DisplayError("Missing argument after -extract command")
1311 os.Exit(1)
1312 }
1313
1314 str := readOneFastaSequence(inp)
1315
1316 str = eutils.SequenceExtract(str, featLoc, isOneBased)
1317
1318 if lower {
1319 str = strings.ToLower(str)
1320 }
1321
1322 os.Stdout.WriteString(str)
1323 if !strings.HasSuffix(str, "\n") {
1324 os.Stdout.WriteString("\n")
1325 }
1326 }
1327
1328 func sequenceSearch(inp io.Reader, args []string) {
1329
1330 if inp == nil {
1331 return
1332 }
1333
1334 // skip past command name
1335 args = args[1:]
1336
1337 protein := false
1338 circular := false
1339 topStrand := false
1340
1341 for len(args) > 0 {
1342 if args[0] == "-protein" {
1343 protein = true
1344 args = args[1:]
1345 } else if args[0] == "-circular" {
1346 circular = true
1347 args = args[1:]
1348 } else if args[0] == "-top" {
1349 topStrand = true
1350 args = args[1:]
1351 } else {
1352 break
1353 }
1354 }
1355
1356 if len(args) < 1 {
1357 eutils.DisplayError("Missing argument after -search command")
1358 os.Exit(1)
1359 }
1360
1361 var arry []string
1362
1363 // allow one or more patterns to be passed in each argument
1364 for len(args) > 0 {
1365 pat := args[0]
1366 args = args[1:]
1367
1368 pat = strings.TrimSpace(pat)
1369 itms := strings.Split(pat, " ")
1370 for _, trm := range itms {
1371 arry = append(arry, trm)
1372 }
1373 }
1374
1375 str := readOneFastaSequence(inp)
1376
1377 srch := eutils.SequenceSearcher(arry, protein, circular, topStrand)
1378
1379 txt := ""
1380
1381 srch.Search(str[:],
1382 func(str, pat string, pos int) bool {
1383 txt = fmt.Sprintf("%d\t%s\n", pos, pat)
1384 os.Stdout.WriteString(txt)
1385 return true
1386 })
1387
1388 if !strings.HasSuffix(txt, "\n") {
1389 os.Stdout.WriteString("\n")
1390 }
1391 }
1392
1393 func readAllIntoString(inp io.Reader) string {
1394
1395 if inp == nil {
1396 return ""
1397 }
1398
1399 data, _ := io.ReadAll(inp)
1400 txt := string(data)
1401
1402 if txt == "" {
1403 return ""
1404 }
1405
1406 // replace whitespace substrings with a single space
1407 re := regexp.MustCompile(`\s+`)
1408 txt = re.ReplaceAllString(txt, " ")
1409
1410 txt = strings.TrimSpace(txt)
1411
1412 return txt
1413 }
1414
1415 func stringFind(inp io.Reader, args []string) {
1416
1417 if inp == nil {
1418 return
1419 }
1420
1421 // skip past command name
1422 args = args[1:]
1423
1424 caseSensitive := false
1425 wholeWord := false
1426 relaxed := false
1427 compress := false
1428 circular := false
1429
1430 for len(args) > 0 {
1431 if args[0] == "-sensitive" {
1432 caseSensitive = true
1433 args = args[1:]
1434 } else if args[0] == "-whole" {
1435 wholeWord = true
1436 args = args[1:]
1437 } else if args[0] == "-relaxed" {
1438 relaxed = true
1439 args = args[1:]
1440 } else if args[0] == "-compress" {
1441 compress = true
1442 args = args[1:]
1443 } else if args[0] == "-circular" {
1444 circular = true
1445 args = args[1:]
1446 } else {
1447 break
1448 }
1449 }
1450
1451 if len(args) < 1 {
1452 eutils.DisplayError("Missing argument after -find command")
1453 os.Exit(1)
1454 }
1455
1456 str := readAllIntoString(inp)
1457
1458 srch := eutils.PatternSearcher(args, caseSensitive, wholeWord, relaxed, compress, circular)
1459
1460 txt := ""
1461
1462 srch.Search(str[:],
1463 func(str, pat string, pos int) bool {
1464 txt = fmt.Sprintf("%d\t%s\n", pos, pat)
1465 os.Stdout.WriteString(txt)
1466 return true
1467 })
1468
1469 if !strings.HasSuffix(txt, "\n") {
1470 os.Stdout.WriteString("\n")
1471 }
1472 }
1473
1474 func relaxString(inp io.Reader) {
1475
1476 str := readAllIntoString(inp)
1477
1478 str = eutils.RelaxString(str)
1479
1480 os.Stdout.WriteString(str)
1481 if !strings.HasSuffix(str, "\n") {
1482 os.Stdout.WriteString("\n")
1483 }
1484 }
1485
1486 func upperString(inp io.Reader) {
1487
1488 str := readAllIntoString(inp)
1489
1490 str = strings.ToUpper(str)
1491
1492 os.Stdout.WriteString(str)
1493 if !strings.HasSuffix(str, "\n") {
1494 os.Stdout.WriteString("\n")
1495 }
1496 }
1497
1498 func lowerString(inp io.Reader) {
1499
1500 str := readAllIntoString(inp)
1501
1502 str = strings.ToLower(str)
1503
1504 os.Stdout.WriteString(str)
1505 if !strings.HasSuffix(str, "\n") {
1506 os.Stdout.WriteString("\n")
1507 }
1508 }
1509
1510 // FASTA BASE COUNT
1511
1512 // baseCount prints a summary of base or residue counts
1513 func baseCount(inp io.Reader) {
1514
1515 if inp == nil {
1516 return
1517 }
1518
1519 fsta := eutils.FASTAConverter(inp, false)
1520
1521 countLetters := func(id, seq string) {
1522
1523 counts := make(map[rune]int)
1524
1525 for _, base := range seq {
1526 counts[base]++
1527 }
1528
1529 keys := slices.Sorted(maps.Keys(counts))
1530
1531 fmt.Fprintf(os.Stdout, "%s", id)
1532 for _, base := range keys {
1533 num := counts[base]
1534 fmt.Fprintf(os.Stdout, "\t%c %d", base, num)
1535 }
1536 fmt.Fprintf(os.Stdout, "\n")
1537 }
1538
1539 for fsa := range fsta {
1540 countLetters(fsa.SeqID, fsa.Sequence)
1541 }
1542 }
1543
1544 // REVERSE SEQUENCE
1545
1546 // seqFlip reverses without complementing - e.g., minus strand proteins translated in reverse order
1547 func seqFlip(inp io.Reader) {
1548
1549 if inp == nil {
1550 return
1551 }
1552
1553 str := readOneFastaSequence(inp)
1554
1555 str = eutils.SequenceReverse(str)
1556
1557 os.Stdout.WriteString(str)
1558 if !strings.HasSuffix(str, "\n") {
1559 os.Stdout.WriteString("\n")
1560 }
1561 }
1562
1563 // REVERSE COMPLEMENT
1564
1565 func nucRevComp(inp io.Reader) {
1566
1567 if inp == nil {
1568 return
1569 }
1570
1571 str := readOneFastaSequence(inp)
1572
1573 str = eutils.ReverseComplement(str)
1574
1575 os.Stdout.WriteString(str)
1576 if !strings.HasSuffix(str, "\n") {
1577 os.Stdout.WriteString("\n")
1578 }
1579 }
1580
1581 /*
1582 func fastaRevComp(inp io.Reader) {
1583
1584 if inp == nil {
1585 return
1586 }
1587
1588 fsta := eutils.FASTAConverter(inp, false)
1589
1590 for fsa := range fsta {
1591
1592 str := fsa.Sequence
1593
1594 str = eutils.ReverseComplement(str)
1595
1596 os.Stdout.WriteString(">")
1597 if fsa.SeqID != "" {
1598 os.Stdout.WriteString(fsa.SeqID)
1599 if fsa.Title != "" {
1600 os.Stdout.WriteString(" ")
1601 os.Stdout.WriteString(fsa.Title)
1602 }
1603 }
1604 os.Stdout.WriteString("\n")
1605
1606 os.Stdout.WriteString(str)
1607 if !strings.HasSuffix(str, "\n") {
1608 os.Stdout.WriteString("\n")
1609 }
1610 }
1611 }
1612 */
1613
1614 // FASTA DIFFERENCES
1615
1616 func printFastaPairs(frst, scnd string) {
1617
1618 frst = strings.ToLower(frst)
1619 scnd = strings.ToLower(scnd)
1620
1621 fst := frst[:]
1622 scd := scnd[:]
1623
1624 // next functions return spaces after end of sequence
1625 nextF := func() rune {
1626
1627 if len(fst) < 1 {
1628 return ' '
1629 }
1630 ch := fst[0]
1631 fst = fst[1:]
1632
1633 return rune(ch)
1634 }
1635
1636 nextS := func() rune {
1637
1638 if len(scd) < 1 {
1639 return ' '
1640 }
1641 ch := scd[0]
1642 scd = scd[1:]
1643
1644 return rune(ch)
1645 }
1646
1647 var fs []rune
1648 var sc []rune
1649 mx := 0
1650
1651 // populate output arrays
1652 for {
1653
1654 f, s := nextF(), nextS()
1655 // if both spaces, end of both sequences
1656 if f == ' ' && s == ' ' {
1657 break
1658 }
1659 if f == s {
1660 fs = append(fs, f)
1661 sc = append(sc, ' ')
1662 } else {
1663 // show mismatches in upper case
1664 fs = append(fs, unicode.ToUpper(f))
1665 sc = append(sc, unicode.ToUpper(s))
1666 }
1667 mx++
1668 }
1669
1670 // pad output to multiple of 50
1671 j := mx % 50
1672 if j > 0 {
1673 for j < 50 {
1674 fs = append(fs, ' ')
1675 sc = append(sc, ' ')
1676 j++
1677 mx++
1678 }
1679 }
1680
1681 // print in blocks of 50 bases or residues
1682 for i := 0; i < mx; i += 50 {
1683 dl := 50
1684 if mx-i < 50 {
1685 dl = mx - i
1686 }
1687 lf := fs[:dl]
1688 rt := sc[:dl]
1689 fs = fs[dl:]
1690 sc = sc[dl:]
1691 tm := strings.TrimRight(string(lf), " ")
1692 fmt.Fprintf(os.Stdout, "%s %6d\n%s\n", string(lf), i+len(tm), string(rt))
1693 }
1694 }
1695
1696 func fastaDiff(inp io.Reader, args []string) {
1697
1698 if inp == nil {
1699 return
1700 }
1701
1702 // skip past command name
1703 args = args[1:]
1704
1705 if len(args) != 2 {
1706 eutils.DisplayError("Two files required by -diff command")
1707 os.Exit(1)
1708 }
1709
1710 frst := args[0]
1711 scnd := args[1]
1712
1713 readSeqFromFile := func(fname string) string {
1714
1715 f, err := os.Open(fname)
1716 if err != nil {
1717 eutils.DisplayError("Unable to open file %s - %s", fname, err.Error())
1718 os.Exit(1)
1719 }
1720
1721 defer f.Close()
1722
1723 seq := readOneFastaSequence(f)
1724
1725 return seq
1726 }
1727
1728 frstFasta := readSeqFromFile(frst)
1729 scndFasta := readSeqFromFile(scnd)
1730
1731 if frstFasta == scndFasta {
1732 return
1733 }
1734
1735 if len(frstFasta) != len(scndFasta) {
1736 eutils.DisplayWarning("-diff expects aligned sequences, but lengths are not identical")
1737 }
1738
1739 // sequences are assumed to be aligned, this code highlight mismatches
1740 printFastaPairs(frstFasta, scndFasta)
1741 }
1742
1743 // PROTEIN WEIGHT
1744
1745 func protWeight(inp io.Reader, args []string) {
1746
1747 if inp == nil {
1748 return
1749 }
1750
1751 trimLeadingMet := true
1752 isFormylMet := false
1753
1754 // skip past command name
1755 args = args[1:]
1756
1757 for len(args) > 0 {
1758
1759 switch args[0] {
1760 case "-met":
1761 trimLeadingMet = false
1762 args = args[1:]
1763 case "-fmet":
1764 trimLeadingMet = false
1765 isFormylMet = true
1766 args = args[1:]
1767 default:
1768 eutils.DisplayError("Unrecognized option after -molwt command")
1769 os.Exit(1)
1770 }
1771 }
1772
1773 str := readOneFastaSequence(inp)
1774
1775 str = eutils.ProteinWeight(str, trimLeadingMet, isFormylMet)
1776
1777 os.Stdout.WriteString(str)
1778 if !strings.HasSuffix(str, "\n") {
1779 os.Stdout.WriteString("\n")
1780 }
1781 }
1782
1783 // cdRegionToProtein reads all of stdin as sequence data
1784 func cdRegionToProtein(inp io.Reader, args []string) {
1785
1786 if inp == nil {
1787 return
1788 }
1789
1790 allSixFrames := false
1791 genCode := 1
1792 circular := false
1793 orf := false
1794 frame := 0
1795 max := 0
1796 includeStop := false
1797 doEveryCodon := false
1798 removeTrailingX := false
1799 is5primeComplete := true
1800 is3primeComplete := true
1801 between := ""
1802
1803 repeat := 1
1804
1805 // skip past command name
1806 args = args[1:]
1807
1808 for len(args) > 0 {
1809
1810 switch args[0] {
1811 case "-code", "-gcode":
1812 genCode = eutils.GetNumericArg(args, "genetic code number", 0, 1, 30)
1813 args = args[2:]
1814 case "-frame", "-frame0", "-frame-0":
1815 frame = eutils.GetNumericArg(args, "offset into coding sequence", 0, 0, 30)
1816 args = args[2:]
1817 case "-frame1", "-frame-1":
1818 frame = eutils.GetNumericArg(args, "offset into coding sequence", 0, 1, 30)
1819 if frame > 0 {
1820 frame--
1821 }
1822 args = args[2:]
1823 case "-stop", "-stops":
1824 includeStop = true
1825 args = args[1:]
1826 case "-every":
1827 doEveryCodon = true
1828 args = args[1:]
1829 case "-trim", "-trailing":
1830 removeTrailingX = true
1831 args = args[1:]
1832 case "-part5", "-partial5", "-lt5":
1833 is5primeComplete = false
1834 args = args[1:]
1835 case "-part3", "-partial3", "-gt3":
1836 is3primeComplete = false
1837 args = args[1:]
1838 case "-between":
1839 between = eutils.GetStringArg(args, "separator between residues")
1840 args = args[2:]
1841 case "-repeat":
1842 repeat = eutils.GetNumericArg(args, "number of repetitions for testing", 1, 1, 100)
1843 args = args[2:]
1844 case "-max":
1845 max = eutils.GetNumericArg(args, "number of characters per line", 70, 1, 100)
1846 args = args[2:]
1847 case "-all", "-six":
1848 allSixFrames = true
1849 args = args[1:]
1850 case "-circular":
1851 circular = true
1852 args = args[1:]
1853 case "-orf":
1854 orf = true
1855 args = args[1:]
1856 case "-":
1857 // lone dash is default for -every -trim
1858 doEveryCodon = true
1859 removeTrailingX = true
1860 args = args[1:]
1861 default:
1862 eutils.DisplayError("Unrecognized option after -cds2prot command")
1863 os.Exit(1)
1864 }
1865 }
1866
1867 txt, id := readOneFastaWithID(inp)
1868
1869 var buffer strings.Builder
1870
1871 printSequence := func(str string) {
1872
1873 if max == 0 {
1874 os.Stdout.WriteString(str)
1875 if !strings.HasSuffix(str, "\n") {
1876 os.Stdout.WriteString("\n")
1877 }
1878 } else {
1879 rem := str
1880 for rem != "" {
1881 mx := len(rem)
1882 if mx > max {
1883 mx = max
1884 }
1885 item := rem[:mx]
1886 rem = rem[mx:]
1887 buffer.WriteString(item)
1888 buffer.WriteString("\n")
1889 }
1890 rst := buffer.String()
1891 os.Stdout.WriteString(rst)
1892 if !strings.HasSuffix(rst, "\n") {
1893 os.Stdout.WriteString("\n")
1894 }
1895 buffer.Reset()
1896 }
1897 }
1898
1899 if allSixFrames {
1900
1901 labels := []string{"1+", "2+", "3+", "1-", "2-", "3-"}
1902
1903 strs := eutils.TranslateAllFrames(txt, genCode, circular, orf)
1904
1905 if id != "" {
1906 id = id + "-"
1907 }
1908
1909 for i, str := range strs {
1910
1911 os.Stdout.WriteString(">" + id + labels[i] + "\n")
1912 printSequence(str)
1913 }
1914
1915 return
1916 }
1917
1918 for range repeat {
1919
1920 // repeat multiple times for performance testing (undocumented)
1921 str := eutils.TranslateCdRegion(txt, genCode, frame, includeStop, doEveryCodon, removeTrailingX, is5primeComplete, is3primeComplete, between)
1922
1923 printSequence(str)
1924 }
1925 }
1926
1927 // nucProtCodonReport prints amino acid residues under nucleotide codons
1928 func nucProtCodonReport(args []string) {
1929
1930 nuc := ""
1931 prt := ""
1932 frame := 0
1933 threeLetter := false
1934
1935 // skip past command name
1936 args = args[1:]
1937
1938 for len(args) > 0 {
1939
1940 switch args[0] {
1941 case "-nuc":
1942 nuc = eutils.GetStringArg(args, "separator between residues")
1943 args = args[2:]
1944 case "-prt":
1945 prt = eutils.GetStringArg(args, "separator between residues")
1946 args = args[2:]
1947 case "-frame", "-frame0", "-frame-0":
1948 frame = eutils.GetNumericArg(args, "offset into coding sequence", 0, 0, 30)
1949 args = args[2:]
1950 case "-frame1", "-frame-1":
1951 frame = eutils.GetNumericArg(args, "offset into coding sequence", 0, 1, 30)
1952 if frame > 0 {
1953 frame--
1954 }
1955 args = args[2:]
1956 case "-three", "-triple", "-triples", "-triplet", "-triplets":
1957 threeLetter = true
1958 args = args[1:]
1959 default:
1960 eutils.DisplayError("Unrecognized option after -cds2prot command")
1961 os.Exit(1)
1962 }
1963 }
1964
1965 str := eutils.NucProtCodonReport(nuc, prt, frame, threeLetter)
1966
1967 os.Stdout.WriteString(str)
1968 if !strings.HasSuffix(str, "\n") {
1969 os.Stdout.WriteString("\n")
1970 }
1971 }
1972
1973 // MAIN FUNCTION
1974
1975 func main() {
1976
1977 // skip past executable name
1978 args := os.Args[1:]
1979
1980 if len(args) < 1 {
1981 eutils.DisplayError("No command-line arguments supplied to transmute")
1982 os.Exit(1)
1983 }
1984
1985 // performance arguments
1986 chanDepth := 0
1987 farmSize := 0
1988 heapSize := 0
1989 numServe := 0
1990 goGc := 0
1991
1992 // processing option arguments
1993 doCompress := false
1994 doCleanup := false
1995 doStrict := false
1996 doMixed := false
1997 doSelf := false
1998 deAccent := false
1999 deSymbol := false
2000 doASCII := false
2001 doStem := false
2002 deStop := true
2003
2004 /*
2005 doUnicode := false
2006 doScript := false
2007 doMathML := false
2008 */
2009
2010 // CONCURRENCY, CLEANUP, AND DEBUGGING FLAGS
2011
2012 // do these first because -defcpu and -maxcpu can be sent from wrapper before other arguments
2013
2014 ncpu := runtime.NumCPU()
2015 if ncpu < 1 {
2016 ncpu = 1
2017 }
2018
2019 // wrapper can limit maximum number of processors to use (undocumented)
2020 maxProcs := ncpu
2021 defProcs := 0
2022
2023 // concurrent performance tuning parameters, can be overridden by -proc and -cons
2024 numProcs := 0
2025 serverRatio := 4
2026
2027 // -flag sets -strict or -mixed cleanup flags from argument
2028 flgs := ""
2029
2030 /*
2031 unicodePolicy := ""
2032 scriptPolicy := ""
2033 mathmlPolicy := ""
2034 */
2035
2036 // read data from file instead of stdin
2037 fileName := ""
2038
2039 // debugging
2040 stts := false
2041 timr := false
2042
2043 // profiling
2044 prfl := false
2045
2046 // use pgzip decompression on release files
2047 zipp := false
2048
2049 inSwitch := true
2050
2051 // get concurrency, cleanup, and debugging flags in any order
2052 for {
2053
2054 inSwitch = true
2055
2056 switch args[0] {
2057
2058 // concurrency override arguments can be passed in by local wrapper script (undocumented)
2059 case "-maxcpu":
2060 maxProcs = eutils.GetNumericArg(args, "Maximum number of processors", 1, 1, ncpu)
2061 args = args[1:]
2062 case "-defcpu":
2063 defProcs = eutils.GetNumericArg(args, "Default number of processors", ncpu, 1, ncpu)
2064 args = args[1:]
2065 // performance tuning flags
2066 case "-proc":
2067 numProcs = eutils.GetNumericArg(args, "Number of processors", ncpu, 1, ncpu)
2068 args = args[1:]
2069 case "-cons":
2070 serverRatio = eutils.GetNumericArg(args, "Parser to processor ratio", 4, 1, 32)
2071 args = args[1:]
2072 case "-serv":
2073 numServe = eutils.GetNumericArg(args, "Concurrent parser count", 0, 1, 128)
2074 args = args[1:]
2075 case "-chan":
2076 chanDepth = eutils.GetNumericArg(args, "Communication channel depth", 0, ncpu, 128)
2077 args = args[1:]
2078 case "-heap":
2079 heapSize = eutils.GetNumericArg(args, "Unshuffler heap size", 8, 8, 64)
2080 args = args[1:]
2081 case "-farm":
2082 farmSize = eutils.GetNumericArg(args, "Node buffer length", 4, 4, 2048)
2083 args = args[1:]
2084 case "-gogc":
2085 goGc = eutils.GetNumericArg(args, "Garbage collection percentage", 0, 50, 1000)
2086 args = args[1:]
2087
2088 // read data from file
2089 case "-input":
2090 if len(args) < 2 {
2091 eutils.DisplayError("Input file name is missing")
2092 os.Exit(1)
2093 }
2094 fileName = args[1]
2095 // skip past first of two arguments
2096 args = args[1:]
2097
2098 // data cleanup flags
2099 case "-compress", "-compressed":
2100 doCompress = true
2101 case "-spaces", "-cleanup":
2102 doCleanup = true
2103 case "-strict":
2104 doStrict = true
2105 case "-mixed":
2106 doMixed = true
2107 case "-self":
2108 doSelf = true
2109 case "-accent":
2110 deAccent = true
2111 case "-symbol":
2112 deSymbol = true
2113 case "-ascii":
2114 doASCII = true
2115
2116 // previously visible processing flags (undocumented)
2117 case "-stems", "-stem":
2118 doStem = true
2119 case "-stops", "-stop":
2120 deStop = false
2121
2122 case "-gzip":
2123 zipp = true
2124
2125 // allow setting of unicode, script, and mathml flags (undocumented)
2126 case "-unicode":
2127 if len(args) < 2 {
2128 eutils.DisplayError("-unicode argument is missing")
2129 os.Exit(1)
2130 }
2131 // unicodePolicy = eutils.GetStringArg(args, "Unicode argument")
2132 args = args[1:]
2133 case "-script":
2134 if len(args) < 2 {
2135 eutils.DisplayError("-script argument is missing")
2136 os.Exit(1)
2137 }
2138 // scriptPolicy = eutils.GetStringArg(args, "Script argument")
2139 args = args[1:]
2140 case "-mathml":
2141 if len(args) < 2 {
2142 eutils.DisplayError("-mathml argument is missing")
2143 os.Exit(1)
2144 }
2145 // mathmlPolicy = eutils.GetStringArg(args, "MathML argument")
2146 args = args[1:]
2147
2148 case "-flag", "-flags":
2149 if len(args) < 2 {
2150 eutils.DisplayError("-flags argument is missing")
2151 os.Exit(1)
2152 }
2153 flgs = eutils.GetStringArg(args, "Flags argument")
2154 args = args[1:]
2155
2156 // debugging flags
2157 case "-stats", "-stat":
2158 stts = true
2159 case "-timer":
2160 timr = true
2161 case "-profile":
2162 prfl = true
2163
2164 default:
2165 // if not any of the controls, set flag to break out of for loop
2166 inSwitch = false
2167 }
2168
2169 if !inSwitch {
2170 break
2171 }
2172
2173 // skip past argument
2174 args = args[1:]
2175
2176 if len(args) < 1 {
2177 break
2178 }
2179 }
2180
2181 // -flag allows script to set -strict or -mixed (or -stems, or -stops) from argument
2182 switch flgs {
2183 case "strict":
2184 doStrict = true
2185 case "mixed":
2186 doMixed = true
2187 case "stems", "stem":
2188 // ignore
2189 case "stops", "stop":
2190 // ignore
2191 case "none", "default":
2192 default:
2193 if flgs != "" {
2194 eutils.DisplayError("Unrecognized -flag value '%s'", flgs)
2195 os.Exit(1)
2196 }
2197 }
2198
2199 /*
2200 UnicodeFix = ParseMarkup(unicodePolicy, "-unicode")
2201 ScriptFix = ParseMarkup(scriptPolicy, "-script")
2202 MathMLFix = ParseMarkup(mathmlPolicy, "-mathml")
2203
2204 if UnicodeFix != NOMARKUP {
2205 doUnicode = true
2206 }
2207
2208 if ScriptFix != NOMARKUP {
2209 doScript = true
2210 }
2211
2212 if MathMLFix != NOMARKUP {
2213 doMathML = true
2214 }
2215 */
2216
2217 if numProcs == 0 {
2218 if defProcs > 0 {
2219 numProcs = defProcs
2220 } else if maxProcs > 0 {
2221 numProcs = maxProcs
2222 }
2223 }
2224 if numProcs > ncpu {
2225 numProcs = ncpu
2226 }
2227 if numProcs > maxProcs {
2228 numProcs = maxProcs
2229 }
2230
2231 eutils.SetTunings(numProcs, numServe, serverRatio, chanDepth, farmSize, heapSize, goGc, false)
2232
2233 eutils.SetOptions(doStrict, doMixed, doSelf, deAccent, deSymbol, doASCII, doCompress, doCleanup, doStem, deStop)
2234
2235 // -stats prints number of CPUs and performance tuning values if no other arguments (undocumented)
2236 if stts && len(args) < 1 {
2237
2238 eutils.PrintStats()
2239
2240 return
2241 }
2242
2243 if len(args) < 1 {
2244 eutils.DisplayError("Insufficient command-line arguments supplied to transmute")
2245 os.Exit(1)
2246 }
2247
2248 // DOCUMENTATION COMMANDS
2249
2250 inSwitch = true
2251
2252 switch args[0] {
2253 case "-version":
2254 fmt.Printf("%s\n", eutils.EDirectVersion)
2255 case "-help", "help", "--help":
2256 eutils.PrintHelp("transmute", "transmute-help.txt")
2257 case "-extra", "-extras":
2258 eutils.PrintHelp("transmute", "transmute-extras.txt")
2259 case "-degenerate":
2260 // generate new genetic code data tables (undocumented)
2261 eutils.GenerateGeneticCodeMaps()
2262 case "-printgcodes":
2263 // print tab-delimited table of all genetic codes (undocumented)
2264 eutils.PrintGeneticCodeTables()
2265 default:
2266 // if not any of the documentation commands, keep going
2267 inSwitch = false
2268 }
2269
2270 if inSwitch {
2271 return
2272 }
2273
2274 // FILE NAME CAN BE SUPPLIED WITH -input COMMAND
2275
2276 inx := os.Stdin
2277
2278 // check for data being piped into stdin
2279 isPipe := false
2280 fi, err := os.Stdin.Stat()
2281 if err == nil {
2282 isPipe = bool((fi.Mode() & os.ModeNamedPipe) != 0)
2283 }
2284
2285 usingFile := false
2286
2287 if fileName != "" {
2288
2289 inFile, err := os.Open(fileName)
2290 if err != nil {
2291 eutils.DisplayError("Unable to open input file '%s'", fileName)
2292 os.Exit(1)
2293 }
2294
2295 defer inFile.Close()
2296
2297 // use indicated file instead of stdin
2298 inx = inFile
2299 usingFile = true
2300
2301 if isPipe && runtime.GOOS != "windows" {
2302 mode := fi.Mode().String()
2303 eutils.DisplayError("Input data from both stdin and file '%s', mode is '%s'", fileName, mode)
2304 os.Exit(1)
2305 }
2306 }
2307
2308 // check for -input command after extraction arguments
2309 for _, str := range args {
2310 if str == "-input" {
2311 eutils.DisplayError("Misplaced -input command")
2312 os.Exit(1)
2313 }
2314 }
2315
2316 // TRIM LEADING BYTE ORDER MARK
2317
2318 const FirstBuffSize = 4096
2319
2320 getFirstBlock := func() string {
2321
2322 buffer := make([]byte, FirstBuffSize)
2323 n, err := inx.Read(buffer)
2324 if err != nil && err != io.EOF {
2325 eutils.DisplayError("Unable to read first block: %s", err.Error())
2326 // os.Exit(1)
2327 }
2328 bufr := buffer[:n]
2329 return string(bufr)
2330 }
2331
2332 first := getFirstBlock()
2333
2334 // trim leading byte order mark, if present
2335 first = eutils.TrimBOM(first)
2336
2337 in := io.MultiReader(strings.NewReader(first), inx)
2338
2339 // START PROFILING IF REQUESTED
2340
2341 if prfl {
2342
2343 f, err := os.Create("cpu.pprof")
2344 if err != nil {
2345 eutils.DisplayError("Unable to create profile output file")
2346 os.Exit(1)
2347 }
2348
2349 pprof.StartCPUProfile(f)
2350
2351 defer pprof.StopCPUProfile()
2352 }
2353
2354 // INITIALIZE RECORD COUNT
2355
2356 recordCount := 0
2357 byteCount := 0
2358
2359 // print processing rate and program duration
2360 printDuration := func(name string) {
2361
2362 eutils.PrintDuration(name, recordCount, byteCount)
2363 }
2364
2365 nextArg := func() (string, bool) {
2366
2367 if len(args) < 1 {
2368 return "", false
2369 }
2370
2371 // remove next token from slice
2372 nxt := args[0]
2373 args = args[1:]
2374
2375 return nxt, true
2376 }
2377
2378 // The several converter functions that follow must be called
2379 // before CreateXMLStreamer starts draining stdin
2380
2381 // JSON TO XML CONVERTER
2382
2383 if args[0] == "-j2x" || args[0] == "-json2xml" {
2384
2385 // skip past command name
2386 args = args[1:]
2387
2388 set := "root"
2389 rec := ""
2390 nest := "element"
2391
2392 // look for optional arguments
2393 for {
2394 arg, ok := nextArg()
2395 if !ok {
2396 break
2397 }
2398
2399 switch arg {
2400 case "-set":
2401 // override set wrapper
2402 set, ok = nextArg()
2403 if ok && set == "-" {
2404 set = ""
2405 }
2406 case "-rec":
2407 // override record wrapper
2408 rec, ok = nextArg()
2409 if ok && rec == "-" {
2410 rec = ""
2411 }
2412 case "-nest":
2413 // specify nested array naming policy
2414 nest, ok = nextArg()
2415 if !ok {
2416 eutils.DisplayError("Nested array naming policy is missing")
2417 os.Exit(1)
2418 }
2419 if ok && nest == "-" {
2420 nest = "flat"
2421 }
2422 lft, rgt := eutils.SplitInTwoLeft(nest, ",")
2423 switch lft {
2424 case "flat", "plural", "name", "singular", "single", "recurse", "recursive", "same", "depth", "deep", "level", "element", "elem", "_E", "":
2425 default:
2426 eutils.DisplayError("Unrecognized nested array naming policy '%s'", lft)
2427 os.Exit(1)
2428 }
2429 switch rgt {
2430 case "flat", "plural", "name", "singular", "single", "recurse", "recursive", "same", "depth", "deep", "level", "element", "elem", "_E", "":
2431 default:
2432 eutils.DisplayError("Unrecognized nested array naming policy '%s'", rgt)
2433 os.Exit(1)
2434 }
2435 default:
2436 // alternative form uses positional arguments to override set and rec
2437 set = arg
2438 if set == "-" {
2439 set = ""
2440 }
2441 rec, ok = nextArg()
2442 if ok && rec == "-" {
2443 rec = ""
2444 }
2445 }
2446 }
2447
2448 // use output channel of tokenizer as input channel of converter
2449 jcnv := eutils.JSONConverter(in, set, rec, nest)
2450
2451 if jcnv == nil {
2452 eutils.DisplayError("Unable to create JSON to XML converter")
2453 os.Exit(1)
2454 }
2455
2456 // drain output of channel
2457 for str := range jcnv {
2458
2459 if str == "" {
2460 continue
2461 }
2462
2463 recordCount++
2464 byteCount += len(str)
2465
2466 // send result to output
2467 os.Stdout.WriteString(str)
2468 if !strings.HasSuffix(str, "\n") {
2469 os.Stdout.WriteString("\n")
2470 }
2471
2472 runtime.Gosched()
2473 }
2474
2475 debug.FreeOSMemory()
2476
2477 if timr {
2478 printDuration("blocks")
2479 }
2480
2481 return
2482 }
2483
2484 // ASN.1 TO XML CONVERTER
2485
2486 if args[0] == "-a2x" || args[0] == "-asn2xml" {
2487
2488 // skip past command name
2489 args = args[1:]
2490
2491 set := ""
2492 rec := ""
2493
2494 // look for optional arguments
2495 for {
2496 arg, ok := nextArg()
2497 if !ok {
2498 break
2499 }
2500
2501 switch arg {
2502 case "-set":
2503 // override set wrapper
2504 set, ok = nextArg()
2505 if ok && set == "-" {
2506 set = ""
2507 }
2508 case "-rec":
2509 // override record wrapper
2510 rec, ok = nextArg()
2511 if ok && rec == "-" {
2512 rec = ""
2513 }
2514 }
2515 }
2516
2517 acnv := eutils.ASN1Converter(in, set, rec)
2518
2519 if acnv == nil {
2520 eutils.DisplayError("Unable to create ASN.1 to XML converter")
2521 os.Exit(1)
2522 }
2523
2524 // drain output of channel
2525 for str := range acnv {
2526
2527 if str == "" {
2528 continue
2529 }
2530
2531 recordCount++
2532 byteCount += len(str)
2533
2534 // send result to output
2535 os.Stdout.WriteString(str)
2536 if !strings.HasSuffix(str, "\n") {
2537 os.Stdout.WriteString("\n")
2538 }
2539
2540 runtime.Gosched()
2541 }
2542
2543 debug.FreeOSMemory()
2544
2545 if timr {
2546 printDuration("blocks")
2547 }
2548
2549 return
2550 }
2551
2552 // READ TAB-DELIMITED FILE AND WRAP IN XML FIELDS
2553
2554 doTable := func(delim string) {
2555
2556 // skip past command name
2557 args = args[1:]
2558
2559 set := ""
2560 rec := ""
2561
2562 skip := 0
2563 header := false
2564 lower := false
2565 upper := false
2566 indent := true
2567 insdx := false
2568
2569 var fields []string
2570 numFlds := 0
2571
2572 for len(args) > 0 {
2573 str := args[0]
2574 switch str {
2575 case "-set":
2576 args = args[1:]
2577 if len(args) < 1 {
2578 eutils.DisplayError("No argument after -set")
2579 os.Exit(1)
2580 }
2581 set = args[0]
2582 args = args[1:]
2583 case "-rec":
2584 args = args[1:]
2585 if len(args) < 1 {
2586 eutils.DisplayError("No argument after -rec")
2587 os.Exit(1)
2588 }
2589 rec = args[0]
2590 args = args[1:]
2591 case "-skip":
2592 args = args[1:]
2593 if len(args) < 1 {
2594 eutils.DisplayError("No argument after -skip")
2595 os.Exit(1)
2596 }
2597 tmp := args[0]
2598 val, err := strconv.Atoi(tmp)
2599 if err != nil {
2600 eutils.DisplayError("-skip argument (%s) is not an integer", tmp)
2601 os.Exit(1)
2602 }
2603 skip = val
2604 args = args[1:]
2605 case "-header", "-headers", "-heading":
2606 header = true
2607 args = args[1:]
2608 case "-lower":
2609 lower = true
2610 args = args[1:]
2611 case "-upper":
2612 upper = true
2613 args = args[1:]
2614 case "-indent":
2615 indent = true
2616 args = args[1:]
2617 case "-flush":
2618 indent = false
2619 args = args[1:]
2620 case "-insdx":
2621 insdx = true
2622 args = args[1:]
2623 if len(args) > 0 {
2624 str = args[0]
2625 if str == "complete" || str == "partial" {
2626 // skip past complete or partial flag
2627 args = args[1:]
2628 }
2629 }
2630 if len(args) > 0 {
2631 // skip past feature name
2632 args = args[1:]
2633 }
2634 // first column is always the accession
2635 fields = append(fields, "accession")
2636 numFlds++
2637 // second column is now the feature key
2638 fields = append(fields, "feature_key")
2639 numFlds++
2640 default:
2641 // remaining arguments are names for columns
2642 if str != "" && str != "*" {
2643
2644 if insdx {
2645 // normalize -insdx qualifier names to lower-case
2646 str = strings.ToLower(str)
2647 // convert pound and percent prefixes into suffixes
2648 if strings.HasPrefix(str, "#") {
2649 str = strings.TrimPrefix(str, "#")
2650 str += "_Num"
2651 } else if strings.HasPrefix(str, "%") {
2652 str = strings.TrimPrefix(str, "%")
2653 str += "_Len"
2654 }
2655 }
2656
2657 fields = append(fields, str)
2658 numFlds++
2659 }
2660 args = args[1:]
2661 }
2662 }
2663
2664 if numFlds < 1 && !header {
2665 eutils.DisplayError("Insufficient arguments for table converter")
2666 os.Exit(1)
2667 }
2668
2669 tble := eutils.TableConverter(in, delim, set, rec, skip, header, lower, upper, indent, insdx, fields)
2670
2671 if tble == nil {
2672 eutils.DisplayError("Unable to create table to XML converter")
2673 os.Exit(1)
2674 }
2675
2676 // drain output of channel
2677 for str := range tble {
2678
2679 if str == "" {
2680 continue
2681 }
2682
2683 recordCount++
2684 byteCount += len(str)
2685
2686 // send result to output
2687 os.Stdout.WriteString(str)
2688 if !strings.HasSuffix(str, "\n") {
2689 os.Stdout.WriteString("\n")
2690 }
2691
2692 runtime.Gosched()
2693 }
2694
2695 debug.FreeOSMemory()
2696
2697 if timr {
2698 printDuration("lines")
2699 }
2700 }
2701
2702 if len(args) > 1 && args[0] == "-t2x" {
2703
2704 doTable("\t")
2705 return
2706 }
2707
2708 if len(args) > 1 && args[0] == "-c2x" {
2709
2710 doTable(",")
2711 return
2712 }
2713
2714 if len(args) > 1 && args[0] == "-s2x" {
2715
2716 doTable(";")
2717 return
2718 }
2719
2720 // CONVERT IDENTIFIERS AND PARENTS TO IDENTIFIERS AND LINEAGE
2721
2722 doParentsToLineage := func() {
2723
2724 tble := eutils.ParentsToLineage(in)
2725
2726 if tble == nil {
2727 eutils.DisplayError("Unable to create parents to lineage converter")
2728 os.Exit(1)
2729 }
2730
2731 // drain output of channel
2732 for str := range tble {
2733
2734 if str == "" {
2735 continue
2736 }
2737
2738 recordCount++
2739 byteCount += len(str)
2740
2741 // send result to output
2742 os.Stdout.WriteString(str)
2743 if !strings.HasSuffix(str, "\n") {
2744 os.Stdout.WriteString("\n")
2745 }
2746
2747 runtime.Gosched()
2748 }
2749
2750 debug.FreeOSMemory()
2751
2752 if timr {
2753 printDuration("lines")
2754 }
2755 }
2756
2757 if len(args) > 0 && args[0] == "-p2l" {
2758
2759 doParentsToLineage()
2760 return
2761 }
2762
2763 // READ INI FILE INTO XML FIELDS
2764
2765 if len(args) > 0 && args[0] == "-i2x" {
2766
2767 ini := eutils.INIConverter(in)
2768
2769 if ini == nil {
2770 eutils.DisplayError("Unable to create INI file to XML converter")
2771 os.Exit(1)
2772 }
2773
2774 // drain output of channel
2775 for str := range ini {
2776
2777 if str == "" {
2778 continue
2779 }
2780
2781 recordCount++
2782 byteCount += len(str)
2783
2784 // send result to output
2785 os.Stdout.WriteString(str)
2786 if !strings.HasSuffix(str, "\n") {
2787 os.Stdout.WriteString("\n")
2788 }
2789
2790 runtime.Gosched()
2791 }
2792
2793 debug.FreeOSMemory()
2794
2795 if timr {
2796 printDuration("lines")
2797 }
2798 return
2799 }
2800
2801 // READ YAML FILE INTO XML FIELDS
2802
2803 if len(args) > 0 && args[0] == "-y2x" {
2804
2805 yml := eutils.YAMLConverter(in)
2806
2807 if yml == nil {
2808 eutils.DisplayError("Unable to create YAML file to XML converter")
2809 os.Exit(1)
2810 }
2811
2812 // drain output of channel
2813 for str := range yml {
2814
2815 if str == "" {
2816 continue
2817 }
2818
2819 recordCount++
2820 byteCount += len(str)
2821
2822 // send result to output
2823 os.Stdout.WriteString(str)
2824 if !strings.HasSuffix(str, "\n") {
2825 os.Stdout.WriteString("\n")
2826 }
2827
2828 runtime.Gosched()
2829 }
2830
2831 debug.FreeOSMemory()
2832
2833 if timr {
2834 printDuration("lines")
2835 }
2836 return
2837 }
2838
2839 // READ TOML FILE INTO XML FIELDS
2840
2841 if len(args) > 0 && args[0] == "-m2x" {
2842
2843 tml := eutils.TOMLConverter(in)
2844
2845 if tml == nil {
2846 eutils.DisplayError("Unable to create TOML file to XML converter")
2847 os.Exit(1)
2848 }
2849
2850 // drain output of channel
2851 for str := range tml {
2852
2853 if str == "" {
2854 continue
2855 }
2856
2857 recordCount++
2858 byteCount += len(str)
2859
2860 // send result to output
2861 os.Stdout.WriteString(str)
2862 if !strings.HasSuffix(str, "\n") {
2863 os.Stdout.WriteString("\n")
2864 }
2865
2866 runtime.Gosched()
2867 }
2868
2869 debug.FreeOSMemory()
2870
2871 if timr {
2872 printDuration("lines")
2873 }
2874 return
2875 }
2876
2877 // READ GENBANK FLATFILE AND TRANSLATE TO INSDSEQ XML
2878
2879 if len(args) > 0 && args[0] == "-g2x" {
2880
2881 /*
2882 gbk := eutils.GenBankConverter(in)
2883
2884 if gbk == nil {
2885 eutils.DisplayError("Unable to create GenBank to XML converter")
2886 os.Exit(1)
2887 }
2888 */
2889
2890 // GenBank and GenPept flatfiles start with LOCUS line
2891 pattern := "LOCUS "
2892
2893 lbsq := eutils.CreateTextStreamer(in)
2894 psrq := eutils.CreateTextProducer(pattern, "", "", 0, 0, lbsq)
2895 gbkq := eutils.CreateGBConverters(psrq)
2896 unsq := eutils.CreateTextUnshuffler(gbkq)
2897
2898 if lbsq == nil || psrq == nil || gbkq == nil || unsq == nil {
2899 eutils.DisplayError("GenBank converters not built")
2900 os.Exit(1)
2901 }
2902
2903 head := `<?xml version="1.0" encoding="UTF-8" ?>
2904 <!DOCTYPE INSDSet PUBLIC "-//NCBI//INSD INSDSeq/EN" "https://www.ncbi.nlm.nih.gov/dtd/INSD_INSDSeq.dtd">
2905 <INSDSet>
2906 `
2907 tail := ""
2908
2909 // drain output of last channel in service chain
2910 for str := range unsq {
2911
2912 if str == "" {
2913 continue
2914 }
2915
2916 recordCount++
2917 byteCount += len(str)
2918
2919 if head != "" {
2920 os.Stdout.WriteString(head)
2921 head = ""
2922 tail = `</INSDSet>
2923 `
2924 }
2925
2926 // send result to stdout
2927 os.Stdout.WriteString(str)
2928 if !strings.HasSuffix(str, "\n") {
2929 os.Stdout.WriteString("\n")
2930 }
2931
2932 runtime.Gosched()
2933 }
2934
2935 if tail != "" {
2936 os.Stdout.WriteString(tail)
2937 }
2938
2939 debug.FreeOSMemory()
2940
2941 if timr {
2942 printDuration("records")
2943 }
2944
2945 return
2946 }
2947
2948 // READ GENBANK FLATFILE AND CREATE REFERENCE INDEX
2949
2950 if len(args) > 0 && args[0] == "-g2r" {
2951
2952 gbk := eutils.GenBankRefIndex(in, deStop, doStem)
2953
2954 if gbk == nil {
2955 eutils.DisplayError("Unable to create GenBank reference indexer")
2956 os.Exit(1)
2957 }
2958
2959 head := "<SET>"
2960 tail := "</SET>"
2961
2962 if head != "" {
2963 os.Stdout.WriteString(head)
2964 os.Stdout.WriteString("\n")
2965 }
2966
2967 // drain output of last channel in service chain
2968 for str := range gbk {
2969
2970 if str == "" {
2971 continue
2972 }
2973
2974 recordCount++
2975 byteCount += len(str)
2976
2977 // send result to stdout
2978 os.Stdout.WriteString(str)
2979 if !strings.HasSuffix(str, "\n") {
2980 os.Stdout.WriteString("\n")
2981 }
2982
2983 runtime.Gosched()
2984 }
2985
2986 if tail != "" {
2987 os.Stdout.WriteString(tail)
2988 os.Stdout.WriteString("\n")
2989 }
2990
2991 debug.FreeOSMemory()
2992
2993 if timr {
2994 printDuration("records")
2995 }
2996
2997 return
2998 }
2999
3000 // READ GENBANK FLATFILE, FILTER BY ACCESSION, TAXID, OR STRING, REMOVE FEATURES AND SEQUENCE
3001
3002 if len(args) > 0 && args[0] == "-gbf" {
3003
3004 // skip past command name
3005 args = args[1:]
3006
3007 truncate := false
3008 require := ""
3009 exclude := ""
3010 taxname := ""
3011
3012 // create maps that records each accession and taxid
3013 accnMap := make(map[string]bool)
3014 taxidMap := make(map[string]bool)
3015
3016 // if no arguments, truncate all records at feature table
3017 if len(args) < 1 {
3018 truncate = true
3019 }
3020
3021 // look for optional arguments
3022 for {
3023 arg, ok := nextArg()
3024 if !ok {
3025 break
3026 }
3027
3028 switch arg {
3029 case "-truncate", "-truncated":
3030 truncate = true
3031 case "-accession":
3032 accn, ok := nextArg()
3033 if ok && accn != "" {
3034 // add single identifier to map
3035 accnMap[accn] = true
3036 }
3037 case "-accessions":
3038 fname, ok := nextArg()
3039 if !ok {
3040 eutils.DisplayError("Missing accession file argument")
3041 os.Exit(1)
3042 }
3043
3044 // read file of accessions to use for filtering
3045 fl, err := os.Open(fname)
3046 if err != nil {
3047 eutils.DisplayError("Unable to open accession file '%s'", fname)
3048 os.Exit(1)
3049 }
3050
3051 scanr := bufio.NewScanner(fl)
3052
3053 // read lines of identifiers
3054 for scanr.Scan() {
3055
3056 line := scanr.Text()
3057
3058 // remove version number
3059 accn, _ := eutils.SplitInTwoLeft(line, ".")
3060
3061 if accn != "" {
3062 // add identifier to map
3063 accnMap[accn] = true
3064 }
3065 }
3066
3067 fl.Close()
3068 case "-taxid":
3069 txid, ok := nextArg()
3070 if ok && txid != "" {
3071 // add single taxid to map
3072 taxidMap[txid] = true
3073 }
3074 case "-taxids":
3075 fname, ok := nextArg()
3076 if !ok {
3077 eutils.DisplayError("Missing taxid file argument")
3078 os.Exit(1)
3079 }
3080
3081 // read file of taxids to use for filtering
3082 fl, err := os.Open(fname)
3083 if err != nil {
3084 eutils.DisplayError("Unable to open taxid file '%s'", fname)
3085 os.Exit(1)
3086 }
3087
3088 scanr := bufio.NewScanner(fl)
3089
3090 // read lines of taxids
3091 for scanr.Scan() {
3092
3093 line := scanr.Text()
3094
3095 if line != "" {
3096 // add taxid to map
3097 taxidMap[line] = true
3098 }
3099 }
3100
3101 fl.Close()
3102 case "-taxname", "-organism":
3103 txt, ok := nextArg()
3104 if ok {
3105 taxname = txt
3106 }
3107 case "-require", "-required":
3108 txt, ok := nextArg()
3109 if ok {
3110 require = txt
3111 }
3112 case "-exclude", "-excluded":
3113 txt, ok := nextArg()
3114 if ok {
3115 exclude = txt
3116 }
3117 default:
3118 if strings.HasPrefix(arg, "-") {
3119 eutils.DisplayError("Unrecognized argument '%s'", arg)
3120 os.Exit(1)
3121 }
3122 }
3123 }
3124
3125 // GenBank and GenPept flatfiles start with LOCUS line
3126 pattern := "LOCUS "
3127
3128 inp := io.Reader(in)
3129
3130 if zipp {
3131
3132 zpr, err := gzip.NewReader(in)
3133
3134 if err != nil {
3135 eutils.DisplayError("Unable to create gzip reader - %s", err.Error())
3136 os.Exit(1)
3137 }
3138
3139 defer zpr.Close()
3140
3141 // replace input io.Reader
3142 inp = zpr
3143 }
3144
3145 lbsq := eutils.CreateTextStreamer(inp)
3146 psrq := eutils.CreateTextProducer(pattern, require, exclude, 0, 0, lbsq)
3147 unsq := eutils.CreateTextUnshuffler(psrq)
3148
3149 if lbsq == nil || psrq == nil || unsq == nil {
3150 eutils.DisplayError("Line streamer not built")
3151 os.Exit(1)
3152 }
3153
3154 itemCount := 0
3155
3156 // read filtered records
3157 for str := range unsq {
3158
3159 if str == "" {
3160 continue
3161 }
3162
3163 itemCount++
3164 if itemCount > 1000 {
3165 itemCount = 0
3166 runtime.Gosched()
3167 }
3168
3169 recordCount++
3170 byteCount += len(str)
3171
3172 if len(accnMap) > 0 {
3173
3174 // filter by accession
3175 pos := strings.Index(str, "ACCESSION")
3176 if pos < 0 {
3177 continue
3178 }
3179
3180 sub := str[pos+9:]
3181
3182 pos = strings.Index(sub, "\n")
3183 if pos < 0 {
3184 continue
3185 }
3186
3187 sub = sub[:pos]
3188
3189 flds := strings.Fields(sub)
3190 if len(flds) < 1 {
3191 continue
3192 }
3193
3194 accn := flds[0]
3195 if !accnMap[accn] {
3196 continue
3197 }
3198 }
3199
3200 if len(taxidMap) > 0 {
3201
3202 // filter by taxid
3203 pos := strings.Index(str, "/db_xref=\"taxon:")
3204 if pos < 0 {
3205 continue
3206 }
3207
3208 sub := str[pos+16:]
3209
3210 pos = strings.Index(sub, "\"")
3211 if pos < 0 {
3212 continue
3213 }
3214
3215 txid := sub[:pos]
3216
3217 if !taxidMap[txid] {
3218 continue
3219 }
3220 }
3221
3222 if taxname != "" {
3223
3224 // filter by organism name
3225 pos := strings.Index(str, "/organism=\"")
3226 if pos < 0 {
3227 continue
3228 }
3229
3230 sub := str[pos+11:]
3231
3232 pos = strings.Index(sub, "\"")
3233 if pos < 0 {
3234 continue
3235 }
3236
3237 txname := sub[:pos]
3238
3239 if taxname != txname {
3240 continue
3241 }
3242 }
3243
3244 if truncate {
3245
3246 // remove features and sequence
3247 pos := strings.Index(str, "FEATURES ")
3248 if pos < 0 {
3249 continue
3250 }
3251
3252 sub := str[:pos]
3253
3254 os.Stdout.WriteString(sub)
3255 if !strings.HasSuffix(sub, "\n") {
3256 os.Stdout.WriteString("\n")
3257 }
3258 os.Stdout.WriteString("//\n")
3259
3260 } else {
3261
3262 os.Stdout.WriteString(str)
3263 if !strings.HasSuffix(str, "\n") {
3264 os.Stdout.WriteString("\n")
3265 }
3266 }
3267
3268 runtime.Gosched()
3269 }
3270
3271 debug.FreeOSMemory()
3272
3273 if timr {
3274 printDuration("records")
3275 }
3276
3277 return
3278 }
3279
3280 // READ TEXT FILE, PARTITION BY PATTERN, FILTER BY STRING
3281
3282 if len(args) > 0 && args[0] == "-txf" {
3283
3284 // skip past command name
3285 args = args[1:]
3286
3287 pattern := ""
3288 require := ""
3289 exclude := ""
3290 min := 0
3291 max := 0
3292
3293 // look for optional arguments
3294 for {
3295 arg, ok := nextArg()
3296 if !ok {
3297 break
3298 }
3299
3300 switch arg {
3301 case "-pattern":
3302 txt, ok := nextArg()
3303 if ok {
3304 pattern = strings.TrimSpace(txt)
3305 }
3306 case "-require", "-required":
3307 txt, ok := nextArg()
3308 if ok {
3309 require = txt
3310 }
3311 case "-exclude", "-excluded":
3312 txt, ok := nextArg()
3313 if ok {
3314 exclude = txt
3315 }
3316 case "-min":
3317 txt, ok := nextArg()
3318 if ok {
3319 val, err := strconv.Atoi(txt)
3320 if err == nil {
3321 min = val
3322 }
3323 }
3324 case "-max":
3325 txt, ok := nextArg()
3326 if ok {
3327 val, err := strconv.Atoi(txt)
3328 if err == nil {
3329 max = val
3330 }
3331 }
3332 default:
3333 if strings.HasPrefix(arg, "-") {
3334 eutils.DisplayError("Unrecognized argument '%s'", arg)
3335 os.Exit(1)
3336 }
3337 }
3338 }
3339
3340 if pattern == "" {
3341 eutils.DisplayError("No required -pattern argument in -txf")
3342 os.Exit(1)
3343 }
3344
3345 inp := io.Reader(in)
3346
3347 if zipp {
3348
3349 zpr, err := gzip.NewReader(in)
3350
3351 if err != nil {
3352 eutils.DisplayError("Unable to create gzip reader - %s", err.Error())
3353 os.Exit(1)
3354 }
3355
3356 defer zpr.Close()
3357
3358 // replace input io.Reader
3359 inp = zpr
3360 }
3361
3362 lbsq := eutils.CreateTextStreamer(inp)
3363 psrq := eutils.CreateTextProducer(pattern, require, exclude, min, max, lbsq)
3364 unsq := eutils.CreateTextUnshuffler(psrq)
3365
3366 if lbsq == nil || psrq == nil || unsq == nil {
3367 eutils.DisplayError("Line streamer not built")
3368 os.Exit(1)
3369 }
3370
3371 // read filtered records
3372 for str := range unsq {
3373
3374 if str == "" {
3375 continue
3376 }
3377
3378 recordCount++
3379 byteCount += len(str)
3380
3381 os.Stdout.WriteString(str)
3382 if !strings.HasSuffix(str, "\n") {
3383 os.Stdout.WriteString("\n")
3384 }
3385
3386 runtime.Gosched()
3387 }
3388
3389 debug.FreeOSMemory()
3390
3391 if timr {
3392 printDuration("records")
3393 }
3394
3395 return
3396 }
3397
3398 // READ FASTA FILE INTO XML FIELDS
3399
3400 if len(args) > 0 && args[0] == "-f2x" {
3401
3402 fcnv := eutils.FASTAConverter(in, false)
3403
3404 if fcnv == nil {
3405 eutils.DisplayError("Unable to create FASTA file to XML converter")
3406 os.Exit(1)
3407 }
3408
3409 var buffer strings.Builder
3410
3411 // drain output of channel
3412 for fsa := range fcnv {
3413
3414 buffer.WriteString("<FASTA>\n")
3415 if fsa.SeqID != "" {
3416 buffer.WriteString(" <ID>")
3417 buffer.WriteString(fsa.SeqID)
3418 buffer.WriteString("</ID>\n")
3419 }
3420 if fsa.Title != "" {
3421 buffer.WriteString(" <Title>")
3422 buffer.WriteString(fsa.Title)
3423 buffer.WriteString("</Title>\n")
3424 }
3425 if fsa.Length != 0 {
3426 buffer.WriteString(" <Length>")
3427 buffer.WriteString(strconv.Itoa(fsa.Length))
3428 buffer.WriteString("</Length>\n")
3429 }
3430 if fsa.Sequence != "" {
3431 buffer.WriteString(" <Seq>")
3432 buffer.WriteString(fsa.Sequence)
3433 buffer.WriteString("</Seq>\n")
3434 }
3435 buffer.WriteString("</FASTA>\n")
3436
3437 txt := buffer.String()
3438
3439 if txt != "" {
3440 os.Stdout.WriteString(txt)
3441 }
3442
3443 buffer.Reset()
3444
3445 runtime.Gosched()
3446 }
3447
3448 debug.FreeOSMemory()
3449
3450 return
3451 }
3452
3453 // STRING CONVERSION COMMANDS
3454
3455 inSwitch = true
3456
3457 switch args[0] {
3458 case "-encodeURL":
3459 encodeURL(in)
3460 case "-decodeURL":
3461 decodeURL(in)
3462 case "-encode64", "-encodeB64", "-encodeBase64":
3463 encodeB64(in)
3464 case "-decode64", "-decodeB64", "-decodeBase64":
3465 decodeB64(in)
3466 case "-plain":
3467 makePlain(in)
3468 case "-hgvs":
3469 decodeHGVS(in)
3470 case "-align":
3471 processAlign(in, args)
3472 case "-f2p", "-fasta":
3473 sequenceFormat(in, args)
3474 case "-remove":
3475 sequenceRemove(in, args)
3476 case "-retain":
3477 sequenceRetain(in, args)
3478 case "-replace":
3479 sequenceReplace(in, args)
3480 case "-extract":
3481 sequenceExtract(in, args)
3482 case "-search":
3483 sequenceSearch(in, args)
3484 case "-find":
3485 stringFind(in, args)
3486 case "-relax":
3487 relaxString(in)
3488 case "-upper":
3489 upperString(in)
3490 case "-lower":
3491 lowerString(in)
3492 case "-counts", "-basecount":
3493 baseCount(in)
3494 case "-revcomp":
3495 nucRevComp(in)
3496 case "-reverse":
3497 seqFlip(in)
3498 case "-molwt":
3499 protWeight(in, args)
3500 case "-cds2prot":
3501 cdRegionToProtein(in, args)
3502 case "-codons":
3503 nucProtCodonReport(args)
3504 case "-diff":
3505 fastaDiff(in, args)
3506 default:
3507 // if not any of the conversion commands, keep going
3508 inSwitch = false
3509 }
3510
3511 if inSwitch {
3512
3513 debug.FreeOSMemory()
3514
3515 if timr {
3516 printDuration("bases")
3517 }
3518
3519 return
3520 }
3521
3522 // CREATE XML BLOCK READER FROM STDIN OR FILE
3523
3524 rdr := eutils.CreateXMLStreamer(in, nil)
3525 if rdr == nil {
3526 eutils.DisplayError("Unable to create XML Block Reader")
3527 os.Exit(1)
3528 }
3529
3530 // CONFIRM INPUT DATA AVAILABILITY AFTER RUNNING COMMAND GENERATORS
3531
3532 if fileName == "" && runtime.GOOS != "windows" {
3533
3534 fromStdin := bool((fi.Mode() & os.ModeCharDevice) == 0)
3535 if !isPipe || !fromStdin {
3536 mode := fi.Mode().String()
3537 eutils.DisplayError("No data supplied to transmute from stdin or file, mode is '%s'", mode)
3538 os.Exit(1)
3539 }
3540 }
3541
3542 if !usingFile && !isPipe {
3543
3544 eutils.DisplayError("No XML input data supplied to transmute")
3545 os.Exit(1)
3546 }
3547
3548 // SPECIAL FORMATTING COMMANDS
3549
3550 inSwitch = true
3551 leaf := false
3552
3553 switch args[0] {
3554 case "-format":
3555 processFormat(rdr, args)
3556 case "-filter":
3557 processFilter(rdr, args)
3558 case "-normalize", "-normal":
3559 if len(args) < 2 {
3560 eutils.DisplayError("No database supplied to -normalize")
3561 os.Exit(1)
3562 }
3563 db := args[1]
3564 nrm := eutils.NormalizeXML(rdr, db)
3565 eutils.ChanToStdout(nrm)
3566 case "-outline":
3567 args = args[1:]
3568 max := 0
3569 if len(args) > 0 {
3570 mx := args[0]
3571 val, err := strconv.Atoi(mx)
3572 if err == nil {
3573 max = val
3574 }
3575 }
3576 processOutline(rdr, max)
3577 case "-contour":
3578 leaf = true
3579 fallthrough
3580 case "-synopsis":
3581 args = args[1:]
3582 delim := "/"
3583 if len(args) > 0 {
3584 delim = args[0]
3585 if len(delim) > 3 {
3586 delim = "/"
3587 }
3588 }
3589 processSynopsis(rdr, leaf, delim)
3590 case "-tokens":
3591 processTokens(rdr)
3592 default:
3593 // if not any of the formatting commands, keep going
3594 inSwitch = false
3595 }
3596
3597 if inSwitch {
3598
3599 debug.FreeOSMemory()
3600
3601 // suppress printing of lines if not properly counted
3602 if recordCount == 1 {
3603 recordCount = 0
3604 }
3605
3606 if timr {
3607 printDuration("lines")
3608 }
3609
3610 return
3611 }
3612
3613 // SPECIFY STRINGS TO GO BEFORE AND AFTER ENTIRE OUTPUT OR EACH RECORD
3614
3615 head := ""
3616 tail := ""
3617
3618 hd := ""
3619 tl := ""
3620
3621 for {
3622
3623 inSwitch = true
3624
3625 switch args[0] {
3626 case "-head":
3627 if len(args) < 2 {
3628 eutils.DisplayError("Pattern missing after -head command")
3629 os.Exit(1)
3630 }
3631 head = eutils.ConvertSlash(args[1])
3632 case "-tail":
3633 if len(args) < 2 {
3634 eutils.DisplayError("Pattern missing after -tail command")
3635 os.Exit(1)
3636 }
3637 tail = eutils.ConvertSlash(args[1])
3638 case "-hd":
3639 if len(args) < 2 {
3640 eutils.DisplayError("Pattern missing after -hd command")
3641 os.Exit(1)
3642 }
3643 hd = eutils.ConvertSlash(args[1])
3644 case "-tl":
3645 if len(args) < 2 {
3646 eutils.DisplayError("Pattern missing after -tl command")
3647 os.Exit(1)
3648 }
3649 tl = eutils.ConvertSlash(args[1])
3650 case "-wrp":
3651 // shortcut to wrap records in XML tags
3652 if len(args) < 2 {
3653 eutils.DisplayError("Pattern missing after -wrp command")
3654 os.Exit(1)
3655 }
3656 tmp := eutils.ConvertSlash(args[1])
3657 lft, rgt := eutils.SplitInTwoLeft(tmp, ",")
3658 if lft != "" {
3659 head = "<" + lft + ">"
3660 tail = "</" + lft + ">"
3661 }
3662 if rgt != "" {
3663 hd = "<" + rgt + ">"
3664 tl = "</" + rgt + ">"
3665 }
3666 case "-set":
3667 if len(args) < 2 {
3668 eutils.DisplayError("Pattern missing after -set command")
3669 os.Exit(1)
3670 }
3671 tmp := eutils.ConvertSlash(args[1])
3672 if tmp != "" {
3673 head = "<" + tmp + ">"
3674 tail = "</" + tmp + ">"
3675 }
3676 case "-rec":
3677 if len(args) < 2 {
3678 eutils.DisplayError("Pattern missing after -rec command")
3679 os.Exit(1)
3680 }
3681 tmp := eutils.ConvertSlash(args[1])
3682 if tmp != "" {
3683 hd = "<" + tmp + ">"
3684 tl = "</" + tmp + ">"
3685 }
3686 default:
3687 // if not any of the controls, set flag to break out of for loop
3688 inSwitch = false
3689 }
3690
3691 if !inSwitch {
3692 break
3693 }
3694
3695 // skip past arguments
3696 args = args[2:]
3697
3698 if len(args) < 1 {
3699 eutils.DisplayError("Insufficient command-line arguments supplied to transmute")
3700 os.Exit(1)
3701 }
3702 }
3703
3704 // READ REFERENCE INDEX AND RETURN RECORDS WITH PMID FIELD
3705
3706 if len(args) > 0 && args[0] == "-r2p" {
3707
3708 // skip past command name
3709 args = args[1:]
3710
3711 var options []string
3712 if len(args) > 1 && args[0] == "-options" {
3713 args = args[1:]
3714 options = args
3715 }
3716
3717 local := true
3718 for _, rgs := range options {
3719 opts := strings.Split(rgs, ",")
3720 for _, opt := range opts {
3721 if opt == "test" {
3722 // citmatch only, skip verify and edirect tests
3723 local = false
3724 }
3725 }
3726 }
3727
3728 jtaMap := make(map[string]string)
3729
3730 if local {
3731
3732 // obtain path from environment variable
3733 dataBase := eutils.GetLocalArchiveFolder("pubmed", "Data", false)
3734
3735 if dataBase != "" {
3736 // check to make sure local archive data directory is mounted
3737 _, err = os.Stat(dataBase)
3738 if err != nil && os.IsNotExist(err) {
3739 eutils.DisplayError("Local mapping data is not mounted")
3740 // allow program to continue
3741 } else {
3742 // load journal title lookup map
3743 jpath := filepath.Join(dataBase, "joursets.txt")
3744 eutils.TableToMap(jpath, jtaMap)
3745 }
3746 }
3747 }
3748
3749 xmlq := eutils.CreateXMLProducer("CITATION", "", false, rdr)
3750 ctmq := eutils.CreateCitMatchers(xmlq, options, deStop, doStem, nil, jtaMap)
3751 unsq := eutils.CreateXMLUnshuffler(ctmq)
3752
3753 if xmlq == nil || ctmq == nil || unsq == nil {
3754 eutils.DisplayError("Unable to create citation matcher")
3755 os.Exit(1)
3756 }
3757
3758 if head != "" {
3759 os.Stdout.WriteString(head)
3760 os.Stdout.WriteString("\n")
3761 }
3762
3763 // drain output channel
3764 for curr := range unsq {
3765
3766 str := curr.Text
3767
3768 if str == "" {
3769 continue
3770 }
3771
3772 if hd != "" {
3773 os.Stdout.WriteString(hd)
3774 os.Stdout.WriteString("\n")
3775 }
3776
3777 // send result to output
3778 os.Stdout.WriteString(str)
3779 if !strings.HasSuffix(str, "\n") {
3780 os.Stdout.WriteString("\n")
3781 }
3782
3783 if tl != "" {
3784 os.Stdout.WriteString(tl)
3785 os.Stdout.WriteString("\n")
3786 }
3787
3788 recordCount++
3789 runtime.Gosched()
3790 }
3791
3792 if tail != "" {
3793 os.Stdout.WriteString(tail)
3794 os.Stdout.WriteString("\n")
3795 }
3796
3797 debug.FreeOSMemory()
3798
3799 if timr {
3800 printDuration("records")
3801 }
3802
3803 return
3804 }
3805
3806 // READ REFERENCE INDEX AND RETURN NORMALIZED RECORDS WITH TEXT FIELD
3807
3808 if len(args) > 0 && args[0] == "-nc" {
3809
3810 // skip past command name
3811 args = args[1:]
3812
3813 xmlq := eutils.CreateXMLProducer("CITATION", "", false, rdr)
3814
3815 if xmlq == nil {
3816 eutils.DisplayError("Unable to create citation normalizer")
3817 os.Exit(1)
3818 }
3819
3820 // drain output channel
3821 for curr := range xmlq {
3822
3823 str := curr.Text
3824
3825 if str == "" {
3826 continue
3827 }
3828
3829 txt := eutils.NormalizeCitation(str)
3830
3831 // send result to output
3832 os.Stdout.WriteString(txt)
3833 if !strings.HasSuffix(txt, "\n") {
3834 os.Stdout.WriteString("\n")
3835 }
3836
3837 recordCount++
3838 runtime.Gosched()
3839 }
3840
3841 debug.FreeOSMemory()
3842
3843 if timr {
3844 printDuration("records")
3845 }
3846
3847 return
3848 }
3849
3850 // ENSURE PRESENCE OF PATTERN ARGUMENT
3851
3852 if len(args) < 1 {
3853 eutils.DisplayError("Insufficient command-line arguments supplied to transmute")
3854 os.Exit(1)
3855 }
3856
3857 // allow -record as synonym of -pattern (undocumented)
3858 if args[0] == "-record" || args[0] == "-Record" {
3859 args[0] = "-pattern"
3860 }
3861
3862 // make sure top-level -pattern command is next
3863 if args[0] != "-pattern" && args[0] != "-Pattern" {
3864 eutils.DisplayError("No -pattern in command-line arguments")
3865 os.Exit(1)
3866 }
3867 if len(args) < 2 {
3868 eutils.DisplayError("Item missing after -pattern command")
3869 os.Exit(1)
3870 }
3871
3872 topPat := args[1]
3873 if topPat == "" {
3874 eutils.DisplayError("Item missing after -pattern command")
3875 os.Exit(1)
3876 }
3877 if strings.HasPrefix(topPat, "-") {
3878 eutils.DisplayError("Misplaced %s command", topPat)
3879 os.Exit(1)
3880 }
3881
3882 // look for -pattern Parent/* construct for heterogeneous data, e.g., -pattern PubmedArticleSet/*
3883 topPattern, star := eutils.SplitInTwoLeft(topPat, "/")
3884 if topPattern == "" {
3885 return
3886 }
3887
3888 // CONCURRENT REFORMATTING OF PARSED XML RECORDS
3889
3890 // -pattern plus -format does concurrent flush-left reformatting
3891 if len(args) > 2 && args[2] == "-format" {
3892
3893 format := "flush"
3894 if len(args) > 3 {
3895 format = args[3]
3896 if strings.HasPrefix(format, "-") {
3897 format = "flush"
3898 }
3899 }
3900
3901 xmlq := eutils.CreateXMLProducer(topPattern, star, false, rdr)
3902 fchq := createFormatters(topPattern, format, xmlq)
3903 unsq := eutils.CreateXMLUnshuffler(fchq)
3904
3905 if xmlq == nil || fchq == nil || unsq == nil {
3906 eutils.DisplayError("Unable to create formatter")
3907 os.Exit(1)
3908 }
3909
3910 if head != "" {
3911 os.Stdout.WriteString(head)
3912 os.Stdout.WriteString("\n")
3913 }
3914
3915 // drain output channel
3916 for curr := range unsq {
3917
3918 str := curr.Text
3919
3920 if str == "" {
3921 continue
3922 }
3923
3924 if hd != "" {
3925 os.Stdout.WriteString(hd)
3926 os.Stdout.WriteString("\n")
3927 }
3928
3929 // send result to output
3930 os.Stdout.WriteString(str)
3931 if !strings.HasSuffix(str, "\n") {
3932 os.Stdout.WriteString("\n")
3933 }
3934
3935 if tl != "" {
3936 os.Stdout.WriteString(tl)
3937 os.Stdout.WriteString("\n")
3938 }
3939
3940 recordCount++
3941 runtime.Gosched()
3942 }
3943
3944 if tail != "" {
3945 os.Stdout.WriteString(tail)
3946 os.Stdout.WriteString("\n")
3947 }
3948
3949 debug.FreeOSMemory()
3950
3951 if timr {
3952 printDuration("records")
3953 }
3954
3955 return
3956 }
3957
3958 // REPORT UNRECOGNIZED COMMAND
3959
3960 eutils.DisplayError("Unrecognized transmute command")
3961 os.Exit(1)
3962 }