!***********************************************************************
!  PDFPlotSet / 2003-11-03 / Vertex Systems                            *
!                                                                      *
!  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 ./pdfplotbook.dbg
!
PdfFolder$ = get($PDFBOOKPATH)
Len = len(PdfFolder$)
if Len<1 then
  message "Virhe: Setup tiedostosta puuttuu set.pdf.folder asetus.", 0  
  exit
endif
if cmp(PdfFolder$[Len,Len],"/")=0 then
  PdfFolder$ = PdfFolder$&"/"
endif

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

Bookmarks$= get($BOOKMARKS)
Drive$= get($DRIVE)

!definitions to get this thing work at all
PdfBookName$ = get($PDFBOOKNAME)
JobName$ = PdfBookName$
ProjPath$ = PdfFolder$

L = len(ProjName$)
if L>6 then
  JobName$ = JobName$&ProjName$[7,Len]
endif

if file_exists(PdfFolder$)=1 then
  PdfDir$ = PdfFolder$
else
  PdfDir$ = ProjPath$&"Pdf/"
  dircreate PdfDir$ 
endif
Path$ = PdfDir$&JobName$&PdfPF$

fileselectdialog 1,Path$,"*.pdf",3
if get($NSELECTEDFILES)<1 then
  set PDF_FILE ""
  exit
endif
Path$ = get($SELECTEDFILE1)
Len = len(Path$)
if not cmp(Path$[Len-3,Len],PdfPF$) then
  set PDF_FILE ""
  exit
endif
P = Len - 4
loop
  exitif P < 0
  exitif cmp(Path$[P,P],"/")
  P = P - 1
endloop
PdfDir$ = Path$[1,P]
JobName$ = Path$[P+1,Len-4]

ProjectDir$ = PdfFolder$
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
endif

! Drawing sheets
if Metric then
  Sheet0 = 9
  SheetWidth(1) =   297; SheetHeight(1) =   210; ! A4
  SheetWidth(2) = 2*210; SheetHeight(2) =   297; ! A3
  SheetWidth(3) = 3*210; SheetHeight(3) =   297; ! 3xA4
  SheetWidth(4) = 4*210; SheetHeight(4) =   297; ! 4xA4
  SheetWidth(5) = 5*210; SheetHeight(5) =   297; ! 5xA4
  SheetWidth(6) = 6*210; SheetHeight(6) =   297; ! 6xA4
  SheetWidth(7) = 2*297; SheetHeight(7) = 2*210; ! A2
  SheetWidth(8) = 4*210; SheetHeight(8) = 2*297; ! A1
  SheetWidth(9) = 4*297; SheetHeight(9) = 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

set PDF_PRINT "1"

JobHeader$ = PdfBookName$
FileName$ = ProjectDir$&JobName$

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

DbId=1
IdIn = get($DATABASE_ID)
SetName$ = get($SETNAME)
dbopen(DbId) "ALREADY_OPEN",IdIn
if dbvalid(DbId) = 0 then
  exit
endif

DbList=1
dbfind(DbList) DbId, 0

! Create pseudo plotter
PlotterDef$ = "plotter= PDF-TEMP 7 5 ""./plot.ps"" """" 6 1 11 5.5 31 """" 32 ""PDF-SHEET"" 33 ""PDF"""
!PlotterDef$ = "plotter= PDF-TEMP 7 5 ""./plot.ps"" """" 6 1 11 5.5 31 """" 32 ""PDF-SHEET"" 33 ""PDF"""
set PLOTTER_DEF PlotterDef$
set PLOTTER_MODE "1"
function PLOTTER_SET

! Create pseudo sheet
set SHEET_MODE "1"
function SHEET_SET

I = 0
FirstPic = 1
Picts0 = dblistnum(DbList)
if Picts0 <= 0 then
  exit
endif
loop Picts0
  I = I+1 
  RowId= dblist(DbList,I)
  PicFile$ = dbgetf(DbId,RowId,"NAME")
  PicName$ = dbgetf(DbId,RowId,"NAME")
  Levels$ =  dbgetf(DbId,RowId,"LEVELGROUP")
  DrawingFile$ =  dbgetf(DbId,RowId,"FULLPATH")
  Type$ = dbgetf(DbId,RowId,"TYPE")
  Ok = dwgopen("PICTURE",DrawingFile$, 10,10,35,100)
  if Ok = 1 then
    dwgactivate "PICTURE"

    ! Calculate drawing size including margins
    Scale = get($SCALE)
    Width = (Xlimit_max-Xlimit_min)/Scale
    Height = (Ylimit_max-Ylimit_min)/Scale

    ! 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
      endif
      if Height>MaxSize then
        Height = MaxSize
        Oversize = 1
      endif
      ShWidth = Width
      ShHeight = Height
    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$
    fileremove TmpPlotFile$

    Settings$ = "interaction=n,rotate=n,plotter=PDF-TEMP"
    if Oversize then
      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

    dwgclose "PICTURE"
     
    ! Write to control file .ctrl
    Pic$ = I
    write(9) Pic$&" "&PicName$
  endif
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$

filecopy FileName$&MarkPF$ FileName$&PsPF$

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

! Convert PostScript to PDF

! PDF = normal PDF, PDFA = PDF/A-1b compliant mode
PdfMode$="PDF"
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
if (file_exists(Bookmarks$)) then
  !Bookmarks must be at the beginning
  filecopy Bookmarks$,PsFile$
  filecopy In$,PsFile$,"append"
else
  filecopy In$ PsFile$
endif

Ret$=call("PDFconvert.prg",Out$,PsFile$,PdfMode$)
if (cmp(Ret$,"OK")) then
  Command$ = "move """&Out$&""" """&PdfDir$&""""
  Ok = system(Command$)
endif

!In$ = FileName$&PsPF$
!Out$ = FileName$&PdfPF$
!Command$ = Ps2PdfBat$&" "&FileName$&" "&PdfProgram&" "&PdfProgramPath$&" "&PdfProgramDrive$&" "&GsLog$
!Ok = system(Command$)
!Command$ = "move "&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 TmpPlotFile$
fileremove Bookmarks$

PdfFile$ = PdfDir$&JobName$&PdfPF$
set PDF_FILE PdfFile$
