!***********************************************************************
!  PDFPlotSet / 2002-01-19 / CAD Serviceburo                           *
!                                                                      *
!  This is an ADT program to create PDF file with multiple drawings.   *
!  This program reads database Pdfpicts, converts drawings listed in   *
!  it to PostScript and then uses Ghostscript (tm) to convert          *
!  PostScript to PDF.                                                  *
!***********************************************************************

! debug ./pdfplotset.dbg

charset = latin1

language= get($LANGUAGE)

RemoveOld = 1
UseDate   = 1

P1 = 1
P2 = 2

if (language==0) then
  PdfDelFailed$  = "PDF-tiedosto on mahdollisesti auki, ei voi korvata uudella.\\n\\n Ole hyvä ja sulje tiedosto:\\n"
  Retry$ = "Yritä uudelleen?"
else
  PdfDelFailed$  = "PDF file is probably open, can't be replaced with the new one.\\n\\n Please close the file:\\n"
  Retry$ = "Retry?"
endif

!***********************************************************************
! Define destination folder

ProjPath$ = get($PROJPATH)
PdfDir$ = ProjPath$&"Pdf"
dircreate PdfDir$
PdfDir$ = PdfDir$&"/"
Drive$ = get($DRIVE)
ColorPrint = 0 ; ! Print PDF in color or B/W
if UseDate then
  Date$ = get($DATE)
  Date$ = "-"&Date$[7,10]&"-"&Date$[4,5]&"-"&Date$[1,2]
else
  Date$ = ""
endif

!***********************************************************************
! Output files and path definitions

ProjectDir$ = get($PROJPATH)
PdfParProgPath$ = get($PDFPROGPATH)          ;! Path for pdf adt programs

PdfProgram = 1                               ;! Needed in Ghostscript
PdfProgramDrive$ = Drive$[1,1]&":"
PdfProgramPath$ = get($PROGPATH)             ;! Ghostscript folder

HomeDir$ = get($DIR_HOME)                    ;! Home folder
Drive$ = HomeDir$[1,2]                       ;! Drive of home folder

Ps2PdfBat$ = PdfParProgPath$&"PDFps2pdf.bat" ;! ps -> pdf bat file
TmpPlotFile$ = HomeDir$&"plot.ps"            ;! Temporary ps file
GsLog$ = "gs.log"

! Test unit system
Metric = 0
Test = dwg_to_mm(1.0)
if Test = 1.0 then Metric = 1

! Drawing sheets
if Metric then
  Sheet0 = 7
  SheetWidth(1) =   210; SheetHeight(1) =    48; ! A4/6
  SheetWidth(2) =   210; SheetHeight(2) =    74; ! A4/4
  SheetWidth(3) =   297; SheetHeight(3) =   210; ! A4
  SheetWidth(4) = 2*210; SheetHeight(4) =   297; ! A3
  SheetWidth(5) = 2*297; SheetHeight(5) = 2*210; ! A2
  SheetWidth(6) = 4*210; SheetHeight(6) = 2*297; ! A1
  SheetWidth(7) = 4*297; SheetHeight(7) = 4*210; ! A0
  else
  Sheet0 = 5
  SheetWidth(1) = 11; SheetHeight(1) = 8.5; ! A
  SheetWidth(2) = 17; SheetHeight(2) = 11;  ! B
  SheetWidth(3) = 22; SheetHeight(3) = 17;  ! C
  SheetWidth(4) = 36; SheetHeight(4) = 24;  ! D
  SheetWidth(5) = 42; SheetHeight(5) = 30;  ! E
endif
!***********************************************************************
! Open Drawing List

DbId   = 1
DbList = 1
IdIn   = get($DATABASE_ID)
dbopen(DbId) "ALREADY_OPEN",IdIn
if (dbvalid(DbId) = 0) then
  prompt$ = " Unable to open PDF drawing list.  Please Contact Administrator."
  message prompt$
  exit
endif

TestLoop=0
if (TestLoop) then
  dbfind(DbList) DbId,0
  Rows = dblistnum(DbList)
  i=1
  loop Rows
    RowId = dblist(DbList,i)
    Test$ = dbgetf(DbId,RowId,"PICNAME")
    Test$ = dbgetf(DbId,RowId,"PICFILE")
    i=i+1
  endloop
  dblclose(DbList)
endif

!***********************************************************************
! Add 3D panel stacking fields
dbalter "",DbId,0,"", STACK_ID    A 32 IND \
                      STACK_ROW   B  4 IND \
                      STACK_COL   B  4 IND

!***********************************************************************
set PDF_PRINT "1"

JobName$ = get($SETNAME)
JobHeader$ = get($ACTPROJNAME)

! Remove old Pdf files
if RemoveOld and UseDate then
  RemoveFiles$= "./removeoldpdf.bat"
  open(1) RemoveFiles$ 
  Line$ = "del "&PdfDir$&JobName$&"-*"
  Line$ = convchars(Line$,"/","\\")
  write(1) Line$
  close(1)
  ok= system(RemoveFiles$)
  fileremove RemoveFiles$

!If in Master Set solving
MSOn = 0
MSOn$ = get($MASTERSETON)
MSOn = MSOn$
if (MSOn > 0) then
  MSGroup$ = get($GROUPNAME)
endif

! Output files
if (MSOn > 0) then
  FileName$ = HomeDir$&JobName$&"_"&MSGroup$
else
  FileName$ = HomeDir$&JobName$
endif

!***********************************************************************
! "SE" Panel Filters

PDFPictsId     = 10
PDFPictsLid    = 11
PDFPictsDBase$ = ProjPath$&"d_pdfpicts"
dbopen(PDFPictsId) PDFPictsDBase$,0
Where$ = "where SET = """&JobName$&""" and PICNAME = *[* and PICNAME = *]*"
dbfind(PDFPictsLid) PDFPictsId,1,Where$
NumOfFilters   = dblistnum(PDFPictsLid)
if (NumOfFilters>0) then
  FilterNum = 0
  loop (NumOfFilters)
    FilterNum = FilterNum + 1
    FilterListRid               = dblist(PDFPictsLid,FilterNum)
    FilterListName$(FilterNum)  = dbgetf(PDFPictsId,FilterListRid,"PICNAME")
    FilterListOrder(FilterNum)  = dbgetf(PDFPictsId,FilterListRid,"ORDER")
    FilterListLGrp$(FilterNum)  = dbgetf(PDFPictsId,FilterListRid,"LEVELGROUP")

    ! Convert Finnish to English for FILEREG
    if cmp(FilterListName$(FilterNum),"[Palkkirakenne]") then FilterListName$(FilterNum) = "[BeamStructure]"
    if cmp(FilterListName$(FilterNum),"[Elementtikokoonpano]") then FilterListName$(FilterNum) = "[PanelAssembly]"
    if cmp(FilterListName$(FilterNum),"[Seinäelementti]") then FilterListName$(FilterNum) = "[WallPanel]"
    if cmp(FilterListName$(FilterNum),"[Lattiaelementti]") then FilterListName$(FilterNum) = "[FloorPanel]"
    if cmp(FilterListName$(FilterNum),"[Yläpohjaelementti]") then FilterListName$(FilterNum) = "[CeilingPanel]"
    if cmp(FilterListName$(FilterNum),"[Kattoelementti]") then FilterListName$(FilterNum) = "[RoofPanel]"
    if cmp(FilterListName$(FilterNum),"[Ristikko]") then FilterListName$(FilterNum) = "[Truss]"
    if cmp(FilterListName$(FilterNum),"[Valitse palkkirakenne]") then FilterListName$(FilterNum) = "[SelectBeamStructure]"
    if cmp(FilterListName$(FilterNum),"[Valitse elementtikokoonpano]") then FilterListName$(FilterNum) = "[SelectPanelAssembly]"
    if cmp(FilterListName$(FilterNum),"[Valitse seinäelementti]") then FilterListName$(FilterNum) = "[SelectWallPanel]"
    if cmp(FilterListName$(FilterNum),"[Valitse lattiaelementti]") then FilterListName$(FilterNum) = "[SelectFloorPanel]"
    if cmp(FilterListName$(FilterNum),"[Valitse yläpohjaelementti") then FilterListName$(FilterNum) = "[SelectCeilingPanel]"
    if cmp(FilterListName$(FilterNum),"[Valitse kattoelementti]") then FilterListName$(FilterNum) = "[SelectRoofPanel]"
    if cmp(FilterListName$(FilterNum),"[Valitse ristikko]") then FilterListName$(FilterNum) = "[SelectTruss]"

    x1 = findstr(FilterListName$(FilterNum),"[")
    x2 = findstr(FilterListName$(FilterNum),"]")
    FilterListName$(FilterNum) = FilterListName$(FilterNum)[x1+1,x2-1]
    if (cmp(FilterListName$(FilterNum)[1,6],"Select")) then
      FilterListName$(FilterNum)  = FilterListName$(FilterNum)[7,0]
      FilterListSelect(FilterNum) = 1
    else
      FilterListSelect(FilterNum) = 0
    endif
  endloop
  dblclose(PDFPictsLid)
  dbclose(PDFPictsId)

  Where$ = "where PICFILE = se/* or PICFILE = SE/*"
  dbfind(DbList) DbId,1,Where$
  NumOfPanels = dblistnum(DbList)

  FileRegId  = 101 
  FileRegLid = 101
  dbopen(FileRegId) "d_FILEREG",0
  PanelListRow = 1
  loop (NumOfPanels)
    PanelListRid   = dblist(DbList,PanelListRow)
    PanelListFile$ = dbgetf(DbId,PanelListRid,"PICFILE")
    x1 = findstr(PanelListFile$,"@")
    if (x1>1) then
      x2 = findstr(PanelListFile$,".vxp")
      PanelListFile$ = PanelListFile$[1,x1-1]&".vxp"
    endif
    Where$ = "where FILE = "&PanelListFile$
    dbfind(FileRegLid) FileRegId,1,Where$
    Done=0
    if (dblistnum(FileRegLid) > 0) then
      FileRegRid   = dblist(FileRegLid,1)
      FileRegFile$ = dbgetf(FileRegId,FileRegRid,"FILE")
      FileRegData$ = dbgetf(FileRegId,FileRegRid,"DATA")
      Manuf = findstr(FileRegData$, "STACK")
      if (Manuf > 0) then
        Manuf$ = FileRegData$[Manuf+6]
        More = findstr(Manuf$, "|")
        if (More > 0) then
          Manuf$ = Manuf$[1,More-1]
        endif
        Comma = findstr(Manuf$, ";")
        StackID$ = Manuf$[1,Comma-1]
        Manuf$ = Manuf$[Comma+1,0]
        Comma = findstr(Manuf$, ";")
        Row$ = Manuf$[1,Comma-1]
        Col$ = Manuf$[Comma+1,0]
      endif
      Type$ = dbgetf(FileRegId,FileRegRid,"TYPE")
      FilterNum = 1
      loop (NumOfFilters)
        if (cmp(Type$,FilterListName$(FilterNum))) then
          if cmp(Type$,"WallPanel") && language == 0 then Type$ = "Seinäelementti"
          if cmp(Type$,"FloorPanel") && language == 0 then Type$ = "Lattiaelementti"
          if cmp(Type$,"RoofPanel") && language == 0 then Type$ = "Kattoelementti"
          if cmp(Type$,"Truss") && language == 0 then Type$ = "Ristikko"
          x1 = findstr(FileRegFile$,"SE_")
          if (x1>1) then
            x2 = findstr(FileRegFile$,".vxp")
            PanelLabel$ = FileRegFile$[x1+3,x2-1]
            PicName$ = Type$&" "&PanelLabel$
          else
            PicName$ = Type$&" "&PanelLabel$
          endif
          dbputf(DbId) PanelListRid,"PICNAME",    PicName$
          dbputf(DbId) PanelListRid,"ORDER",      FilterListOrder(FilterNum)$
          dbputf(DbId) PanelListRid,"LEVELGROUP", FilterListLGrp$(FilterNum)$
          if (Manuf > 0) then
            dbputf(DbId) PanelListRid,"STACK_ID",   StackID$
            dbputf(DbId) PanelListRid,"STACK_ROW",  Row$
            dbputf(DbId) PanelListRid,"STACK_COL",  Col$
          endif
          Done=1
        endif
        exitif (Done)
        FilterNum = FilterNum + 1
      endloop
    endif   
    if (Done=0) then
      dbdelrow(DbId) PanelListRid
    endif
    dblclose(FileRegLid)
    PanelListRow = PanelListRow+1
  endloop
  dblclose(DbList)
  dbclose(FileRegId)
else
  dblclose(PDFPictsLid)
  dbclose(PDFPictsId)
endif

!***********************************************************************
! Select SE panels

Lid_selected = 12
FilterNum = 1
loop (NumOfFilters)
  if (FilterListSelect(FilterNum)) then
    SelFilter$ = FilterListName$(FilterNum)
    if language == 0 then
      if cmp(FilterListName$(FilterNum),"WallPanel") then SelFilter$ = "Seinäelementti"
      if cmp(FilterListName$(FilterNum),"FloorPanel") then SelFilter$ = "Lattiaelementti"
      if cmp(FilterListName$(FilterNum),"RoofPanel") then SelFilter$ = "Kattoelementti"
      if cmp(FilterListName$(FilterNum),"Truss") then SelFilter$ = "Ristikko"    
    endif
    Where$ = "where PICNAME = """&SelFilter$&"*"""
    dbfind(DbList) DbId,1, Where$
    NumofTotPanels = dblistnum(DbList)
    if language == 0 then
      dbselect(Lid_selected) DbList, "selpdfpanels", 0, 0, 0, "Valitse elementit"
    else
      dbselect(Lid_selected) DbList, "selpdfpanels", 0, 0, 0, "Select Panels"
    endif
    NumofSelPanels = dblistnum(Lid_selected)
    if (NumofSelPanels < NumofTotPanels) then
      i = 1
      loop NumofTotPanels
        TestRowId = dblist(DbList,i)
        DeleteRow = 1
        n = 1
        loop NumofSelPanels
          SelRowId = dblist(Lid_selected,n)
          if (TestRowId = SelRowId) then DeleteRow = 0
          exitif (DeleteRow=0)
          n=n+1
        endloop
        if (DeleteRow) then
          dbdelrow(DbId) TestRowId
        endif
        i=i+1
      endloop
    endif
    dblclose(Lid_selected)
    dblclose(DbList)
  endif
  FilterNum = FilterNum + 1
endloop

!***********************************************************************
! Test for user selected classic wall panels

dbfind(DbList) DbId,1,"where PICFILE = *select_wall_panels*"
SelectPanels = dblistnum(DbList)
dblclose(DbList)

!***********************************************************************
! Delete *wall_panels* rows

dbfind(DbList) DbId,1,"where PICFILE = *wall_panels*"
WPKeyword = dblistnum(DbList)
i=1
loop WPKeyword
  RowId = dblist(DbList,i)
  dbdelrow(DbId) RowId
  i=i+1
endloop
dblclose(DbList)

!***********************************************************************
! Refresh the list

dbfind(DbList) DbId,0,""
RowId = dblist(DbList,1)

!***********************************************************************
! check for existence of ORDER, ACT, -fields

OrderTest = dbfieldexist("ORDER",DbId)
if (OrderTest) then
  OrderTest = dbgetf(DbId,RowId,"ORDER")
endif

SelectActive = dbfieldexist("ACT",DbId)

!***********************************************************************
! for Ordered print sets

if (OrderTest) then
  dblsort(DbList) "ORDER"

! check for selected drawings
  NumPicts = dblistnum(DbList)
  i=1
  loop NumPicts
    CheckAct = 0
    WPPict   = 0
    RowId    = dblist(DbList,i)
    Set$     = dbgetf(DbId,RowId,"SET")
    Order    = dbgetf(DbId,RowId,"ORDER")
    PicName$ = dbgetf(DbId,RowId,"PICNAME")
    PicFile$ = dbgetf(DbId,RowId,"PICFILE")
  
    if findstr(PicFile$[1,6],"PANEL.") then WPPict=1

    if (SelectActive) then
      CheckAct=1
      if ((WPPict) and (SelectPanels)) then CheckAct=0
      if (CheckAct) then
        Active$ = dbgetf(DbId,RowId,"ACT")
        if (!cmp(Active$,"YES") and !cmp(Active$,"1")) then
          dbdelrow(DbId) RowId
        endif
      endif
    endif

    i=i+1
  endloop

  dblclose(DbList)
  dbfind(DbList) DbId,0,""

! Check for printing of Like-Panels
  if (!PrintLikePanels) then
    Picts0 = dblistnum(DbList)
    I=0
    loop Picts0
      I = I+1 
      RowId    = dblist(DbList,I)
      PicFile$ = dbgetf(DbId,RowId,"PICFILE")
      PicName$ = dbgetf(DbId,RowId,"PICNAME")
      PrefPic$ = PicFile$[1,6]
      if cmp(PrefPic$,"PANEL.") then
        WPnl=2
        dbfind(WPnl) DbId,1,"where PICFILE = """&PicFile$&""""
        WPanel = dblistnum(WPnl)
        if WPanel>1 then dbdelrow(DbId)RowId
        dblclose(WPnl)
      endif
    endloop
  endif
endif


FileName$ = HomeDir$&JobName$&Date$
ControlPF$ = ".ctrl"            ;! PDF control file
MarkPF$ = ".mark"               ;! PDF pdfmark file
DrwgPF$ = ".drwg"               ;! All drawings in one PS -file
PdfPF$ = ".pdf"                 ;! PDF -file
PsPF$ = ".ps"                   ;! PS -file

! Open .ctrl file and plot drawings
open(9) FileName$&ControlPF$
write(9) "0 0 """&JobHeader$&""""

SetName$ = get($SETNAME)
if dbvalid(DbId) = 0 then exit

dblclose(DbList)

Where$ = "where SET = "&SetName$
dbfind(DbList) DbId, 1, Where$
if (OrderTest) then
  if findstr(JobName$,"ManufOrder")=0 then
    dblsort(DbList) "ORDER PICNAME"
  else
    dblsort(DbList) "ORDER STACK_ID STACK_ROW STACK_COL"
  endif
endif

! instellen om in kleur af te drukken
if findstr(SetName$,"COL") then
  ColorPrint= 1
endif
if findstr(SetName$,"TRUE") then
  ColorPrint= 2
endif

!***********************************************************************
! Checking number or drawings to print. Quit if empty book.

I = 0
FirstPic = 1
Picts0 = dblistnum(DbList)
if Picts0 <= 0 then
  dblclose(DbList)
  dbclose(DbId)
  close(9)
  fileremove GSControl$
  if language == 0 then
    show_error "PDF-kirja on tyhjä. Tiedostoa ei luotu!"
  else
    show_error "Empty PDF book. File not created!" 
  endif
  exit
endif

!*************************************************************************************************************
! Create pseudo plotter
!
I = 1
RowId= dblist(DbList,I)
! All rows should have same LineWidthFile.
LineWidthFile$ =  dbgetf(DbId,RowId,"LINEWIDTH_FILE")

if empty_string(LineWidthFile$) then
  PlotterDef$ = "plotter= PDF-TEMP 7 5 ""./plot.ps"" """" 6 1 11 5.5 31 """" 32 ""PDF-SHEET"" 33 ""PDF"""
else
  if cmp(LineWidthFile$,"TRUE") then
    PlotterDef$ = "plotter= PDF-TEMP 7 5 ""./plot.ps"" """" 6 -1 11 5.5 31 """" 32 ""PDF-SHEET"" 33 """""
  else
    if cmp(LineWidthFile$,"VECTORS") then
      PlotterDef$ = "plotter= PDF-TEMP 7 5 ""./plot.ps"" """" 1 1 6 1 11 5.5 31 """" 32 ""PDF-SHEET"" 33 ""PDF"""
    else
      PlotterDef$ = "plotter= PDF-TEMP 7 5 ""./plot.ps"" """" 6 1 11 5.5 31 """" 32 ""PDF-SHEET"" 33 """&LineWidthFile$&""""
    endif
  endif
endif
!*************************************************************************************************************

set PLOTTER_DEF PlotterDef$
set PLOTTER_MODE "1"
function PLOTTER_SET

! Create pseudo sheet
set SHEET_MODE "1"
function SHEET_SET

I = 0
PdfMode$=""
FirstPic = 1
Picts0 = dblistnum(DbList)
if Picts0 <= 0 then exit
loop Picts0
  I = I+1 
  RowId= dblist(DbList,I)
  PicFile$ = dbgetf(DbId,RowId,"PICFILE")
  PicName$ = dbgetf(DbId,RowId,"PICNAME")
  LevelsB$=  dbgetf(DbId,RowId,"LEVELGROUP")
  Sheet$  =  dbgetf(DbId,RowId,"SHEET")
  SheetSize$ =  dbgetf(DbId,RowId,"SHEETSIZE")
  Force$ =  dbgetf(DbId,RowId,"FORCE")
  ! All rows should have same PdfMode.
  PdfMode$ =  dbgetf(DbId,RowId,"PDFMODE")
  if findstr(PicFile$,"./")=1 then
    DrawingFile$ =  HomeDir$&PicFile$[2,0]
  else
    DrawingFile$ =  ProjectDir$&PicFile$
    PosXFile     =  findstr(PicFile$,"PANEL")
    if PosXFile>0 then
      FilePart1$   = PicFile$[1,PosXFile+4]
      FilePart2$   = PicFile$[PosXFile+5,0]
      DrawingFileM$= ProjectDir$&FilePart1$&"X"&FilePart2$
      if !file_exists(DrawingFileM$) then
        DrawingFileM$ = DrawingFile$
      endif
      Wallpanel    = 2 
    else
      DrawingFileM$= ""
      Wallpanel    = 1
    endif      
  endif
  
  ! Voor wanden moet de lus 2x doorlopen worden, 1e voor uitzicht buiten, 2e voor uitzicht binnen
  Lus=0
  loop Wallpanel
    Levels$= LevelsB$
    ! Juiste tekening instellen
    Lus=Lus+1
    if Lus=1 then
      DrawingFile$=DrawingFile$
    else
      DrawingFile$=DrawingFileM$
    endif
    ! Aantal lagengroepen instellen (Inside afkoppelen van rest)
    Li=0
    pos=findstr(Levels$,"|")
    loop
      if pos=0 then
        Levelt$ = Levels$
      else
        Levelt$ = Levels$[1,pos-1]
      endif
      if Lus=1 && findstr(Levelt$,"Inside")=0 then
        Li= Li+1
        Levels$(Li) = Levelt$
      endif
      if Lus=2 && findstr(Levelt$,"Inside")>0 then
        Li= Li+1
        Levels$(Li) = Levelt$
      endif
      exitif pos=0
      Levels$ = Levels$[pos+1,0]
      pos=findstr(Levels$,"|")
    endloop
    
    Lin=0; ! Eerste Levelgroep instellen om af te drukken
    ! Tekeningen openen
    if file_exists(DrawingFile$) then
      Ok1 = dwgopen("PICTURE",DrawingFile$, 10,10,35,100)
      if Ok1 then
        Ok2=dwgactivate("PICTURE")
        dwgsetlimits 0.5, 0.5, 0.5, 0.5
        ok=dwgstore(DrawingFile$,0)
        
        loop Li
          Lin=Lin+1
            
          ! Controleer of de kritische laag is gebruikt in wandpanelen
          if Wallpanel=2 then
            PrintOK= 1
            if cmp(Levels$(Lin),"Wall-Inside") then
              Laag=157
              PrintOK= 0
            endif
            if cmp(Levels$(Lin),"Wall-Outside") then
              Laag=156
              PrintOK= 0
            endif
            if cmp(Levels$(Lin),"Wall-Inside-Finish") then
              Laag=155
              PrintOK= 0
            endif
            ! Zoeken naar de plaat in de laag
            if !PrintOK then
              find_line_param(1) level=Laag
              if line_found(1) then
                PrintOK= 1
              endif
            endif
          else
            PrintOK= 1
          endif          
            
          if PrintOK then
            ! Check if there is a printwindow in the drawing
            Aant=0; Nr=0
            find_macro_param(1) "",0,105
            if macro_found(1) then
              First_found= macro_found(1)
              Nr=0
              loop
                ! Punten van macro opvragen (linksonder + rechtsboven)
                Nr=Nr+1
                get_macro_point(P1) M1,"XMINYMIN"
                Xmin(Nr)= vec_get_x(P1) - 0.5
                Ymin(Nr)= vec_get_y(P1) - 0.5
                get_macro_point(P2) M1,"XMAXYMAX"
                Xmax(Nr)= vec_get_x(P2) + 0.5
                Ymax(Nr)= vec_get_y(P2) + 0.5 
                find_macro_param(1) "",0,105
                exitif (macro_found(1) = First_found)
                exitif (macro_found(1) = 0)
              endloop
              ! Array sorteren, grootste Y-waarde Ymax, kleinste X-waarde Xmin
              Aant=Nr
              Nr=1
              if Aant>1 then
                loop
                  found=0
                  loop Aant-1
                    if (Ymax(Nr+1)>Ymax(Nr)) || ((Ymax(Nr+1)=Ymax(Nr))&&(Xmin(Nr+1)<Xmin(Nr))) then
                      SWAP       = Xmin(Nr)
                      Xmin(Nr)   = Xmin(Nr+1)
                      Xmin(Nr+1) = SWAP
                      SWAP       = Ymin(Nr)
                      Ymin(Nr)   = Ymin(Nr+1)
                      Ymin(Nr+1) = SWAP
                      SWAP       = Xmax(Nr)
                      Xmax(Nr)   = Xmax(Nr+1)
                      Xmax(Nr+1) = SWAP
                      SWAP       = Ymax(Nr)
                      Ymax(Nr)   = Ymax(Nr+1)
                      Ymax(Nr+1) = SWAP
                      found=1
                      Nr=1
                      exitif 1
                    endif
                    Nr=Nr+1
                  endloop
                  exitif !found
                endloop
              endif
              Nr=1
            endif
            
            ! Calculate drawing size including margins
            Scale = get($SCALE)
            if Nr=0 then
              Width  = ((Xlimit_max-Xlimit_min)/Scale)
              Height = ((Ylimit_max-Ylimit_min)/Scale)
              Aant = 1
            endif
            
            loop Aant
              if Nr>0 then
                dwgsetlimits Xmin(Nr), Xmax(Nr), Ymin(Nr), Ymax(Nr)
                Width  = ((Xmax(Nr)- Xmin(Nr))/Scale)
                Height = ((Ymax(Nr)- Ymin(Nr))/Scale)
                Nr = Nr+1 
              endif
                
              if cmp(Sheet$[1,1],"A") then      
                ! Find Matching scale for drawing
                ! Depending on chosen format A4, A4P, A3, A3P, A2, A2P, A1, A1P, A0, A0P
                ! Both portrait and landscape orientations are checked.
                ShSize$ = SetName$[5,7]

                ! Base setting for sheet size (A4)
                ShWidth = SheetWidth(3)
                ShHeight = SheetHeight(3)

                ! Find matching sheetsize from SetName
                ! A4
                if cmp(Sheet$,"A4L") then
                  ShWidth = SheetWidth(3)
                  ShHeight = SheetHeight(3)
                endif
                if cmp(Sheet$,"A4P") then
                  ShWidth = SheetHeight(3)
                  ShHeight = SheetWidth(3)
                endif
                ! A3
                if cmp(Sheet$,"A3L") then
                  ShWidth = SheetWidth(4)
                  ShHeight = SheetHeight(4)
                endif
                if cmp(Sheet$,"A3P") then
                  ShWidth = SheetHeight(4)
                  ShHeight = SheetWidth(4)
                endif
                ! A2
                if cmp(Sheet$,"A2L") then
                  ShWidth = SheetWidth(5)
                  ShHeight = SheetHeight(5)
                endif
                if cmp(Sheet$,"A2P") then
                  ShWidth = SheetHeight(5)
                  ShHeight = SheetWidth(5)
                endif
                ! A1
                if cmp(Sheet$,"A1L") then
                  ShWidth = SheetWidth(6)
                  ShHeight = SheetHeight(6)
                endif
                if cmp(Sheet$,"A1P") then
                  ShWidth = SheetHeight(6)
                  ShHeight = SheetWidth(6)
                endif
                ! A0
                if cmp(Sheet$,"A0L") then
                  ShWidth = SheetWidth(7)
                  ShHeight = SheetHeight(7)
                endif
                if cmp(Sheet$,"A0P") then
                  ShWidth = SheetHeight(7)
                  ShHeight = SheetWidth(7)
                endif

                ! Calculate scale based on selected size
                Shscale1 = Width/ShWidth
                Shscale2 = Height/ShHeight
                if Shscale1 > Shscale2 then
                  ! dwgsetscale Shscale1
                  Shscale = Shscale1
                else
                  ! dwgsetscale Shscale2
                  Shscale = Shscale2
                endif

                ! Set other needed parameters for pdf
                Oversize = 1
              else
              ! Find smallest sheet on which the drawing fits. Both
              ! portrait and landscape orientations are checked.      
                J = 0
                loop
                  J = J+1
                  exitif J>Sheet0
                  exitif Width<=SheetWidth(J)  and Height<=SheetHeight(J)
                  exitif Width<=SheetHeight(J) and Height<=SheetWidth(J)
                endloop

                Oversize = 0
                if J <= Sheet0 then
                  if Width<SheetWidth(J) and Height<=SheetHeight(J) then
                    ShWidth = SheetWidth(J)
                    ShHeight = SheetHeight(J)
                  else
                    ShWidth = SheetHeight(J)
                    ShHeight = SheetWidth(J)
                  endif
                else
                  MaxSize = inch_to_dwg(45.0)
                  if Width>MaxSize then
                    Width = MaxSize
                    Oversize = 1
                    Shscale = 1
                  endif
                  if Height>MaxSize then
                    Height = MaxSize
                    Oversize = 1
                    Shscale = 1
                  endif
                  ShWidth = Width
                  ShHeight = Height
                endif
              endif

              set TMPSHEET_XMIN "0"
              set TMPSHEET_XMAX ShWidth
              set TMPSHEET_YMIN "0"
              set TMPSHEET_YMAX ShHeight
              function SET_PDF_SHEET

              ! dwgupdatetext interactive= no
              dwgsetlevels "level_group="&Levels$(Lin)
              fileremove TmpPlotFile$

              Settings$ = "interaction=n,rotate=n,plotter=PDF-TEMP"
              if Oversize then
                Xo = (ShWidth-Width/Shscale)/2
                Yo = (ShHeight-Height/Shscale)/2
                Settings$ = Settings$&",xorg="&Xo
                Settings$ = Settings$&",yorg="&Yo
                Settings$ = Settings$&",free_scale=y"
              else
                Xo = (ShWidth-Width)/2
                Yo = (ShHeight-Height)/2
                Settings$ = Settings$&",xorg="&Xo
                Settings$ = Settings$&",yorg="&Yo
                Settings$ = Settings$&",free_scale=n"
              endif
              dwgplot Settings$

              ! Write all ps files in one .drwg file
              if FirstPic then
                filecopy TmpPlotFile$ FileName$&DrwgPF$
                FirstPic = 0
              else
                Command$ ="type "&TmpPlotFile$&" >> "&FileName$&DrwgPF$
                Ok = system(Command$)
              endif
                 
              ! Write to control file .ctrl
              Pic$ = I
              Epos= len(PicName$)-4
              PicNm$ = PicName$[1,Epos]
              ! write(9) Pic$&" "&PicNm$&"-"&Levels$(Lin)
              ! Wegschrijven van Filenaam om gemakkelijk in de tree te kunnen terugvinden
              if Wildcard then
                PosSlash = findstr(PicFile$,"/")
                PosAt    = findstr(PicFile$,"@")
                FileNm$  = PicFile$
                if PosSlash > 0 && PosAt > 0 then
                  FileNm$ = PicFile$[PosSlash+1,PosAt-1]
                else
                  if PosSlash > 0 then
                    FileNm$ = PicFile$[PosSlash+1]
                  else
                    FileNm$ = PicFile$[1,PosAt-1]
                  endif
                endif
              else
                FileNm$ = PicName$
              endif
              write(9) Pic$&" "&FileNm$
            endloop
          endif
        endloop
        dwgclose "PICTURE"
      endif
    endif
  endloop
endloop

!***********************************************************************
! Delete pseudo plotter and sheet
set SHEET_MODE "0"
function SHEET_SET
set PLOTTER_MODE "0"
function PLOTTER_SET

! dwgactivate "OLDDWG"
! Close .ctrl file
close(9)

! Create table of contents using control file
file_roman8toiso FileName$&ControlPF$
set PS_CONTROL_FILE FileName$&ControlPF$
set PDF_MARK_FILE FileName$&MarkPF$
set PDF_MARK_NO_METADATA "1"
MarkProg$ = PdfParProgPath$&"PDFcontrol2mark"
call MarkProg$
unset PDF_MARK_NO_METADATA
filecopy FileName$&MarkPF$ FileName$&PsPF$

! Attach ps drawings
Command$ = "type "&FileName$&DrwgPF$&" >> "&FileName$&PsPF$
Ok = system(Command$)

! Convert PostScript to PDF

Title$=get($ACTPROJNAME)
Author$="Vertex BD"
Keywords$=get($ACTPROJNAME)
! PDF = normal PDF, PDFA = PDF/A-1b compliant mode
if cmp(PdfMode$,"PDFA")=0 then
  PdfMode$="PDF"
endif
In$ = FileName$&PsPF$
Out$ = FileName$&PdfPF$
PsFile$ = HomeDir$&"PDFtmp.ps"
! Copy ps file to user for a case that there are scandies in path or filename - Ghostscript doesn't accept scandies
filecopy In$ PsFile$
Ret$=call("PDFconvert.prg",Out$,PsFile$,PdfMode$,Title$,Author$,Keywords$)
PdfFile$ = PdfDir$&JobName$&Date$&PdfPF$
if (cmp(Ret$,"OK")) then
  CopyFile = 1
  Question$=PdfDelFailed$&PdfFile$&"\\n\\n"&Retry$
  loop
    exitif !file_is_open(PdfFile$)
    CopyFile = really(Question$,1)
    exitif !CopyFile
  endloop
  if (CopyFile) then
    Command$ = "copy """&Out$&""" """&PdfDir$&""""
    Ok = system(Command$)
  else
    PdfFile$ = ""
  endif
endif

!In$ = FileName$&PsPF$
!Out$ = FileName$&PdfPF$
!Command$ = Ps2PdfBat$&" "&FileName$&" "&PdfProgram&" "&PdfProgramPath$&" "&PdfProgramDrive$&" "&GsLog$
!Ok = system(Command$)
!Command$ = "copy "&Out$&" """&PdfDir$&""""
!Ok = system(Command$)
!open(9) PdfProgramPath$&GsLog$
!FirstRow$ = read(9)
!close(9)

fileremove In$
fileremove PdfProgramPath$&GsLog$
fileremove FileName$&DrwgPF$
fileremove FileName$&MarkPF$
fileremove FileName$&ControlPF$
fileremove FileName$&PdfPF$
fileremove TmpPlotFile$

! Create new pdf file
set PDF_FILE PdfFile$