TMGMEDIC ;TMG/kst/Interface from old MEDIC PMS ;03/25/06
         ;;1.0;TMG-LIB;**1**;11/01/04
 
 ;"TMG MEDIC INTERFACE FUNCTIONS
 
 ;"=======================================================================
 ;" API -- Public Functions.
 ;"=======================================================================
 ;"ASKCONVD
 ;"CONVDICT(FullNamePath)
 
 ;"=======================================================================
 ;"PRIVATE API FUNCTIONS
 ;"=======================================================================
 ;"ExtractOneNote(Array,OneNote)
 ;"ConvertOneNote(OneNote,NoteInfo)
 ;"WriteOneNote(.OneNote,NoteInfo,.ResultFile)
 
 ;"=======================================================================
 ;"=======================================================================
 
FULLDIRCVD
        ;"Purpose: To convert files created for old Medic system into format ready for
        ;"              upload into VistA
        ;"              This will allow conversion of all files in a directory.
        ;"Input: None (Filename will be asked)
        ;"Output: none (A new file will be created at same site as old file, with .vista extension
        ;"Result: none
 
        new FullNamePath
        new JustFile,JustPath
        new DoAll
        new TMGMask,TMGFiles
        new FileName
        new result set result=1
        new PriorErrorFound
        new ErrorFiles
        new OfficeLoc
        new abort set abort=0
        new SkipExisting set SkipExisting=0
        new noAskSkip set noAskSkip=0
        new NoDestDir set NoDestDir=" "
        new DestDir set DestDir=NoDestDir
 
        write !!
        write "*************************************",!
        write "Medic/Autochart Format Converter",!
        write "*************************************",!,!
 
        new s set s="Please select Medic transcription file to convert (or directory for all files)"
        set FullNamePath=$$GetFName^TMGIOUTL(s,"/var/local/OpenVistA_UserData/transcription","","",.JustPath,.JustFile)
        if FullNamePath="" do  goto FDCDone
        . do ShowError^TMGDEBUG(.PriorErrorFound,"No file selected. Aborting")
 
        if ($get(JustFile)="")&($data(JustPath)>0) do
        . set DoAll="Y"
        else  do
        . read "Convert all files in same directory?  YES// ",DoAll:$get(DTIME,3600),!
        if DoAll="" set DoAll="Y"
        set DoAll=$$UP^XLFSTR(DoAll)
        if DoAll["Y" do
        . new result
        . set TMGMask("*")=""
        . set result=$$LIST^%ZISH(JustPath,"TMGMask","TMGFiles")
        else  do
        . set TMGFiles(JustFile)=""
        if DoAll="^" goto FDCDone
 
        for  do  quit:(DestDir'="")
        . set s="Enter DESTINATION directory to move originals file(s) into after conversion.\n Leave blank to NOT move."
        . new Discard
        . set Discard=$$GetFName^TMGIOUTL(s,JustPath_"originals/","","",.DestDir,,"Enter Directory Name (? for Help): ")
        . write !
        . if DestDir=JustPath set DestDir=NoDestDir quit
 
        set FileName=$order(TMGFiles(""))
        if FileName'="" for  do  quit:(FileName="")!(abort=1)
        . new skipThis set skipThis=SkipExisting
        . new isDir set isDir=0
        . set FullNamePath=JustPath_FileName
        . if $$IsDir^TMGIOUTL(FullNamePath) set skipThis=1,isDir=1
        . if (skipThis=0)&(noAskSkip=0)&($$FileExists^TMGIOUTL(FullNamePath_".vista")) do  quit:(abort)
        . . new redo
        . . write "File ",FullNamePath," has already been converted.",!
        . . read "Convert anyway? (Yes/No/Yes-Always/No-Always) (Y/N/YA/NA/^) YA// ",redo:$get(DTIME,3600),!
        . . set redo=$$UP^XLFSTR(redo)
        . . if redo="" set redo="YA"
        . . if redo="^" set abort=1 quit
        . . if redo="YA" set noAskSkip=1
        . . if redo="NA" set SkipExisting=1,skipThis=1
        . . if "NO"[redo set skipThis=1
        . if (FullNamePath'[".vista")&(skipThis=0) do
        . . write !,"Converting file: ",FullNamePath,"...",!
        . . write "--------------------------------------------------------",!
        . . set result=$$CONVDICT(FullNamePath,.OfficeLoc)
        . . if result'>0 do
        . . . do ShowError^TMGDEBUG(.PriorErrorFound,"Error converting file.")
        . . . set PriorErrorFound=0  ;"clear errors, to allow reporting of future errors.
        . . . set ErrorFiles(FullNamePath)=1
        . . . if result=-1 set abort=1 quit
        . . else  if DestDir'=NoDestDir do
        . . . new Dest set Dest=DestDir_FileName
        . . . ;"write "Moving: ",FullNamePath,!
        . . . ;"write "To: ",Dest,!
        . . . if $$Move^TMGIOUTL(FullNamePath,Dest)=0 do
        . . . . write "Moved ",FileName,!," to: ",Dest,!
        . if (skipThis=1)&(FullNamePath'[".vista")&(isDir=0) do
        . . write "Skipping over file, as requested: ",FullNamePath,!
        . set FileName=$order(TMGFiles(FileName))
 
        if $data(ErrorFiles) do
        . write !!,"The following files contained notes with errors...",!
        . set FileName=$order(ErrorFiles(""))
        . if FileName'="" for  do  quit:(FileName="")
        . . write FileName,!
        . . set FileName=$order(ErrorFiles(FileName))
 
FDCDone
        write !,"Goodbye.",!
        quit
 
 
ASKCONVD
        ;"Purpose: To convert files created for old Medic system into format ready for
        ;"              upload into VistA
        ;"Input: None (Filename will be asked)
        ;"Output: none (A new file will be created at same site as old file, with .vista extension
        ;"Result: none
 
        new FullNamePath
        new JustFile,JustPath
        new result
        new PriorErrorFound
 
        set FullNamePath=$$GetFName^TMGIOUTL("Please select Medic transcription file to convert","/","","",.JustPath,.JustFile)
        if FullNamePath="" do  goto CDDone
        . do ShowError^TMGDEBUG(.PriorErrorFound,"No file selected. Aborting")
 
        set result=$$CONVDICT(FullNamePath)
 
        write "Goodbye.",!
 
        quit
 
 
CONVDICT(FullNamePath,OfficeLoc)
        ;"Purpose: To convert files created for old Medic system into format ready for
        ;"              upload into VistA
        ;"Input: FullNamePath -- full path and filename.
        ;"         OfficeLoc -OPTIONAL (if not provided, user may be quered for info)
        ;"              OfficeLoc(DUZ)="Full Name of Location"
        ;"              e.g. OfficeLoc(12)="Main_Office"
        ;"Output: none (A new file will be created at same site as old file, with .vista extension
        ;"Result: 1 if success, 0 if failure; -1 abort
 
        new JustFile,JustPath
        new TempFile
        new ResultFile
        new index
        new abort set abort=0
        new result
        new error set error=0
        new retry set retry=0
        new ErrorFound set ErrorFound=0
 
        do SplitFNamePath^TMGIOUTL(FullNamePath,.JustPath,.JustFile)
 
        if $$Dos2Unix^TMGIOUTL(FullNamePath)>0 do  goto CDDone
        . do ShowError^TMGDEBUG(.PriorErrorFound,"Error while converting file ('"_FullNamePath_"') to Linux text format. Aborting")
 
LoadFile
        if $$FTG^%ZISH(JustPath,JustFile,"TempFile(0)",1)=0 do  goto CDDone
        . do ShowError^TMGDEBUG(.PriorErrorFound,"Error loading file. Aborting")
 
        for  do  quit:($data(TempFile)=0)!(abort=1)
        . new OneNote,NoteInfo
        . set error=0
        . do ExtractOneNote(.TempFile,.OneNote)
        . if $$ConvertOneNote(.OneNote,.NoteInfo,.OfficeLoc)=0 do  quit
        . . set ErrorFound=1
        . . set PriorErrorFound=0
        . . do ShowError^TMGDEBUG(.PriorErrorFound,"Error while processing note.")
        . . set PriorErrorFound=0
        . . write "Will run through that again, this time in verbose/debug mode",!
        . . set error=$$ConvertOneNote(.OneNote,.NoteInfo,.OfficeLoc,1)
        . . write "<Verbose information above>",!
        . . write "File: ",FullNamePath,!
        . . if $data(NoteInfo) do
        . . . write "Here is the Note Info that was successfully gathered:",!
        . . . zwr NoteInfo(*)
        . . new temp
        . . read !,"Show more info? (^ to abort) NO// ",temp:$get(DTIME,3600),!
        . . if $$UP^XLFSTR(temp)["Y" do
        . . . write "Here is the note to be processed:",!
        . . . zwr OneNote(*)
        . . . if $data(NoteInfo) do
        . . . . write "Here is the info that was extracted:",!
        . . . . zwr NoteInfo(*)
        . . . write !,"That was the info...",!
        . . . read !,"Press enter to continue (^ to abort)...",temp:$get(DTIME,3600),!
        . . if temp="^" set abort=1,error=1
        . . write !,"File: ",FullNamePath,!
        . . read "Edit file? (^ to abort) NO// ",temp:$get(DTIME,3600),!
        . . if $$UP^XLFSTR(temp)["Y" do  quit
        . . . do LinuxEdit^TMGEDIT("joe",$$LinuxStr^TMGSTUTL(FullNamePath))
        . . . set retry=1,abort=1
        . . if temp="^" set abort=1,error=1
        . if error=0 do WriteOneNote(.OneNote,.NoteInfo,.ResultFile)
 
        if retry=1 do  goto LoadFile
        . kill TempFile
        . set retry=0,abort=0,error=0
 
        if abort=1 goto CDDone
        set index=$order(ResultFile(""))
        new ref set ref="ResultFile("_index_")"
        if $$GTF^%ZISH(ref,1,JustPath,JustFile_".vista")=0 do  goto CDDone
        . do ShowError^TMGDEBUG(.PriorErrorFound,"Error saving  file. Aborting")
        else  do
        . write !,"File successfully written to: '",JustFile_".vista'",!!
        . if $$IsDir^TMGIOUTL(JustPath_"orig/") do
        . . if $$Move^TMGIOUTL(JustPath_JustFile,JustPath_"orig/"_JustFile)=0 do
        . . . write "Original file moved to: ",JustPath_"orig/",!
        . . else  do
        . . . write "Unable to move file moved to: ",JustPath_"orig/",!
 
 
CDDone
        set result='ErrorFound
        if abort=1 set result=-1
        quit result
 
 
ExtractOneNote(Array,OneNote)
        ;"Purpose: To extract one note from Array, and return in OneNote
        ;"Input: Array:  PASS BY REFERENCE.  This should be array holding entire transcription file
        ;"                      extracted note will be removed from Array
        ;"        OneNote: PASS BY REFERENCE.  This array will hold the extracted note.
        ;"                      Anything in OneNote array will be killed before refilling
        ;"Note: notes are always divided by a line that looks like this:
        ;"      !PAT(xxxx)    !DATE(xxxx)   (Note: I will use !DATE as my signal, because if we use this
        ;"              system in the future, !PAT may not be available.
        ;"      This function will assume that Array is at the first line of the new note (i.e. no lead lines)
        ;"      The new note will be copied from the beginning of Array until the next occurance of
        ;"      !PAT/!DATE, or until the end of the Array.
        ;"Output: one note is copied into OneNote
        ;"Results: none
 
        new index
        new j
        new NextLine set NextLine=""
        kill OneNote
 
        set index=$order(Array(""))
        set j=0 ;"<-- Start numbering of array at 0 (because 0 header line will be killed later)
        if index'="" for  do  quit:(index="")!(NextLine["!DATE")
        . set OneNote(j)=$get(Array(index))
        . set j=j+1
        . kill Array(index)
        . set index=$order(Array(index))
        . if index'="" set NextLine=$get(Array(index))
        . else  set NextLine=""
 
        quit
 
 
 
ConvertOneNote(OneNote,NoteInfo,OfficeLoc,DebugMode)
        ;"Purpose: To take a note (in older MEDIC upload format) and extract information needed to make a VistA upload note
        ;"Input: OneNote -- PASS BY REFERENCE -- a single note to be converted.  Format will be like this:
        ;"              OneNote(0)="first line"
        ;"              OneNote(1)="second line"
        ;"              etc.
        ;"              ---Content of note---
        ;"              !PAT(123456)    !DATE(05/12/05)    <--- always the first line  (OneNote(0))
        ;"              <blank line>
        ;"              PATIENT NAME:[TAB]Sarah P. Doe[TAB]DATE:  05/12/2005    <---Date of encounter
        ;"              CHART#:  123456[TAB]DOB:  05/06/1995
        ;"              <blank line>
        ;"              <start of free text of document>
        ;"              ...
        ;"
        ;"              <Sometimes, if dictation extends to a second page, the following will be inserted>
        ;"              <blank line>
        ;"              PATIENT NAME:[TAB]Sarah P. Doe[TAB]DATE:  05/12/2005
        ;"              CHART#:  123456[TAB]DOB:  05/06/1995
        ;"              Page Two
        ;"              <blank line>
        ;"              ...
        ;"
        ;"              <blank line>                              <--- end of note
        ;"              Kevin S. Toppenberg M.D.
        ;"              KST/kle
        ;"              <blank line>
        ;"
        ;"       NoteInfo -- PASS BY REFERENCE.  This is an array to return note into into, as follows:
        ;"              NoteInfo("PATIENT")="Lastname,firstname initial"
        ;"              NoteInfo("DOB")="5/12/05"
        ;"              NoteInfo("AUTHOR")="Toppenberg,Kevin S"
        ;"              NoteInfo("TRANS INITS")="kle"
        ;"              NoteInfo("MEDIC NUMBER")=123456
        ;"              NoteInfo("DATE OF ENCOUNTER")="05/12/05"
        ;"              NoteInfo("LOCATION")="Main_Office"
        ;"      OfficeLoc -- PASS BY REFERENCE -- OPTIONAL
        ;"                     an array storing default locations for authors.  See format in CONVDICT
        ;"                       If not passed, into will be looked for in^TMG(
        ;"                Note: **First looks in file 8926 for def. office
        ;"      DebugMode -- OPTIONAL. If value=1, then verbose info written
        ;"Output: Results are returned in NoteInfo.  OneNote is modified to remove !PAT() and !DATE() line
        ;"Results: 1 if success, 0 if error
        ;"Note: accesses a global var: PriorErrorFound (OK if not defined)
 
        new result set result=1
        Kill NoteInfo
        new index set index=0
        new Line
        new Debug set Debug=$get(DebugMode,0)
 
        new HeaderLine set HeaderLine=$get(OneNote(index))
        ;"kill OneNote(index)
 
        if Debug do
        . write !,"========================================================",!
        . write "Processing the following line: ",!
        . write "--------------------------------------------------------",!
        . write HeaderLine,!
        . write "--------------------------------------------------------",!
        . write "Expecting line to contain '!PAT   [!DATE]",!
        . write "========================================================",!
 
        if (HeaderLine="")!((HeaderLine'["!DATE")&(HeaderLine'["!PAT")) do  goto CONDone
        . set result=0
        . do ShowError^TMGDEBUG(.PriorErrorFound,"Header line not correct.")
 
        if Debug do
        . write "Checking header line for '!PAT(xxx)'"
        if HeaderLine["!PAT(" do
        . if Debug write "...found.",!
        . new s,s1,s2
        . set s=$piece(HeaderLine,"!PAT(",2)
        . set s1=$$Trim^TMGSTUTL(s)
        . set s1=$piece(s,")",1)
        . set s1=$$Trim^TMGSTUTL(s1)
        . if s1'="" do
        . . set NoteInfo("MEDIC NUMBER")=s1
        . . if Debug write "!PAT() --> Patient number found was: ",s1,!
        . else  write "Patient number unexpectedly not found!",!
 
        if HeaderLine["!DATE(" do
        . new s,s1,s2
        . set s=$piece(HeaderLine,"!DATE(",2)
        . set s1=$piece(s,")",1)
        . set s1=$$Trim^TMGSTUTL(s1)
        . if s1'="" do
        . . set NoteInfo("DATE OF ENCOUNTER")=s1
        . . if Debug write "!DATE() --> Date of encounter found was: ",s1,!
        . else  write "Date of encounter unexpectedly not found!",!
 
        set index=index+1
        if $$Trim^TMGSTUTL($get(OneNote(index)))="" set index=index+1 ;"Skip any blank line
        ;"e.g. line-- PATIENT NAME:[TAB]Sarah P. Doe[TAB]DATE:  05/12/2005    <---Date of encounter
        set Line=$get(OneNote(index))
        set Line=$translate(Line,$char(9),"  ")  ;"convert tabs to space
 
        if Debug do
        . write !,"========================================================",!
        . write "Processing the following line: ",!
        . write "--------------------------------------------------------",!
        . write Line,!
        . write "--------------------------------------------------------",!
        . write "Expecting pattern line this: ",!
        . write "[PATIENT NAME: ]Sarah P. Doe  [DATE:05/12/2005] [DOS:5/12/2005] [DOB:1/1/1920]",!
        . write "========================================================",!
 
        if (Line["PATIENT NAME:")!(Line["DATE:")!(Line["DOS:")!(Line["DOB:") do
        . new s,s1,s2
        . s s=""
        . if (Line["PATIENT NAME:") set s=$piece(Line,"PATIENT NAME:",2)
        . else  set s=Line
        . ;"if (Line'["DATE:")&(Line'["DOS:")&(Line'["DOB:") do
        . ;". set result=0
        . ;". do ShowError^TMGDEBUG(.PriorErrorFound,"'DATE' or 'DOS' or 'DOB' not found in note header.")
        . ;". write "-->'",Line,"'",!
        . set s1=""
        . new doneloop set doneloop=0
        . for  do  quit:(doneloop)
        . . if (s["DATE:") set s=$piece(s,"DATE:",1) quit
        . . if (s["DOB:") set s=$piece(s,"DOB:",1) quit
        . . if (s["DOS:") set s=$piece(s,"DOS:",1) quit
        . . set s1=$$Trim^TMGSTUTL(s)
        . . set s1=$$FormatName^TMGMISC(s1)
        . . set doneloop=1
        . if s1'="" set NoteInfo("PATIENT")=s1
        . if Debug write "Patient Name found was: ",s1,!
        . if (Line["DOB:") do     ;"expects date to contain NO spaces... e.g. 1/1/05, not 'Jan 1, 2005'
        . . if Debug write "Looking at ",Line,!
        . . set s1=$piece(Line,"DOB:",2)
        . . set s1=$$Trim^TMGSTUTL(s1)
        . . set s1=$piece(s1," ",1)
        . . set NoteInfo("DOB")=s1
        . . if Debug write "Patient DOB found was: ",s1,!
        . if (Line["DOS:") do     ;"expects date to contain NO spaces... e.g. 1/1/05, not 'Jan 1, 2005'
        . . if Debug write "Looking at ",Line,!
        . . set s1=$piece(Line,"DOS:",2)
        . . set s1=$$Trim^TMGSTUTL(s1)
        . . set s1=$piece(s1," ",1)
        . . set NoteInfo("DATE OF ENCOUNTER")=s1
        . . if Debug write "Date of Encounter: ",s1,!
        . if (Line["DATE:") do     ;"expects date to contain NO spaces... e.g. 1/1/05, not 'Jan 1, 2005'
        . . if Debug write "Looking at ",Line,!
        . . set s1=$piece(Line,"DATE:",2)
        . . set s1=$$Trim^TMGSTUTL(s1)
        . . set s1=$piece(s1," ",1)
        . . set NoteInfo("DATE OF ENCOUNTER")=s1
        . . if Debug write "Date of Encounter: ",s1,!
        else  do  goto CONDone
        . set result=0
        . do ShowError^TMGDEBUG(.PriorErrorFound,"'PATIENT NAME:' or 'DATE:' or 'DOS:' or 'DOB:' not found.")
 
        set index=index+1
        if $$Trim^TMGSTUTL($get(OneNote(index)))="" set index=index+1 ;"Skip any blank line
        ;"e.g. line -- CHART#:  123456[TAB]DOB:  05/06/1995
        set Line=$get(OneNote(index))
        set Line=$translate(Line,$char(9),"  ")  ;"convert tabs to space
 
        if Debug do
        . write !,"========================================================",!
        . write "Processing the following line: ",!
        . write "--------------------------------------------------------",!
        . write Line,!
        . write "--------------------------------------------------------",!
        . write "Expecting pattern line this: ",!
        . write "     CHART#:  123456  DOB:  05/06/1995",!
        . write "(Note: This line is optional)",!
        . write "========================================================",!
 
        if $get(NoteInfo("MEDIC NUMBER"))="" do
        . if Line["CHART#:" do
        . . new s,s1,s2
        . . set s=$piece(Line,"CHART#:",2)
        . . set s1=$piece(s,"DOB:",1)
        . . set NoteInfo("MEDIC NUMBER")=$$Trim^TMGSTUTL(s1)
        . else  do
        . . set result=0
        . . do ShowError^TMGDEBUG(.PriorErrorFound,"'CHART#:' not found in line.")
        . . write "-->'",Line,"'",!
 
        if $get(NoteInfo("DOB"))="" do  if result=0 goto CONDone
        . if Line["DOB:" do
        . . new s,s1,s2
        . . set s1=$piece(Line,"DOB:",2)
        . . set s1=$$Trim^TMGSTUTL(s1)
        . . if s1'="" set NoteInfo("DOB")=s1
        . else  do
        . . set result=0
        . . do ShowError^TMGDEBUG(.PriorErrorFound,"'DOB:' not found in line.")
        . . write "-->'",Line,"'",!
 
        if $get(NoteInfo("DATE OF ENCOUNTER"))="" do  goto CONDone
        . set result=0
        . do ShowError^TMGDEBUG(.PriorErrorFound,"Done with header, but no Date of Encounter found.")
 
        ;"Main header processing now done.  Now scan for a header for subsequent pages, and delete.
        if Debug write !!,"Now scanning for unneeded header info in middle of note.",!
        set index=index+1
        for  do  quit:(index="")
        . set Line=$get(OneNote(index))
        . if Debug write "."
        . ;"if Debug write ">>",Line,!
        . if (Line["PATIENT NAME:")&(Line["DATE:") do
        . . if Debug do
        . . . write !,"Found one...",!
        . . . write "-->",Line,!
        . . kill OneNote(index)
        . . if $$Trim^TMGSTUTL($get(OneNote(index-1)))="" kill OneNote(index-1)
        . . set index=index+1
        . . set Line=$get(OneNote(index))
        . . if (Line["CHART#")&(Line["DOB") kill OneNote(index)
        . . if Debug write "And-->",Line,!
        . . set index=index+1
        . . set Line=$$Trim^TMGSTUTL($$UP^XLFSTR($get(OneNote(index))))
        . . if ($piece(Line," ",1)="PAGE")&($piece(Line," ",3)="") do
        . . . if Debug write "And-->",Line,!
        . . . kill OneNote(index)
        . set index=$order(OneNote(index))
 
        ;"Now work backwards from end of note to get transcriptionist name and author name
        if Debug write !!,"Now trimming blank lines from the end of the note (scanning backwards).",!
        ;"Trim blank lines from end of note.
        set index=$order(OneNote(""),-1)
        for  do  quit:(Line'="")!(+index<4)
        . set Line=$get(OneNote(index))
        . set Line=$translate(Line,$char(9),"  ")  ;"convert tabs to space
        . set Line=$$Trim^TMGSTUTL(Line)
        . ;"if Debug write ">> '",Line,"'",!
        . if Debug write "."
        . if Line="" kill OneNote(index)
        . set index=$order(OneNote(index),-1)
 
        if Debug write !!,"Now looking for Transcriptionist initials. (scanning backwards)",!
        new InitsFound set InitsFound=0
        ;"Get transcriptionist initials
        set index=$order(OneNote(""),-1)
        for  do  quit:(InitsFound)!(index="")!(+index<4)
        . set Line=$get(OneNote(index))
        . set Line=$translate(Line,$char(9),"  ")  ;"convert tabs to space
        . set Line=$$Trim^TMGSTUTL(Line)
        . ;"if Debug write ">",Line,!
        . if Debug write "."
        . if (Line["/")&($piece(Line," ",2)="") do  quit
        . . set InitsFound=1
        . . if Debug write "...found a line (#",index,") with '/' -->",Line,!
        . set index=$order(OneNote(index),-1)
 
        if Debug do
        . write !,"========================================================",!
        . write "Now looking for transcriptionist's name",!
        . write "Processing the following line: ",!
        . write "--------------------------------------------------------",!
        . write Line,!
        . write "--------------------------------------------------------",!
        . write "Expecting pattern: 'Author's inits/tran's inits'"
        . write " (with no other text on line.)",!
        . write "  e.g. KST/abc",!
        . write "========================================================",!
        if (Line[" ")&(Debug) do
        . write "? trim not working?",!
        . write "OneNote(index)='",OneNote(index),"'",!
        . write "After trim, resulting Line='",Line,"'",!
        . write "Will try another trim.",!
        . set Line=$$Trim^TMGSTUTL(Line)
        . write "Now Line='",Line,"'",!
        if (Line["/")&($piece(Line," ",2)="") do
        . new inits
        . set inits=$piece(Line,"/",2)
        . set NoteInfo("TRANS INITS")=inits
        . if Debug write "...found a line with '/': ",Line,!
        . ;"now turn initials into full name via database lookup
        . set DIC=200,DIC(0)="M"
        . set X=inits
        . do ^DIC
        . if Y'>0 do  quit
        . . set result=0
        . . do ShowError^TMGDEBUG(.PriorErrorFound,"Unable to find '"_inits_"' in database.")
        . set NoteInfo("TRANSCRIPTIONIST")=$piece(Y,"^",2)
        else  do  goto CONDone
        . set result=0,PriorErrorFound=0
        . do ShowError^TMGDEBUG(.PriorErrorFound,"Transcriptionists initials not found")
 
        ;"Get author
        for  do  quit:(Line'="")
        . set index=$order(OneNote(index),-1)
        . set Line=$$Trim^TMGSTUTL($get(OneNote(index)))
        if Debug do
        . write !,"========================================================",!
        . write "Now looking for author's name",!
        . write "Processing the following line: ",!
        . write "--------------------------------------------------------",!
        . write Line,!
        . write "--------------------------------------------------------",!
        . write "Expecting pattern: 'Doctor's name'",!
        . write "========================================================",!
        if Line'="" do
        . set Line=$$FormatName^TMGMISC(Line,1)
        . If Line="TOPPENBERG,M DEE" set Line="TOPPENBERG,MARCIA D"
        . if Line="SVENDSEN,CLAES V" set Line="SVENDSEN,CLAES U"
        . set NoteInfo("AUTHOR")=Line
 
        if $get(NoteInfo("DOB"))="" do  goto CONDone
        . set result=0
        . do ShowError^TMGDEBUG(.PriorErrorFound,"Patient DOB not found.")
 
        ;"Ensure provider name is correct
        if Debug do
        . write "Looking up Author in VistA database to ensure it's correct.",!
        set DIC=200
        set DIC(0)=""
        set X=$get(NoteInfo("AUTHOR"))
        do ^DIC
        if Y'>0 do  goto CONDone
        . set result=0
        . do ShowError^TMGDEBUG(.PriorErrorFound,"Provider name in note ('"_$get(NoteInfo("AUTHOR"))_"') incorrect.  Aborting")
        ;"Now get office location based on provider
        if Debug write "Found: ",Y,!
        new Office set Office=""
        new AuthDUZ
        set AuthDUZ=+Y
        new i set i=$order(^TIU(8926,"B",AuthDUZ,""))  ;"file 8926: def. office
        if i'="" do
        . new j set j=$get(TIU(8926,i,0))
        . if j="" quit
        . new IENOffice set IENOffice=$piece(j,"^",2)
        . if IENOffice="" quit
        . set Office=$piece($get(^SC(IENOffice,0)),"^",1)
        if Office="" set Office=$get(OfficeLoc(AuthDUZ))
        if Office="" set Office=$get(^TMG("MEDIC CONV","Office",AuthDUZ))
        if Office="" do
        . set DIC=44  ;"HOSPITAL LOCATION
        . set DIC(0)="AEQ"
        . set X=""
        . set DIC("A")="Which office does "_$piece(Y,"^",2)_" work in (Type ? for list)?: "
        . do ^DIC
        . write !
        . if Y>0 do
        . . set Office=$piece(Y,"^",2)
        . . set OfficeLoc(AuthDUZ)=Office
        . . set ^TMG("MEDIC CONV","Office",AuthDUZ)=Office
        if Office="" do  goto CONDone
        . set result=0
        . do ShowError^TMGDEBUG(.PriorErrorFound,"Can't determine office location.  Aborting")
        set NoteInfo("LOCATION")=Office
 
CONDone
        quit result
 
 
WriteOneNote(OneNote,NoteInfo,ResultFile)
        ;"Purpose: To take One note, and append to Result File, with appropriate header, based on NoteInfo
        ;"Input: OneNote -- PASS BY REFERENCE-- the text array to append to resulting file
        ;"        NoteInfo -- array with note info.  See format in ConvertOneNote
        ;"        ResultFile -- PASS BY REFERENCE  this is the array built to the cumulative output
        ;"
        ;"      Here is the needed format for vista upload. (at our site)
        ;"      [NewDict]:              NOTE
        ;"      Patient Name:         Doe,John A
        ;"      DOB:                       08/01/0931
        ;"      Date of Encounter:  06/08/2005
        ;"      Provider:                  Welby,Marcus
        ;"      Visit Location:         Laughlin_Office
        ;"      Transcriptionist:      Fingers,Speedy
        ;"      [TEXT]
        ;"      (Here is the text of the note...
        ;"      [END]
 
        kill OneNote(0)  ;"the !PAT() !DATE etc. line
 
        set OneNote(.1)="[NewDict]:              NOTE"
        set OneNote(.2)="Patient Name:        "_$get(NoteInfo("PATIENT"))
        set OneNote(.3)="DOB:                    "_$get(NoteInfo("DOB"))
        set OneNote(.4)="Date of Encounter:  "_$get(NoteInfo("DATE OF ENCOUNTER"))
        set OneNote(.5)="Provider:               "_$get(NoteInfo("AUTHOR"))
        set OneNote(.6)="Visit Location:       "_$get(NoteInfo("LOCATION"))
        set OneNote(.7)="Transcriptionist:     "_$get(NoteInfo("TRANSCRIPTIONIST"))
        set OneNote(.8)="[TEXT]"
 
        new s
        set s=$get(NoteInfo("PATIENT"))
        set s=s_" on "_$get(NoteInfo("DATE OF ENCOUNTER"))_"; "
        set s=s_$get(NoteInfo("AUTHOR"))
        set s=s_" at "_$get(NoteInfo("LOCATION"))
        write "Done: ",s,!
 
        new index,j
        set index=$order(OneNote(""),-1)
        set index=index+1
        set OneNote(index)="[END]"
        set OneNote(index+1)=" "
 
        ;"Now append OneNote to ResultFile
        set j=$order(ResultFile(""),-1)+1
        set index=$order(OneNote(""))
        for  do  quit:(index="")
        . set ResultFile(j)=$get(OneNote(index))
        . set j=j+1
        . set index=$order(OneNote(index))
 
        quit
 
 
TELNET
        ;"Purpose: to provide ability to telnet to medic server (AIX)
 
        new HookCmd
        set HookCmd="telnet medic"
        zsystem HookCmd
 
        write !,!,"Done.  Returning to VistA",!
        new temp read "Press Enter to Continue...",temp:$get(DTIME,3600),!
 
        quit
